blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
73c9e6559f2fd53a694cfe3b549f13a61c62dbc5 | 556854947daa06ab8202c9b596099cb1cbbd3746 | /include/Skin/CommandBars/XTPMenuBar.h | 6d92d514feb53961dedd670ebcb2c9c84fe6c589 | [] | no_license | Hyuanwen/ShapFile | d271b22e1f90498f26d5cc690a2571ae2da9d1e8 | 8e070e977ffab61712b042cb11079cf438e56b97 | refs/heads/master | 2021-01-02T09:05:06.625427 | 2019-01-23T03:49:55 | 2019-01-23T03:49:55 | 99,137,521 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,072 | h | // XTPMenuBar.h : interface for the CXTPMenuBar class.
//
// This file is a part of the XTREME COMMANDBARS MFC class library.
// (c)1998-2008 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
//{{AFX_CODEJOCK_PRIVATE
#if !defined(__XTPMENUBAR_H__)
#define __XTPMENUBAR_H__
//}}AFX_CODEJOCK_PRIVATE
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "XTPToolBar.h"
#include "XTPCommandBarsDefines.h"
#define XTP_IDR_MENUBAR 1
class CXTPCommandBars;
//===========================================================================
// Summary:
// CXTPMenuBarMDIMenuInfo structure used to describe parameters of application MDI menus.
//===========================================================================
class CXTPMenuBarMDIMenuInfo : public CXTPCmdTarget
{
public:
CXTPMenuBarMDIMenuInfo(CXTPCommandBars* pCommandBars, UINT nIDResource);
~CXTPMenuBarMDIMenuInfo();
public:
CXTPControls* m_pControls; // Menu controls
CString m_strTitle; // Title of MDI menu
CString m_strDescription; // Description of MDI menu
HICON m_hIcon; // Menu Icon
UINT m_nIDResource; // Template identifier
BOOL m_bChanged; // TRUE if menu was changed.
};
class CXTPMenuBar;
//===========================================================================
// Summary:
// CXTPMenuBarMDIMenus represents collection of MDI menus for CXTPMenuBar
//===========================================================================
class _XTP_EXT_CLASS CXTPMenuBarMDIMenus : public CXTPCmdTarget
{
public:
//-----------------------------------------------------------------------
// Summary:
// Constructs a CXTPMenuBarMDIMenus object.
// Parameters:
// pMenuBar - Parent CXTPMenuBar
//-----------------------------------------------------------------------
CXTPMenuBarMDIMenus(CXTPMenuBar* pMenuBar);
//-------------------------------------------------------------------------
// Summary:
// Destroys a CXTPMenuBarMDIMenus object, handles clean up and deallocation
//-------------------------------------------------------------------------
~CXTPMenuBarMDIMenus();
public:
//-------------------------------------------------------------------------
// Summary:
// Returns number of MDI menus in collection
//-------------------------------------------------------------------------
int GetCount() const;
//{{AFX_CODEJOCK_PRIVATE
void SetAt(UINT nIDResource, CXTPMenuBarMDIMenuInfo* pInfo);
CXTPMenuBarMDIMenuInfo* Lookup(UINT nIDResource) const;
void Remove(UINT nIDResource);
void RemoveAll();
POSITION GetStartPosition() const;
void GetNextMenu(POSITION& pos, CXTPMenuBarMDIMenuInfo*& pInfo) const;
//}}AFX_CODEJOCK_PRIVATE
protected:
CMap<UINT, UINT, CXTPMenuBarMDIMenuInfo*, CXTPMenuBarMDIMenuInfo*> m_mapMenus; // Menu map
CXTPMenuBar* m_pMenuBar; // Parent Menu Bar
};
//===========================================================================
// Summary:
// CXTPMenuBar is a CXTPToolBar derived class. It represents menu bar of frame window.
//===========================================================================
class _XTP_EXT_CLASS CXTPMenuBar : public CXTPToolBar
{
public:
//-----------------------------------------------------------------------
// Summary:
// Constructs a CXTPMenuBar object
//-----------------------------------------------------------------------
CXTPMenuBar();
//-----------------------------------------------------------------------
// Summary:
// Destroys a CXTPMenuBar object, handles cleanup and deallocation
//-----------------------------------------------------------------------
~CXTPMenuBar();
public:
//-----------------------------------------------------------------------
// Summary:
// Loads the menu from resource.
// Parameters:
// nIDResource - Menu identifier to load.
// Returns:
// TRUE if successful; otherwise returns FALSE
//-----------------------------------------------------------------------
virtual BOOL LoadMenuBar(UINT nIDResource);
//------------------------------------------------------------------------
// Summary:
// Destroy all MDI menus.
//------------------------------------------------------------------------
void FreeMDIMenus();
//-----------------------------------------------------------------------
// Summary:
// This member function will refresh the menus
//-----------------------------------------------------------------------
void RefreshMenu();
//-----------------------------------------------------------------------
// Summary:
// Call this method to retrieve identifier of currently visible menu
//-----------------------------------------------------------------------
UINT GetCurrentMenuResource() const;
//-----------------------------------------------------------------------
// Summary:
// Call this method to retrieve identifier of default menu
//-----------------------------------------------------------------------
UINT GetDefaultMenuResource() const;
//-----------------------------------------------------------------------
// Summary:
// Retrieves collection of application MDI menus
//-----------------------------------------------------------------------
CXTPMenuBarMDIMenus* GetMDIMenus() const;
//-----------------------------------------------------------------------
// Summary: This method is called to switch to MDI menu from MDI menus collection
// Parameters:
// nIDMenu - Menu identifier to switch
// pMenu - Menu to switch
// See Also: SwitchActiveMenu
//-----------------------------------------------------------------------
virtual void SwitchMDIMenu(UINT nIDMenu, CMenu* pMenu = NULL);
//-----------------------------------------------------------------------
// Summary:
// Call this method to manually load MDI menu in application initialization
// Parameters:
// nIDResource - Template identifier
//-----------------------------------------------------------------------
CXTPMenuBarMDIMenuInfo* AddMDIMenu(UINT nIDResource);
//-------------------------------------------------------------------------
// Summary:
// This method is called to switch menu to active document menu.
// See Also: GetActiveDocTemplate, SwitchMDIMenu
//-------------------------------------------------------------------------
void SwitchActiveMenu();
//-----------------------------------------------------------------------
// Summary:
// Resets the controls to their original state.
// Parameters:
// bShowWarningMessage - TRUE to show warning message
//-----------------------------------------------------------------------
virtual void Reset(BOOL bShowWarningMessage);
protected:
//-----------------------------------------------------------------------
// Summary:
// This member function is called by WindowProc, or is called during
// message reflection.
// Parameters:
// hWnd - Window handle message belongs to.
// nMessage - Specifies the message to be sent.
// wParam - Specifies additional message-dependent information.
// lParam - Specifies additional message-dependent information.
// lResult - The return value of WindowProc. Depends on the message;
// may be NULL.
//-----------------------------------------------------------------------
int OnHookMessage(HWND hWnd, UINT nMessage, WPARAM& wParam, LPARAM& lParam, LRESULT& lResult);
//-----------------------------------------------------------------------
// Summary:
// Reads or writes this object from or to an archive.
// Parameters:
// pPX - A CXTPPropExchange object to serialize to or from.
//----------------------------------------------------------------------
void DoPropExchange(CXTPPropExchange* pPX);
//-----------------------------------------------------------------------
// Summary:
// This method makes a copy of the command bar.
// Parameters:
// pCommandBar - Command bar needed to be copied.
// bRecursive - TRUE to copy recursively.
//-----------------------------------------------------------------------
virtual void Copy(CXTPCommandBar* pCommandBar, BOOL bRecursive = FALSE);
protected:
//-------------------------------------------------------------------------
// Summary:
// This method is called create hooks for main window .
//-------------------------------------------------------------------------
void SetupHook();
//-----------------------------------------------------------------------
// Summary:
// Retrieves active MDI child window handle
// Parameters:
// bMaximized - If this parameter is not NULL, it is a pointer to a value that indicates the maximized state of the MDI child window.
// Returns:
// The return value is the handle to the active MDI child window.
//-----------------------------------------------------------------------
HWND GetActiveMdiChildWnd(BOOL* bMaximized = NULL);
//-------------------------------------------------------------------------
// Summary:
// This method is called to update active mdi window hooks.
//-------------------------------------------------------------------------
void SyncActiveMdiChild();
//-------------------------------------------------------------------------
// Summary:
// This method is called to update system buttons of menu bar.
//-------------------------------------------------------------------------
virtual void RefreshSysButtons();
//-----------------------------------------------------------------------
// Summary:
// This method is called to switch current MDI menu.
// Parameters:
// hMenu - Active menu need to select.
//-----------------------------------------------------------------------
void SwitchMDIMenu(HMENU hMenu);
//-----------------------------------------------------------------------
// Summary:
// This method is called to assign self identifiers for serialization process.
// Parameters:
// nID - Identifier to assign
// pCommandBarList - List of CommandBars.
// pParam - Address of a XTP_COMMANDBARS_PROPEXCHANGE_PARAM structure.
//-----------------------------------------------------------------------
void GenerateCommandBarList(DWORD& nID, CXTPCommandBarList* pCommandBarList, XTP_COMMANDBARS_PROPEXCHANGE_PARAM* pParam);
//-----------------------------------------------------------------------
// Summary:
// This method is called in serialization process.to restore popups from list of command bars.
// Parameters:
// pCommandBarList - List of CommandBars.
//-----------------------------------------------------------------------
void RestoreCommandBarList(CXTPCommandBarList* pCommandBarList);
//-----------------------------------------------------------------------
// Summary:
// This method is called to check if Toolbar was changed and have to be saved
// Returns:
// TRUE if toolbar have to be saved
//-----------------------------------------------------------------------
BOOL ShouldSerializeBar();
protected:
//{{AFX_CODEJOCK_PRIVATE
DECLARE_MESSAGE_MAP()
//{{AFX_MSG(CXTPMenuBar)
afx_msg void OnTimer(UINT_PTR nIDEvent);
//}}AFX_MSG
//}}AFX_CODEJOCK_PRIVATE
private:
void AddSysButton(CXTPControl* pControl, int nId, LPCTSTR lpszParameter, int nBefore = -1);
BOOL IsMDIMenusChanged();
BOOL IsOleDocumentActive(HWND hWndActiveChild) const;
protected:
BOOL m_bMdiApp; // TRUE if parent frame is CMDIFrameWnd derived.
HWND m_hWndActiveChild; // Active MDI window handle.
HMENU m_hMenuDefault; // Default menu handle.
UINT m_nIDResource; // Resource of default menu.
UINT m_nIDResourceCurrent; // Currently active menu.
CXTPMenuBarMDIMenus* m_pMDIMenus; // MDI menus.
private:
BOOL m_bDirtyMenu;
private:
DECLARE_XTP_COMMANDBAR(CXTPMenuBar)
class CControlMDIButton;
class CControlMDISysMenuPopup;
friend class CXTPCommandBars;
friend class CControlMDIButton;
friend class CCommandBarsSite;
friend class CCommandBarsCtrl;
};
AFX_INLINE UINT CXTPMenuBar::GetCurrentMenuResource() const {
return m_nIDResourceCurrent;
}
AFX_INLINE UINT CXTPMenuBar::GetDefaultMenuResource() const {
return m_nIDResource;
}
AFX_INLINE CXTPMenuBarMDIMenus* CXTPMenuBar::GetMDIMenus() const {
return m_pMDIMenus;
}
#endif //#if !defined(__XTPMENUBAR_H__)
| [
"742623475@qq.com"
] | 742623475@qq.com |
f33a7225b3bc7b586cf4ec6f2abef13f44aaeffd | 1942a0d16bd48962e72aa21fad8d034fa9521a6c | /aws-cpp-sdk-ssm/include/aws/ssm/model/PatchFilterKey.h | 6634682e5ef2c6d9e08f220fe072ebf629ba414c | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | yecol/aws-sdk-cpp | 1aff09a21cfe618e272c2c06d358cfa0fb07cecf | 0b1ea31e593d23b5db49ee39d0a11e5b98ab991e | refs/heads/master | 2021-01-20T02:53:53.557861 | 2018-02-11T11:14:58 | 2018-02-11T11:14:58 | 83,822,910 | 0 | 1 | null | 2017-03-03T17:17:00 | 2017-03-03T17:17:00 | null | UTF-8 | C++ | false | false | 1,116 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/ssm/SSM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace SSM
{
namespace Model
{
enum class PatchFilterKey
{
NOT_SET,
PRODUCT,
CLASSIFICATION,
MSRC_SEVERITY,
PATCH_ID
};
namespace PatchFilterKeyMapper
{
AWS_SSM_API PatchFilterKey GetPatchFilterKeyForName(const Aws::String& name);
AWS_SSM_API Aws::String GetNameForPatchFilterKey(PatchFilterKey value);
} // namespace PatchFilterKeyMapper
} // namespace Model
} // namespace SSM
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
368dbd851471a13ee3eae221c82d6d49fe99cd56 | 9192aaa5dea50e359e0625daa41ffeb189a913c8 | /sahist.h | e3d96aa1629ab8786086fecbd4fc7cf05eefdf83 | [] | no_license | tibordp/super_sahist | bb9758e134a9d08b17d416d4ea512fdc7aa0b7e8 | d5351af5576f6056631576f392b03d3ab7ac52ce | refs/heads/master | 2020-06-03T10:17:29.478478 | 2019-06-12T08:48:31 | 2019-06-12T08:48:31 | 191,533,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,489 | h | #pragma once
#include <algorithm>
#include <array>
#include <cassert>
#include <limits>
#include <map>
#include <random>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <thread>
#include <mutex>
#include <vector>
using namespace std;
using namespace std::rel_ops;
namespace Sahist {
enum class Figure {
nic,
kralj, kraljica, trdnjava,
tekac, konj, kmet
};
enum class Barva {
nobena, bela, crna
};
enum class Poteze {
konec, standardna, velika_rosada, mala_rosada, promocija, mimohod
};
struct Figura {
Figure tip;
Barva barva;
bool operator==(Figura rhs) const;
static Figura prazna() {
return {Figure::nic, Barva::nobena };
}
static Barva nasprotna_barva(Barva barva) {
return (barva == Barva::bela) ? Barva::crna : Barva::bela;
}
};
struct Koordinata {
int stolpec;
int vrstica;
bool operator==(Koordinata rhs) const;
Koordinata operator+(Koordinata rhs) const;
Koordinata& operator+=(Koordinata rhs);
inline operator bool() const;
static Koordinata neveljavna(){
return {-1,-1};
}
Koordinata() = default;
Koordinata(int stolpec_, int vrstica_)
: stolpec(stolpec_), vrstica(vrstica_)
{}
};
struct Poteza {
Poteze tip;
Koordinata od_koordinata;
Koordinata do_koordinata;
Figure tip_figure;
bool operator==(Poteza rhs) const;
};
class Sahovnica {
array<array<Figura, 8>, 8> deska;
map<Barva, bool> velike_rosade;
map<Barva, bool> male_rosade;
map<Barva, bool> ima_kralja;
Koordinata mimohod;
void inicializiraj();
public:
/*
Vrne nam smer premikanja kmeta v odvisnosti od barve
*/
static int smer_kmeta(Barva barva) {
return (barva == Barva::bela) ? 1 : -1;
}
/*
Vrne nam vrstico kmetov v odvisnosti od barve
*/
static int zacetek_kmeta(Barva barva) {
return (barva == Barva::bela) ? 2 : 7;
}
/*
Vrne nam zacetno vrstico v odvisnosti od barve
*/
static int zacetna_vrstica(Barva barva) {
return (barva == Barva::bela) ? 1 : 8;
}
/*
Vrne nam zadnjo vrstico v odvisnosti od barve
*/
static int konec_kmeta(Barva barva) {
return (barva == Barva::bela) ? 8 : 1;
}
void prestej_figure(unordered_map<Figura, int>&);
Sahovnica(bool postavi_figure = true);
Figura& polje(Koordinata pos);
bool zasedeno(Koordinata pos) const;
void premakni(Poteza p);
void dosegljive_pozicije(Koordinata pos, unordered_set<Koordinata>& results, bool samo_zajemi = false);
void vse_poteze(Barva barva, vector<Poteza>& results);
bool veljavna_poteza(Poteza poteza);
double alfa_beta(Poteza poteza, double alpha, double beta, int globina, Barva maksimiziraj);
double oceni_potezo(Poteza poteza, Barva maksimiziraj);
void dobre_poteze(Barva barva, vector<pair<double, Poteza>>& rezultat);
Poteza predlagaj(Barva barva);
bool sah(Barva barva);
void mozne_poteze(Barva barva, vector<Poteza>& rezultat);
bool premakni_nakljucno(Barva barva);
};
};
namespace std {
template<> struct hash<Sahist::Koordinata> {
inline size_t operator()(Sahist::Koordinata pos) const {
return pos.stolpec * 8 + pos.vrstica;
}
};
template<> struct hash<Sahist::Poteza> {
inline size_t operator()(Sahist::Poteza poteza) const {
return hash<Sahist::Koordinata>()(poteza.od_koordinata) * 64 +
hash<Sahist::Koordinata>()(poteza.do_koordinata);
}
};
template<> struct hash<Sahist::Figura> {
inline size_t operator()(Sahist::Figura figura) const {
return static_cast<int>(figura.barva) * 10 + // Število figur
static_cast<int>(figura.tip);
}
};
};
| [
"tibord@microsoft.com"
] | tibord@microsoft.com |
baa47dbe1834ee972db683ee8e5fc7065d70c23c | a3effde3c27c072090f0021bdae3306961eb2d92 | /Codeforces/1342/C.cpp | 409ed0560dd87215cee1a5e18a32917a04e777d6 | [] | no_license | anmolgup/Competitive-programming-code | f4837522bf648c90847d971481f830a47722da29 | 329101c4e45be68192715c9a0718f148e541b58b | refs/heads/master | 2022-12-03T19:00:40.261727 | 2020-08-08T09:21:58 | 2020-08-08T09:21:58 | 286,011,774 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | cpp | #include<bits/stdc++.h>
#define god dimasi5eks
#pragma GCC optimize("O3")
#define fi first
#define se second
#define pb push_back
#define pf push_front
// #define fisier 1
using namespace std;
typedef long long ll;
const int mod = 1000000007;
const double dancila = 3.14159265359; // PI
const double eps = 1e-9;
int ps[40002];
ll a, b;
ll cnt(ll xx)
{
return 1LL * ps[a*b-1] * (xx/(a*b)) + ps[xx%(a*b)];
}
int main()
{
#ifdef fisier
ifstream f("input.in");
ofstream g("output.out");
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
for(; t; --t)
{
ll q;
cin >> a >> b >> q;
for(int i = 0; i < a*b; ++i)
{
if(i == 0)
ps[i] = 0;
else
{
int va = ((i%a)%b);
int vb = ((i%b)%a);
ps[i] = ps[i-1];
if(va != vb)
++ps[i];
}
}
for(; q; --q)
{
ll l, r;
cin >> l >> r;
if(a == b)
cout << 0 << " ";
else
cout << cnt(r) - cnt(l-1) << " ";
}
cout << '\n';
}
return 0;
} | [
"anmolgupta9557@gmail.com"
] | anmolgupta9557@gmail.com |
54d5179184e4474cfec4387e1b425d4edcc03227 | 2db137cc7275e5254cb66fc0fb98e067fcf4381a | /Osiris/menu/menu.h | 3dd7b87470644a1ab090486a876e1b43bfdd3c59 | [] | no_license | MyNameIsKodak/osirisv3 | f30a8d588fdd90ef20735960c13cae8d1761a7ec | ccedda9790c898d3bef40e8232fac26d52089a9e | refs/heads/master | 2023-07-18T02:49:26.421968 | 2021-08-25T13:28:54 | 2021-08-25T13:28:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,335 | h | #pragma once
#include <Windows.h>
#include "../imgui/imgui.h"
#include "../imgui/imgui_internal.h"
#include <string>
#include <functional>
#include <map>
#include <d3dx9.h>
#define ITEM_WIDTH_WITH_COLOR -1.f
#define ITEM_WIDTH_WITH_COLOR2 -2.f
constexpr auto MENU_TAB_HEIGHT = 52.f;
constexpr auto WINDOW_PADDING_SAMELINE = 15.f;
constexpr auto WINDOW_PADDING_SPACING = 5;
constexpr auto WINDOW_WIDGETS_PADDING_SAMELINE = 17.f;
constexpr auto WINDOW_WIDGETS_PADDING_SPACING = 6;
constexpr auto WINDOW_UNDERGROUND_HEIGHT = 18.f;
constexpr auto FEATURE_BUTTON_SIZE = 32.f;
struct LinkData
{
std::string url;
bool hovered;
bool clicked;
};
struct TabWidgetsData
{
std::string label;
float fading_value;
};
class CMenuPopupModal
{
public:
bool Begin(std::string name, const ImVec2& size);
void End();
void Input(std::string name, char* buf, size_t buf_size);
void Message(std::string message);
bool Button(std::string name);
private:
float GetItemWidth();
};
class KeyBind;
class CMenuGui
{
public:
bool Begin(std::string name, const ImVec2& size);
void BeginCanvas(std::string name, const ImVec2& size, bool border = false);
void BeginGroupBox(std::string name, const ImVec2& size, bool border = true);
void BeginWidgetsGroup();
void End();
void EndCanvas();
void EndGroupBox();
void EndWidgetsGroup();
void SmallGroupBox(std::string name, const ImVec2& size, std::function<void()> widget_first, std::function<void()> widget_second);
void UnderBackground();
void UnderContents();
void TabBackground();
bool TabList(std::vector<TabWidgetsData>& data, int& selected, int& hovered);
bool TabFeaturesList(std::vector<TabWidgetsData>& data, int& selected, int& hovered);
bool TabWeaponList(std::vector<TabWidgetsData>& data, int& selected, int& hovered);
void TabSeparator();
void TabShadow(const ImVec2& pos, const ImVec2& size, const ImVec4& color);
void SetID(const char* str_id);
void SetChildSize(ImVec2& size);
void Text(const char* fmt, ...);
bool Checkbox(bool* v, std::string label, std::string message = "");
bool Combo(int* v, std::string label, const char* items[], int size, std::string message = "", bool owned = false);
bool MultiCombo(bool* v, std::string label, const char* items[], int size, std::string message = "");
bool Slider(float* v, std::string label, float min, float max, const char* format, float power, std::string message = "");
bool Slider(int* v, std::string label, int min, int max, const char* format, std::string message = "");
bool ListBox(const char* label, int* current_item, std::vector<std::string>& values, int height_in_items);
void Separator();
void Link(std::string url);
bool Key(void* v, std::string label, bool owned = false);
bool KeyToggle(KeyBind* v, std::string label, bool owned);
bool KeyToggle(void* v, std::string label, bool owned = false);
bool KeyPress(void* v, std::string label, bool owned = false);
bool ColorEdit(float* v, std::string label);
void BeginCheckChangeValue();
void EndCheckChangeValue();
bool IsChangedValue();
private:
std::map<std::string, float> m_widgets_list;
std::string m_id;
std::string m_message;
bool m_check_change_value;
bool m_changed_value;
//std::unique_ptr<CMenuPopupModal> m_pPopupModal;
float& FindWidgetsFadingValue(std::string label);
void UpdateWidgetsFadingValue(float& fading_value);
};
namespace ImGui
{
IMGUI_API bool ImageButtonTab(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // <0 frame_padding uses default frame padding settings. 0 for no padding
IMGUI_API bool ImageButtonBySize(ImTextureID user_texture_id, const ImVec2& size, const ImVec2 image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0)); // <0 frame_padding uses default frame padding settings. 0 for no padding
IMGUI_API bool BeginCustom(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0);
IMGUI_API bool BeginChildCustom(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0);
IMGUI_API void EndChildCustom();
IMGUI_API void Separator(float width);
}
typedef unsigned int FontFlags_t;
enum FontFlagList
{
FontFlags_None = 1 << 0,
FontFlags_Shadow = 1 << 1,
FontFlags_Outline = 1 << 2,
FontFlags_CenterX = 1 << 3,
FontFlags_CenterY = 1 << 4,
};
class CDrawList
{
public:
void AddLine(const ImVec2& a, const ImVec2& b, const ImColor& col);
void AddRect(const ImVec2& a, const ImVec2& b, const ImColor& col, bool outline = false, float rounding = 0.f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.f);
void AddRectCorner(const ImVec2& a, const ImVec2& b, const ImColor& col, bool outline = false);
void AddRectFilled(const ImVec2& a, const ImVec2& b, const ImColor& col, float rounding = 0.f, int rounding_corners_flags = ImDrawCornerFlags_All);
void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImColor col_upr_left, ImColor col_upr_right, ImColor col_bot_right, ImColor col_bot_left);
void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImColor& col, float thickness = 1.f);
void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImColor& col);
void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImColor& col, float thickness = 1.f);
void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImColor& col);
void AddCircle(const ImVec2& centre, float radius, const ImColor& col, int num_segments = 12, float thickness = 1.f);
void AddCircleFilled(const ImVec2& centre, float radius, const ImColor& col, int num_segments = 12);
void AddText(const ImVec2& pos, const ImColor& col, FontFlags_t flags, const char* fmt, ...);
void AddTextWrapped(const ImVec2& pos, const ImColor& col, float wrap_width, FontFlags_t flags, const char* fmt, ...);
void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(), const ImVec2& uv_b = ImVec2(1, 1), const ImColor& col = ImColor(IM_COL32_WHITE));
void PushLine(const ImVec2& a, const ImVec2& b, const ImColor& col);
void PushRect(const ImVec2& a, const ImVec2& b, const ImColor& col, bool outline = false, float rounding = 0.f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.f);
void PushRectCorner(const ImVec2& a, const ImVec2& b, const ImColor& col, bool outline = false);
void PushRectFilled(const ImVec2& a, const ImVec2& b, const ImColor& col, float rounding = 0.f, int rounding_corners_flags = ImDrawCornerFlags_All);
void PushRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImColor col_upr_left, ImColor col_upr_right, ImColor col_bot_right, ImColor col_bot_left);
void PushQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImColor& col, float thickness = 1.f);
void PushQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImColor& col);
void PushTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImColor& col, float thickness = 1.f);
void PushTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImColor& col);
void PushCircle(const ImVec2& centre, float radius, const ImColor& col, int num_segments = 12, float thickness = 1.f);
void PushCircleFilled(const ImVec2& centre, float radius, const ImColor& col, int num_segments = 12);
void PushText(const ImVec2& pos, const ImColor& col, FontFlags_t flags, const char* fmt, ...);
void PushTextWrapped(const ImVec2& pos, const ImColor& col, float wrap_width, FontFlags_t flags, const char* fmt, ...);
void PushImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(), const ImVec2& uv_b = ImVec2(1, 1), const ImColor& col = ImColor(IM_COL32_WHITE));
};
inline CDrawList* DrawList = new CDrawList();
enum EFontList
{
ProggyClean_13px,
Verdana_1px,
Verdana_2px,
Verdana_3px,
Verdana_4px,
Verdana_5px,
Verdana_6px,
Verdana_7px,
Verdana_8px,
Verdana_9px,
Verdana_10px,
Verdana_11px,
Verdana_12px,
Verdana_13px,
Verdana_14px,
Verdana_15px,
Verdana_16px,
Verdana_17px,
Verdana_18px,
Verdana_19px,
Verdana_20px,
Verdana_21px,
Verdana_22px,
Verdana_23px,
Verdana_24px,
Verdana_25px,
MAX_FONTS
};
enum EFontOffsetList
{
FontProggyCleanOffset = 0,
FontVerdanaOffset = 1
};
enum EImageList
{
MenuTitleBg,
TabRageIcon,
TabLegitIcon,
TabVisualsIcon,
TabKreedzIcon,
TabMiscIcon,
TabConfigsIcon,
TabConsoleIcon,
WpnPistolsIcon,
WpnSmgsIcon,
WpnRiflesIcon,
WpnShotgunsIcon,
WpnSnipersIcon,
WPN_NONE,
WPN_P228,
WPN_GLOCK,
WPN_SCOUT,
WPN_HEGRENADE,
WPN_XM1014,
WPN_C4,
WPN_MAC10,
WPN_AUG,
WPN_SMOKEGRENADE,
WPN_ELITE,
WPN_FIVESEVEN,
WPN_UMP45,
WPN_SG550,
WPN_GALIL,
WPN_FAMAS,
WPN_USP,
WPN_GLOCK18,
WPN_AWP,
WPN_MP5N,
WPN_M249,
WPN_M3,
WPN_M4A1,
WPN_TMP,
WPN_G3SG1,
WPN_FLASHBANG,
WPN_DEAGLE,
WPN_SG552,
WPN_AK47,
WPN_KNIFE,
WPN_P90,
DefuserIcon,
MAX_IMAGES
};
enum EImageOffsetsList
{
IconsTabsOffset = 1,
IconsWpnsOffset = 8,
IconsEspWpnsOffset = 13
};
struct ImageInfo
{
IDirect3DTexture9* data;
ImVec2 size;
};
extern ImFont* g_pFontList[MAX_FONTS];
extern ImageInfo g_pImageList[MAX_IMAGES];
class CMenuThemes
{
public:
void SetDefaultDarkTheme();
};
class CMenu
{
public:
bool IsOpened();
bool InitTextures(LPDIRECT3DDEVICE9 pDevice);
void Open();
void Close();
void Toggle();
void CursorState();
void DrawFadeBg();
void Draw();
void BeginScene();
void EndScene();
//private:
inline static CMenuGui* m_pGui = new CMenuGui();
//std::unique_ptr<CMenuPopupModal> m_pPopupModal;
//std::unique_ptr<CMenuHotkeys> m_pHotkeys;
//std::unique_ptr<CMenuSettingsList> m_pSettingsList;
//std::unique_ptr<CMenuFadeBg> m_pFadeBg;
inline static CMenuThemes* m_pThemes = new CMenuThemes();
bool m_bIsOpened;
ImVec2 m_WindowPos;
ImVec2 m_WindowSize;
ImVec2 m_WindowCanvasPos;
ImVec2 m_WindowCanvasSize;
int m_iSelectedTab;
int m_iHoveredTab;
void DialogSettingsSaveAs(char* buf, size_t size);
void DialogSettingsRename(char* buf, size_t size);
void DialogSettingsReset();
void DialogSettingsRemove();
void DialogFindAndReplace(char* buf);
void DrawRage();
void DrawLegit();
void DrawVisuals();
};
inline static CMenu* g_pMenu = new CMenu();
struct bind_t
{
int keynum;
int type;
};
struct cvars_ragebot
{
bool active;
bool friendly_fire;
bool raim_delayshot[2];
bool raim_tapping_mode;
bool raim_auto_fire;
int raim_auto_scope;
bool raim_remove_recoil;
int raim_remove_spread;
int raim_type;
float raim_fov;
bool raim_low_fps_mitigations[3];
float raim_low_fps_value;
int raim_resolver_pitch;
int raim_resolver_yaw;
bind_t raim_force_body_key;
bool raim_target_selection[3];
int raim_target_weight_damage;
int raim_target_weight_fov;
int raim_target_weight_head;
int raim_target_weight_neck;
int raim_target_weight_chest;
int raim_target_weight_stomach;
int raim_target_weight_arms;
int raim_target_weight_legs;
bool aa_enabled;
bool aa_teammates;
int aa_at_targets;
int aa_stand_pitch;
int aa_stand_yaw;
int aa_stand_desync;
bool aa_stand_desync_helper;
int aa_side;
bind_t aa_side_key;
bool aa_side_switch_when_take_damage;
int aa_move_pitch;
int aa_move_yaw;
int aa_roll;
float aa_stand_yaw_static;
float aa_roll_static;
bool aa_untrusted_checks;
bool aa_conditions[3];
bool fakelag_enabled;
bool fakelag_while_shooting;
bool fakelag_on_enemy_in_pvs;
bool fakelag_on_peek;
bool fakelag_triggers[2];
int fakelag_type;
int fakelag_choke_limit;
};
struct cvars_legitbot
{
bool active;
bool friendly_fire;
bool position_adjustment;
bool desync_helper;
int target_switch_delay;
bool aim_auto_scope;
bool aim_smooth_independence_fps;
int aim_block_attack_after_kill;
bool aim_dont_shoot_in_shield;
bool aim_demochecker_bypass;
int aim_recoil_standalone;
bind_t aim_key;
bind_t aim_psilent_key;
bool trigger_only_scoped;
bool trigger_accurate_traces;
float trigger_hitbox_scale;
bind_t trigger_key;
};
struct cvars_weapons
{
bool aim_enabled;
bool aim_hitboxes[6];
bool aim_auto_fire;
bool aim_auto_penetration;
int aim_auto_penetration_min_damage;
bool aim_psilent_tapping_mode;
float aim_psilent_angle;
float aim_fov;
float aim_smooth_auto;
float aim_smooth_in_attack;
float aim_smooth_scale_fov;
float aim_recoil_smooth;
float aim_recoil_fov;
int aim_recoil_start;
float aim_recoil_pitch;
float aim_recoil_yaw;
int aim_maximum_lock_on_time;
int aim_delay_before_aiming;
int aim_delay_before_firing;
bool aim_psilent_triggers[3];
int aim_psilent_type;
int aim_accuracy_boost;
bool trigger_enabled;
bool trigger_auto_penetration;
int trigger_auto_penetration_min_damage;
bool trigger_hitboxes[6];
int trigger_accuracy_boost;
bool raim_enabled;
bool raim_hitboxes[6];
bool raim_auto_penetration;
int raim_auto_penetration_min_damage;
float raim_head_scale;
float raim_neck_scale;
float raim_chest_scale;
float raim_stomach_scale;
float raim_arms_scale;
float raim_legs_scale;
int raim_autostop;
bool raim_autostop_crouch;
};
struct cvars_visuals
{
bool active;
bind_t panic_key;
bool copyright;
float copyright_position[3];
bool antiscreen;
bool streamer_mode;
float esp_dormant_time;
bool esp_dormant_fadeout;
bool esp_dormant_update_by_sound;
bool esp_interpolate_history;
int esp_font_size;
bool esp_player;
bool esp_player_players[3];
int esp_player_box;
bool esp_player_box_outline;
int esp_player_box_filled;
float esp_player_box_color_t[4];
float esp_player_box_color_ct[4];
int esp_player_health;
bool esp_player_health_percentage;
float esp_player_health_percentage_color[4];
int esp_player_armor;
float esp_player_armor_color[4];
int esp_player_name;
float esp_player_name_color[4];
int esp_player_weapon_text;
float esp_player_weapon_text_color[4];
int esp_player_weapon_icon;
float esp_player_weapon_icon_color[4];
int esp_player_money;
float esp_player_money_color[4];
int esp_player_distance;
int esp_player_distance_measurement;
float esp_player_distance_color[4];
int esp_player_actions;
float esp_player_actions_color[4];
bool esp_player_actions_bar;
float esp_player_actions_bar_color[4];
int esp_player_has_c4;
float esp_player_has_c4_color[4];
int esp_player_has_defusal_kits;
float esp_player_has_defusal_kits_color[4];
float esp_player_line_of_sight;
float esp_player_line_of_sight_color[4];
int esp_player_hitboxes;
float esp_player_hitboxes_color[4];
bool esp_player_hitboxes_hit_position;
float esp_player_hitboxes_hit_position_time;
float esp_player_hitboxes_hit_position_color[4];
float esp_player_hitboxes_hit_position_color2[4];
bool esp_player_skeleton;
float esp_player_skeleton_color[4];
bool esp_player_skeleton_backtrack;
float esp_player_skeleton_backtrack_color[4];
bool esp_player_glow;
bool esp_player_glow_players[3];
int esp_player_glow_amount;
bool esp_player_glow_color_health_based;
float esp_player_glow_color_t[4];
float esp_player_glow_color_ct[4];
bool esp_player_sounds;
bool esp_player_sounds_players[3];
float esp_player_sounds_time;
float esp_player_sounds_circle_radius;
float esp_player_sounds_color_t[4];
float esp_player_sounds_color_ct[4];
bool esp_player_out_of_fov;
int esp_player_out_of_fov_draw_type;
bool esp_player_out_of_fov_players[2];
bool esp_player_out_of_fov_additional_info[3];
float esp_player_out_of_fov_size;
float esp_player_out_of_fov_radius;
bool esp_player_out_of_fov_aspect_ratio;
float esp_player_out_of_fov_color_t[4];
float esp_player_out_of_fov_color_ct[4];
bool esp_player_out_of_fov_impulse_alpha;
bool esp_player_out_of_fov_outline;
float colored_models_dormant_time;
bool colored_models_dormant_fadeout;
bool colored_models_paint_players_weapons;
int colored_models_players;
bool colored_models_players_wireframe;
bool colored_models_players_players[3];
bool colored_models_players_behind_wall;
int colored_models_players_color_health_based;
float colored_models_players_color_t_hide[4];
float colored_models_players_color_t_vis[4];
float colored_models_players_color_ct_hide[4];
float colored_models_players_color_ct_vis[4];
int colored_models_players_on_the_dead;
float colored_models_players_on_the_dead_color[4];
int colored_models_players_hit_position;
float colored_models_players_hit_position_time;
float colored_models_players_hit_position_color[4];
int colored_models_players_desync_aa;
float colored_models_players_desync_aa_color[4];
int colored_models_backtrack;
bool colored_models_backtrack_wireframe;
bool colored_models_backtrack_players[2];
bool colored_models_backtrack_behind_wall;
float colored_models_backtrack_color_t_hide[4];
float colored_models_backtrack_color_t_vis[4];
float colored_models_backtrack_color_ct_hide[4];
float colored_models_backtrack_color_ct_vis[4];
int colored_models_hands;
bool colored_models_hands_wireframe;
float colored_models_hands_color[4];
bool colored_models_hands_color_rainbow;
float colored_models_hands_color_rainbow_speed;
bool colored_models_dlight;
bool colored_models_dlight_players[3];
int colored_models_dlight_origin;
float colored_models_dlight_radius;
float colored_models_dlight_minlight;
bool colored_models_dlight_fading_lighting;
float colored_models_dlight_fading_lighting_speed;
float colored_models_dlight_color[4];
bool colored_models_elight;
bool colored_models_elight_players[3];
float colored_models_elight_radius;
float colored_models_elight_color[4];
bool esp_other_local_aa_side_arrows;
bool esp_other_local_sniper_crosshair;
bool esp_other_local_recoil_point;
float esp_other_local_recoil_point_color[4];
bool esp_other_local_spread_point;
float esp_other_local_spread_point_color[4];
bool esp_other_local_spread_circle;
float esp_other_local_spread_circle_color[4];
float esp_other_local_spread_circle_color2[4];
bool esp_other_local_aim_fov;
float esp_other_local_aim_fov_color[4];
float esp_other_local_aim_fov_color2[4];
bool esp_other_local_toggle_status;
float esp_other_local_toggle_status_color[4];
float esp_other_local_toggle_status_color2[4];
bool effects_hud_clear;
int effects_thirdperson;
bind_t effects_thirdperson_key;
int effects_custom_render_fov;
bool remove_scope;
};
struct cvars_kreedz
{
bool active;
};
struct cvars_misc
{
bind_t fakelatency_key;
bool fakelatency;
int fakelatency_amount;
bool namestealer;
int namestealer_interval;
bool automatic_reload;
bool automatic_pistol;
bool replace_models_with_original;
bool steamid_spoofer;
bind_t kb_key;
bool kb_enabled;
bool kb_friendly_fire;
bool kb_conditions[3];
bool kb_position_adjustment;
int kb_attack_type;
int kb_aim_type;
bool kb_aim_hitbox[6];
float kb_fov;
float kb_swing_distance;
float kb_stab_distance;
float kb_aim_hitbox_scale;
};
namespace cvars
{
inline cvars_ragebot ragebot;
inline cvars_legitbot legitbot;
inline cvars_weapons weapons[1024];
inline cvars_visuals visuals;
inline cvars_kreedz kreedz;
inline cvars_misc misc;
}
| [
"somageller06@gmail.com"
] | somageller06@gmail.com |
c14ccd66490b8c775fe48272a8ee1ca5d4edb543 | 49419386395f4699178d7eb5b0408255edf6bd03 | /sketch.ino | 10a62026d4d498f527102c77a133cef0c839b65f | [] | no_license | JoaoDias-223/Smart-Weight-Sensor | 931f1d8d87e9f52d164157a807f6c8b9e333699b | e626046cd5d882eb75bddb76200497f035946c43 | refs/heads/main | 2022-12-25T19:35:33.526664 | 2020-10-15T19:39:42 | 2020-10-15T19:39:42 | 304,425,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,546 | ino | #define BLYNK_PRINT Serial
#define BUILTIN_LED D0 // Led interno do Nodemcu.
#define DOUT D1 // Porta digital de output serial do componente HX711.
#define CLK D2 // Porta do clock do input serial.
#define GREEN_LED D3 // Porta digital do LED Verde.
#define VIRTUAL_PORT_1 V1 // Portal virtual 1 do Blynk
#define VIRTUAL_PORT_2 V2 // Portal virtual 2 do Blynk
#define VIRTUAL_PORT_3 V3 // Portal virtual 3 do Blynk
#define VIRTUAL_PORT_4 V4 // Portal virtual 4 do Blynk
#define VIRTUAL_PORT_4 V5 // Portal virtual 5 do Blynk
#include <HX711.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
HX711 scale(DOUT, CLK); // Criação do objeto que representa a balança.
char ssid[] = "nome_da_rede"; // Nome da rede wifi em que o Nodemcu será conectado.
char pswd[] = "senha_da_rede"; // Senha da rede wifi em que o Nodemcu será conectado.
char auth[] = "ws_cJB9BgAMi-BZhx9j-I82vsXu3eyQv"; // Token de autenticação do aplicativo da Blynk que permite a conexão do Nodemcu ao servidor.
float calibration_factor = 22375.00; // Fator de calibragem da balança.
float current_weight = 0; // Variável que guarda o peso atual da balança.
int rounded_weight = 0; // Variável que guarda o peso em gramas.
bool notifyUser = 0; // Variável que serve para checar se o aplicativo enviará uma notificação ou não.
bool isDirty = 0; // Variável que serve para checar se o lcd precisa ser limpado.
BlynkTimer timer; // Timer do Blynk.
WidgetLCD lcd(VIRTUAL_PORT_3); // LCD do Blynk.
WidgetLED led(VIRTUAL_PORT_2); // LED do Blynk.
void blinkLED(int port, int delay_time); // Função que faz o LED interno piscar. Serve puramente para debug.
bool checkWeight(int weight, int threshold, int port); // Função que checa se o peso está acima do limiar definido.
void send_notification(bool notifyUser); // Função que envia uma notificação ao usuário.
void send_weight(); // Função que envia o peso atual ao aplicativo.
void print_info(); // Função que imprime as informações do peso atual e do peso arrendodado no monitor serial.
void clear_lcd(); // Função que limpa o LCD dependendo da variável isDirty.
BLYNK_WRITE(V4) // Função que checa a borda de subida da porta virtual 5 e diminui o fator de alibragem em 100
{
int pinValue = param.asInt();
Serial.print("Pin value (V4): ");Serial.println(pinValue);
calibration_factor -= 100;
}
BLYNK_WRITE(V5) // Função que checa a borda de subida da porta virtual 5 e aumenta o fator de alibragem em 100
{
int pinValue = param.asInt();
Serial.print("Pin value (V5): ");Serial.println(pinValue);
calibration_factor += 100;
}
void setup() {
pinMode (BUILTIN_LED, OUTPUT);
pinMode (GREEN_LED, OUTPUT);
Serial.begin(9600);
Blynk.begin(auth, ssid, pswd); // Conexão do Nodemcu com o servidor da nuvem da Blynk.
scale.set_scale(); // Função que seta o fator de calibragem da balança com o fator de calibragem padrão da classe.
scale.tare(); // Reseta o valor da balança para zero.
timer.setInterval(100L, send_weight);
timer.setInterval(10000L, clear_lcd);
}
void loop() {
Blynk.run(); // Função que mantém as rotinas da biblioteca rodando.
timer.run(); // Função que executa um ciclo do relógio interno do Nodemcu através da biblioteca do Blynk.
scale.set_scale(calibration_factor); // Função que seta o fator de calibragem da balança com o valor correto.
current_weight = scale.get_units(); // A função get_units() retorna o valor atual da balança já convertido para kg e ele é guardado na variável current_weight.
rounded_weight = current_weight * 1000;
rounded_weight = round(abs(rounded_weight));
notifyUser = checkWeight(rounded_weight, 1000, GREEN_LED);
send_notification(notifyUser);
print_info();
blinkLED (BUILTIN_LED, 100);
}
void blinkLED (int port, int delay_time) {
digitalWrite(port, LOW);
delay(delay_time);
digitalWrite(port, HIGH);
delay(delay_time);
}
bool checkWeight(int weight, int threshold, int port){
if (weight >= threshold){
digitalWrite(port, HIGH);
led.on();
return true;
}
digitalWrite(port, LOW);
led.off();
return false;
}
void send_notification(bool notifyUser){
if (notifyUser){
Blynk.notify("Ei, tem alguém no seu sensor! É bom dar uma olhada.");
lcd.clear();
lcd.print(0, 0, "Individuo");
lcd.print(0, 1, "Detectado!");
isDirty = true;
}
}
void send_weight(){
Blynk.virtualWrite(VIRTUAL_PORT_1, rounded_weight); // Envia o valor do peso atual em gramas para a porta virtual 1 do aplicativo Blynk.
}
void clear_lcd(){
if (isDirty){
lcd.clear();
isDirty = false;
}
}
void print_info(){
Serial.print("Peso atual: "); Serial.print(current_weight, 4);Serial.println(" kg");
Serial.print("Peso arredondado: "); Serial.print(rounded_weight);Serial.println(" g");
Serial.print("Fator de calibragem: "); Serial.print(calibration_factor);Serial.println();
Serial.println("############################################################");
}
| [
"joao.dias.santos223@gmail.com"
] | joao.dias.santos223@gmail.com |
0cb0d490d8936e5f58a31420792d931530e2bcde | c05c9cf3bd36d50b04901deb8726f0db8865262f | /mainwindow.h | 08b21ac5b782f6d8d6c71f43bd7262954892017e | [] | no_license | feakuru/fealizer | bbbb005b9fea4316c60f0ccb7adc4c9f06583021 | 6decbc99dd60346e5ef05ac82320e4a7c16a128d | refs/heads/master | 2021-01-19T07:55:03.221426 | 2017-05-18T07:57:09 | 2017-05-18T07:57:09 | 82,065,094 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,235 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileDialog>
#include <QTimer>
#include "equalizer.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_openButton_clicked();
void on_playButton_clicked();
void on_verticalSlider_sliderMoved(int position);
void on_verticalSlider_2_sliderMoved(int position);
void on_verticalSlider_3_sliderMoved(int position);
void on_verticalSlider_4_sliderMoved(int position);
void on_verticalSlider_5_sliderMoved(int position);
void on_verticalSlider_6_sliderMoved(int position);
void on_verticalSlider_7_sliderMoved(int position);
void on_verticalSlider_8_sliderMoved(int position);
void on_verticalSlider_9_sliderMoved(int position);
void on_verticalSlider_10_sliderMoved(int position);
void on_stopButton_clicked();
void on_delay_checkBox_toggled(bool checked);
void on_vibrato_checkBox_toggled(bool checked);
private:
Ui::MainWindow *ui;
QString currentFileName;
double coeffs[10];
FilteredStream eq;
};
#endif // MAINWINDOW_H
| [
"feanarokurufinve@mail.ru"
] | feanarokurufinve@mail.ru |
eb72513cf1451ffec45e95a63a505ddf051be36b | 76f8b3780ec03413f5a1a31782953a3efa40a0cf | /src/sound/AudioDevOss.h | 5f94581ee371b13ab603a0fcf28eaf5923c7699d | [] | no_license | wanwanland/qvwm | b898faf76117268a36875d2129c6f44f476a5d83 | fb1fb46596dff24d789fb0b0558a38c9705484ce | refs/heads/master | 2020-12-11T05:25:45.056351 | 2012-12-20T19:07:42 | 2012-12-20T19:07:42 | 15,181,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,943 | h | /*
* audiodev_oss.h
*
* Copyright (C) 1995-2001 Kenichi Kourai
*
* 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, 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 qvwm; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef AUDIODEV_OSS_H_
#define AUDIODEV_OSS_H_
#if defined(__linux__) || defined(__FreeBSD__)
#define OSS
#endif
#ifdef OSS
// OSS header
#ifdef __linux__
#include <linux/soundcard.h>
#endif
#ifdef __FreeBSD__
#include <machine/soundcard.h>
#endif
// set endian
#if !defined(SND_LITTLE_ENDIAN) && !defined(SND_BIG_ENDIAN)
#ifdef __linux__
#include <endian.h>
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define SND_LITTLE_ENDIAN
#elif __BYTE_ORDER == __BIG_ENDIAN
#define SND_BIG_ENDIAN
#else
#error "Unsupported endian"
#endif
#endif // __linux__
#ifdef __FreeBSD__
#define SND_LITTLE_ENDIAN // XXX
#endif // __FreeBSD__
#endif // !SND_LITTLE_ENDIAN && !SND_BIG_ENDIAN
// set extra definition
#ifndef SNDCTL_DSP_CHANNELS
#define SNDCTL_DSP_CHANNELS SOUND_PCM_WRITE_CHANNELS
#endif
#include "sound/AudioDev.h"
class AudiodevOss : public Audiodev {
private:
char* m_audiodev;
int m_fd;
public:
AudiodevOss(char* audiodev) : m_audiodev(audiodev) {}
int open();
int close();
int output(char* buf, int size);
int setFormat(int bits, int encoding);
int setChannels(int channels);
int setSamplingRate(int rate);
};
#endif // OSS
#endif // AUDIODEV_OSS_H_
| [
"mytoh@gmail.com"
] | mytoh@gmail.com |
f71fc656cefc3cf0c5c0aa5795c5e951d1c04306 | 9d5516dbaa51d5c14b71cfb75e844eebe7e650a1 | /src/main/cpp/Detection/TargetDetection.cpp | 59381a2378a1fe5188eb7e6a6bc1543c76868ffe | [] | no_license | Machine-Mavericks/FRC-2020-Development-Build | fe01a39a8e1b5453cb61f6ac8e1e9db2b3500a4e | dc2acbdc578cf270a27c55cfdaffffd91e09a740 | refs/heads/master | 2022-12-27T05:02:30.181404 | 2020-10-02T21:40:27 | 2020-10-02T21:40:27 | 232,212,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | // Target detection and estimation functions
// These functions may use various robot systems as required
#include "detection/TargetDetection.h"
// ---------- Target Detection Routines ----------
// Test Data from Lab (Feb 3/18 estimates - requires retest for better accuracy)
// Size (typ x and y) Distance
// 84 42" (1.1m)
// 36 93" (2.4m) (base case)
// 16 168" (4.3m)
TARGET_DATA GetTargetEstimation(void)
{
TARGET_DATA target;
// assume no target detected unless proven otherwise
target.Detected = false;
// determine if camera has acquired a target
bool detected = Robot::m_Limelight.IsTargetPresent();
// get target side lengths
float vert = Robot::m_Limelight.GetVerticalSideLength();
float hor = Robot::m_Limelight.GetHorizontalSideLength();
// get target area of target (in sq pixels)
float area = vert*hor;
if (detected==true && area > MIN_HEX_DETECTION_AREA && vert > MIN_HEX_VERT_SIZE)
{
target.Detected = true;
target.TargetType = 0;
target.Area = area;
target.XAngle = Robot::m_Limelight.GetHorizontalTargetOffsetAngle();
target.ZDistance = (235.0 / vert);
}
// return target data
return target;
}
| [
"44274239+oliviaod9@users.noreply.github.com"
] | 44274239+oliviaod9@users.noreply.github.com |
f435be96d01eeaacc3ac69fab3442affed9a46cf | 641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2 | /third_party/WebKit/Source/core/css/StylePropertySet.h | edf15327815ac3a3577e500375fa7d3a32e60927 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"LGPL-2.0-only",
"LGPL-2.1-only",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft"
] | permissive | massnetwork/mass-browser | 7de0dfc541cbac00ffa7308541394bac1e945b76 | 67526da9358734698c067b7775be491423884339 | refs/heads/master | 2022-12-07T09:01:31.027715 | 2017-01-19T14:29:18 | 2017-01-19T14:29:18 | 73,799,690 | 4 | 4 | BSD-3-Clause | 2022-11-26T11:53:23 | 2016-11-15T09:49:29 | null | UTF-8 | C++ | false | false | 11,110 | h | /*
* (C) 1999-2003 Lars Knoll (knoll@kde.org)
* Copyright (C) 2004, 2005, 2006, 2008, 2012 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef StylePropertySet_h
#define StylePropertySet_h
#include "core/CSSPropertyNames.h"
#include "core/CoreExport.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSProperty.h"
#include "core/css/PropertySetCSSStyleDeclaration.h"
#include "core/css/parser/CSSParserMode.h"
#include "wtf/ListHashSet.h"
#include "wtf/Noncopyable.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
#include <algorithm>
namespace blink {
class CSSStyleDeclaration;
class ImmutableStylePropertySet;
class MutableStylePropertySet;
class StyleSheetContents;
class CORE_EXPORT StylePropertySet
: public GarbageCollectedFinalized<StylePropertySet> {
WTF_MAKE_NONCOPYABLE(StylePropertySet);
friend class PropertyReference;
public:
void finalizeGarbageCollectedObject();
class PropertyReference {
STACK_ALLOCATED();
public:
PropertyReference(const StylePropertySet& propertySet, unsigned index)
: m_propertySet(&propertySet), m_index(index) {}
CSSPropertyID id() const {
return static_cast<CSSPropertyID>(propertyMetadata().m_propertyID);
}
CSSPropertyID shorthandID() const {
return propertyMetadata().shorthandID();
}
bool isImportant() const { return propertyMetadata().m_important; }
bool isInherited() const { return propertyMetadata().m_inherited; }
bool isImplicit() const { return propertyMetadata().m_implicit; }
const CSSValue& value() const { return propertyValue(); }
// FIXME: Remove this.
CSSProperty toCSSProperty() const {
return CSSProperty(propertyMetadata(), propertyValue());
}
const StylePropertyMetadata& propertyMetadata() const;
private:
const CSSValue& propertyValue() const;
Member<const StylePropertySet> m_propertySet;
unsigned m_index;
};
unsigned propertyCount() const;
bool isEmpty() const;
PropertyReference propertyAt(unsigned index) const {
return PropertyReference(*this, index);
}
template <typename T> // CSSPropertyID or AtomicString
int findPropertyIndex(T property) const;
bool hasProperty(CSSPropertyID property) const {
return findPropertyIndex(property) != -1;
}
template <typename T> // CSSPropertyID or AtomicString
const CSSValue* getPropertyCSSValue(T property) const;
template <typename T> // CSSPropertyID or AtomicString
String getPropertyValue(T property) const;
template <typename T> // CSSPropertyID or AtomicString
bool propertyIsImportant(T property) const;
bool shorthandIsImportant(CSSPropertyID) const;
bool shorthandIsImportant(AtomicString customPropertyName) const;
CSSPropertyID getPropertyShorthand(CSSPropertyID) const;
bool isPropertyImplicit(CSSPropertyID) const;
CSSParserMode cssParserMode() const {
return static_cast<CSSParserMode>(m_cssParserMode);
}
MutableStylePropertySet* mutableCopy() const;
ImmutableStylePropertySet* immutableCopyIfNeeded() const;
MutableStylePropertySet* copyPropertiesInSet(
const Vector<CSSPropertyID>&) const;
String asText() const;
bool isMutable() const { return m_isMutable; }
bool hasFailedOrCanceledSubresources() const;
static unsigned averageSizeInBytes();
#ifndef NDEBUG
void showStyle();
#endif
bool propertyMatches(CSSPropertyID, const CSSValue&) const;
DECLARE_TRACE();
DEFINE_INLINE_TRACE_AFTER_DISPATCH() {}
protected:
enum { MaxArraySize = (1 << 28) - 1 };
StylePropertySet(CSSParserMode cssParserMode)
: m_cssParserMode(cssParserMode), m_isMutable(true), m_arraySize(0) {}
StylePropertySet(CSSParserMode cssParserMode, unsigned immutableArraySize)
: m_cssParserMode(cssParserMode),
m_isMutable(false),
m_arraySize(std::min(immutableArraySize, unsigned(MaxArraySize))) {}
unsigned m_cssParserMode : 3;
mutable unsigned m_isMutable : 1;
unsigned m_arraySize : 28;
friend class PropertySetCSSStyleDeclaration;
};
// Used for lazily parsing properties.
class CSSLazyPropertyParser
: public GarbageCollectedFinalized<CSSLazyPropertyParser> {
WTF_MAKE_NONCOPYABLE(CSSLazyPropertyParser);
public:
CSSLazyPropertyParser() {}
virtual ~CSSLazyPropertyParser() {}
virtual StylePropertySet* parseProperties() = 0;
DECLARE_VIRTUAL_TRACE();
};
class CORE_EXPORT ImmutableStylePropertySet : public StylePropertySet {
public:
~ImmutableStylePropertySet();
static ImmutableStylePropertySet* create(const CSSProperty* properties,
unsigned count,
CSSParserMode);
unsigned propertyCount() const { return m_arraySize; }
const Member<const CSSValue>* valueArray() const;
const StylePropertyMetadata* metadataArray() const;
template <typename T> // CSSPropertyID or AtomicString
int findPropertyIndex(T property) const;
DECLARE_TRACE_AFTER_DISPATCH();
void* operator new(std::size_t, void* location) { return location; }
void* m_storage;
private:
ImmutableStylePropertySet(const CSSProperty*, unsigned count, CSSParserMode);
};
inline const Member<const CSSValue>* ImmutableStylePropertySet::valueArray()
const {
return reinterpret_cast<const Member<const CSSValue>*>(
const_cast<const void**>(&(this->m_storage)));
}
inline const StylePropertyMetadata* ImmutableStylePropertySet::metadataArray()
const {
return reinterpret_cast<const StylePropertyMetadata*>(
&reinterpret_cast<const char*>(
&(this->m_storage))[m_arraySize * sizeof(Member<CSSValue>)]);
}
DEFINE_TYPE_CASTS(ImmutableStylePropertySet,
StylePropertySet,
set,
!set->isMutable(),
!set.isMutable());
class CORE_EXPORT MutableStylePropertySet : public StylePropertySet {
public:
~MutableStylePropertySet() {}
static MutableStylePropertySet* create(CSSParserMode);
static MutableStylePropertySet* create(const CSSProperty* properties,
unsigned count);
unsigned propertyCount() const { return m_propertyVector.size(); }
// Returns whether this style set was changed.
bool addParsedProperties(const HeapVector<CSSProperty, 256>&);
bool addRespectingCascade(const CSSProperty&);
struct SetResult {
bool didParse;
bool didChange;
};
// These expand shorthand properties into multiple properties.
SetResult setProperty(CSSPropertyID unresolvedProperty,
const String& value,
bool important = false,
StyleSheetContents* contextStyleSheet = 0);
SetResult setProperty(const AtomicString& customPropertyName,
const String& value,
bool important,
StyleSheetContents* contextStyleSheet,
bool isAnimationTainted);
void setProperty(CSSPropertyID, const CSSValue&, bool important = false);
// These do not. FIXME: This is too messy, we can do better.
bool setProperty(CSSPropertyID,
CSSValueID identifier,
bool important = false);
bool setProperty(const CSSProperty&, CSSProperty* slot = 0);
template <typename T> // CSSPropertyID or AtomicString
bool removeProperty(T property, String* returnText = 0);
bool removePropertiesInSet(const CSSPropertyID* set, unsigned length);
void removeEquivalentProperties(const StylePropertySet*);
void removeEquivalentProperties(const CSSStyleDeclaration*);
void mergeAndOverrideOnConflict(const StylePropertySet*);
void clear();
void parseDeclarationList(const String& styleDeclaration,
StyleSheetContents* contextStyleSheet);
CSSStyleDeclaration* ensureCSSStyleDeclaration();
template <typename T> // CSSPropertyID or AtomicString
int findPropertyIndex(T property) const;
DECLARE_TRACE_AFTER_DISPATCH();
private:
explicit MutableStylePropertySet(CSSParserMode);
explicit MutableStylePropertySet(const StylePropertySet&);
MutableStylePropertySet(const CSSProperty* properties, unsigned count);
bool removePropertyAtIndex(int, String* returnText);
bool removeShorthandProperty(CSSPropertyID);
bool removeShorthandProperty(const AtomicString& customPropertyName) {
return false;
}
CSSProperty* findCSSPropertyWithID(
CSSPropertyID,
const AtomicString& customPropertyName = nullAtom);
Member<PropertySetCSSStyleDeclaration> m_cssomWrapper;
friend class StylePropertySet;
HeapVector<CSSProperty, 4> m_propertyVector;
};
DEFINE_TYPE_CASTS(MutableStylePropertySet,
StylePropertySet,
set,
set->isMutable(),
set.isMutable());
inline MutableStylePropertySet* toMutableStylePropertySet(
const Persistent<StylePropertySet>& set) {
return toMutableStylePropertySet(set.get());
}
inline MutableStylePropertySet* toMutableStylePropertySet(
const Member<StylePropertySet>& set) {
return toMutableStylePropertySet(set.get());
}
inline const StylePropertyMetadata&
StylePropertySet::PropertyReference::propertyMetadata() const {
if (m_propertySet->isMutable())
return toMutableStylePropertySet(*m_propertySet)
.m_propertyVector.at(m_index)
.metadata();
return toImmutableStylePropertySet(*m_propertySet).metadataArray()[m_index];
}
inline const CSSValue& StylePropertySet::PropertyReference::propertyValue()
const {
if (m_propertySet->isMutable())
return *toMutableStylePropertySet(*m_propertySet)
.m_propertyVector.at(m_index)
.value();
return *toImmutableStylePropertySet(*m_propertySet).valueArray()[m_index];
}
inline unsigned StylePropertySet::propertyCount() const {
if (m_isMutable)
return toMutableStylePropertySet(this)->m_propertyVector.size();
return m_arraySize;
}
inline bool StylePropertySet::isEmpty() const {
return !propertyCount();
}
template <typename T>
inline int StylePropertySet::findPropertyIndex(T property) const {
if (m_isMutable)
return toMutableStylePropertySet(this)->findPropertyIndex(property);
return toImmutableStylePropertySet(this)->findPropertyIndex(property);
}
} // namespace blink
#endif // StylePropertySet_h
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
651f82ffe40b57767e3decdacfa09a107693210b | d19d5f5f2f7e44884932aa087c63a549f53f0907 | /SwingEngine/SEGeometricTools/Intersection/SEIntrSegment3Sphere3.h | 7032b6fd15ac539f7b6b6a7b3fbc8203d0536c74 | [] | no_license | jazzboysc/SwingEngine2 | d26c60f4cbf89f0d7207e5152cae69677a4d7b18 | d7dbd09a5e7748def0bd3fa6a547b1c734529f61 | refs/heads/master | 2021-03-27T11:05:20.543758 | 2018-07-13T09:42:22 | 2018-07-13T09:42:22 | 44,491,987 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,176 | h | // Swing Engine Version 2 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 and 5 open-source game engine. The author of Swing Engine
// learned a lot from Eberly's experience of architecture and algorithm.
// Several subsystems are totally new, and others are reorganized or
// reimplimented based on Wild Magic's subsystems.
// Copyright (c) 2007-2011
//
// David Eberly's permission:
// Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
#ifndef Swing_IntrSegment3Sphere3_H
#define Swing_IntrSegment3Sphere3_H
#include "SEGeometricToolsLIB.h"
#include "SEIntersector.h"
#include "SESegment3.h"
#include "SESphere3.h"
namespace Swing
{
//----------------------------------------------------------------------------
// Description:
// Date:20081220
//----------------------------------------------------------------------------
class SE_GEOMETRICTOOLS_API SEIntrSegment3Sphere3f : public SEIntersector<float,
SEVector3f>
{
public:
SEIntrSegment3Sphere3f(const SESegment3f& rSegment, const SESphere3f&
rSphere);
// 对象访问.
const SESegment3f& GetSegment(void) const;
const SESphere3f& GetSphere(void) const;
// test-intersection查询.
virtual bool Test(void);
// find-intersection查询.
virtual bool Find(void);
int GetCount(void) const;
const SEVector3f& GetPoint(int i) const;
float GetSegmentT(int i) const;
// dynamic test-intersection查询.
virtual bool Test(float fTMax, const SEVector3f& rVelocity0,
const SEVector3f& rVelocity1);
// dynamic find-intersection查询.
virtual bool Find(float fTMax, const SEVector3f& rVelocity0,
const SEVector3f& rVelocity1);
float ZeroThreshold; // default = SEMath<float>::ZERO_TOLERANCE
private:
// 待检查对象.
const SESegment3f* m_pSegment;
const SESphere3f* m_pSphere;
// 相交集相关信息.
int m_iCount;
SEVector3f m_aPoint[2];
float m_afSegmentT[2];
};
}
#endif
| [
"S515380c"
] | S515380c |
56d9bb61a689efdf7bc3dff8329052ee9fb07b2c | 00f5829156d5f6ca7af2a97503ac960a70520c40 | /first_implementation/pch.h | 0dbb6e0839ab34da77545d78253885db58b634db | [
"MIT"
] | permissive | thiago-rezende/distributed-systems-assignment | 7524e36f849fa6f4b1d03cbea95c17907a0c9296 | 3d54444844704e04365309193750cec08d0aa02f | refs/heads/master | 2023-02-12T01:49:56.255576 | 2021-01-09T01:29:07 | 2021-01-09T01:29:07 | 327,729,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 472 | h | /**
* @file pch.h
* @author Thiago Rezende (thiago-rezende.github.io)
* @brief Pre-Compiled Header
* @version 0.1
* @date 2020-09-26
*
* @copyright Copyright (c) 2020 Thiago Rezende
*
*/
#pragma once
#include <deque>
#include <mutex>
#include <vector>
#include <chrono>
#include <string>
#include <random>
#include <thread>
#include <sstream>
#include <iostream>
#include <functional>
#include <condition_variable>
#include <first_implementation/core/logger.h>
| [
"bitrateti@gmail.com"
] | bitrateti@gmail.com |
22e63351453fba6d6d9e6ed76bd1d606e17590fd | 5bff290beff08d610cee3079d233ae12959159d1 | /MPI/task5/task5/task5.cpp | 795e9ec6f990032f02ebd7f94fad756b5553345a | [] | no_license | dman1994/6-semester | 7a2c94586f3ca3bb30c8032a1ba7f700a3afc4da | 20d0a5536dda9cc8a1a269f4160ebc453aa8d7a6 | refs/heads/master | 2020-12-11T06:14:36.656485 | 2015-06-19T20:22:13 | 2015-06-19T20:22:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,333 | cpp | #include "stdafx.h"
#include <mpi.h>
#include <random>
#include <time.h>
#include <iostream>
#include <string>
#pragma warning(disable : 4996)
using namespace std;
int sum(int *a,int *b, int len)
{
int sum = 0;
for (int i =0; i<len; i++)
sum+=a[i]*b[i];
return sum;
}
int _tmain(int argc, char* argv[])
{
const int DIMENSION = 1;
int i,j,size,rank,rank_pred,rank_next,max,current;
int dims[DIMENSION],periods[DIMENSION],new_coords[DIMENSION];
MPI_Status status;
MPI_Comm new_comm;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
int* A = new int[size];
int* B = new int[size];
for(i=0; i<DIMENSION; i++)
{
dims[i]=0;
periods[i]=1;
}
MPI_Dims_create(size, DIMENSION, dims);
MPI_Cart_create (MPI_COMM_WORLD, DIMENSION, dims, periods, 0, &new_comm);
MPI_Cart_coords (new_comm, rank, DIMENSION, new_coords);
MPI_Cart_shift(new_comm, 0, -1, &rank_pred, &rank_next);
char str[300]="A[";
char buf[5];
itoa(rank,buf,10);
strncat(str,buf,strlen(buf));
strncat(str,"] = [",5);
srand(time(NULL)+rank);
for (i=0;i<size;i++)
{
A[i]=rand()%100;
itoa(A[i],buf,10);
strncat(str,buf,strlen(buf));
strncat(str,", ",2);
}
strncat(str,"]\nB[",5);
itoa(rank,buf,10);
strncat(str,buf,strlen(buf));
strncat(str,"] = [",5);
for (i=0;i<size;i++)
{
B[i]=rand()%100;
itoa(B[i],buf,10);
strncat(str,buf,strlen(buf));
strncat(str," ",2);
}
strncat(str,"]\nResults:\n sum(A[",22);
itoa(rank,buf,10);
strncat(str,buf,strlen(buf));
strncat(str,",k]*B[k,0]) = ",14);
current=sum(A,B,size);
max=current;
itoa(current,buf,10);
strncat(str,buf,strlen(buf));
strncat(str,"\n",2);
for (j=1;j<size;j++)
{
MPI_Sendrecv_replace(B,size,MPI_INT,rank_next,2,rank_pred,2,new_comm,&status);
current=sum(A,B,size);
if (current>max)
max=current;
strncat(str," sum(A[",9);
itoa(rank,buf,10);
strncat(str,buf,strlen(buf));
strncat(str,",k]*B[k,",8);
itoa(j,buf,10);
strncat(str,buf,strlen(buf));
strncat(str,"]) = ",5);
itoa(current,buf,10);
strncat(str,buf,strlen(buf));
strncat(str,"\n",2);
}
strncat(str," Maximum = ",11);
itoa(max,buf,10);
strncat(str,buf,strlen(buf));
strncat(str,"\n",2);
printf("%s\n",str);
MPI_Comm_free(&new_comm) ;
free(A);
free(B);
MPI_Finalize();
return 0;
} | [
"chevron19941@gmail.com"
] | chevron19941@gmail.com |
256f945f789a0d881e6f1db1444c1e23e530cd48 | ffac4c8e2734ee1cf7c8fda52325c8da50bc07de | /stdList.cpp | 4d1220c72d12ab9bbdced77d771c4d8463344220 | [] | no_license | alinavoronko/G9 | 7471406ca7598663e62f441573f1df7d1216dc9c | fa2b626911f1180318e6a50c77db4bf711b238e6 | refs/heads/master | 2023-03-17T12:35:24.608732 | 2021-03-23T08:03:14 | 2021-03-23T08:03:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,053 | cpp | /*d*/
#include<iostream>
#include<fstream>
#include<list>
using namespace std;
void print(const list<int>& a) {
for (auto& i : a) {
cout << i << " ";
}
cout << endl;
}
/*/*C1[5]. Funkcija deleteAfterLastOdd, kas izdzēš no saraksta skaitli, kas novietots aiz pirmā no labās esošā nepāra skaitļa.
Piemēram, {2,3,7,4,5}→{2,3,7,4,5}, {2,3,7,4,6}→{2,3,7,6}
*/
void deleteAfterLastOdd(list<int>& a) {
auto k = a.begin();
bool irOdd = 0;
auto lastOdd = a.begin();
++k;
for (auto i = a.begin(); k != a.end(); i++, k++) {
if (*i % 2 == 1) {
irOdd = 1;
lastOdd = i;
}
}
if (irOdd) {
++lastOdd;
a.erase(lastOdd);
}
}
/*
C2[8]. Funkcija deleteLastOdd, kas izdzēš no saraksta pirmo no labās esošo nepāra skaitli. Piemēram, {2,3,7,4,5}→{2,3,7,4}, {2,3,7,4,6}→{2,3,4,6}, {2,4,6,8}→{2,4,6,8}, {1,2,4,6,8}→{2,4,6,8}
*/
void deleteLastOdd(list<int>& a) {
auto k = a.begin();
bool irOdd = 0;
auto lastOdd = a.begin();
for (auto i = a.begin(); i != a.end(); i++) {
if (*i % 2 == 1) {
irOdd = 1;
lastOdd = i;
}
}
if (irOdd) {
a.erase(lastOdd);
}
}
/*C1[5].Funkcija incOddBeforeEven, kas sarakstā palielina par 1 nepāra skaitļus, kas atrodas pirms pāra skaitļa.Piemēram, { 2,3,7,4,5 }→{ 2,3,8,4,5 }*/
void incOddBeforeEven(list<int>& a) {
auto k = a.begin();
++k;
for (auto i = a.begin(); k != a.end(); i++, k++) {
if (*i % 2 == 1 and *k % 2 == 0) {
(*i)++;
}
}
}
/*C2[8].Funkcija eliminateNonAscending, kas, ejot no kreisās uz labo, izmet no saraksta visus elementus, kas ir pretrunā augošai sakārtotai secībai(tādējādi beigās iegūstot sakārtotu virkni).
Piemēram, { 2,3,8,4,5,9,3 }→{ 2,3,8,9 }*/
void eliminateNonAscending(list<int>& mylist) {
auto it = mylist.begin();
int max = *it;
it++;
for (; it != mylist.end(); it++) {
if (*it <= max) {
it = mylist.erase(it);
it--;
}
else {
max = *it;
}
}
}
/*void eliminateNonAscending(list<int>& a) {
auto k = a.begin();
++k;
for (auto i = a.begin(); k != a.end(); i++, k++) {
if (*i >= *k ) {
a.erase(k);
if (i != --a.end()) {
k = i;
k++;
}
else break;
}
}
}
*/
void deleteFirstEvenBeforeOdd(list<int>& a) {
auto k = a.begin();
++k;
for (auto i = a.begin(); k != a.end(); i++, k++) {
if (*i % 2 == 0 and *k % 2 != 0) {
a.erase(i);
return;
}
}
}
int main() {
//list<int> a = { 2,3,7,4,6 };
//list<int> a = { 2, 3, 7, 4, 5 };
//list<int> a = { 2,3,8,4,5,9,3 };
list<int> a = { 2,3,5,3,2,1};
print(a);
//deleteAfterLastOdd(a);
//deleteLastOdd(a);
//incOddBeforeEven(a);
eliminateNonAscending(a);
print(a);
}
| [
"noreply@github.com"
] | noreply@github.com |
4e2696f47fd6b6dff85b01225e640ccb22285ceb | 3438e8c139a5833836a91140af412311aebf9e86 | /cc/blink/web_content_layer_impl.h | 46b087ae7cfacda31924fbad40aa0ebb27eb81fa | [
"BSD-3-Clause"
] | permissive | Exstream-OpenSource/Chromium | 345b4336b2fbc1d5609ac5a67dbf361812b84f54 | 718ca933938a85c6d5548c5fad97ea7ca1128751 | refs/heads/master | 2022-12-21T20:07:40.786370 | 2016-10-18T04:53:43 | 2016-10-18T04:53:43 | 71,210,435 | 0 | 2 | BSD-3-Clause | 2022-12-18T12:14:22 | 2016-10-18T04:58:13 | null | UTF-8 | C++ | false | false | 1,483 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CC_BLINK_WEB_CONTENT_LAYER_IMPL_H_
#define CC_BLINK_WEB_CONTENT_LAYER_IMPL_H_
#include <stddef.h>
#include <memory>
#include "base/macros.h"
#include "cc/blink/cc_blink_export.h"
#include "cc/blink/web_layer_impl.h"
#include "cc/layers/content_layer_client.h"
#include "third_party/WebKit/public/platform/WebContentLayer.h"
namespace cc {
class IntRect;
class FloatRect;
}
namespace blink {
class WebContentLayerClient;
}
namespace cc_blink {
class WebContentLayerImpl : public blink::WebContentLayer,
public cc::ContentLayerClient {
public:
CC_BLINK_EXPORT explicit WebContentLayerImpl(blink::WebContentLayerClient*);
~WebContentLayerImpl() override;
// WebContentLayer implementation.
blink::WebLayer* layer() override;
protected:
// ContentLayerClient implementation.
gfx::Rect PaintableRegion() override;
scoped_refptr<cc::DisplayItemList> PaintContentsToDisplayList(
PaintingControlSetting painting_control) override;
bool FillsBoundsCompletely() const override;
size_t GetApproximateUnsharedMemoryUsage() const override;
std::unique_ptr<WebLayerImpl> layer_;
blink::WebContentLayerClient* client_;
private:
DISALLOW_COPY_AND_ASSIGN(WebContentLayerImpl);
};
} // namespace cc_blink
#endif // CC_BLINK_WEB_CONTENT_LAYER_IMPL_H_
| [
"support@opentext.com"
] | support@opentext.com |
4be82a93e0d091599537b1285de4b7c74e511de9 | 36c200fc4f2b0fc7c143446be839129c723d87ca | /src/partition/MultiBisector.hpp | 90643dd9d13ad7b1a7c03c67d391da21a30d6451 | [
"MIT"
] | permissive | dlasalle/poros | 8b3ac0998222e87fc5a51097b6fcc18f0e566d3c | af25fd353c4a81ad055c06303997a7bc9b00fd33 | refs/heads/master | 2023-03-11T05:19:52.552744 | 2023-02-25T19:46:14 | 2023-02-25T19:46:14 | 161,862,683 | 2 | 0 | MIT | 2023-02-25T19:46:16 | 2018-12-15T02:38:45 | C++ | UTF-8 | C++ | false | false | 2,442 | hpp | /**
* @file MultiBisector.hpp
* @brief The MultiBisector class.
* @author Dominique LaSalle <dominique@solidlake.com>
* Copyright 2018
* @version 1
* @date 2018-07-20
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef POROS_SRC_MULTIBISECTOR_HPP
#define POROS_SRC_MULTIBISECTOR_HPP
#include "IBisector.hpp"
#include <memory>
namespace poros
{
class MultiBisector : public IBisector
{
public:
/**
* @brief Create a new multibiesctor object.
*
* @param numBisections The number of bisections to make.
* @param bisector The bisector to use.
*/
MultiBisector(
int numBisections,
std::unique_ptr<IBisector> bisector);
/**
* @brief Deleted copy constructor.
*
* @param lhs The bisector to copy.
*/
MultiBisector(
MultiBisector& lhs) = delete;
/**
* @brief Deleted copy assignment operator.
*
* @param lhs The bisector to assign.
*
* @return This bisector.
*/
MultiBisector operator=(
MultiBisector& lhs) = delete;
/**
* @brief Virtual destructor.
*/
virtual ~MultiBisector();
/**
* @brief Create a new bisection.
*
* @param target The target bisection.
* @param graph The graph.
*
* @return The best bisection created.
*/
virtual Partitioning execute(
TargetPartitioning const * target,
Graph const * graph) override;
private:
int m_numBisections;
std::unique_ptr<IBisector> m_bisector;
};
}
#endif
| [
"dominique@solidlake.com"
] | dominique@solidlake.com |
f4cd8607e601d16b24cad4a5f4402054db5bc34e | e85165e254a7c22586953529e2a2cf078c9d1670 | /stream/stream.cpp | 1e935a1a00d69cf431ec118b6f51c1ebad114830 | [
"LicenseRef-scancode-stream-benchmark"
] | permissive | telmin/YAMADABenchmarkSuite | 52284f9cfbe6d07e6cbe87b278dedb590b1757c3 | cd789a8f601345012ba049050846e9c10b6bba59 | refs/heads/master | 2021-01-20T06:16:54.414891 | 2020-12-01T04:13:45 | 2020-12-01T04:13:45 | 83,872,041 | 5 | 2 | null | 2020-12-01T04:13:46 | 2017-03-04T06:40:05 | C++ | UTF-8 | C++ | false | false | 11,879 | cpp | /*-----------------------------------------------------------------------*/
/* Program: STREAM */
/* Revision: $Id: stream.c,v 5.10 2013/01/17 16:01:06 mccalpin Exp mccalpin $ */
/* Original code developed by John D. McCalpin */
/* Programmers: John D. McCalpin */
/* Joe R. Zagar */
/* */
/* This program measures memory transfer rates in MB/s for simple */
/* computational kernels coded in C. */
/*-----------------------------------------------------------------------*/
/* Copyright 1991-2013: John D. McCalpin */
/*-----------------------------------------------------------------------*/
/* License: */
/* 1. You are free to use this program and/or to redistribute */
/* this program. */
/* 2. You are free to modify this program for your own use, */
/* including commercial use, subject to the publication */
/* restrictions in item 3. */
/* 3. You are free to publish results obtained from running this */
/* program, or from works that you derive from this program, */
/* with the following limitations: */
/* 3a. In order to be referred to as "STREAM benchmark results", */
/* published results must be in conformance to the STREAM */
/* Run Rules, (briefly reviewed below) published at */
/* http://www.cs.virginia.edu/stream/ref.html */
/* and incorporated herein by reference. */
/* As the copyright holder, John McCalpin retains the */
/* right to determine conformity with the Run Rules. */
/* 3b. Results based on modified source code or on runs not in */
/* accordance with the STREAM Run Rules must be clearly */
/* labelled whenever they are published. Examples of */
/* proper labelling include: */
/* "tuned STREAM benchmark results" */
/* "based on a variant of the STREAM benchmark code" */
/* Other comparable, clear, and reasonable labelling is */
/* acceptable. */
/* 3c. Submission of results to the STREAM benchmark web site */
/* is encouraged, but not required. */
/* 4. Use of this program or creation of derived works based on this */
/* program constitutes acceptance of these licensing restrictions. */
/* 5. Absolutely no warranty is expressed or implied. */
/*-----------------------------------------------------------------------*/
#include <iostream>
#include <limits>
#include <string>
#include <algorithm>
#include <vector>
#include <chrono>
#include <iomanip>
#include <cstdio>
#include "parsearg.hpp"
static void PrintMessages(size_t STREAM_ARRAY_SIZE, size_t NTIMES, size_t OFFSET, size_t SizeOfStream)
{
const std::string HLINE = "-------------------------------------------------------------";
std::cout << HLINE << std::endl;
std::cout << "STREAM version $Revision : 5.10 $" << std::endl;
std::cout << HLINE << std::endl;
std::cout << "This system uses " << SizeOfStream << " bytes per array element." << std::endl;
std::cout << HLINE << std::endl;
std::cout << "Array Size = " << STREAM_ARRAY_SIZE << " (elements), Offset = " << OFFSET << " (elements) " << std::endl;
std::cout << "Memory per array = " << SizeOfStream * ((double)STREAM_ARRAY_SIZE / 1024.0 / 1024.0) << " MiB (= " <<
SizeOfStream * ((double)STREAM_ARRAY_SIZE / 1024.0 / 1024.0 / 1024.0) << " GiB)." << std::endl;
std::cout << "Total Memory required = " << (3.0 * SizeOfStream) * ((double)STREAM_ARRAY_SIZE / 1024.0 / 1024.0) << " MiB (= " <<
(3.0 * SizeOfStream) * ((double)STREAM_ARRAY_SIZE / 1024.0 / 1024.0 / 1024.0) << " GiB). " << std::endl;
std::cout << "Each kernel will be executed " << NTIMES << " times." << std::endl;
}
template <typename T>
static double Copy(std::vector<T>& c, const std::vector<T>& a)
{
const auto SIZE = c.size();
auto start = std::chrono::system_clock::now();
#pragma omp parallel for
for(auto j = decltype(SIZE)(0); j < SIZE; ++j) {
c[j] = a[j];
}
auto end = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> dur = (end - start);
return dur.count() / 1000.0;
}
template <typename T>
static double Scale(std::vector<T>& b, const std::vector<T>& c, T scalar)
{
const auto SIZE = b.size();
auto start = std::chrono::system_clock::now();
#pragma omp parallel for
for(auto j = decltype(SIZE)(0); j < SIZE; ++j) {
b[j] = scalar * c[j];
}
auto end = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> dur = (end - start);
return dur.count() / 1000.0;
}
template <typename T>
static double Add(std::vector<T>& c, const std::vector<T>& a, const std::vector<T>& b)
{
const auto SIZE = c.size();
auto start = std::chrono::system_clock::now();
#pragma omp parallel for
for(auto j = decltype(SIZE)(0); j < SIZE; ++j) {
c[j] = a[j] + b[j];
}
auto end = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> dur = (end - start);
return dur.count() / 1000.0;
}
template <typename T>
static double Triad(std::vector<T>& a, const std::vector<T>& b, const std::vector<T>& c, T scalar)
{
const auto SIZE = a.size();
auto start = std::chrono::system_clock::now();
#pragma omp parallel for
for(auto j = decltype(SIZE)(0); j < SIZE; ++j) {
a[j] = b[j] + scalar * c[j];
}
auto end = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> dur = (end - start);
return dur.count() / 1000.0;
}
template <typename STREAM_TYPE>
static void ShowSummary(const std::vector<std::vector<double>>& times, size_t STREAM_ARRAY_SIZE, size_t NTIMES)
{
// Summary
std::vector<double> avgtime(4, 0);
std::vector<double> mintime(4, std::numeric_limits<double>::max());
std::vector<double> maxtime(4, std::numeric_limits<double>::min());
for(auto k = decltype(NTIMES)(1); k < NTIMES; ++k) {
const auto& cur_time = times[k];
for(size_t j = 0; j < 4; ++j) {
avgtime[j] += cur_time[j];
mintime[j] = std::min(mintime[j], cur_time[j]);
maxtime[j] = std::max(maxtime[j], cur_time[j]);
}
}
const std::string label[4] = {"Copy: ", "Scale: ",
"Add: ", "Triad: "};
const double bytes[4] = { 2.0 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
2.0 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
3.0 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
3.0 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE};
// 諦めた
printf("Function Best Rate MB/s Avg time Min time Max time\n");
for(size_t j = 0; j < 4; ++j) {
auto avg = avgtime[j] / static_cast<double>(NTIMES - 1);
printf("%s%12.1f %11.6f %11.6f %11.6f\n", label[j].c_str(),
1.0e-6 * bytes[j] / mintime[j],
avg, mintime[j], maxtime[j]);
}
const std::string HLINE = "-------------------------------------------------------------";
std::cout << HLINE << std::endl;
}
template <typename STREAM_TYPE>
void checkSTREAMresults (const std::vector<STREAM_TYPE>& a, const std::vector<STREAM_TYPE>& b, const std::vector<STREAM_TYPE>& c,
size_t STREAM_ARRAY_SIZE, size_t NTIMES)
{
STREAM_TYPE aj,bj,cj,scalar;
STREAM_TYPE aSumErr,bSumErr,cSumErr;
STREAM_TYPE aAvgErr,bAvgErr,cAvgErr;
double epsilon;
ssize_t j;
int k,ierr,err;
/* reproduce initialization */
aj = 1.0;
bj = 2.0;
cj = 0.0;
/* a[] is modified during timing check */
aj = 2.0E0 * aj;
/* now execute timing loop */
scalar = 3.0;
for (k=0; k<NTIMES; k++)
{
cj = aj;
bj = scalar*cj;
cj = aj+bj;
aj = bj+scalar*cj;
}
/* accumulate deltas between observed and expected results */
aSumErr = 0.0;
bSumErr = 0.0;
cSumErr = 0.0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
aSumErr += abs(a[j] - aj);
bSumErr += abs(b[j] - bj);
cSumErr += abs(c[j] - cj);
// if (j == 417) printf("Index 417: c[j]: %f, cj: %f\n",c[j],cj); // MCCALPIN
}
aAvgErr = aSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
bAvgErr = bSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
cAvgErr = cSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
if (sizeof(STREAM_TYPE) == 4) {
epsilon = 1.e-6;
}
else if (sizeof(STREAM_TYPE) == 8) {
epsilon = 1.e-13;
}
else {
printf("WEIRD: sizeof(STREAM_TYPE) = %lu\n",sizeof(STREAM_TYPE));
epsilon = 1.e-6;
}
err = 0;
if (abs(aAvgErr/aj) > epsilon) {
err++;
printf ("Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n",epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",aj,aAvgErr,abs(aAvgErr)/aj);
ierr = 0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
if (abs(a[j]/aj-1.0) > epsilon) {
ierr++;
#ifdef VERBOSE
if (ierr < 10) {
printf(" array a: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j,aj,a[j],abs((aj-a[j])/aAvgErr));
}
#endif
}
}
printf(" For array a[], %d errors were found.\n",ierr);
}
if (abs(bAvgErr/bj) > epsilon) {
err++;
printf ("Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n",epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",bj,bAvgErr,abs(bAvgErr)/bj);
printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon);
ierr = 0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
if (abs(b[j]/bj-1.0) > epsilon) {
ierr++;
#ifdef VERBOSE
if (ierr < 10) {
printf(" array b: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j,bj,b[j],abs((bj-b[j])/bAvgErr));
}
#endif
}
}
printf(" For array b[], %d errors were found.\n",ierr);
}
if (abs(cAvgErr/cj) > epsilon) {
err++;
printf ("Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n",epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",cj,cAvgErr,abs(cAvgErr)/cj);
printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon);
ierr = 0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
if (abs(c[j]/cj-1.0) > epsilon) {
ierr++;
#ifdef VERBOSE
if (ierr < 10) {
printf(" array c: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j,cj,c[j],abs((cj-c[j])/cAvgErr));
}
#endif
}
}
printf(" For array c[], %d errors were found.\n",ierr);
}
if (err == 0) {
printf ("Solution Validates: avg error less than %e on all three arrays\n",epsilon);
}
#ifdef VERBOSE
printf ("Results Validation Verbose Results: \n");
printf (" Expected a(1), b(1), c(1): %f %f %f \n",aj,bj,cj);
printf (" Observed a(1), b(1), c(1): %f %f %f \n",a[1],b[1],c[1]);
printf (" Rel Errors on a, b, c: %e %e %e \n",abs(aAvgErr/aj),abs(bAvgErr/bj),abs(cAvgErr/cj));
#endif
}
int main(int argc, char** argv)
{
ParseArg parser(argc, argv);
const size_t STREAM_ARRAY_SIZE = parser.getArraySize();
const size_t NTIMES = parser.getTimes();
constexpr size_t OFFSET = 0;
using STREAM_TYPE = double;
auto a = std::vector<STREAM_TYPE>(STREAM_ARRAY_SIZE + OFFSET);
auto b = std::vector<STREAM_TYPE>(STREAM_ARRAY_SIZE + OFFSET);
auto c = std::vector<STREAM_TYPE>(STREAM_ARRAY_SIZE + OFFSET);
PrintMessages(STREAM_ARRAY_SIZE, NTIMES, OFFSET, sizeof(STREAM_TYPE));
// initial
std::fill(a.begin(), a.end(), 1.0);
std::fill(b.begin(), b.end(), 2.0);
std::fill(c.begin(), c.end(), 0.0);
for(auto& ia : a) {
ia *= 2.0E0;
}
std::vector<std::vector<double>> times(NTIMES);
for(auto& it : times) {
it.resize(4);
}
STREAM_TYPE scalar = 3.0;
for(auto k = decltype(NTIMES)(0); k < NTIMES; ++k) {
// copy
times[k][0] = Copy(c, a);
// scale
times[k][1] = Scale(b, c, scalar);
// add
times[k][2] = Add(c, a, b);
// triad
times[k][3] = Triad(a, b, c, scalar);
}
ShowSummary<STREAM_TYPE>(times, STREAM_ARRAY_SIZE, NTIMES);
checkSTREAMresults<STREAM_TYPE>(a, b, c, STREAM_ARRAY_SIZE, NTIMES);
return 0;
}
| [
"godo.cell@gmail.com"
] | godo.cell@gmail.com |
aa8dbd2df2644dad2f768bc8cd218b540612180a | c95ae6fdeade88fc665f961e4d121642b75d05c4 | /src/gen-cpp/DBService.cpp | 33abdaa12a4eb021a098de77d3738d94a75a5a8b | [
"MIT"
] | permissive | freedomofkeima/TippyDB | 0cf54cbc4e9a1a193e4bb48e52b9f8234d18c50f | 6eb3d888af8b589b33ccfb61b5e8488b58f5eda1 | refs/heads/master | 2021-01-01T06:17:09.627813 | 2015-05-20T05:18:17 | 2015-05-20T05:18:17 | 31,669,376 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 128,442 | cpp | /**
* Autogenerated by Thrift Compiler (0.9.2)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#include "DBService.h"
namespace dbservice {
DBService_ping_args::~DBService_ping_args() throw() {
}
uint32_t DBService_ping_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
xfer += iprot->skip(ftype);
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_ping_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_ping_args");
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_ping_pargs::~DBService_ping_pargs() throw() {
}
uint32_t DBService_ping_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_ping_pargs");
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_ping_result::~DBService_ping_result() throw() {
}
uint32_t DBService_ping_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
xfer += iprot->skip(ftype);
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_ping_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_ping_result");
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_ping_presult::~DBService_ping_presult() throw() {
}
uint32_t DBService_ping_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
xfer += iprot->skip(ftype);
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_putData_args::~DBService_putData_args() throw() {
}
uint32_t DBService_putData_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->value);
this->__isset.value = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_putData_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_putData_args");
xfer += oprot->writeFieldBegin("value", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString(this->value);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_putData_pargs::~DBService_putData_pargs() throw() {
}
uint32_t DBService_putData_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_putData_pargs");
xfer += oprot->writeFieldBegin("value", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString((*(this->value)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_putData_result::~DBService_putData_result() throw() {
}
uint32_t DBService_putData_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_putData_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_putData_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_STRING, 0);
xfer += oprot->writeString(this->success);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_putData_presult::~DBService_putData_presult() throw() {
}
uint32_t DBService_putData_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_putDataForce_args::~DBService_putDataForce_args() throw() {
}
uint32_t DBService_putDataForce_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->value);
this->__isset.value = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_region);
this->__isset.remote_region = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_node);
this->__isset.remote_node = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_putDataForce_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_putDataForce_args");
xfer += oprot->writeFieldBegin("value", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString(this->value);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32(this->remote_region);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 3);
xfer += oprot->writeI32(this->remote_node);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_putDataForce_pargs::~DBService_putDataForce_pargs() throw() {
}
uint32_t DBService_putDataForce_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_putDataForce_pargs");
xfer += oprot->writeFieldBegin("value", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString((*(this->value)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32((*(this->remote_region)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 3);
xfer += oprot->writeI32((*(this->remote_node)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_putDataForce_result::~DBService_putDataForce_result() throw() {
}
uint32_t DBService_putDataForce_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_putDataForce_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_putDataForce_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_STRING, 0);
xfer += oprot->writeString(this->success);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_putDataForce_presult::~DBService_putDataForce_presult() throw() {
}
uint32_t DBService_putDataForce_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_updateData_args::~DBService_updateData_args() throw() {
}
uint32_t DBService_updateData_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->d.read(iprot);
this->__isset.d = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_updateData_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_updateData_args");
xfer += oprot->writeFieldBegin("d", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->d.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_updateData_pargs::~DBService_updateData_pargs() throw() {
}
uint32_t DBService_updateData_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_updateData_pargs");
xfer += oprot->writeFieldBegin("d", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += (*(this->d)).write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_updateData_result::~DBService_updateData_result() throw() {
}
uint32_t DBService_updateData_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_updateData_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_updateData_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_BOOL, 0);
xfer += oprot->writeBool(this->success);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_updateData_presult::~DBService_updateData_presult() throw() {
}
uint32_t DBService_updateData_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_updateSecondaryData_args::~DBService_updateSecondaryData_args() throw() {
}
uint32_t DBService_updateSecondaryData_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->d.read(iprot);
this->__isset.d = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_region);
this->__isset.remote_region = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_node);
this->__isset.remote_node = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_updateSecondaryData_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_updateSecondaryData_args");
xfer += oprot->writeFieldBegin("d", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->d.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32(this->remote_region);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 3);
xfer += oprot->writeI32(this->remote_node);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_updateSecondaryData_pargs::~DBService_updateSecondaryData_pargs() throw() {
}
uint32_t DBService_updateSecondaryData_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_updateSecondaryData_pargs");
xfer += oprot->writeFieldBegin("d", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += (*(this->d)).write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32((*(this->remote_region)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 3);
xfer += oprot->writeI32((*(this->remote_node)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_updateSecondaryData_result::~DBService_updateSecondaryData_result() throw() {
}
uint32_t DBService_updateSecondaryData_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_updateSecondaryData_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_updateSecondaryData_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_BOOL, 0);
xfer += oprot->writeBool(this->success);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_updateSecondaryData_presult::~DBService_updateSecondaryData_presult() throw() {
}
uint32_t DBService_updateSecondaryData_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_getData_args::~DBService_getData_args() throw() {
}
uint32_t DBService_getData_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->sharded_key);
this->__isset.sharded_key = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_getData_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_getData_args");
xfer += oprot->writeFieldBegin("sharded_key", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString(this->sharded_key);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_getData_pargs::~DBService_getData_pargs() throw() {
}
uint32_t DBService_getData_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_getData_pargs");
xfer += oprot->writeFieldBegin("sharded_key", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString((*(this->sharded_key)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_getData_result::~DBService_getData_result() throw() {
}
uint32_t DBService_getData_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_getData_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_getData_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_STRING, 0);
xfer += oprot->writeString(this->success);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_getData_presult::~DBService_getData_presult() throw() {
}
uint32_t DBService_getData_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_deleteData_args::~DBService_deleteData_args() throw() {
}
uint32_t DBService_deleteData_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->sharded_key);
this->__isset.sharded_key = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_deleteData_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_deleteData_args");
xfer += oprot->writeFieldBegin("sharded_key", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString(this->sharded_key);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_deleteData_pargs::~DBService_deleteData_pargs() throw() {
}
uint32_t DBService_deleteData_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_deleteData_pargs");
xfer += oprot->writeFieldBegin("sharded_key", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString((*(this->sharded_key)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_deleteData_result::~DBService_deleteData_result() throw() {
}
uint32_t DBService_deleteData_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_deleteData_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_deleteData_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_BOOL, 0);
xfer += oprot->writeBool(this->success);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_deleteData_presult::~DBService_deleteData_presult() throw() {
}
uint32_t DBService_deleteData_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_deleteSecondaryData_args::~DBService_deleteSecondaryData_args() throw() {
}
uint32_t DBService_deleteSecondaryData_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->sharded_key);
this->__isset.sharded_key = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_region);
this->__isset.remote_region = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_node);
this->__isset.remote_node = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_deleteSecondaryData_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_deleteSecondaryData_args");
xfer += oprot->writeFieldBegin("sharded_key", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString(this->sharded_key);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32(this->remote_region);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 3);
xfer += oprot->writeI32(this->remote_node);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_deleteSecondaryData_pargs::~DBService_deleteSecondaryData_pargs() throw() {
}
uint32_t DBService_deleteSecondaryData_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_deleteSecondaryData_pargs");
xfer += oprot->writeFieldBegin("sharded_key", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString((*(this->sharded_key)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32((*(this->remote_region)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 3);
xfer += oprot->writeI32((*(this->remote_node)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_deleteSecondaryData_result::~DBService_deleteSecondaryData_result() throw() {
}
uint32_t DBService_deleteSecondaryData_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_deleteSecondaryData_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_deleteSecondaryData_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_BOOL, 0);
xfer += oprot->writeBool(this->success);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_deleteSecondaryData_presult::~DBService_deleteSecondaryData_presult() throw() {
}
uint32_t DBService_deleteSecondaryData_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_replicateData_args::~DBService_replicateData_args() throw() {
}
uint32_t DBService_replicateData_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->d.read(iprot);
this->__isset.d = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_region);
this->__isset.remote_region = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_node);
this->__isset.remote_node = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_replicateData_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_replicateData_args");
xfer += oprot->writeFieldBegin("d", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->d.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32(this->remote_region);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 3);
xfer += oprot->writeI32(this->remote_node);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_replicateData_pargs::~DBService_replicateData_pargs() throw() {
}
uint32_t DBService_replicateData_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_replicateData_pargs");
xfer += oprot->writeFieldBegin("d", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += (*(this->d)).write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32((*(this->remote_region)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 3);
xfer += oprot->writeI32((*(this->remote_node)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_replicateData_result::~DBService_replicateData_result() throw() {
}
uint32_t DBService_replicateData_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_replicateData_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_replicateData_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_BOOL, 0);
xfer += oprot->writeBool(this->success);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_replicateData_presult::~DBService_replicateData_presult() throw() {
}
uint32_t DBService_replicateData_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_resyncData_args::~DBService_resyncData_args() throw() {
}
uint32_t DBService_resyncData_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_region);
this->__isset.remote_region = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_node);
this->__isset.remote_node = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_resyncData_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_resyncData_args");
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 1);
xfer += oprot->writeI32(this->remote_region);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32(this->remote_node);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_resyncData_pargs::~DBService_resyncData_pargs() throw() {
}
uint32_t DBService_resyncData_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_resyncData_pargs");
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 1);
xfer += oprot->writeI32((*(this->remote_region)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32((*(this->remote_node)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_resyncData_result::~DBService_resyncData_result() throw() {
}
uint32_t DBService_resyncData_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->success.read(iprot);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_resyncData_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_resyncData_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_STRUCT, 0);
xfer += this->success.write(oprot);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_resyncData_presult::~DBService_resyncData_presult() throw() {
}
uint32_t DBService_resyncData_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += (*(this->success)).read(iprot);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_pushResyncData_args::~DBService_pushResyncData_args() throw() {
}
uint32_t DBService_pushResyncData_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->contents.read(iprot);
this->__isset.contents = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_pushResyncData_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_pushResyncData_args");
xfer += oprot->writeFieldBegin("contents", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->contents.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_pushResyncData_pargs::~DBService_pushResyncData_pargs() throw() {
}
uint32_t DBService_pushResyncData_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_pushResyncData_pargs");
xfer += oprot->writeFieldBegin("contents", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += (*(this->contents)).write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_pushResyncData_result::~DBService_pushResyncData_result() throw() {
}
uint32_t DBService_pushResyncData_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_pushResyncData_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_pushResyncData_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_BOOL, 0);
xfer += oprot->writeBool(this->success);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_pushResyncData_presult::~DBService_pushResyncData_presult() throw() {
}
uint32_t DBService_pushResyncData_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_getRecover_args::~DBService_getRecover_args() throw() {
}
uint32_t DBService_getRecover_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_region);
this->__isset.remote_region = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->remote_node);
this->__isset.remote_node = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_getRecover_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_getRecover_args");
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 1);
xfer += oprot->writeI32(this->remote_region);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32(this->remote_node);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_getRecover_pargs::~DBService_getRecover_pargs() throw() {
}
uint32_t DBService_getRecover_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_getRecover_pargs");
xfer += oprot->writeFieldBegin("remote_region", ::apache::thrift::protocol::T_I32, 1);
xfer += oprot->writeI32((*(this->remote_region)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("remote_node", ::apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32((*(this->remote_node)));
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_getRecover_result::~DBService_getRecover_result() throw() {
}
uint32_t DBService_getRecover_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->success.read(iprot);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_getRecover_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_getRecover_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_STRUCT, 0);
xfer += this->success.write(oprot);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_getRecover_presult::~DBService_getRecover_presult() throw() {
}
uint32_t DBService_getRecover_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += (*(this->success)).read(iprot);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_sendAppend_args::~DBService_sendAppend_args() throw() {
}
uint32_t DBService_sendAppend_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->request.read(iprot);
this->__isset.request = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_sendAppend_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_sendAppend_args");
xfer += oprot->writeFieldBegin("request", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->request.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_sendAppend_pargs::~DBService_sendAppend_pargs() throw() {
}
uint32_t DBService_sendAppend_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_sendAppend_pargs");
xfer += oprot->writeFieldBegin("request", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += (*(this->request)).write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_sendAppend_result::~DBService_sendAppend_result() throw() {
}
uint32_t DBService_sendAppend_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->success.read(iprot);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_sendAppend_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_sendAppend_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_STRUCT, 0);
xfer += this->success.write(oprot);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_sendAppend_presult::~DBService_sendAppend_presult() throw() {
}
uint32_t DBService_sendAppend_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += (*(this->success)).read(iprot);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_sendVote_args::~DBService_sendVote_args() throw() {
}
uint32_t DBService_sendVote_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->request.read(iprot);
this->__isset.request = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_sendVote_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_sendVote_args");
xfer += oprot->writeFieldBegin("request", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->request.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_sendVote_pargs::~DBService_sendVote_pargs() throw() {
}
uint32_t DBService_sendVote_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_sendVote_pargs");
xfer += oprot->writeFieldBegin("request", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += (*(this->request)).write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_sendVote_result::~DBService_sendVote_result() throw() {
}
uint32_t DBService_sendVote_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->success.read(iprot);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_sendVote_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_sendVote_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_STRUCT, 0);
xfer += this->success.write(oprot);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_sendVote_presult::~DBService_sendVote_presult() throw() {
}
uint32_t DBService_sendVote_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += (*(this->success)).read(iprot);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_followerAppend_args::~DBService_followerAppend_args() throw() {
}
uint32_t DBService_followerAppend_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRUCT) {
xfer += this->request.read(iprot);
this->__isset.request = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_followerAppend_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_followerAppend_args");
xfer += oprot->writeFieldBegin("request", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += this->request.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_followerAppend_pargs::~DBService_followerAppend_pargs() throw() {
}
uint32_t DBService_followerAppend_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_followerAppend_pargs");
xfer += oprot->writeFieldBegin("request", ::apache::thrift::protocol::T_STRUCT, 1);
xfer += (*(this->request)).write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_followerAppend_result::~DBService_followerAppend_result() throw() {
}
uint32_t DBService_followerAppend_result::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool(this->success);
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_followerAppend_result::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("DBService_followerAppend_result");
if (this->__isset.success) {
xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_BOOL, 0);
xfer += oprot->writeBool(this->success);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
DBService_followerAppend_presult::~DBService_followerAppend_presult() throw() {
}
uint32_t DBService_followerAppend_presult::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 0:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool((*(this->success)));
this->__isset.success = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
DBService_zip_args::~DBService_zip_args() throw() {
}
uint32_t DBService_zip_args::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
xfer += iprot->skip(ftype);
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
uint32_t DBService_zip_args::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_zip_args");
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
DBService_zip_pargs::~DBService_zip_pargs() throw() {
}
uint32_t DBService_zip_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
oprot->incrementRecursionDepth();
xfer += oprot->writeStructBegin("DBService_zip_pargs");
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
oprot->decrementRecursionDepth();
return xfer;
}
void DBServiceClient::ping()
{
send_ping();
recv_ping();
}
void DBServiceClient::send_ping()
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("ping", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_ping_pargs args;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void DBServiceClient::recv_ping()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("ping") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
DBService_ping_presult result;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
return;
}
void DBServiceClient::putData(std::string& _return, const std::string& value)
{
send_putData(value);
recv_putData(_return);
}
void DBServiceClient::send_putData(const std::string& value)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("putData", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_putData_pargs args;
args.value = &value;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void DBServiceClient::recv_putData(std::string& _return)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("putData") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
DBService_putData_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
// _return pointer has now been filled
return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "putData failed: unknown result");
}
void DBServiceClient::putDataForce(std::string& _return, const std::string& value, const int32_t remote_region, const int32_t remote_node)
{
send_putDataForce(value, remote_region, remote_node);
recv_putDataForce(_return);
}
void DBServiceClient::send_putDataForce(const std::string& value, const int32_t remote_region, const int32_t remote_node)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("putDataForce", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_putDataForce_pargs args;
args.value = &value;
args.remote_region = &remote_region;
args.remote_node = &remote_node;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void DBServiceClient::recv_putDataForce(std::string& _return)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("putDataForce") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
DBService_putDataForce_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
// _return pointer has now been filled
return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "putDataForce failed: unknown result");
}
bool DBServiceClient::updateData(const Data& d)
{
send_updateData(d);
return recv_updateData();
}
void DBServiceClient::send_updateData(const Data& d)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("updateData", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_updateData_pargs args;
args.d = &d;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
bool DBServiceClient::recv_updateData()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("updateData") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
bool _return;
DBService_updateData_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
return _return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "updateData failed: unknown result");
}
bool DBServiceClient::updateSecondaryData(const Data& d, const int32_t remote_region, const int32_t remote_node)
{
send_updateSecondaryData(d, remote_region, remote_node);
return recv_updateSecondaryData();
}
void DBServiceClient::send_updateSecondaryData(const Data& d, const int32_t remote_region, const int32_t remote_node)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("updateSecondaryData", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_updateSecondaryData_pargs args;
args.d = &d;
args.remote_region = &remote_region;
args.remote_node = &remote_node;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
bool DBServiceClient::recv_updateSecondaryData()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("updateSecondaryData") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
bool _return;
DBService_updateSecondaryData_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
return _return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "updateSecondaryData failed: unknown result");
}
void DBServiceClient::getData(std::string& _return, const std::string& sharded_key)
{
send_getData(sharded_key);
recv_getData(_return);
}
void DBServiceClient::send_getData(const std::string& sharded_key)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("getData", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_getData_pargs args;
args.sharded_key = &sharded_key;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void DBServiceClient::recv_getData(std::string& _return)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("getData") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
DBService_getData_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
// _return pointer has now been filled
return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "getData failed: unknown result");
}
bool DBServiceClient::deleteData(const std::string& sharded_key)
{
send_deleteData(sharded_key);
return recv_deleteData();
}
void DBServiceClient::send_deleteData(const std::string& sharded_key)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("deleteData", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_deleteData_pargs args;
args.sharded_key = &sharded_key;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
bool DBServiceClient::recv_deleteData()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("deleteData") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
bool _return;
DBService_deleteData_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
return _return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "deleteData failed: unknown result");
}
bool DBServiceClient::deleteSecondaryData(const std::string& sharded_key, const int32_t remote_region, const int32_t remote_node)
{
send_deleteSecondaryData(sharded_key, remote_region, remote_node);
return recv_deleteSecondaryData();
}
void DBServiceClient::send_deleteSecondaryData(const std::string& sharded_key, const int32_t remote_region, const int32_t remote_node)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("deleteSecondaryData", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_deleteSecondaryData_pargs args;
args.sharded_key = &sharded_key;
args.remote_region = &remote_region;
args.remote_node = &remote_node;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
bool DBServiceClient::recv_deleteSecondaryData()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("deleteSecondaryData") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
bool _return;
DBService_deleteSecondaryData_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
return _return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "deleteSecondaryData failed: unknown result");
}
bool DBServiceClient::replicateData(const Data& d, const int32_t remote_region, const int32_t remote_node)
{
send_replicateData(d, remote_region, remote_node);
return recv_replicateData();
}
void DBServiceClient::send_replicateData(const Data& d, const int32_t remote_region, const int32_t remote_node)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("replicateData", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_replicateData_pargs args;
args.d = &d;
args.remote_region = &remote_region;
args.remote_node = &remote_node;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
bool DBServiceClient::recv_replicateData()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("replicateData") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
bool _return;
DBService_replicateData_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
return _return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "replicateData failed: unknown result");
}
void DBServiceClient::resyncData(ShardContent& _return, const int32_t remote_region, const int32_t remote_node)
{
send_resyncData(remote_region, remote_node);
recv_resyncData(_return);
}
void DBServiceClient::send_resyncData(const int32_t remote_region, const int32_t remote_node)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("resyncData", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_resyncData_pargs args;
args.remote_region = &remote_region;
args.remote_node = &remote_node;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void DBServiceClient::recv_resyncData(ShardContent& _return)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("resyncData") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
DBService_resyncData_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
// _return pointer has now been filled
return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "resyncData failed: unknown result");
}
bool DBServiceClient::pushResyncData(const ShardContent& contents)
{
send_pushResyncData(contents);
return recv_pushResyncData();
}
void DBServiceClient::send_pushResyncData(const ShardContent& contents)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("pushResyncData", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_pushResyncData_pargs args;
args.contents = &contents;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
bool DBServiceClient::recv_pushResyncData()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("pushResyncData") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
bool _return;
DBService_pushResyncData_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
return _return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "pushResyncData failed: unknown result");
}
void DBServiceClient::getRecover(GetRecover& _return, const int32_t remote_region, const int32_t remote_node)
{
send_getRecover(remote_region, remote_node);
recv_getRecover(_return);
}
void DBServiceClient::send_getRecover(const int32_t remote_region, const int32_t remote_node)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("getRecover", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_getRecover_pargs args;
args.remote_region = &remote_region;
args.remote_node = &remote_node;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void DBServiceClient::recv_getRecover(GetRecover& _return)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("getRecover") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
DBService_getRecover_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
// _return pointer has now been filled
return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "getRecover failed: unknown result");
}
void DBServiceClient::sendAppend(AppendResponse& _return, const AppendRequest& request)
{
send_sendAppend(request);
recv_sendAppend(_return);
}
void DBServiceClient::send_sendAppend(const AppendRequest& request)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("sendAppend", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_sendAppend_pargs args;
args.request = &request;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void DBServiceClient::recv_sendAppend(AppendResponse& _return)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("sendAppend") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
DBService_sendAppend_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
// _return pointer has now been filled
return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "sendAppend failed: unknown result");
}
void DBServiceClient::sendVote(VoteResponse& _return, const VoteRequest& request)
{
send_sendVote(request);
recv_sendVote(_return);
}
void DBServiceClient::send_sendVote(const VoteRequest& request)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("sendVote", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_sendVote_pargs args;
args.request = &request;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
void DBServiceClient::recv_sendVote(VoteResponse& _return)
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("sendVote") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
DBService_sendVote_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
// _return pointer has now been filled
return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "sendVote failed: unknown result");
}
bool DBServiceClient::followerAppend(const AppendRequest& request)
{
send_followerAppend(request);
return recv_followerAppend();
}
void DBServiceClient::send_followerAppend(const AppendRequest& request)
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("followerAppend", ::apache::thrift::protocol::T_CALL, cseqid);
DBService_followerAppend_pargs args;
args.request = &request;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
bool DBServiceClient::recv_followerAppend()
{
int32_t rseqid = 0;
std::string fname;
::apache::thrift::protocol::TMessageType mtype;
iprot_->readMessageBegin(fname, mtype, rseqid);
if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {
::apache::thrift::TApplicationException x;
x.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
throw x;
}
if (mtype != ::apache::thrift::protocol::T_REPLY) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
if (fname.compare("followerAppend") != 0) {
iprot_->skip(::apache::thrift::protocol::T_STRUCT);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
}
bool _return;
DBService_followerAppend_presult result;
result.success = &_return;
result.read(iprot_);
iprot_->readMessageEnd();
iprot_->getTransport()->readEnd();
if (result.__isset.success) {
return _return;
}
throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "followerAppend failed: unknown result");
}
void DBServiceClient::zip()
{
send_zip();
}
void DBServiceClient::send_zip()
{
int32_t cseqid = 0;
oprot_->writeMessageBegin("zip", ::apache::thrift::protocol::T_ONEWAY, cseqid);
DBService_zip_pargs args;
args.write(oprot_);
oprot_->writeMessageEnd();
oprot_->getTransport()->writeEnd();
oprot_->getTransport()->flush();
}
bool DBServiceProcessor::dispatchCall(::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, const std::string& fname, int32_t seqid, void* callContext) {
ProcessMap::iterator pfn;
pfn = processMap_.find(fname);
if (pfn == processMap_.end()) {
iprot->skip(::apache::thrift::protocol::T_STRUCT);
iprot->readMessageEnd();
iprot->getTransport()->readEnd();
::apache::thrift::TApplicationException x(::apache::thrift::TApplicationException::UNKNOWN_METHOD, "Invalid method name: '"+fname+"'");
oprot->writeMessageBegin(fname, ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return true;
}
(this->*(pfn->second))(seqid, iprot, oprot, callContext);
return true;
}
void DBServiceProcessor::process_ping(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.ping", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.ping");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.ping");
}
DBService_ping_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.ping", bytes);
}
DBService_ping_result result;
try {
iface_->ping();
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.ping");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("ping", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.ping");
}
oprot->writeMessageBegin("ping", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.ping", bytes);
}
}
void DBServiceProcessor::process_putData(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.putData", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.putData");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.putData");
}
DBService_putData_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.putData", bytes);
}
DBService_putData_result result;
try {
iface_->putData(result.success, args.value);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.putData");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("putData", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.putData");
}
oprot->writeMessageBegin("putData", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.putData", bytes);
}
}
void DBServiceProcessor::process_putDataForce(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.putDataForce", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.putDataForce");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.putDataForce");
}
DBService_putDataForce_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.putDataForce", bytes);
}
DBService_putDataForce_result result;
try {
iface_->putDataForce(result.success, args.value, args.remote_region, args.remote_node);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.putDataForce");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("putDataForce", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.putDataForce");
}
oprot->writeMessageBegin("putDataForce", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.putDataForce", bytes);
}
}
void DBServiceProcessor::process_updateData(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.updateData", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.updateData");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.updateData");
}
DBService_updateData_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.updateData", bytes);
}
DBService_updateData_result result;
try {
result.success = iface_->updateData(args.d);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.updateData");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("updateData", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.updateData");
}
oprot->writeMessageBegin("updateData", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.updateData", bytes);
}
}
void DBServiceProcessor::process_updateSecondaryData(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.updateSecondaryData", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.updateSecondaryData");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.updateSecondaryData");
}
DBService_updateSecondaryData_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.updateSecondaryData", bytes);
}
DBService_updateSecondaryData_result result;
try {
result.success = iface_->updateSecondaryData(args.d, args.remote_region, args.remote_node);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.updateSecondaryData");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("updateSecondaryData", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.updateSecondaryData");
}
oprot->writeMessageBegin("updateSecondaryData", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.updateSecondaryData", bytes);
}
}
void DBServiceProcessor::process_getData(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.getData", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.getData");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.getData");
}
DBService_getData_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.getData", bytes);
}
DBService_getData_result result;
try {
iface_->getData(result.success, args.sharded_key);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.getData");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("getData", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.getData");
}
oprot->writeMessageBegin("getData", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.getData", bytes);
}
}
void DBServiceProcessor::process_deleteData(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.deleteData", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.deleteData");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.deleteData");
}
DBService_deleteData_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.deleteData", bytes);
}
DBService_deleteData_result result;
try {
result.success = iface_->deleteData(args.sharded_key);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.deleteData");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("deleteData", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.deleteData");
}
oprot->writeMessageBegin("deleteData", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.deleteData", bytes);
}
}
void DBServiceProcessor::process_deleteSecondaryData(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.deleteSecondaryData", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.deleteSecondaryData");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.deleteSecondaryData");
}
DBService_deleteSecondaryData_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.deleteSecondaryData", bytes);
}
DBService_deleteSecondaryData_result result;
try {
result.success = iface_->deleteSecondaryData(args.sharded_key, args.remote_region, args.remote_node);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.deleteSecondaryData");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("deleteSecondaryData", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.deleteSecondaryData");
}
oprot->writeMessageBegin("deleteSecondaryData", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.deleteSecondaryData", bytes);
}
}
void DBServiceProcessor::process_replicateData(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.replicateData", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.replicateData");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.replicateData");
}
DBService_replicateData_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.replicateData", bytes);
}
DBService_replicateData_result result;
try {
result.success = iface_->replicateData(args.d, args.remote_region, args.remote_node);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.replicateData");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("replicateData", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.replicateData");
}
oprot->writeMessageBegin("replicateData", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.replicateData", bytes);
}
}
void DBServiceProcessor::process_resyncData(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.resyncData", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.resyncData");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.resyncData");
}
DBService_resyncData_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.resyncData", bytes);
}
DBService_resyncData_result result;
try {
iface_->resyncData(result.success, args.remote_region, args.remote_node);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.resyncData");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("resyncData", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.resyncData");
}
oprot->writeMessageBegin("resyncData", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.resyncData", bytes);
}
}
void DBServiceProcessor::process_pushResyncData(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.pushResyncData", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.pushResyncData");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.pushResyncData");
}
DBService_pushResyncData_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.pushResyncData", bytes);
}
DBService_pushResyncData_result result;
try {
result.success = iface_->pushResyncData(args.contents);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.pushResyncData");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("pushResyncData", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.pushResyncData");
}
oprot->writeMessageBegin("pushResyncData", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.pushResyncData", bytes);
}
}
void DBServiceProcessor::process_getRecover(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.getRecover", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.getRecover");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.getRecover");
}
DBService_getRecover_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.getRecover", bytes);
}
DBService_getRecover_result result;
try {
iface_->getRecover(result.success, args.remote_region, args.remote_node);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.getRecover");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("getRecover", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.getRecover");
}
oprot->writeMessageBegin("getRecover", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.getRecover", bytes);
}
}
void DBServiceProcessor::process_sendAppend(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.sendAppend", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.sendAppend");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.sendAppend");
}
DBService_sendAppend_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.sendAppend", bytes);
}
DBService_sendAppend_result result;
try {
iface_->sendAppend(result.success, args.request);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.sendAppend");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("sendAppend", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.sendAppend");
}
oprot->writeMessageBegin("sendAppend", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.sendAppend", bytes);
}
}
void DBServiceProcessor::process_sendVote(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.sendVote", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.sendVote");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.sendVote");
}
DBService_sendVote_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.sendVote", bytes);
}
DBService_sendVote_result result;
try {
iface_->sendVote(result.success, args.request);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.sendVote");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("sendVote", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.sendVote");
}
oprot->writeMessageBegin("sendVote", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.sendVote", bytes);
}
}
void DBServiceProcessor::process_followerAppend(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.followerAppend", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.followerAppend");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.followerAppend");
}
DBService_followerAppend_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.followerAppend", bytes);
}
DBService_followerAppend_result result;
try {
result.success = iface_->followerAppend(args.request);
result.__isset.success = true;
} catch (const std::exception& e) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.followerAppend");
}
::apache::thrift::TApplicationException x(e.what());
oprot->writeMessageBegin("followerAppend", ::apache::thrift::protocol::T_EXCEPTION, seqid);
x.write(oprot);
oprot->writeMessageEnd();
oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preWrite(ctx, "DBService.followerAppend");
}
oprot->writeMessageBegin("followerAppend", ::apache::thrift::protocol::T_REPLY, seqid);
result.write(oprot);
oprot->writeMessageEnd();
bytes = oprot->getTransport()->writeEnd();
oprot->getTransport()->flush();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postWrite(ctx, "DBService.followerAppend", bytes);
}
}
void DBServiceProcessor::process_zip(int32_t, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol*, void* callContext)
{
void* ctx = NULL;
if (this->eventHandler_.get() != NULL) {
ctx = this->eventHandler_->getContext("DBService.zip", callContext);
}
::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "DBService.zip");
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->preRead(ctx, "DBService.zip");
}
DBService_zip_args args;
args.read(iprot);
iprot->readMessageEnd();
uint32_t bytes = iprot->getTransport()->readEnd();
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->postRead(ctx, "DBService.zip", bytes);
}
try {
iface_->zip();
} catch (const std::exception&) {
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->handlerError(ctx, "DBService.zip");
}
return;
}
if (this->eventHandler_.get() != NULL) {
this->eventHandler_->asyncComplete(ctx, "DBService.zip");
}
return;
}
::boost::shared_ptr< ::apache::thrift::TProcessor > DBServiceProcessorFactory::getProcessor(const ::apache::thrift::TConnectionInfo& connInfo) {
::apache::thrift::ReleaseHandler< DBServiceIfFactory > cleanup(handlerFactory_);
::boost::shared_ptr< DBServiceIf > handler(handlerFactory_->getHandler(connInfo), cleanup);
::boost::shared_ptr< ::apache::thrift::TProcessor > processor(new DBServiceProcessor(handler));
return processor;
}
} // namespace
| [
"iskandarsetiadi@students.itb.ac.id"
] | iskandarsetiadi@students.itb.ac.id |
c434f0aa042d824977f97734ecebf5556a181ee6 | 13ad52069c868a2191aea3583f29114340f8aca4 | /8025580.2/raw_files/new/src/share/vm/oops/method.cpp | bafa19449ceae35fd91141db73290bdaec063dc6 | [] | no_license | ygaevsky/openjdk | 0fd13e5bfc9a48d3f1e94a90198c86c1baa35903 | e981cea0ff1324ecc76e6045677bcf09668bf17e | refs/heads/master | 2016-09-10T17:07:22.238555 | 2014-05-14T15:50:19 | 2014-05-14T15:50:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 71,014 | cpp | /*
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/metadataOnStackMark.hpp"
#include "classfile/systemDictionary.hpp"
#include "code/debugInfoRec.hpp"
#include "gc_interface/collectedHeap.inline.hpp"
#include "interpreter/bytecodeStream.hpp"
#include "interpreter/bytecodeTracer.hpp"
#include "interpreter/bytecodes.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/oopMapCache.hpp"
#include "memory/gcLocker.hpp"
#include "memory/generation.hpp"
#include "memory/heapInspection.hpp"
#include "memory/metadataFactory.hpp"
#include "memory/oopFactory.hpp"
#include "oops/constMethod.hpp"
#include "oops/methodData.hpp"
#include "oops/method.hpp"
#include "oops/oop.inline.hpp"
#include "oops/symbol.hpp"
#include "prims/jvmtiExport.hpp"
#include "prims/methodHandles.hpp"
#include "prims/nativeLookup.hpp"
#include "runtime/arguments.hpp"
#include "runtime/compilationPolicy.hpp"
#include "runtime/frame.inline.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/relocator.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/signature.hpp"
#include "utilities/quickSort.hpp"
#include "utilities/xmlstream.hpp"
// Implementation of Method
Method* Method::allocate(ClassLoaderData* loader_data,
int byte_code_size,
AccessFlags access_flags,
InlineTableSizes* sizes,
ConstMethod::MethodType method_type,
TRAPS) {
assert(!access_flags.is_native() || byte_code_size == 0,
"native methods should not contain byte codes");
ConstMethod* cm = ConstMethod::allocate(loader_data,
byte_code_size,
sizes,
method_type,
CHECK_NULL);
int size = Method::size(access_flags.is_native());
return new (loader_data, size, false, MetaspaceObj::MethodType, THREAD) Method(cm, access_flags, size);
}
Method::Method(ConstMethod* xconst, AccessFlags access_flags, int size) {
No_Safepoint_Verifier no_safepoint;
set_constMethod(xconst);
set_access_flags(access_flags);
set_method_size(size);
#ifdef CC_INTERP
set_result_index(T_VOID);
#endif
set_intrinsic_id(vmIntrinsics::_none);
set_jfr_towrite(false);
set_force_inline(false);
set_hidden(false);
set_dont_inline(false);
set_method_data(NULL);
set_method_counters(NULL);
set_vtable_index(Method::garbage_vtable_index);
// Fix and bury in Method*
set_interpreter_entry(NULL); // sets i2i entry and from_int
set_adapter_entry(NULL);
clear_code(); // from_c/from_i get set to c2i/i2i
if (access_flags.is_native()) {
clear_native_function();
set_signature_handler(NULL);
}
NOT_PRODUCT(set_compiled_invocation_count(0);)
}
// Release Method*. The nmethod will be gone when we get here because
// we've walked the code cache.
void Method::deallocate_contents(ClassLoaderData* loader_data) {
MetadataFactory::free_metadata(loader_data, constMethod());
set_constMethod(NULL);
MetadataFactory::free_metadata(loader_data, method_data());
set_method_data(NULL);
MetadataFactory::free_metadata(loader_data, method_counters());
set_method_counters(NULL);
// The nmethod will be gone when we get here.
if (code() != NULL) _code = NULL;
}
address Method::get_i2c_entry() {
assert(_adapter != NULL, "must have");
return _adapter->get_i2c_entry();
}
address Method::get_c2i_entry() {
assert(_adapter != NULL, "must have");
return _adapter->get_c2i_entry();
}
address Method::get_c2i_unverified_entry() {
assert(_adapter != NULL, "must have");
return _adapter->get_c2i_unverified_entry();
}
char* Method::name_and_sig_as_C_string() const {
return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature());
}
char* Method::name_and_sig_as_C_string(char* buf, int size) const {
return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature(), buf, size);
}
char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature) {
const char* klass_name = klass->external_name();
int klass_name_len = (int)strlen(klass_name);
int method_name_len = method_name->utf8_length();
int len = klass_name_len + 1 + method_name_len + signature->utf8_length();
char* dest = NEW_RESOURCE_ARRAY(char, len + 1);
strcpy(dest, klass_name);
dest[klass_name_len] = '.';
strcpy(&dest[klass_name_len + 1], method_name->as_C_string());
strcpy(&dest[klass_name_len + 1 + method_name_len], signature->as_C_string());
dest[len] = 0;
return dest;
}
char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size) {
Symbol* klass_name = klass->name();
klass_name->as_klass_external_name(buf, size);
int len = (int)strlen(buf);
if (len < size - 1) {
buf[len++] = '.';
method_name->as_C_string(&(buf[len]), size - len);
len = (int)strlen(buf);
signature->as_C_string(&(buf[len]), size - len);
}
return buf;
}
int Method::fast_exception_handler_bci_for(methodHandle mh, KlassHandle ex_klass, int throw_bci, TRAPS) {
// exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
// access exception table
ExceptionTable table(mh());
int length = table.length();
// iterate through all entries sequentially
constantPoolHandle pool(THREAD, mh->constants());
for (int i = 0; i < length; i ++) {
//reacquire the table in case a GC happened
ExceptionTable table(mh());
int beg_bci = table.start_pc(i);
int end_bci = table.end_pc(i);
assert(beg_bci <= end_bci, "inconsistent exception table");
if (beg_bci <= throw_bci && throw_bci < end_bci) {
// exception handler bci range covers throw_bci => investigate further
int handler_bci = table.handler_pc(i);
int klass_index = table.catch_type_index(i);
if (klass_index == 0) {
return handler_bci;
} else if (ex_klass.is_null()) {
return handler_bci;
} else {
// we know the exception class => get the constraint class
// this may require loading of the constraint class; if verification
// fails or some other exception occurs, return handler_bci
Klass* k = pool->klass_at(klass_index, CHECK_(handler_bci));
KlassHandle klass = KlassHandle(THREAD, k);
assert(klass.not_null(), "klass not loaded");
if (ex_klass->is_subtype_of(klass())) {
return handler_bci;
}
}
}
}
return -1;
}
void Method::mask_for(int bci, InterpreterOopMap* mask) {
Thread* myThread = Thread::current();
methodHandle h_this(myThread, this);
#ifdef ASSERT
bool has_capability = myThread->is_VM_thread() ||
myThread->is_ConcurrentGC_thread() ||
myThread->is_GC_task_thread();
if (!has_capability) {
if (!VerifyStack && !VerifyLastFrame) {
// verify stack calls this outside VM thread
warning("oopmap should only be accessed by the "
"VM, GC task or CMS threads (or during debugging)");
InterpreterOopMap local_mask;
method_holder()->mask_for(h_this, bci, &local_mask);
local_mask.print();
}
}
#endif
method_holder()->mask_for(h_this, bci, mask);
return;
}
int Method::bci_from(address bcp) const {
#ifdef ASSERT
{ ResourceMark rm;
assert(is_native() && bcp == code_base() || contains(bcp) || is_error_reported(),
err_msg("bcp doesn't belong to this method: bcp: " INTPTR_FORMAT ", method: %s", bcp, name_and_sig_as_C_string()));
}
#endif
return bcp - code_base();
}
// Return (int)bcx if it appears to be a valid BCI.
// Return bci_from((address)bcx) if it appears to be a valid BCP.
// Return -1 otherwise.
// Used by profiling code, when invalid data is a possibility.
// The caller is responsible for validating the Method* itself.
int Method::validate_bci_from_bcx(intptr_t bcx) const {
// keep bci as -1 if not a valid bci
int bci = -1;
if (bcx == 0 || (address)bcx == code_base()) {
// code_size() may return 0 and we allow 0 here
// the method may be native
bci = 0;
} else if (frame::is_bci(bcx)) {
if (bcx < code_size()) {
bci = (int)bcx;
}
} else if (contains((address)bcx)) {
bci = (address)bcx - code_base();
}
// Assert that if we have dodged any asserts, bci is negative.
assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0");
return bci;
}
address Method::bcp_from(int bci) const {
assert((is_native() && bci == 0) || (!is_native() && 0 <= bci && bci < code_size()), err_msg("illegal bci: %d", bci));
address bcp = code_base() + bci;
assert(is_native() && bcp == code_base() || contains(bcp), "bcp doesn't belong to this method");
return bcp;
}
int Method::size(bool is_native) {
// If native, then include pointers for native_function and signature_handler
int extra_bytes = (is_native) ? 2*sizeof(address*) : 0;
int extra_words = align_size_up(extra_bytes, BytesPerWord) / BytesPerWord;
return align_object_size(header_size() + extra_words);
}
Symbol* Method::klass_name() const {
Klass* k = method_holder();
assert(k->is_klass(), "must be klass");
InstanceKlass* ik = (InstanceKlass*) k;
return ik->name();
}
// Attempt to return method oop to original state. Clear any pointers
// (to objects outside the shared spaces). We won't be able to predict
// where they should point in a new JVM. Further initialize some
// entries now in order allow them to be write protected later.
void Method::remove_unshareable_info() {
unlink_method();
}
bool Method::was_executed_more_than(int n) {
// Invocation counter is reset when the Method* is compiled.
// If the method has compiled code we therefore assume it has
// be excuted more than n times.
if (is_accessor() || is_empty_method() || (code() != NULL)) {
// interpreter doesn't bump invocation counter of trivial methods
// compiler does not bump invocation counter of compiled methods
return true;
}
else if ((method_counters() != NULL &&
method_counters()->invocation_counter()->carry()) ||
(method_data() != NULL &&
method_data()->invocation_counter()->carry())) {
// The carry bit is set when the counter overflows and causes
// a compilation to occur. We don't know how many times
// the counter has been reset, so we simply assume it has
// been executed more than n times.
return true;
} else {
return invocation_count() > n;
}
}
void Method::print_invocation_count() {
if (is_static()) tty->print("static ");
if (is_final()) tty->print("final ");
if (is_synchronized()) tty->print("synchronized ");
if (is_native()) tty->print("native ");
tty->print("%s::", method_holder()->external_name());
name()->print_symbol_on(tty);
signature()->print_symbol_on(tty);
if (WizardMode) {
// dump the size of the byte codes
tty->print(" {%d}", code_size());
}
tty->cr();
tty->print_cr (" interpreter_invocation_count: %8d ", interpreter_invocation_count());
tty->print_cr (" invocation_counter: %8d ", invocation_count());
tty->print_cr (" backedge_counter: %8d ", backedge_count());
#ifndef PRODUCT
if (CountCompiledCalls) {
tty->print_cr (" compiled_invocation_count: %8d ", compiled_invocation_count());
}
#endif
}
// Build a MethodData* object to hold information about this method
// collected in the interpreter.
void Method::build_interpreter_method_data(methodHandle method, TRAPS) {
// Do not profile method if current thread holds the pending list lock,
// which avoids deadlock for acquiring the MethodData_lock.
if (InstanceRefKlass::owns_pending_list_lock((JavaThread*)THREAD)) {
return;
}
// Grab a lock here to prevent multiple
// MethodData*s from being created.
MutexLocker ml(MethodData_lock, THREAD);
if (method->method_data() == NULL) {
ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
MethodData* method_data = MethodData::allocate(loader_data, method, CHECK);
method->set_method_data(method_data);
if (PrintMethodData && (Verbose || WizardMode)) {
ResourceMark rm(THREAD);
tty->print("build_interpreter_method_data for ");
method->print_name(tty);
tty->cr();
// At the end of the run, the MDO, full of data, will be dumped.
}
}
}
MethodCounters* Method::build_method_counters(Method* m, TRAPS) {
methodHandle mh(m);
ClassLoaderData* loader_data = mh->method_holder()->class_loader_data();
MethodCounters* counters = MethodCounters::allocate(loader_data, CHECK_NULL);
if (mh->method_counters() == NULL) {
mh->set_method_counters(counters);
} else {
MetadataFactory::free_metadata(loader_data, counters);
}
return mh->method_counters();
}
void Method::cleanup_inline_caches() {
// The current system doesn't use inline caches in the interpreter
// => nothing to do (keep this method around for future use)
}
int Method::extra_stack_words() {
// not an inline function, to avoid a header dependency on Interpreter
return extra_stack_entries() * Interpreter::stackElementSize;
}
void Method::compute_size_of_parameters(Thread *thread) {
ArgumentSizeComputer asc(signature());
set_size_of_parameters(asc.size() + (is_static() ? 0 : 1));
}
#ifdef CC_INTERP
void Method::set_result_index(BasicType type) {
_result_index = Interpreter::BasicType_as_index(type);
}
#endif
BasicType Method::result_type() const {
ResultTypeFinder rtf(signature());
return rtf.type();
}
bool Method::is_empty_method() const {
return code_size() == 1
&& *code_base() == Bytecodes::_return;
}
bool Method::is_vanilla_constructor() const {
// Returns true if this method is a vanilla constructor, i.e. an "<init>" "()V" method
// which only calls the superclass vanilla constructor and possibly does stores of
// zero constants to local fields:
//
// aload_0
// invokespecial
// indexbyte1
// indexbyte2
//
// followed by an (optional) sequence of:
//
// aload_0
// aconst_null / iconst_0 / fconst_0 / dconst_0
// putfield
// indexbyte1
// indexbyte2
//
// followed by:
//
// return
assert(name() == vmSymbols::object_initializer_name(), "Should only be called for default constructors");
assert(signature() == vmSymbols::void_method_signature(), "Should only be called for default constructors");
int size = code_size();
// Check if size match
if (size == 0 || size % 5 != 0) return false;
address cb = code_base();
int last = size - 1;
if (cb[0] != Bytecodes::_aload_0 || cb[1] != Bytecodes::_invokespecial || cb[last] != Bytecodes::_return) {
// Does not call superclass default constructor
return false;
}
// Check optional sequence
for (int i = 4; i < last; i += 5) {
if (cb[i] != Bytecodes::_aload_0) return false;
if (!Bytecodes::is_zero_const(Bytecodes::cast(cb[i+1]))) return false;
if (cb[i+2] != Bytecodes::_putfield) return false;
}
return true;
}
bool Method::compute_has_loops_flag() {
BytecodeStream bcs(this);
Bytecodes::Code bc;
while ((bc = bcs.next()) >= 0) {
switch( bc ) {
case Bytecodes::_ifeq:
case Bytecodes::_ifnull:
case Bytecodes::_iflt:
case Bytecodes::_ifle:
case Bytecodes::_ifne:
case Bytecodes::_ifnonnull:
case Bytecodes::_ifgt:
case Bytecodes::_ifge:
case Bytecodes::_if_icmpeq:
case Bytecodes::_if_icmpne:
case Bytecodes::_if_icmplt:
case Bytecodes::_if_icmpgt:
case Bytecodes::_if_icmple:
case Bytecodes::_if_icmpge:
case Bytecodes::_if_acmpeq:
case Bytecodes::_if_acmpne:
case Bytecodes::_goto:
case Bytecodes::_jsr:
if( bcs.dest() < bcs.next_bci() ) _access_flags.set_has_loops();
break;
case Bytecodes::_goto_w:
case Bytecodes::_jsr_w:
if( bcs.dest_w() < bcs.next_bci() ) _access_flags.set_has_loops();
break;
}
}
_access_flags.set_loops_flag_init();
return _access_flags.has_loops();
}
bool Method::is_final_method(AccessFlags class_access_flags) const {
// or "does_not_require_vtable_entry"
// default method or overpass can occur, is not final (reuses vtable entry)
// private methods get vtable entries for backward class compatibility.
if (is_overpass() || is_default_method()) return false;
return is_final() || class_access_flags.is_final();
}
bool Method::is_final_method() const {
return is_final_method(method_holder()->access_flags());
}
bool Method::is_default_method() const {
if (method_holder() != NULL &&
method_holder()->is_interface() &&
!is_abstract()) {
return true;
} else {
return false;
}
}
bool Method::can_be_statically_bound(AccessFlags class_access_flags) const {
if (is_final_method(class_access_flags)) return true;
#ifdef ASSERT
ResourceMark rm;
bool is_nonv = (vtable_index() == nonvirtual_vtable_index);
if (class_access_flags.is_interface()) {
assert(is_nonv == is_static(), err_msg("is_nonv=%s", name_and_sig_as_C_string()));
}
#endif
assert(valid_vtable_index() || valid_itable_index(), "method must be linked before we ask this question");
return vtable_index() == nonvirtual_vtable_index;
}
bool Method::can_be_statically_bound() const {
return can_be_statically_bound(method_holder()->access_flags());
}
bool Method::is_accessor() const {
if (code_size() != 5) return false;
if (size_of_parameters() != 1) return false;
if (java_code_at(0) != Bytecodes::_aload_0 ) return false;
if (java_code_at(1) != Bytecodes::_getfield) return false;
if (java_code_at(4) != Bytecodes::_areturn &&
java_code_at(4) != Bytecodes::_ireturn ) return false;
return true;
}
bool Method::is_initializer() const {
return name() == vmSymbols::object_initializer_name() || is_static_initializer();
}
bool Method::has_valid_initializer_flags() const {
return (is_static() ||
method_holder()->major_version() < 51);
}
bool Method::is_static_initializer() const {
// For classfiles version 51 or greater, ensure that the clinit method is
// static. Non-static methods with the name "<clinit>" are not static
// initializers. (older classfiles exempted for backward compatibility)
return name() == vmSymbols::class_initializer_name() &&
has_valid_initializer_flags();
}
objArrayHandle Method::resolved_checked_exceptions_impl(Method* method, TRAPS) {
int length = method->checked_exceptions_length();
if (length == 0) { // common case
return objArrayHandle(THREAD, Universe::the_empty_class_klass_array());
} else {
methodHandle h_this(THREAD, method);
objArrayOop m_oop = oopFactory::new_objArray(SystemDictionary::Class_klass(), length, CHECK_(objArrayHandle()));
objArrayHandle mirrors (THREAD, m_oop);
for (int i = 0; i < length; i++) {
CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe
Klass* k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle()));
assert(k->is_subclass_of(SystemDictionary::Throwable_klass()), "invalid exception class");
mirrors->obj_at_put(i, k->java_mirror());
}
return mirrors;
}
};
int Method::line_number_from_bci(int bci) const {
if (bci == SynchronizationEntryBCI) bci = 0;
assert(bci == 0 || 0 <= bci && bci < code_size(), "illegal bci");
int best_bci = 0;
int best_line = -1;
if (has_linenumber_table()) {
// The line numbers are a short array of 2-tuples [start_pc, line_number].
// Not necessarily sorted and not necessarily one-to-one.
CompressedLineNumberReadStream stream(compressed_linenumber_table());
while (stream.read_pair()) {
if (stream.bci() == bci) {
// perfect match
return stream.line();
} else {
// update best_bci/line
if (stream.bci() < bci && stream.bci() >= best_bci) {
best_bci = stream.bci();
best_line = stream.line();
}
}
}
}
return best_line;
}
bool Method::is_klass_loaded_by_klass_index(int klass_index) const {
if( constants()->tag_at(klass_index).is_unresolved_klass() ) {
Thread *thread = Thread::current();
Symbol* klass_name = constants()->klass_name_at(klass_index);
Handle loader(thread, method_holder()->class_loader());
Handle prot (thread, method_holder()->protection_domain());
return SystemDictionary::find(klass_name, loader, prot, thread) != NULL;
} else {
return true;
}
}
bool Method::is_klass_loaded(int refinfo_index, bool must_be_resolved) const {
int klass_index = constants()->klass_ref_index_at(refinfo_index);
if (must_be_resolved) {
// Make sure klass is resolved in constantpool.
if (constants()->tag_at(klass_index).is_unresolved_klass()) return false;
}
return is_klass_loaded_by_klass_index(klass_index);
}
void Method::set_native_function(address function, bool post_event_flag) {
assert(function != NULL, "use clear_native_function to unregister natives");
assert(!is_method_handle_intrinsic() || function == SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), "");
address* native_function = native_function_addr();
// We can see racers trying to place the same native function into place. Once
// is plenty.
address current = *native_function;
if (current == function) return;
if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
function != NULL) {
// native_method_throw_unsatisfied_link_error_entry() should only
// be passed when post_event_flag is false.
assert(function !=
SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
"post_event_flag mis-match");
// post the bind event, and possible change the bind function
JvmtiExport::post_native_method_bind(this, &function);
}
*native_function = function;
// This function can be called more than once. We must make sure that we always
// use the latest registered method -> check if a stub already has been generated.
// If so, we have to make it not_entrant.
nmethod* nm = code(); // Put it into local variable to guard against concurrent updates
if (nm != NULL) {
nm->make_not_entrant();
}
}
bool Method::has_native_function() const {
if (is_method_handle_intrinsic())
return false; // special-cased in SharedRuntime::generate_native_wrapper
address func = native_function();
return (func != NULL && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
}
void Method::clear_native_function() {
// Note: is_method_handle_intrinsic() is allowed here.
set_native_function(
SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
!native_bind_event_is_interesting);
clear_code();
}
address Method::critical_native_function() {
methodHandle mh(this);
return NativeLookup::lookup_critical_entry(mh);
}
void Method::set_signature_handler(address handler) {
address* signature_handler = signature_handler_addr();
*signature_handler = handler;
}
void Method::print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason) {
if (PrintCompilation && report) {
ttyLocker ttyl;
tty->print("made not %scompilable on ", is_osr ? "OSR " : "");
if (comp_level == CompLevel_all) {
tty->print("all levels ");
} else {
tty->print("levels ");
for (int i = (int)CompLevel_none; i <= comp_level; i++) {
tty->print("%d ", i);
}
}
this->print_short_name(tty);
int size = this->code_size();
if (size > 0) {
tty->print(" (%d bytes)", size);
}
if (reason != NULL) {
tty->print(" %s", reason);
}
tty->cr();
}
if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
ttyLocker ttyl;
xtty->begin_elem("make_not_%scompilable thread='" UINTX_FORMAT "'",
is_osr ? "osr_" : "", os::current_thread_id());
if (reason != NULL) {
xtty->print(" reason=\'%s\'", reason);
}
xtty->method(this);
xtty->stamp();
xtty->end_elem();
}
}
bool Method::is_always_compilable() const {
// Generated adapters must be compiled
if (is_method_handle_intrinsic() && is_synthetic()) {
assert(!is_not_c1_compilable(), "sanity check");
assert(!is_not_c2_compilable(), "sanity check");
return true;
}
return false;
}
bool Method::is_not_compilable(int comp_level) const {
if (number_of_breakpoints() > 0)
return true;
if (is_always_compilable())
return false;
if (comp_level == CompLevel_any)
return is_not_c1_compilable() || is_not_c2_compilable();
if (is_c1_compile(comp_level))
return is_not_c1_compilable();
if (is_c2_compile(comp_level))
return is_not_c2_compilable();
return false;
}
// call this when compiler finds that this method is not compilable
void Method::set_not_compilable(int comp_level, bool report, const char* reason) {
if (is_always_compilable()) {
// Don't mark a method which should be always compilable
return;
}
print_made_not_compilable(comp_level, /*is_osr*/ false, report, reason);
if (comp_level == CompLevel_all) {
set_not_c1_compilable();
set_not_c2_compilable();
} else {
if (is_c1_compile(comp_level))
set_not_c1_compilable();
if (is_c2_compile(comp_level))
set_not_c2_compilable();
}
CompilationPolicy::policy()->disable_compilation(this);
assert(!CompilationPolicy::can_be_compiled(this, comp_level), "sanity check");
}
bool Method::is_not_osr_compilable(int comp_level) const {
if (is_not_compilable(comp_level))
return true;
if (comp_level == CompLevel_any)
return is_not_c1_osr_compilable() || is_not_c2_osr_compilable();
if (is_c1_compile(comp_level))
return is_not_c1_osr_compilable();
if (is_c2_compile(comp_level))
return is_not_c2_osr_compilable();
return false;
}
void Method::set_not_osr_compilable(int comp_level, bool report, const char* reason) {
print_made_not_compilable(comp_level, /*is_osr*/ true, report, reason);
if (comp_level == CompLevel_all) {
set_not_c1_osr_compilable();
set_not_c2_osr_compilable();
} else {
if (is_c1_compile(comp_level))
set_not_c1_osr_compilable();
if (is_c2_compile(comp_level))
set_not_c2_osr_compilable();
}
CompilationPolicy::policy()->disable_compilation(this);
assert(!CompilationPolicy::can_be_osr_compiled(this, comp_level), "sanity check");
}
// Revert to using the interpreter and clear out the nmethod
void Method::clear_code() {
// this may be NULL if c2i adapters have not been made yet
// Only should happen at allocate time.
if (_adapter == NULL) {
_from_compiled_entry = NULL;
} else {
_from_compiled_entry = _adapter->get_c2i_entry();
}
OrderAccess::storestore();
_from_interpreted_entry = _i2i_entry;
OrderAccess::storestore();
_code = NULL;
}
// Called by class data sharing to remove any entry points (which are not shared)
void Method::unlink_method() {
_code = NULL;
_i2i_entry = NULL;
_from_interpreted_entry = NULL;
if (is_native()) {
*native_function_addr() = NULL;
set_signature_handler(NULL);
}
NOT_PRODUCT(set_compiled_invocation_count(0);)
_adapter = NULL;
_from_compiled_entry = NULL;
// In case of DumpSharedSpaces, _method_data should always be NULL.
//
// During runtime (!DumpSharedSpaces), when we are cleaning a
// shared class that failed to load, this->link_method() may
// have already been called (before an exception happened), so
// this->_method_data may not be NULL.
assert(!DumpSharedSpaces || _method_data == NULL, "unexpected method data?");
set_method_data(NULL);
set_method_counters(NULL);
}
// Called when the method_holder is getting linked. Setup entrypoints so the method
// is ready to be called from interpreter, compiler, and vtables.
void Method::link_method(methodHandle h_method, TRAPS) {
// If the code cache is full, we may reenter this function for the
// leftover methods that weren't linked.
if (_i2i_entry != NULL) return;
assert(_adapter == NULL, "init'd to NULL" );
assert( _code == NULL, "nothing compiled yet" );
// Setup interpreter entrypoint
assert(this == h_method(), "wrong h_method()" );
address entry = Interpreter::entry_for_method(h_method);
assert(entry != NULL, "interpreter entry must be non-null");
// Sets both _i2i_entry and _from_interpreted_entry
set_interpreter_entry(entry);
// Don't overwrite already registered native entries.
if (is_native() && !has_native_function()) {
set_native_function(
SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
!native_bind_event_is_interesting);
}
// Setup compiler entrypoint. This is made eagerly, so we do not need
// special handling of vtables. An alternative is to make adapters more
// lazily by calling make_adapter() from from_compiled_entry() for the
// normal calls. For vtable calls life gets more complicated. When a
// call-site goes mega-morphic we need adapters in all methods which can be
// called from the vtable. We need adapters on such methods that get loaded
// later. Ditto for mega-morphic itable calls. If this proves to be a
// problem we'll make these lazily later.
(void) make_adapters(h_method, CHECK);
// ONLY USE the h_method now as make_adapter may have blocked
}
address Method::make_adapters(methodHandle mh, TRAPS) {
// Adapters for compiled code are made eagerly here. They are fairly
// small (generally < 100 bytes) and quick to make (and cached and shared)
// so making them eagerly shouldn't be too expensive.
AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
if (adapter == NULL ) {
THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), "out of space in CodeCache for adapters");
}
mh->set_adapter_entry(adapter);
mh->_from_compiled_entry = adapter->get_c2i_entry();
return adapter->get_c2i_entry();
}
void Method::restore_unshareable_info(TRAPS) {
// Since restore_unshareable_info can be called more than once for a method, don't
// redo any work. If this field is restored, there is nothing to do.
if (_from_compiled_entry == NULL) {
// restore method's vtable by calling a virtual function
restore_vtable();
methodHandle mh(THREAD, this);
link_method(mh, CHECK);
}
}
// The verified_code_entry() must be called when a invoke is resolved
// on this method.
// It returns the compiled code entry point, after asserting not null.
// This function is called after potential safepoints so that nmethod
// or adapter that it points to is still live and valid.
// This function must not hit a safepoint!
address Method::verified_code_entry() {
debug_only(No_Safepoint_Verifier nsv;)
assert(_from_compiled_entry != NULL, "must be set");
return _from_compiled_entry;
}
// Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
// (could be racing a deopt).
// Not inline to avoid circular ref.
bool Method::check_code() const {
// cached in a register or local. There's a race on the value of the field.
nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
return code == NULL || (code->method() == NULL) || (code->method() == (Method*)this && !code->is_osr_method());
}
// Install compiled code. Instantly it can execute.
void Method::set_code(methodHandle mh, nmethod *code) {
assert( code, "use clear_code to remove code" );
assert( mh->check_code(), "" );
guarantee(mh->adapter() != NULL, "Adapter blob must already exist!");
// These writes must happen in this order, because the interpreter will
// directly jump to from_interpreted_entry which jumps to an i2c adapter
// which jumps to _from_compiled_entry.
mh->_code = code; // Assign before allowing compiled code to exec
int comp_level = code->comp_level();
// In theory there could be a race here. In practice it is unlikely
// and not worth worrying about.
if (comp_level > mh->highest_comp_level()) {
mh->set_highest_comp_level(comp_level);
}
OrderAccess::storestore();
#ifdef SHARK
mh->_from_interpreted_entry = code->insts_begin();
#else //!SHARK
mh->_from_compiled_entry = code->verified_entry_point();
OrderAccess::storestore();
// Instantly compiled code can execute.
if (!mh->is_method_handle_intrinsic())
mh->_from_interpreted_entry = mh->get_i2c_entry();
#endif //!SHARK
}
bool Method::is_overridden_in(Klass* k) const {
InstanceKlass* ik = InstanceKlass::cast(k);
if (ik->is_interface()) return false;
// If method is an interface, we skip it - except if it
// is a miranda method
if (method_holder()->is_interface()) {
// Check that method is not a miranda method
if (ik->lookup_method(name(), signature()) == NULL) {
// No implementation exist - so miranda method
return false;
}
return true;
}
assert(ik->is_subclass_of(method_holder()), "should be subklass");
assert(ik->vtable() != NULL, "vtable should exist");
if (!has_vtable_index()) {
return false;
} else {
Method* vt_m = ik->method_at_vtable(vtable_index());
return vt_m != this;
}
}
// give advice about whether this Method* should be cached or not
bool Method::should_not_be_cached() const {
if (is_old()) {
// This method has been redefined. It is either EMCP or obsolete
// and we don't want to cache it because that would pin the method
// down and prevent it from being collectible if and when it
// finishes executing.
return true;
}
// caching this method should be just fine
return false;
}
/**
* Returns true if this is one of the specially treated methods for
* security related stack walks (like Reflection.getCallerClass).
*/
bool Method::is_ignored_by_security_stack_walk() const {
if (intrinsic_id() == vmIntrinsics::_invoke) {
// This is Method.invoke() -- ignore it
return true;
}
if (JDK_Version::is_gte_jdk14x_version() &&
method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass())) {
// This is an auxilary frame -- ignore it
return true;
}
if (is_method_handle_intrinsic() || is_compiled_lambda_form()) {
// This is an internal adapter frame for method handles -- ignore it
return true;
}
return false;
}
// Constant pool structure for invoke methods:
enum {
_imcp_invoke_name = 1, // utf8: 'invokeExact', etc.
_imcp_invoke_signature, // utf8: (variable Symbol*)
_imcp_limit
};
// Test if this method is an MH adapter frame generated by Java code.
// Cf. java/lang/invoke/InvokerBytecodeGenerator
bool Method::is_compiled_lambda_form() const {
return intrinsic_id() == vmIntrinsics::_compiledLambdaForm;
}
// Test if this method is an internal MH primitive method.
bool Method::is_method_handle_intrinsic() const {
vmIntrinsics::ID iid = intrinsic_id();
return (MethodHandles::is_signature_polymorphic(iid) &&
MethodHandles::is_signature_polymorphic_intrinsic(iid));
}
bool Method::has_member_arg() const {
vmIntrinsics::ID iid = intrinsic_id();
return (MethodHandles::is_signature_polymorphic(iid) &&
MethodHandles::has_member_arg(iid));
}
// Make an instance of a signature-polymorphic internal MH primitive.
methodHandle Method::make_method_handle_intrinsic(vmIntrinsics::ID iid,
Symbol* signature,
TRAPS) {
ResourceMark rm;
methodHandle empty;
KlassHandle holder = SystemDictionary::MethodHandle_klass();
Symbol* name = MethodHandles::signature_polymorphic_intrinsic_name(iid);
assert(iid == MethodHandles::signature_polymorphic_name_id(name), "");
if (TraceMethodHandles) {
tty->print_cr("make_method_handle_intrinsic MH.%s%s", name->as_C_string(), signature->as_C_string());
}
// invariant: cp->symbol_at_put is preceded by a refcount increment (more usually a lookup)
name->increment_refcount();
signature->increment_refcount();
int cp_length = _imcp_limit;
ClassLoaderData* loader_data = holder->class_loader_data();
constantPoolHandle cp;
{
ConstantPool* cp_oop = ConstantPool::allocate(loader_data, cp_length, CHECK_(empty));
cp = constantPoolHandle(THREAD, cp_oop);
}
cp->set_pool_holder(InstanceKlass::cast(holder()));
cp->symbol_at_put(_imcp_invoke_name, name);
cp->symbol_at_put(_imcp_invoke_signature, signature);
cp->set_has_preresolution();
// decide on access bits: public or not?
int flags_bits = (JVM_ACC_NATIVE | JVM_ACC_SYNTHETIC | JVM_ACC_FINAL);
bool must_be_static = MethodHandles::is_signature_polymorphic_static(iid);
if (must_be_static) flags_bits |= JVM_ACC_STATIC;
assert((flags_bits & JVM_ACC_PUBLIC) == 0, "do not expose these methods");
methodHandle m;
{
InlineTableSizes sizes;
Method* m_oop = Method::allocate(loader_data, 0,
accessFlags_from(flags_bits), &sizes,
ConstMethod::NORMAL, CHECK_(empty));
m = methodHandle(THREAD, m_oop);
}
m->set_constants(cp());
m->set_name_index(_imcp_invoke_name);
m->set_signature_index(_imcp_invoke_signature);
assert(MethodHandles::is_signature_polymorphic_name(m->name()), "");
assert(m->signature() == signature, "");
#ifdef CC_INTERP
ResultTypeFinder rtf(signature);
m->set_result_index(rtf.type());
#endif
m->compute_size_of_parameters(THREAD);
m->init_intrinsic_id();
assert(m->is_method_handle_intrinsic(), "");
#ifdef ASSERT
if (!MethodHandles::is_signature_polymorphic(m->intrinsic_id())) m->print();
assert(MethodHandles::is_signature_polymorphic(m->intrinsic_id()), "must be an invoker");
assert(m->intrinsic_id() == iid, "correctly predicted iid");
#endif //ASSERT
// Finally, set up its entry points.
assert(m->can_be_statically_bound(), "");
m->set_vtable_index(Method::nonvirtual_vtable_index);
m->link_method(m, CHECK_(empty));
if (TraceMethodHandles && (Verbose || WizardMode))
m->print_on(tty);
return m;
}
Klass* Method::check_non_bcp_klass(Klass* klass) {
if (klass != NULL && klass->class_loader() != NULL) {
if (klass->oop_is_objArray())
klass = ObjArrayKlass::cast(klass)->bottom_klass();
return klass;
}
return NULL;
}
methodHandle Method::clone_with_new_data(methodHandle m, u_char* new_code, int new_code_length,
u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
// Code below does not work for native methods - they should never get rewritten anyway
assert(!m->is_native(), "cannot rewrite native methods");
// Allocate new Method*
AccessFlags flags = m->access_flags();
ConstMethod* cm = m->constMethod();
int checked_exceptions_len = cm->checked_exceptions_length();
int localvariable_len = cm->localvariable_table_length();
int exception_table_len = cm->exception_table_length();
int method_parameters_len = cm->method_parameters_length();
int method_annotations_len = cm->method_annotations_length();
int parameter_annotations_len = cm->parameter_annotations_length();
int type_annotations_len = cm->type_annotations_length();
int default_annotations_len = cm->default_annotations_length();
InlineTableSizes sizes(
localvariable_len,
new_compressed_linenumber_size,
exception_table_len,
checked_exceptions_len,
method_parameters_len,
cm->generic_signature_index(),
method_annotations_len,
parameter_annotations_len,
type_annotations_len,
default_annotations_len,
0);
ClassLoaderData* loader_data = m->method_holder()->class_loader_data();
Method* newm_oop = Method::allocate(loader_data,
new_code_length,
flags,
&sizes,
m->method_type(),
CHECK_(methodHandle()));
methodHandle newm (THREAD, newm_oop);
int new_method_size = newm->method_size();
// Create a shallow copy of Method part, but be careful to preserve the new ConstMethod*
ConstMethod* newcm = newm->constMethod();
int new_const_method_size = newm->constMethod()->size();
memcpy(newm(), m(), sizeof(Method));
// Create shallow copy of ConstMethod.
memcpy(newcm, m->constMethod(), sizeof(ConstMethod));
// Reset correct method/const method, method size, and parameter info
newm->set_constMethod(newcm);
newm->constMethod()->set_code_size(new_code_length);
newm->constMethod()->set_constMethod_size(new_const_method_size);
newm->set_method_size(new_method_size);
assert(newm->code_size() == new_code_length, "check");
assert(newm->method_parameters_length() == method_parameters_len, "check");
assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
assert(newm->exception_table_length() == exception_table_len, "check");
assert(newm->localvariable_table_length() == localvariable_len, "check");
// Copy new byte codes
memcpy(newm->code_base(), new_code, new_code_length);
// Copy line number table
if (new_compressed_linenumber_size > 0) {
memcpy(newm->compressed_linenumber_table(),
new_compressed_linenumber_table,
new_compressed_linenumber_size);
}
// Copy method_parameters
if (method_parameters_len > 0) {
memcpy(newm->method_parameters_start(),
m->method_parameters_start(),
method_parameters_len * sizeof(MethodParametersElement));
}
// Copy checked_exceptions
if (checked_exceptions_len > 0) {
memcpy(newm->checked_exceptions_start(),
m->checked_exceptions_start(),
checked_exceptions_len * sizeof(CheckedExceptionElement));
}
// Copy exception table
if (exception_table_len > 0) {
memcpy(newm->exception_table_start(),
m->exception_table_start(),
exception_table_len * sizeof(ExceptionTableElement));
}
// Copy local variable number table
if (localvariable_len > 0) {
memcpy(newm->localvariable_table_start(),
m->localvariable_table_start(),
localvariable_len * sizeof(LocalVariableTableElement));
}
// Copy stackmap table
if (m->has_stackmap_table()) {
int code_attribute_length = m->stackmap_data()->length();
Array<u1>* stackmap_data =
MetadataFactory::new_array<u1>(loader_data, code_attribute_length, 0, CHECK_NULL);
memcpy((void*)stackmap_data->adr_at(0),
(void*)m->stackmap_data()->adr_at(0), code_attribute_length);
newm->set_stackmap_data(stackmap_data);
}
// copy annotations over to new method
newcm->copy_annotations_from(cm);
return newm;
}
vmSymbols::SID Method::klass_id_for_intrinsics(Klass* holder) {
// if loader is not the default loader (i.e., != NULL), we can't know the intrinsics
// because we are not loading from core libraries
// exception: the AES intrinsics come from lib/ext/sunjce_provider.jar
// which does not use the class default class loader so we check for its loader here
InstanceKlass* ik = InstanceKlass::cast(holder);
if ((ik->class_loader() != NULL) && !SystemDictionary::is_ext_class_loader(ik->class_loader())) {
return vmSymbols::NO_SID; // regardless of name, no intrinsics here
}
// see if the klass name is well-known:
Symbol* klass_name = ik->name();
return vmSymbols::find_sid(klass_name);
}
void Method::init_intrinsic_id() {
assert(_intrinsic_id == vmIntrinsics::_none, "do this just once");
const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte));
assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size");
assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), "");
// the klass name is well-known:
vmSymbols::SID klass_id = klass_id_for_intrinsics(method_holder());
assert(klass_id != vmSymbols::NO_SID, "caller responsibility");
// ditto for method and signature:
vmSymbols::SID name_id = vmSymbols::find_sid(name());
if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
&& name_id == vmSymbols::NO_SID)
return;
vmSymbols::SID sig_id = vmSymbols::find_sid(signature());
if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
&& sig_id == vmSymbols::NO_SID) return;
jshort flags = access_flags().as_short();
vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
if (id != vmIntrinsics::_none) {
set_intrinsic_id(id);
return;
}
// A few slightly irregular cases:
switch (klass_id) {
case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_StrictMath):
// Second chance: check in regular Math.
switch (name_id) {
case vmSymbols::VM_SYMBOL_ENUM_NAME(min_name):
case vmSymbols::VM_SYMBOL_ENUM_NAME(max_name):
case vmSymbols::VM_SYMBOL_ENUM_NAME(sqrt_name):
// pretend it is the corresponding method in the non-strict class:
klass_id = vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_Math);
id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
break;
}
break;
// Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*.
case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle):
if (!is_native()) break;
id = MethodHandles::signature_polymorphic_name_id(method_holder(), name());
if (is_static() != MethodHandles::is_signature_polymorphic_static(id))
id = vmIntrinsics::_none;
break;
}
if (id != vmIntrinsics::_none) {
// Set up its iid. It is an alias method.
set_intrinsic_id(id);
return;
}
}
// These two methods are static since a GC may move the Method
bool Method::load_signature_classes(methodHandle m, TRAPS) {
if (THREAD->is_Compiler_thread()) {
// There is nothing useful this routine can do from within the Compile thread.
// Hopefully, the signature contains only well-known classes.
// We could scan for this and return true/false, but the caller won't care.
return false;
}
bool sig_is_loaded = true;
Handle class_loader(THREAD, m->method_holder()->class_loader());
Handle protection_domain(THREAD, m->method_holder()->protection_domain());
ResourceMark rm(THREAD);
Symbol* signature = m->signature();
for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
if (ss.is_object()) {
Symbol* sym = ss.as_symbol(CHECK_(false));
Symbol* name = sym;
Klass* klass = SystemDictionary::resolve_or_null(name, class_loader,
protection_domain, THREAD);
// We are loading classes eagerly. If a ClassNotFoundException or
// a LinkageError was generated, be sure to ignore it.
if (HAS_PENDING_EXCEPTION) {
if (PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass()) ||
PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
CLEAR_PENDING_EXCEPTION;
} else {
return false;
}
}
if( klass == NULL) { sig_is_loaded = false; }
}
}
return sig_is_loaded;
}
bool Method::has_unloaded_classes_in_signature(methodHandle m, TRAPS) {
Handle class_loader(THREAD, m->method_holder()->class_loader());
Handle protection_domain(THREAD, m->method_holder()->protection_domain());
ResourceMark rm(THREAD);
Symbol* signature = m->signature();
for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
if (ss.type() == T_OBJECT) {
Symbol* name = ss.as_symbol_or_null();
if (name == NULL) return true;
Klass* klass = SystemDictionary::find(name, class_loader, protection_domain, THREAD);
if (klass == NULL) return true;
}
}
return false;
}
// Exposed so field engineers can debug VM
void Method::print_short_name(outputStream* st) {
ResourceMark rm;
#ifdef PRODUCT
st->print(" %s::", method_holder()->external_name());
#else
st->print(" %s::", method_holder()->internal_name());
#endif
name()->print_symbol_on(st);
if (WizardMode) signature()->print_symbol_on(st);
else if (MethodHandles::is_signature_polymorphic(intrinsic_id()))
MethodHandles::print_as_basic_type_signature_on(st, signature(), true);
}
// Comparer for sorting an object array containing
// Method*s.
static int method_comparator(Method* a, Method* b) {
return a->name()->fast_compare(b->name());
}
// This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
// default_methods also uses this without the ordering for fast find_method
void Method::sort_methods(Array<Method*>* methods, bool idempotent, bool set_idnums) {
int length = methods->length();
if (length > 1) {
{
No_Safepoint_Verifier nsv;
QuickSort::sort<Method*>(methods->data(), length, method_comparator, idempotent);
}
// Reset method ordering
if (set_idnums) {
for (int i = 0; i < length; i++) {
Method* m = methods->at(i);
m->set_method_idnum(i);
}
}
}
}
//-----------------------------------------------------------------------------------
// Non-product code unless JVM/TI needs it
#if !defined(PRODUCT) || INCLUDE_JVMTI
class SignatureTypePrinter : public SignatureTypeNames {
private:
outputStream* _st;
bool _use_separator;
void type_name(const char* name) {
if (_use_separator) _st->print(", ");
_st->print(name);
_use_separator = true;
}
public:
SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) {
_st = st;
_use_separator = false;
}
void print_parameters() { _use_separator = false; iterate_parameters(); }
void print_returntype() { _use_separator = false; iterate_returntype(); }
};
void Method::print_name(outputStream* st) {
Thread *thread = Thread::current();
ResourceMark rm(thread);
SignatureTypePrinter sig(signature(), st);
st->print("%s ", is_static() ? "static" : "virtual");
sig.print_returntype();
st->print(" %s.", method_holder()->internal_name());
name()->print_symbol_on(st);
st->print("(");
sig.print_parameters();
st->print(")");
}
#endif // !PRODUCT || INCLUDE_JVMTI
void Method::print_codes_on(outputStream* st) const {
print_codes_on(0, code_size(), st);
}
void Method::print_codes_on(int from, int to, outputStream* st) const {
Thread *thread = Thread::current();
ResourceMark rm(thread);
methodHandle mh (thread, (Method*)this);
BytecodeStream s(mh);
s.set_interval(from, to);
BytecodeTracer::set_closure(BytecodeTracer::std_closure());
while (s.next() >= 0) BytecodeTracer::trace(mh, s.bcp(), st);
}
// Simple compression of line number tables. We use a regular compressed stream, except that we compress deltas
// between (bci,line) pairs since they are smaller. If (bci delta, line delta) fits in (5-bit unsigned, 3-bit unsigned)
// we save it as one byte, otherwise we write a 0xFF escape character and use regular compression. 0x0 is used
// as end-of-stream terminator.
void CompressedLineNumberWriteStream::write_pair_regular(int bci_delta, int line_delta) {
// bci and line number does not compress into single byte.
// Write out escape character and use regular compression for bci and line number.
write_byte((jubyte)0xFF);
write_signed_int(bci_delta);
write_signed_int(line_delta);
}
// See comment in method.hpp which explains why this exists.
#if defined(_M_AMD64) && _MSC_VER >= 1400
#pragma optimize("", off)
void CompressedLineNumberWriteStream::write_pair(int bci, int line) {
write_pair_inline(bci, line);
}
#pragma optimize("", on)
#endif
CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
_bci = 0;
_line = 0;
};
bool CompressedLineNumberReadStream::read_pair() {
jubyte next = read_byte();
// Check for terminator
if (next == 0) return false;
if (next == 0xFF) {
// Escape character, regular compression used
_bci += read_signed_int();
_line += read_signed_int();
} else {
// Single byte compression used
_bci += next >> 3;
_line += next & 0x7;
}
return true;
}
Bytecodes::Code Method::orig_bytecode_at(int bci) const {
BreakpointInfo* bp = method_holder()->breakpoints();
for (; bp != NULL; bp = bp->next()) {
if (bp->match(this, bci)) {
return bp->orig_bytecode();
}
}
{
ResourceMark rm;
fatal(err_msg("no original bytecode found in %s at bci %d", name_and_sig_as_C_string(), bci));
}
return Bytecodes::_shouldnotreachhere;
}
void Method::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
BreakpointInfo* bp = method_holder()->breakpoints();
for (; bp != NULL; bp = bp->next()) {
if (bp->match(this, bci)) {
bp->set_orig_bytecode(code);
// and continue, in case there is more than one
}
}
}
void Method::set_breakpoint(int bci) {
InstanceKlass* ik = method_holder();
BreakpointInfo *bp = new BreakpointInfo(this, bci);
bp->set_next(ik->breakpoints());
ik->set_breakpoints(bp);
// do this last:
bp->set(this);
}
static void clear_matches(Method* m, int bci) {
InstanceKlass* ik = m->method_holder();
BreakpointInfo* prev_bp = NULL;
BreakpointInfo* next_bp;
for (BreakpointInfo* bp = ik->breakpoints(); bp != NULL; bp = next_bp) {
next_bp = bp->next();
// bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
// do this first:
bp->clear(m);
// unhook it
if (prev_bp != NULL)
prev_bp->set_next(next_bp);
else
ik->set_breakpoints(next_bp);
delete bp;
// When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
// at same location. So we have multiple matching (method_index and bci)
// BreakpointInfo nodes in BreakpointInfo list. We should just delete one
// breakpoint for clear_breakpoint request and keep all other method versions
// BreakpointInfo for future clear_breakpoint request.
// bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
// which is being called when class is unloaded. We delete all the Breakpoint
// information for all versions of method. We may not correctly restore the original
// bytecode in all method versions, but that is ok. Because the class is being unloaded
// so these methods won't be used anymore.
if (bci >= 0) {
break;
}
} else {
// This one is a keeper.
prev_bp = bp;
}
}
}
void Method::clear_breakpoint(int bci) {
assert(bci >= 0, "");
clear_matches(this, bci);
}
void Method::clear_all_breakpoints() {
clear_matches(this, -1);
}
int Method::invocation_count() {
MethodCounters *mcs = method_counters();
if (TieredCompilation) {
MethodData* const mdo = method_data();
if (((mcs != NULL) ? mcs->invocation_counter()->carry() : false) ||
((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
return InvocationCounter::count_limit;
} else {
return ((mcs != NULL) ? mcs->invocation_counter()->count() : 0) +
((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
}
} else {
return (mcs == NULL) ? 0 : mcs->invocation_counter()->count();
}
}
int Method::backedge_count() {
MethodCounters *mcs = method_counters();
if (TieredCompilation) {
MethodData* const mdo = method_data();
if (((mcs != NULL) ? mcs->backedge_counter()->carry() : false) ||
((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
return InvocationCounter::count_limit;
} else {
return ((mcs != NULL) ? mcs->backedge_counter()->count() : 0) +
((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
}
} else {
return (mcs == NULL) ? 0 : mcs->backedge_counter()->count();
}
}
int Method::highest_comp_level() const {
const MethodData* mdo = method_data();
if (mdo != NULL) {
return mdo->highest_comp_level();
} else {
return CompLevel_none;
}
}
int Method::highest_osr_comp_level() const {
const MethodData* mdo = method_data();
if (mdo != NULL) {
return mdo->highest_osr_comp_level();
} else {
return CompLevel_none;
}
}
void Method::set_highest_comp_level(int level) {
MethodData* mdo = method_data();
if (mdo != NULL) {
mdo->set_highest_comp_level(level);
}
}
void Method::set_highest_osr_comp_level(int level) {
MethodData* mdo = method_data();
if (mdo != NULL) {
mdo->set_highest_osr_comp_level(level);
}
}
BreakpointInfo::BreakpointInfo(Method* m, int bci) {
_bci = bci;
_name_index = m->name_index();
_signature_index = m->signature_index();
_orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
if (_orig_bytecode == Bytecodes::_breakpoint)
_orig_bytecode = m->orig_bytecode_at(_bci);
_next = NULL;
}
void BreakpointInfo::set(Method* method) {
#ifdef ASSERT
{
Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
if (code == Bytecodes::_breakpoint)
code = method->orig_bytecode_at(_bci);
assert(orig_bytecode() == code, "original bytecode must be the same");
}
#endif
Thread *thread = Thread::current();
*method->bcp_from(_bci) = Bytecodes::_breakpoint;
method->incr_number_of_breakpoints(thread);
SystemDictionary::notice_modification();
{
// Deoptimize all dependents on this method
HandleMark hm(thread);
methodHandle mh(thread, method);
Universe::flush_dependents_on_method(mh);
}
}
void BreakpointInfo::clear(Method* method) {
*method->bcp_from(_bci) = orig_bytecode();
assert(method->number_of_breakpoints() > 0, "must not go negative");
method->decr_number_of_breakpoints(Thread::current());
}
// jmethodID handling
// This is a block allocating object, sort of like JNIHandleBlock, only a
// lot simpler. There aren't many of these, they aren't long, they are rarely
// deleted and so we can do some suboptimal things.
// It's allocated on the CHeap because once we allocate a jmethodID, we can
// never get rid of it.
// It would be nice to be able to parameterize the number of methods for
// the null_class_loader but then we'd have to turn this and ClassLoaderData
// into templates.
// I feel like this brain dead class should exist somewhere in the STL
class JNIMethodBlock : public CHeapObj<mtClass> {
enum { number_of_methods = 8 };
Method* _methods[number_of_methods];
int _top;
JNIMethodBlock* _next;
public:
static Method* const _free_method;
JNIMethodBlock() : _next(NULL), _top(0) {
for (int i = 0; i< number_of_methods; i++) _methods[i] = _free_method;
}
Method** add_method(Method* m) {
if (_top < number_of_methods) {
// top points to the next free entry.
int i = _top;
_methods[i] = m;
_top++;
return &_methods[i];
} else if (_top == number_of_methods) {
// if the next free entry ran off the block see if there's a free entry
for (int i = 0; i< number_of_methods; i++) {
if (_methods[i] == _free_method) {
_methods[i] = m;
return &_methods[i];
}
}
// Only check each block once for frees. They're very unlikely.
// Increment top past the end of the block.
_top++;
}
// need to allocate a next block.
if (_next == NULL) {
_next = new JNIMethodBlock();
}
return _next->add_method(m);
}
bool contains(Method** m) {
for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
for (int i = 0; i< number_of_methods; i++) {
if (&(b->_methods[i]) == m) {
return true;
}
}
}
return false; // not found
}
// Doesn't really destroy it, just marks it as free so it can be reused.
void destroy_method(Method** m) {
#ifdef ASSERT
assert(contains(m), "should be a methodID");
#endif // ASSERT
*m = _free_method;
}
// During class unloading the methods are cleared, which is different
// than freed.
void clear_all_methods() {
for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
for (int i = 0; i< number_of_methods; i++) {
_methods[i] = NULL;
}
}
}
#ifndef PRODUCT
int count_methods() {
// count all allocated methods
int count = 0;
for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
for (int i = 0; i< number_of_methods; i++) {
if (_methods[i] != _free_method) count++;
}
}
return count;
}
#endif // PRODUCT
};
// Something that can't be mistaken for an address or a markOop
Method* const JNIMethodBlock::_free_method = (Method*)55;
// Add a method id to the jmethod_ids
jmethodID Method::make_jmethod_id(ClassLoaderData* loader_data, Method* m) {
ClassLoaderData* cld = loader_data;
if (!SafepointSynchronize::is_at_safepoint()) {
// Have to add jmethod_ids() to class loader data thread-safely.
// Also have to add the method to the list safely, which the cld lock
// protects as well.
MutexLockerEx ml(cld->metaspace_lock(), Mutex::_no_safepoint_check_flag);
if (cld->jmethod_ids() == NULL) {
cld->set_jmethod_ids(new JNIMethodBlock());
}
// jmethodID is a pointer to Method*
return (jmethodID)cld->jmethod_ids()->add_method(m);
} else {
// At safepoint, we are single threaded and can set this.
if (cld->jmethod_ids() == NULL) {
cld->set_jmethod_ids(new JNIMethodBlock());
}
// jmethodID is a pointer to Method*
return (jmethodID)cld->jmethod_ids()->add_method(m);
}
}
// Mark a jmethodID as free. This is called when there is a data race in
// InstanceKlass while creating the jmethodID cache.
void Method::destroy_jmethod_id(ClassLoaderData* loader_data, jmethodID m) {
ClassLoaderData* cld = loader_data;
Method** ptr = (Method**)m;
assert(cld->jmethod_ids() != NULL, "should have method handles");
cld->jmethod_ids()->destroy_method(ptr);
}
void Method::change_method_associated_with_jmethod_id(jmethodID jmid, Method* new_method) {
// Can't assert the method_holder is the same because the new method has the
// scratch method holder.
assert(resolve_jmethod_id(jmid)->method_holder()->class_loader()
== new_method->method_holder()->class_loader(),
"changing to a different class loader");
// Just change the method in place, jmethodID pointer doesn't change.
*((Method**)jmid) = new_method;
}
bool Method::is_method_id(jmethodID mid) {
Method* m = resolve_jmethod_id(mid);
assert(m != NULL, "should be called with non-null method");
InstanceKlass* ik = m->method_holder();
ClassLoaderData* cld = ik->class_loader_data();
if (cld->jmethod_ids() == NULL) return false;
return (cld->jmethod_ids()->contains((Method**)mid));
}
Method* Method::checked_resolve_jmethod_id(jmethodID mid) {
if (mid == NULL) return NULL;
Method* o = resolve_jmethod_id(mid);
if (o == NULL || o == JNIMethodBlock::_free_method || !((Metadata*)o)->is_method()) {
return NULL;
}
return o;
};
void Method::set_on_stack(const bool value) {
// Set both the method itself and its constant pool. The constant pool
// on stack means some method referring to it is also on the stack.
_access_flags.set_on_stack(value);
constants()->set_on_stack(value);
if (value) MetadataOnStackMark::record(this);
}
// Called when the class loader is unloaded to make all methods weak.
void Method::clear_jmethod_ids(ClassLoaderData* loader_data) {
loader_data->jmethod_ids()->clear_all_methods();
}
// Check that this pointer is valid by checking that the vtbl pointer matches
bool Method::is_valid_method() const {
if (this == NULL) {
return false;
} else if (!is_metaspace_object()) {
return false;
} else {
Method m;
// This assumes that the vtbl pointer is the first word of a C++ object.
// This assumption is also in universe.cpp patch_klass_vtble
void* vtbl2 = dereference_vptr((void*)&m);
void* this_vtbl = dereference_vptr((void*)this);
return vtbl2 == this_vtbl;
}
}
#ifndef PRODUCT
void Method::print_jmethod_ids(ClassLoaderData* loader_data, outputStream* out) {
out->print_cr("jni_method_id count = %d", loader_data->jmethod_ids()->count_methods());
}
#endif // PRODUCT
// Printing
#ifndef PRODUCT
void Method::print_on(outputStream* st) const {
ResourceMark rm;
assert(is_method(), "must be method");
st->print_cr(internal_name());
// get the effect of PrintOopAddress, always, for methods:
st->print_cr(" - this oop: "INTPTR_FORMAT, (intptr_t)this);
st->print (" - method holder: "); method_holder()->print_value_on(st); st->cr();
st->print (" - constants: "INTPTR_FORMAT" ", (address)constants());
constants()->print_value_on(st); st->cr();
st->print (" - access: 0x%x ", access_flags().as_int()); access_flags().print_on(st); st->cr();
st->print (" - name: "); name()->print_value_on(st); st->cr();
st->print (" - signature: "); signature()->print_value_on(st); st->cr();
st->print_cr(" - max stack: %d", max_stack());
st->print_cr(" - max locals: %d", max_locals());
st->print_cr(" - size of params: %d", size_of_parameters());
st->print_cr(" - method size: %d", method_size());
if (intrinsic_id() != vmIntrinsics::_none)
st->print_cr(" - intrinsic id: %d %s", intrinsic_id(), vmIntrinsics::name_at(intrinsic_id()));
if (highest_comp_level() != CompLevel_none)
st->print_cr(" - highest level: %d", highest_comp_level());
st->print_cr(" - vtable index: %d", _vtable_index);
st->print_cr(" - i2i entry: " INTPTR_FORMAT, interpreter_entry());
st->print( " - adapters: ");
AdapterHandlerEntry* a = ((Method*)this)->adapter();
if (a == NULL)
st->print_cr(INTPTR_FORMAT, a);
else
a->print_adapter_on(st);
st->print_cr(" - compiled entry " INTPTR_FORMAT, from_compiled_entry());
st->print_cr(" - code size: %d", code_size());
if (code_size() != 0) {
st->print_cr(" - code start: " INTPTR_FORMAT, code_base());
st->print_cr(" - code end (excl): " INTPTR_FORMAT, code_base() + code_size());
}
if (method_data() != NULL) {
st->print_cr(" - method data: " INTPTR_FORMAT, (address)method_data());
}
st->print_cr(" - checked ex length: %d", checked_exceptions_length());
if (checked_exceptions_length() > 0) {
CheckedExceptionElement* table = checked_exceptions_start();
st->print_cr(" - checked ex start: " INTPTR_FORMAT, table);
if (Verbose) {
for (int i = 0; i < checked_exceptions_length(); i++) {
st->print_cr(" - throws %s", constants()->printable_name_at(table[i].class_cp_index));
}
}
}
if (has_linenumber_table()) {
u_char* table = compressed_linenumber_table();
st->print_cr(" - linenumber start: " INTPTR_FORMAT, table);
if (Verbose) {
CompressedLineNumberReadStream stream(table);
while (stream.read_pair()) {
st->print_cr(" - line %d: %d", stream.line(), stream.bci());
}
}
}
st->print_cr(" - localvar length: %d", localvariable_table_length());
if (localvariable_table_length() > 0) {
LocalVariableTableElement* table = localvariable_table_start();
st->print_cr(" - localvar start: " INTPTR_FORMAT, table);
if (Verbose) {
for (int i = 0; i < localvariable_table_length(); i++) {
int bci = table[i].start_bci;
int len = table[i].length;
const char* name = constants()->printable_name_at(table[i].name_cp_index);
const char* desc = constants()->printable_name_at(table[i].descriptor_cp_index);
int slot = table[i].slot;
st->print_cr(" - %s %s bci=%d len=%d slot=%d", desc, name, bci, len, slot);
}
}
}
if (code() != NULL) {
st->print (" - compiled code: ");
code()->print_value_on(st);
}
if (is_native()) {
st->print_cr(" - native function: " INTPTR_FORMAT, native_function());
st->print_cr(" - signature handler: " INTPTR_FORMAT, signature_handler());
}
}
#endif //PRODUCT
void Method::print_value_on(outputStream* st) const {
assert(is_method(), "must be method");
st->print(internal_name());
print_address_on(st);
st->print(" ");
name()->print_value_on(st);
st->print(" ");
signature()->print_value_on(st);
st->print(" in ");
method_holder()->print_value_on(st);
if (WizardMode) st->print("#%d", _vtable_index);
if (WizardMode) st->print("[%d,%d]", size_of_parameters(), max_locals());
if (WizardMode && code() != NULL) st->print(" ((nmethod*)%p)", code());
}
#if INCLUDE_SERVICES
// Size Statistics
void Method::collect_statistics(KlassSizeStats *sz) const {
int mysize = sz->count(this);
sz->_method_bytes += mysize;
sz->_method_all_bytes += mysize;
sz->_rw_bytes += mysize;
if (constMethod()) {
constMethod()->collect_statistics(sz);
}
if (method_data()) {
method_data()->collect_statistics(sz);
}
}
#endif // INCLUDE_SERVICES
// Verification
void Method::verify_on(outputStream* st) {
guarantee(is_method(), "object must be method");
guarantee(constants()->is_constantPool(), "should be constant pool");
guarantee(constMethod()->is_constMethod(), "should be ConstMethod*");
MethodData* md = method_data();
guarantee(md == NULL ||
md->is_methodData(), "should be method data");
}
| [
"yuri.gaevsky@gmail.com"
] | yuri.gaevsky@gmail.com |
2aa5f2c07c1b1d67da95565066319d9becf2224e | 41a76318e5b9eef2c69bbf922724f8b191d7d124 | /kokkos/core/unit_test/threads/TestThreads_FunctorAnalysis.cpp | 7fe71715e0612fd3e148c38f81e0a83f393ca19c | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | zishengye/compadre | d0ff10deca224284e7e153371a738e053e66012a | 75b738a6a613c89e3c3232cbf7b2589a6b28d0a3 | refs/heads/master | 2021-06-25T06:16:38.327543 | 2021-04-02T02:08:48 | 2021-04-02T02:08:48 | 223,650,267 | 0 | 0 | NOASSERTION | 2019-11-23T20:41:03 | 2019-11-23T20:41:02 | null | UTF-8 | C++ | false | false | 2,086 | cpp |
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <threads/TestThreads_Category.hpp>
#include <TestFunctorAnalysis.hpp>
| [
"pakuber@sandia.gov"
] | pakuber@sandia.gov |
46b6f260a7cbbee178e6f3d32661dd537267b6ff | 12515ec6948c38434342fc051b42d3c6e7d63264 | /opengl/IOEvent.cpp | 80da3f16b40b8eea3c85f4d1629a37df2c466072 | [
"Apache-2.0"
] | permissive | yanshil/Nova_Examples | cad6cfe9c187110e7f6fc24c2fdc88a2d1ab5b60 | 0807c5a3bc24e4f3efc399f424e2e4fb0da2d4fe | refs/heads/master | 2020-04-14T01:05:03.423866 | 2018-12-30T01:03:25 | 2018-12-30T01:03:25 | 163,551,524 | 0 | 0 | Apache-2.0 | 2018-12-30T00:49:36 | 2018-12-30T00:49:36 | null | UTF-8 | C++ | false | false | 13,911 | cpp | #include "IOEvent.h"
int Nova::IOEvent::TranslateAction( std::string code ){
if( code == "M_MOTION" )
return M_MOTION;
if( code == "M_UP" )
return M_UP;
if( code == "M_DOWN" )
return M_DOWN;
if( code == "M_SCROLL" )
return M_SCROLL;
if( code == "K_UP" )
return K_UP;
if( code == "K_DOWN" )
return K_DOWN;
if( code == "K_HOLD" )
return K_HOLD;
return -1;
}
int Nova::IOEvent::TranslateModifier( std::string code ){
if( code == "MOD_SHIFT" )
return mSHIFT;
if( code == "MOD_CONTROL" )
return mCONTROL;
if( code == "MOD_ALT" )
return mALT;
if( code == "MOD_SUPER" )
return mSUPER;
return -1;
}
int Nova::IOEvent::TranslateCode( std::string code ){
if( code == "M_LEFT" )
return M_LEFT;
if( code == "M_RIGHT" )
return M_RIGHT;
if( code == "M_MIDDLE" )
return M_MIDDLE;
if( code == "M_MOVE" )
return M_MOVE;
if( code == "KEY_SPACE" )
return KEY_SPACE;
if( code == "KEY_APOSTROPHE" )
return KEY_APOSTROPHE;
if( code == "KEY_COMMA" )
return KEY_COMMA;
if( code == "KEY_MINUS" )
return KEY_MINUS;
if( code == "KEY_PERIOD" )
return KEY_PERIOD;
if( code == "KEY_SLASH" )
return KEY_SLASH;
if( code == "KEY_0" )
return KEY_0;
if( code == "KEY_1" )
return KEY_1;
if( code == "KEY_2" )
return KEY_2;
if( code == "KEY_3" )
return KEY_3;
if( code == "KEY_4" )
return KEY_4;
if( code == "KEY_5" )
return KEY_5;
if( code == "KEY_6" )
return KEY_6;
if( code == "KEY_7" )
return KEY_7;
if( code == "KEY_8" )
return KEY_8;
if( code == "KEY_9" )
return KEY_9;
if( code == "KEY_SEMICOLON" )
return KEY_SEMICOLON;
if( code == "KEY_EQUAL" )
return KEY_EQUAL;
if( code == "KEY_A" )
return KEY_A;
if( code == "KEY_B" )
return KEY_B;
if( code == "KEY_C" )
return KEY_C;
if( code == "KEY_D" )
return KEY_D;
if( code == "KEY_E" )
return KEY_E;
if( code == "KEY_F" )
return KEY_F;
if( code == "KEY_G" )
return KEY_G;
if( code == "KEY_H" )
return KEY_H;
if( code == "KEY_I" )
return KEY_I;
if( code == "KEY_J" )
return KEY_J;
if( code == "KEY_K" )
return KEY_K;
if( code == "KEY_L" )
return KEY_L;
if( code == "KEY_M" )
return KEY_M;
if( code == "KEY_N" )
return KEY_N;
if( code == "KEY_O" )
return KEY_O;
if( code == "KEY_P" )
return KEY_P;
if( code == "KEY_Q" )
return KEY_Q;
if( code == "KEY_R" )
return KEY_R;
if( code == "KEY_S" )
return KEY_S;
if( code == "KEY_T" )
return KEY_T;
if( code == "KEY_U" )
return KEY_U;
if( code == "KEY_V" )
return KEY_V;
if( code == "KEY_W" )
return KEY_W;
if( code == "KEY_X" )
return KEY_X;
if( code == "KEY_Y" )
return KEY_Y;
if( code == "KEY_Z" )
return KEY_Z;
if( code == "KEY_LEFT_BRACKET" )
return KEY_LEFT_BRACKET;
if( code == "KEY_BACKSLASH" )
return KEY_BACKSLASH;
if( code == "KEY_RIGHT_BRACKET" )
return KEY_RIGHT_BRACKET;
if( code == "KEY_GRAVE_ACCENT" )
return KEY_GRAVE_ACCENT;
if( code == "KEY_WORLD_1" )
return KEY_WORLD_1;
if( code == "KEY_WORLD_2" )
return KEY_WORLD_2;
if( code == "KEY_ESCAPE" )
return KEY_ESCAPE;
if( code == "KEY_ENTER" )
return KEY_ENTER;
if( code == "KEY_TAB" )
return KEY_TAB;
if( code == "KEY_BACKSPACE" )
return KEY_BACKSPACE;
if( code == "KEY_INSERT" )
return KEY_INSERT;
if( code == "KEY_DELETE" )
return KEY_DELETE;
if( code == "KEY_RIGHT" )
return KEY_RIGHT;
if( code == "KEY_LEFT" )
return KEY_LEFT;
if( code == "KEY_DOWN" )
return KEY_DOWN;
if( code == "KEY_UP" )
return KEY_UP;
if( code == "KEY_PAGE_UP" )
return KEY_PAGE_UP;
if( code == "KEY_PAGE_DOWN" )
return KEY_PAGE_DOWN;
if( code == "KEY_HOME" )
return KEY_HOME;
if( code == "KEY_END" )
return KEY_END;
if( code == "KEY_CAPS_LOCK" )
return KEY_CAPS_LOCK;
if( code == "KEY_SCROLL_LOCK" )
return KEY_SCROLL_LOCK;
if( code == "KEY_NUM_LOCK" )
return KEY_NUM_LOCK;
if( code == "KEY_PRINT_SCREEN" )
return KEY_PRINT_SCREEN;
if( code == "KEY_PAUSE" )
return KEY_PAUSE;
if( code == "KEY_F1" )
return KEY_F1;
if( code == "KEY_F2" )
return KEY_F2;
if( code == "KEY_F3" )
return KEY_F3;
if( code == "KEY_F4" )
return KEY_F4;
if( code == "KEY_F5" )
return KEY_F5;
if( code == "KEY_F6" )
return KEY_F6;
if( code == "KEY_F7" )
return KEY_F7;
if( code == "KEY_F8" )
return KEY_F8;
if( code == "KEY_F9" )
return KEY_F9;
if( code == "KEY_F10" )
return KEY_F10;
if( code == "KEY_F11" )
return KEY_F11;
if( code == "KEY_F12" )
return KEY_F12;
if( code == "KEY_F13" )
return KEY_F13;
if( code == "KEY_F14" )
return KEY_F14;
if( code == "KEY_F15" )
return KEY_F15;
if( code == "KEY_F16" )
return KEY_F16;
if( code == "KEY_F17" )
return KEY_F17;
if( code == "KEY_F18" )
return KEY_F18;
if( code == "KEY_F19" )
return KEY_F19;
if( code == "KEY_F20" )
return KEY_F20;
if( code == "KEY_F21" )
return KEY_F21;
if( code == "KEY_F22" )
return KEY_F22;
if( code == "KEY_F23" )
return KEY_F23;
if( code == "KEY_F24" )
return KEY_F24;
if( code == "KEY_F25" )
return KEY_F25;
if( code == "KEY_KP_0" )
return KEY_KP_0;
if( code == "KEY_KP_1" )
return KEY_KP_1;
if( code == "KEY_KP_2" )
return KEY_KP_2;
if( code == "KEY_KP_3" )
return KEY_KP_3;
if( code == "KEY_KP_4" )
return KEY_KP_4;
if( code == "KEY_KP_5" )
return KEY_KP_5;
if( code == "KEY_KP_6" )
return KEY_KP_6;
if( code == "KEY_KP_7" )
return KEY_KP_7;
if( code == "KEY_KP_8" )
return KEY_KP_8;
if( code == "KEY_KP_9" )
return KEY_KP_9;
if( code == "KEY_KP_DECIMAL" )
return KEY_KP_DECIMAL;
if( code == "KEY_KP_DIVIDE" )
return KEY_KP_DIVIDE;
if( code == "KEY_KP_MULTIPLY" )
return KEY_KP_MULTIPLY;
if( code == "KEY_KP_SUBTRACT" )
return KEY_KP_SUBTRACT;
if( code == "KEY_KP_ADD" )
return KEY_KP_ADD;
if( code == "KEY_KP_ENTER" )
return KEY_KP_ENTER;
if( code == "KEY_KP_EQUAL" )
return KEY_KP_EQUAL;
if( code == "KEY_LEFT_SHIFT" )
return KEY_LEFT_SHIFT;
if( code == "KEY_LEFT_CONTROL" )
return KEY_LEFT_CONTROL;
if( code == "KEY_LEFT_ALT" )
return KEY_LEFT_ALT;
if( code == "KEY_LEFT_SUPER" )
return KEY_LEFT_SUPER;
if( code == "KEY_RIGHT_SHIFT" )
return KEY_RIGHT_SHIFT;
if( code == "KEY_RIGHT_CONTROL" )
return KEY_RIGHT_CONTROL;
if( code == "KEY_RIGHT_ALT" )
return KEY_RIGHT_ALT;
if( code == "KEY_RIGHT_SUPER" )
return KEY_RIGHT_SUPER;
if( code == "KEY_MENU" )
return KEY_MENU;
return -1;
}
std::string Nova::IOEvent::TranslateCode( int code ){
if( code == M_LEFT )
return "LEFT_MOUSE";
if( code == M_RIGHT )
return "RIGHT_MOUSE";
if( code == M_MIDDLE )
return "MIDDLE_MOUSE";
if( code == M_MOVE )
return "MOVE_MOUSE";
if( code == KEY_SPACE )
return "[SPACE]";
if( code == KEY_APOSTROPHE )
return "'";
if( code == KEY_COMMA )
return ",";
if( code == KEY_MINUS )
return "-";
if( code == KEY_PERIOD )
return ".";
if( code == KEY_SLASH )
return "/";
if( code == KEY_0 )
return "0";
if( code == KEY_1 )
return "1";
if( code == KEY_2 )
return "2";
if( code == KEY_3 )
return "3";
if( code == KEY_4 )
return "4";
if( code == KEY_5 )
return "5";
if( code == KEY_6 )
return "6";
if( code == KEY_7 )
return "7";
if( code == KEY_8 )
return "8";
if( code == KEY_9 )
return "9";
if( code == KEY_SEMICOLON )
return ";";
if( code == KEY_EQUAL )
return "=";
if( code == KEY_A )
return "A";
if( code == KEY_B )
return "B";
if( code == KEY_C )
return "C";
if( code == KEY_D )
return "D";
if( code == KEY_E )
return "E";
if( code == KEY_F )
return "F";
if( code == KEY_G )
return "G";
if( code == KEY_H )
return "H";
if( code == KEY_I )
return "I";
if( code == KEY_J )
return "J";
if( code == KEY_K )
return "K";
if( code == KEY_L )
return "L";
if( code == KEY_M )
return "M";
if( code == KEY_N )
return "N";
if( code == KEY_O )
return "O";
if( code == KEY_P )
return "P";
if( code == KEY_Q )
return "Q";
if( code == KEY_R )
return "R";
if( code == KEY_S )
return "S";
if( code == KEY_T )
return "T";
if( code == KEY_U )
return "U";
if( code == KEY_V )
return "V";
if( code == KEY_W )
return "W";
if( code == KEY_X )
return "X";
if( code == KEY_Y )
return "Y";
if( code == KEY_Z )
return "Z";
if( code == KEY_LEFT_BRACKET )
return "[";
if( code == KEY_BACKSLASH )
return "\\";
if( code == KEY_RIGHT_BRACKET )
return "]";
if( code == KEY_GRAVE_ACCENT )
return "`";
if( code == KEY_WORLD_1 )
return "WORLD_1";
if( code == KEY_WORLD_2 )
return "WORLD_2";
if( code == KEY_ESCAPE )
return "[ESCAPE]";
if( code == KEY_ENTER )
return "[ENTER]";
if( code == KEY_TAB )
return "[TAB]";
if( code == KEY_BACKSPACE )
return "[BACKSPACE]";
if( code == KEY_INSERT )
return "[INSERT]";
if( code == KEY_DELETE )
return "[DELETE]";
if( code == KEY_RIGHT )
return "[RIGHT]";
if( code == KEY_LEFT )
return "[LEFT]";
if( code == KEY_DOWN )
return "[DOWN]";
if( code == KEY_UP )
return "[UP]";
if( code == KEY_PAGE_UP )
return "[PAGE_UP]";
if( code == KEY_PAGE_DOWN )
return "[PAGE_DOWN]";
if( code == KEY_HOME )
return "[HOME]";
if( code == KEY_END )
return "[END]";
if( code == KEY_CAPS_LOCK )
return "[CAPS_LOCK]";
if( code == KEY_SCROLL_LOCK )
return "[SCROLL_LOCK]";
if( code == KEY_NUM_LOCK )
return "[NUM_LOCK]";
if( code == KEY_PRINT_SCREEN )
return "[PRINT_SCREEN]";
if( code == KEY_PAUSE )
return "[PAUSE]";
if( code == KEY_F1 )
return "F1";
if( code == KEY_F2 )
return "F2";
if( code == KEY_F3 )
return "F3";
if( code == KEY_F4 )
return "F4";
if( code == KEY_F5 )
return "F5";
if( code == KEY_F6 )
return "F6";
if( code == KEY_F7 )
return "F7";
if( code == KEY_F8 )
return "F8";
if( code == KEY_F9 )
return "F9";
if( code == KEY_F10 )
return "F10";
if( code == KEY_F11 )
return "F11";
if( code == KEY_F12 )
return "F12";
if( code == KEY_F13 )
return "F13";
if( code == KEY_F14 )
return "F14";
if( code == KEY_F15 )
return "F15";
if( code == KEY_F16 )
return "F16";
if( code == KEY_F17 )
return "F17";
if( code == KEY_F18 )
return "F18";
if( code == KEY_F19 )
return "F19";
if( code == KEY_F20 )
return "F20";
if( code == KEY_F21 )
return "F21";
if( code == KEY_F22 )
return "F22";
if( code == KEY_F23 )
return "F23";
if( code == KEY_F24 )
return "F24";
if( code == KEY_F25 )
return "F25";
if( code == KEY_KP_0 )
return "KP_0";
if( code == KEY_KP_1 )
return "KP_1";
if( code == KEY_KP_2 )
return "KP_2";
if( code == KEY_KP_3 )
return "KP_3";
if( code == KEY_KP_4 )
return "KP_4";
if( code == KEY_KP_5 )
return "KP_5";
if( code == KEY_KP_6 )
return "KP_6";
if( code == KEY_KP_7 )
return "KP_7";
if( code == KEY_KP_8 )
return "KP_8";
if( code == KEY_KP_9 )
return "KP_9";
if( code == KEY_KP_DECIMAL )
return "KP_DECIMAL";
if( code == KEY_KP_DIVIDE )
return "KP_DIVIDE";
if( code == KEY_KP_MULTIPLY )
return "KP_MULTIPLY";
if( code == KEY_KP_SUBTRACT )
return "KP_SUBTRACT";
if( code == KEY_KP_ADD )
return "KP_ADD";
if( code == KEY_KP_ENTER )
return "KP_ENTER";
if( code == KEY_KP_EQUAL )
return "KP_EQUAL";
if( code == KEY_LEFT_SHIFT )
return "LEFT_SHIFT";
if( code == KEY_LEFT_CONTROL )
return "LEFT_CONTROL";
if( code == KEY_LEFT_ALT )
return "LEFT_ALT";
if( code == KEY_LEFT_SUPER )
return "LEFT_SUPER";
if( code == KEY_RIGHT_SHIFT )
return "RIGHT_SHIFT";
if( code == KEY_RIGHT_CONTROL )
return "RIGHT_CONTROL";
if( code == KEY_RIGHT_ALT )
return "RIGHT_ALT";
if( code == KEY_RIGHT_SUPER )
return "RIGHT_SUPER";
if( code == KEY_MENU )
return "MENU";
return "";
}
| [
"mridul.aanjaneya@rutgers.edu"
] | mridul.aanjaneya@rutgers.edu |
5d95b95fe0439c91948776a233ac102b9b5491a5 | b97f0d918bdce8d1b0a7fa9c4c044af1bc0766b2 | /include/xercesc2.5/util/Platforms/Solaris/SolarisDefs.hpp | a7ea9a20d58c87922e934e43d89e9c9a153d3d07 | [] | no_license | rauls/newscaster | 47ade74338c9d7032a275858ebbaa3deb2aa0b6c | 2557eee7b146454042e93382d734d7ca4a5ca2df | refs/heads/master | 2021-01-01T20:16:34.236163 | 2014-02-08T09:17:31 | 2014-02-08T09:17:31 | 2,427,760 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,717 | hpp | /*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log: SolarisDefs.hpp,v $
* Revision 1.2 2003/11/17 16:18:01 peiyongz
* Fix to #4556
*
* Revision 1.1.1.1 2002/02/01 22:22:25 peiyongz
* sane_include
*
* Revision 1.4 2000/03/02 19:55:30 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.3 2000/02/17 03:36:54 rahulj
* Fixed a cut-paste typo in the comments.
*
* Revision 1.2 2000/02/06 07:48:30 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:06:30 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:32 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// SPARC runs in big endian mode
// ---------------------------------------------------------------------------
#define ENDIANMODE_BIG
typedef int FileHandle;
#ifndef SOLARIS
#define SOLARIS
#endif
| [
"Raul.sobon@gmail.com"
] | Raul.sobon@gmail.com |
afa715b37af5393ab2d21da889edf0e77d65faca | 5a076617e29016fe75d6421d235f22cc79f8f157 | /catcake-0.9.5-android/include/draw/ck_scr.h | b3677c762db7c4976b1f6db369000c37cf731006 | [] | no_license | dddddttttt/androidsourcecodes | 516b8c79cae7f4fa71b97a2a470eab52844e1334 | 3d13ab72163bbeed2ef226a476e29ca79766ea0b | refs/heads/master | 2020-08-17T01:38:54.095515 | 2018-04-08T15:17:24 | 2018-04-08T15:17:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,531 | h | /*
Copyright (c) 2007-2010 Takashi Kitao
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.
*/
/*!
@ingroup ckDraw
A screen, which has a rectangle area and an order for drawing.
*/
class CK_API ckScr
{
friend class ckDraw;
friend class ckDrawMgr;
public:
//! @cond
ckDefineException(ExceptionInvalidArgument);
ckDefineException(ExceptionInvalidCall);
//! @endcond
/*!
The default focal length.
*/
static const u32 DEFAULT_FOCUS_DIST = 1000;
/*!
The default distance of near clipping.
*/
static const u32 DEFAULT_NEAR_CLIP_DIST = 10;
/*!
The default distance of far clipping.
*/
static const u32 DEFAULT_FAR_CLIP_DIST = 100000;
/*!
The number of the guest screens.
*/
static const u32 GUEST_SCREEN_NUM = 4;
/*!
Returns the previous screen. If the first screen doesn't exist, returns NULL.
*/
ckScr* getPrevN() const;
/*!
Returns the next screen. If the next screen doesn't exit, returns NULL.
*/
ckScr* getNextN() const;
/*!
Changes the order of this screen to the first.
*/
void moveFirst();
/*!
Changes the order of this screen to the last.
*/
void moveLast();
/*!
Changes the order of this screen to the previous of the specified screen.
@param[in] id A screen ID.
*/
void moveBefore(ckID id);
/*!
Changes the order of this screen to the next of the specified screen.
@param[in] id A screen ID.
*/
void moveAfter(ckID id);
/*!
Returns the first drawing object. If the firs drawing object doesn't exist, return. NULL.
*/
ckDraw* getFirstDrawN();
/*!
Returns the last drawing object. If the last drawing object doesn't exist, returns NULL.
*/
ckDraw* getLastDrawN();
/*!
Returns the ID of this screen.
@return The ID of this screen.
*/
ckID getID() const;
/*!
Returns the left position of this screen in the framebuffer.
@return The left position of this screen in the framebuffer.
*/
s16 getLeftInFramebuffer() const;
/*!
Returns the top position of this screen in the framebuffer.
@return The top position of this screen in the framebuffer.
*/
s16 getTopInFramebuffer() const;
/*!
Returns the width of this screen in the framebuffer.
@return The width of this screen in the framebuffer.
*/
s16 getWidthInFramebuffer() const;
/*!
Returns the height of this screen in the framebuffer.
@return The height of this screen in the framebuffer.
*/
s16 getHeightInFramebuffer() const;
/*!
Sets the size of this screen in the framebuffer.
@param[in] left The left position of a screen.
@param[in] top The top position of a screen.
@param[in] width The width of a screen.
@param[in] height The height of a screen.
*/
void setAreaInFramebuffer(s16 left, s16 top, u16 width, u16 height);
/*!
Returns the width of the view.
@return The width of the view.
*/
r32 getViewWidth() const;
/*!
Returns the height of the view.
@return The height of the view.
*/
r32 getViewHeight() const;
/*!
Sets the size of the view.
@param[in] width The width of the view.
@param[in] height The height of the view.
*/
void setViewSize(r32 width, r32 height);
/*!
Returns whether this screen is active.
@return Whether this screen is active.
*/
bool isActive() const;
/*!
Determines whether this screen is active.
@param[in] is_active Whether this screen is active.
*/
void setActive(bool is_active);
/*!
Returns whether clears color when this screen is updated.
@return Whether clears color when this screen is updated.
*/
bool isClearColor() const;
/*!
Returns whether clears depthbuffer when this screen is updated.
@return Whether clears depthbuffer when this screen is updated.
*/
bool isClearDepth() const;
/*!
Sets the clear modes.
@param[in] is_clear_color Whether clears color.
@param[in] is_clear_depth Whether clears depthbuffer.
*/
void setClearMode(bool is_clear_color, bool is_clear_depth);
/*!
Returns the clear color.
@return The clear color.
*/
ckCol getClearColor() const;
/*!
Sets the clear color.
@param[in] col A clear color.
*/
void setClearColor(ckCol col);
/*!
Returns whether perspective is on.
@return Whether perspective is on.
*/
bool isPerspective() const;
/*!
Determines whether pserspetive is on.
@param[in] is_perspective Whether pserspetive is on.
*/
void setPerspective(bool is_perspective);
/*!
Returns the focal length.
@return The focal length.
*/
r32 getFocusDist() const;
/*!
Sets the focal length.
@param[in] focus_dist A focal length.
*/
void setFocusDist(r32 focus_dist);
/*!
Returns the distance of near clipping.
@return The distance of near clipping.
*/
r32 getNearClipDist() const;
/*!
Returns the distance of far clipping.
@return The distance of far clipping.
*/
r32 getFarClipDist() const;
/*!
Sets the distances of clipping.
@param[in] near The distance of near clipping.
@param[in] far The distance of far clipping.
*/
void setClipDist(r32 near, r32 far);
/*!
Returns the reference to the view of this screen.
@return The reference to the view of this screen.
*/
ckMat& view();
/*!
Returns whether this screen has the texture.
@return Whether this screen has the texture.
*/
bool hasScreenTexture() const;
/*!
Returns the texture ID of this screen.
@return The texture ID of this screen.
*/
ckID getScreenTextureID() const;
/*!
Creates the texture for this screen.
@param[in] format The format type of a texture.
*/
void attachScreenTexture(ckTex::TexFormat format);
/*!
Deletes the texture of this screen.
*/
void detachScreenTexture();
/*!
Updates the texture of this screen.
@param[in] is_frame_skip_reset Whether disallow frame skip.
*/
void updateScreenTexture(bool is_frame_skip_reset);
/*!
Returns the ID of the specified guest screen.
@param[in] index The index of a guest screen.
*/
ckID getGuestScreenID(u8 index) const;
/*!
Sets the ID of the specified guest screen.
@param[in] index The index of a guest screen.
@param[in] scr_id A screen ID.
*/
void setGuestScreenID(u8 index, ckID scr_id);
/*!
Calculates the x-coordinate in the framebuffer from the specified x-coordinate in this screen.
@param[in] x_in_screen A x-coordinate in this screen.
@return The x-coordinate in the framebuffer.
*/
r32 screenXToFramebufferX(r32 x_in_screen) const;
/*!
Calculates the y-coordinates in the framebuffer from the specified y-coordinate in this screen.
@param[in] y_in_screen A y-coordinate in this screen.
@return The y-coordinate in the framebuffer.
*/
r32 screenYToFramebufferY(r32 y_in_screen) const;
/*!
Calculates the x-coordinates in this screen from the specified x-coordinate in the framebuffer.
@param[in] x_in_framebuffer A x-coordinate in the framebuffer.
@return The x-coordinate in this screen.
*/
r32 framebufferXToScreenX(r32 x_in_framebuffer) const;
/*!
Calculates the y-coordinates in this screen from the specified y-coordinate in the framebuffer.
@param[in] y_in_framebuffer A y-coordinate in the framebuffer.
@return The y-coordinate in this screen.
*/
r32 framebufferYToScreenY(r32 y_in_framebuffer) const;
/*!
Calculates the posision in screen from the specified world position.
@param[in] pos_in_world A world position.
@return The position in this screen.
*/
ckVec worldToScreen(const ckVec& pos_in_world);
/*!
Calculates the posision in the framebuffer from the specified world position.
@param[in] pos_in_world A world position.
@return The position in the framebuffer.
*/
ckVec worldToFramebuffer(const ckVec& pos_in_world);
/*!
Calculates the position in the specified plane from the position in this screen.
@param[in] x_in_screen A x-coordinate in this screen.
@param[in] y_in_screen A y-coordinate in this screen.
@param[in] xy_plane A xy-plane.
@return The position in the specified xy-plane.
*/
ckVec screenToPlane(r32 x_in_screen, r32 y_in_screen, const ckMat& xy_plane) const;
/*!
Calculates the position in the specified plane from the position in the framebuffer.
@param[in] x_in_framebuffer A x-coordinate in the framebuffer.
@param[in] y_in_framebuffer A y-coordinate in the framebuffer.
@param[in] xy_plane A xy-plane.
@return The position in the specified xy-plane.
*/
ckVec framebufferToPlane(r32 x_in_framebuffer, r32 y_in_framebuffer, const ckMat& xy_plane) const;
/*!
Returns whether the specified position in the world is in this screen.
@param[in] pos_in_world A position in the world.
@return Whether the specified position in the world is in this screen.
*/
bool isInScreen(const ckVec& pos_in_world);
/*!
Returns whether clipping by bounding box is possible.
@param[in] world The world matrix of a bounding box.
@param[in] bound_max The maximum bound clip.
@param[in] bound_min The minimum bound clip.
@return Whether clipping by bounding box is possible.
*/
bool canBoundClip(const ckMat& world, const ckVec& bound_max, const ckVec& bound_min);
/*!
Calculates the visible direction from the specified line.
@param[in] pos1 A position of a line.
@param[in] pos2 A position of a line.
@return The visible direction.
*/
ckVec calcVisibleVector(const ckVec& pos1, const ckVec& pos2);
private:
enum ScrFlag
{
FLAG_ACTIVE, //
FLAG_CLEAR_COLOR, //
FLAG_CLEAR_DEPTH, //
FLAG_PERSPECTIVE, //
FLAG_COPY_SCREEN
};
ckScr(ckID scr_id);
~ckScr();
void operator=(const ckScr&);
void calcProjection();
void setupProjection();
ckVec worldToClip_noCalcProjection(const ckVec& pos_in_world) const;
bool canBoundClip_noCalcProjection(const ckMat& world, const ckVec& bound_max, const ckVec& bound_min) const;
void copyScreenTexture();
ckFlag<u8, ScrFlag> m_flag;
ckID m_id;
s16 m_left_in_framebuffer;
s16 m_top_in_framebuffer;
u16 m_width_in_framebuffer;
u16 m_height_in_framebuffer;
r32 m_view_width;
r32 m_view_height;
ckCol m_clear_col;
r32 m_focus_dist;
r32 m_near_clip_dist;
r32 m_far_clip_dist;
ckMat m_view;
ckDraw m_root_draw;
ckTex* m_scr_tex;
ckID m_guest_id[GUEST_SCREEN_NUM];
r32 m_view_to_clip[16];
r32 m_world_to_view[16];
r32 m_world_to_clip[16];
};
| [
"harry.han@gmail.com"
] | harry.han@gmail.com |
2f5f0e28ec2512de99cf8bd48cd78e633599161c | 9903fdc90a0e90b71bb9b7a3c1ecd8cf13bc93c8 | /WPFTencentQQ/MobileQQ/MBLBindSet.h | 6f314420e21f41cb7d1f1e081808dd78d36030bd | [
"MIT"
] | permissive | hexin46373/TencentQQ | 6cba42a98db3a7a57c8fbfc21783b0e0dead8004 | 75b70356f50745f5a1e03e54ad0303a5af4e2254 | refs/heads/master | 2020-07-03T08:39:52.973969 | 2019-08-08T08:06:11 | 2019-08-08T08:06:11 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 862 | h | #pragma once
#include "afxwin.h"
#include"resource.h"
#include"../CCodecWarpper/ConfigData.h"
#include<NetLib.h>
#include"UserMsg.h"
// CMBLBindSet 对话框
class CMBLBindSet : public CDialogEx
{
DECLARE_DYNAMIC(CMBLBindSet)
public:
CMBLBindSet(CWnd* pParent = NULL); // 标准构造函数
virtual ~CMBLBindSet();
// 对话框数据
enum { IDD = IDD_DIALOG3 };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
afx_msg LRESULT OnReceivedMsg(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
public:
// 手机号码
CEdit mEditPhoneNo;
// 验证码
CEdit mEditCheckNo;
CConfigData *pConfig;
std::string strsessionSid;
public:
afx_msg void OnBnClickedButton1();
afx_msg void OnBnClickedButton8();
afx_msg void OnBnClickedButton2();
virtual BOOL OnInitDialog();
};
| [
"40445799+SurrealSky@users.noreply.github.com"
] | 40445799+SurrealSky@users.noreply.github.com |
c25d38f73040f2cf7dc9879aba57d8375e03296a | ef2d5dccbb72a2a501f7769629bb8376e2d050ea | /dia009/lst09-14.cxx | 36535dcb8baf7633aa0415d8abbcd92ff13a7c80 | [] | no_license | ricardo-rios/programacionii-2018 | 7e11f5c300c2e29721c8050f943d394acdd2aab9 | 2f60809920634e71a57ec7ae268ddd7930a12c0f | refs/heads/master | 2020-03-27T09:38:17.895088 | 2018-11-05T17:18:12 | 2018-11-05T17:18:12 | 146,358,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 908 | cxx | // Listado 9.10
#include <iostream>
using namespace std;
class GatoSimple
{
public:
GatoSimple(int edad, int peso);
~GatoSimple() {}
int ObtenerEdad()
{ return suEdad; }
int ObtenerPeso()
{ return suPeso; }
private:
int suEdad;
int suPeso;
};
GatoSimple::GatoSimple(int edad, int peso)
{
suEdad = edad;
suPeso = peso;
}
GatoSimple & LaFuncion();
int main()
{
GatoSimple & rGato = LaFuncion();
int edad = rGato.ObtenerEdad();
cout << "!rGato tiene " << edad << " años de edad!\n";
cout << "&rGato: " << &rGato << endl;
// Como nos deshacemos de esa memoria?
GatoSimple * apGato = &rGato;
delete apGato;
// Hmmm?, ¿a quien se refiere ahora rGato??
return 0;
}
GatoSimple & LaFuncion()
{
GatoSimple * apPelusa = new GatoSimple(5, 9);
cout << "apPelusa: " << apPelusa << endl;
return *apPelusa;
}
| [
"gambitorey@gmail.com"
] | gambitorey@gmail.com |
0916da7c4ae66f13786e7b0608bed0e9bf3160d0 | 1cc51c1d4c0c3af92b55ff2c32d093313d0aac80 | /蓝桥杯训练/蓝桥杯训练/6.兰顿蚂蚁.cpp | bec6b8397a16f0ec591f3e6d88bdddba17864c7f | [] | no_license | ghostgt222/Lan-Qiao-Bei-Practice | a66ca13fd33a808ae29ac7277958221a33249bec | 8641b71ce5c3c8e6430a03b9b8b68fbb945ebeec | refs/heads/master | 2021-03-26T14:32:09.763438 | 2020-03-16T13:49:11 | 2020-03-16T13:49:11 | 247,712,886 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,055 | cpp | /*
题目描述
兰顿蚂蚁,是于1986年,由克里斯·兰顿提出来的,属于细胞自动机的一种。
平面上的正方形格子被填上黑色或白色。在其中一格正方形内有一只“蚂蚁”。
蚂蚁的头部朝向为:上下左右其中一方。
蚂蚁的移动规则十分简单:
若蚂蚁在黑格,右转90度,将该格改为白格,并向前移一格;
若蚂蚁在白格,左转90度,将该格改为黑格,并向前移一格。
规则虽然简单,蚂蚁的行为却十分复杂。刚刚开始时留下的路线都会有接近对称,像是会重复,但不论起始状态如何,蚂蚁经过漫长的混乱活动后,会开辟出一条规则的“高速公路”。
蚂蚁的路线是很难事先预测的。
你的任务是根据初始状态,用计算机模拟兰顿蚂蚁在第n步行走后所处的位置。
输入
输入数据的第一行是 m n 两个整数(3 < m, n < 100),表示正方形格子的行数和列数。
接下来是 m 行数据。
每行数据为 n 个被空格分开的数字。0 表示白格,1 表示黑格。
接下来是一行数据:x y s k, 其中x y为整数,表示蚂蚁所在行号和列号(行号从上到下增长,列号从左到右增长,都是从0开始编号)。s 是一个大写字母,表示蚂蚁头的朝向,我们约定:上下左右分别用:UDLR表示。k 表示蚂蚁走的步数。
输出
输出数据为一个空格分开的整数 p q, 分别表示蚂蚁在k步后,所处格子的行号和列号。
样例输入
5 6
0 0 0 0 0 0
0 0 0 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
2 3 L 5
样例输出
1 3
*/
#include<iostream>
using namespace std;
class ant_def {
public:
int x;
int y;
};
int **map6;
void move(ant_def *ant, char *s);
int main6() {
int m, n;
cin >> m >> n;
map6 = new int*[m];
for (int i = 0; i < m; i++)
map6[i] = new int[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
cin >> map6[i][j];
int x, y, k;
char s;
cin >> x >> y >> s >> k;
ant_def ant = { x,y };
for (int i = 0; i < k; i++)
move(&ant, &s);
cout << ant.x << ' ' << ant.y << endl;
return 0;
}
void move(ant_def *ant, char *s) {
int x = ant->x;
int y = ant->y;
switch (*s)
{
case 'U':
if (map6[x][y] == 1) {
ant->y += 1;
map6[x][y] = 0;
*s = 'R';
}
else {
ant->y -= 1;
map6[x][y] = 1;
*s = 'L';
}
break;
case 'D':
if (map6[x][y] == 1) {
ant->y -= 1;
map6[x][y] = 0;
*s = 'L';
}
else {
ant->y += 1;
map6[x][y] = 1;
*s = 'R';
}
break;
case 'L':
if (map6[x][y] == 1) {
ant->x -= 1;
map6[x][y] = 0;
*s = 'U';
}
else {
ant->x += 1;
map6[x][y] = 1;
*s = 'D';
}
break;
case 'R':
if (map6[x][y] == 1) {
ant->x += 1;
map6[x][y] = 0;
*s = 'D';
}
else {
ant->x -= 1;
map6[x][y] = 1;
*s = 'U';
}
break;
}
} | [
"noreply@github.com"
] | noreply@github.com |
3c865b6dd1aa6265d3487b0b8fbbcc7112e8a4bb | 1d12d9baf028aacfaf843f711c8da0031c8d2902 | /Lab1_2.h | 1c9cf2ed1dc30d825d3306b8a15aa69a4193f8ef | [] | no_license | SUSU-CMI-OOP/Lab-1 | ec26c7d5f4fa6c186d264f6565936eb3017ee1b9 | b964f3b0af70a54dc7aec9779aad8ea39eb95c15 | refs/heads/master | 2021-01-01T20:12:17.493939 | 2014-09-20T04:17:55 | 2014-09-20T04:17:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 102 | h | #pragma once
class Lab1_2
{
public:
Lab1_2(void);
~Lab1_2(void);
SomeMethod();
int SomeField;
};
| [
"dmitriyn@ws-chl104b.chelyabinsk.fuse8.local"
] | dmitriyn@ws-chl104b.chelyabinsk.fuse8.local |
35ffe7219ba8253f8a32a7d82a3f9e0256990bd0 | 2bf472c0d74220b1c5c143e30727a6f71ede520d | /파티.cpp | da9fecb5498cc7e15e5938ab9644a3fb8157f707 | [] | no_license | 20163156/algorithm | 2fd1ff94fc9dd7166afa7a8f4d181678cf0c6ce2 | 5548d4f3d86ee83824e770ee130b26331414140e | refs/heads/master | 2020-03-31T00:06:28.173965 | 2020-02-18T00:30:56 | 2020-02-18T00:30:56 | 151,725,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,034 | cpp | #include <iostream>
#define MAX 100000
using namespace std;
int N;
int dist[1002][1002];
void Init()
{
for(int i = 0;i < 1002;++i){
for(int j = 0;j < 1002;++j){
dist[i][j] = MAX;
}
}
}
void Floyd()
{
//k: 중간 i: 시작 j: 끝
for(int k = 1; k <= N;++k){
for(int i = 1; i <= N;++i){
for(int j = 1;j <= N;++j){
if(i == j){
continue;
}
if (dist[i][k] + dist[k][j] < dist[i][j]){
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
}
int main()
{
int M,X;
int start,end,cost;
cin >> N >> M >> X;
Init();
for(int i = 0;i < M;++i){
cin >> start >> end >> cost;
dist[start][end] = cost;
}
Floyd();
for(int i = 1;i <= N;++i)
{
for(int j = 1;j <= N;++j)
{
if(dist[i][j] == MAX)
{
dist[i][j] = 0;
}
}
}
int max;
max = dist[1][X] + dist[X][1];
for(int i = 2;i <= N;++i){
if( max < dist[i][X] + dist[X][i])
max = dist[i][X] + dist[X][i];
}
cout << max;
}
| [
"97jjy@naver.com"
] | 97jjy@naver.com |
94139a062cf96404c859018f70b556263faf7798 | 6059ef7bc48ab49c938f075dc5210a19ec08538e | /src/plugins/azoth/plugins/xoox/inbandaccountregfirstpage.h | c4586b96fee46494f94227f3a5f35f519b294d99 | [
"BSL-1.0"
] | permissive | Laura-lc/leechcraft | 92b40aff06af9667aca9edd0489407ffc22db116 | 8cd066ad6a6ae5ee947919a97b2a4dc96ff00742 | refs/heads/master | 2021-01-13T19:34:09.767365 | 2020-01-11T15:25:31 | 2020-01-11T15:25:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,149 | h | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#ifndef PLUGINS_AZOTH_PLUGINS_XOOX_INBANDACCOUNTREGFIRSTPAGE_H
#define PLUGINS_AZOTH_PLUGINS_XOOX_INBANDACCOUNTREGFIRSTPAGE_H
#include <QWizardPage>
#include "ui_inbandaccountregfirstpage.h"
namespace LC
{
namespace Azoth
{
namespace Xoox
{
class InBandAccountRegFirstPage : public QWizardPage
{
Q_OBJECT
Ui::InBandAccountRegFirstPage Ui_;
public:
InBandAccountRegFirstPage (QWidget* = 0);
QString GetServerName () const;
bool isComplete () const;
};
}
}
}
#endif
| [
"0xd34df00d@gmail.com"
] | 0xd34df00d@gmail.com |
accb5862797b070d6220ba22d920d4186514ed84 | 0c5d6a9de5b865f957a660b0226b130c169c1e91 | /Networked_Physics/src/DebugGraph.cpp | b28035b40700773e329e09cfa488dc635663be54 | [] | no_license | Jordan-Blackett/Networked-Physics | 423960716d7963f0b8a0aea8e21eb1e4fc15cdde | 0bc978822e292b1f356cf5c84268a5025588edcc | refs/heads/master | 2020-04-29T03:14:27.296577 | 2019-03-15T11:21:56 | 2019-03-15T11:21:56 | 175,801,520 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,359 | cpp | #include "DebugGraph.h"
DebugGraph::DebugGraph()
{
}
DebugGraph::~DebugGraph()
{
}
void DebugGraph::Init(sf::Vector2i position, std::string text)
{
position_ = position;
int tempOffset = 0;
for (int i = 0; i < (sizeof(debugBars_) / sizeof(*debugBars_)); i++)
{
debugBars_[i].setSize(sf::Vector2f(3, 5));
debugBars_[i].setPosition(position_.x + tempOffset, position_.y);
debugBars_[i].setFillColor(barColour_);
tempOffset += barSpaceOffset_;
}
lastBarIndex_ = numberOfBars_ - 1;
text_ = text;
if (!debugFont.loadFromFile("Resources/Fonts/closeness/Closeness.ttf")) {}
debugText.setFont(debugFont);
debugText.setCharacterSize(debugTextSize);
debugText.setFillColor(debugTextColor);
debugText.setPosition(sf::Vector2f(position_.x, position_.y - 25));
debugText.setString(text_ + "0kb/s");
}
void DebugGraph::Update(float data)
{
// New Data - Once per second
//int randTemp = (rand() % 10) + 1;
//debugBars_[lastBarIndex_].setSize(sf::Vector2f(debugBars_[lastBarIndex_].getSize().x, 25 + randTemp));
//debugBars_[lastBarIndex_].setPosition(position_.x, position_.y);
// TODO: packet loss = red bar
//
//sf::Time ticktime_ = sf::milliseconds(1000);
//if (timeLastUpdated_ > ticktime_)
//{
//std::cout << clock.getElapsedTime().asSeconds() << std::endl;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << data;
std::string s = stream.str();
debugText.setString(text_ + ": " + s + "kb/s");
// Scroll
for (int i = 0; i < (sizeof(debugBars_) / sizeof(*debugBars_)); i++)
{
// Bar reached the end
if (debugBars_[i].getPosition().x > position_.x + (barSpaceOffset_ * numberOfBars_))
{
float percentage = 100 / (maxDataSize / data);
debugBars_[i].setSize(sf::Vector2f(debugBars_[i].getSize().x, percentage));
debugBars_[i].setPosition(position_.x, position_.y);
}
else
{
debugBars_[i].setPosition(debugBars_[i].getPosition().x + scrollSpeed_, position_.y);
}
}
// Last Bar Index
lastBarIndex_--;
if (lastBarIndex_ < 0)
lastBarIndex_ = numberOfBars_ - 1;
//timeLastUpdated_ = clock.restart();
//}
//timeLastUpdated_ = clock.getElapsedTime();
}
void DebugGraph::Render(sf::RenderWindow &Window)
{
Window.draw(debugText);
for (int i = 0; i < (sizeof(debugBars_)/ sizeof(*debugBars_)); i++)
{
Window.draw(debugBars_[i]);
}
}
| [
"Jordan.blackett@gmail.com"
] | Jordan.blackett@gmail.com |
2c010484c0cfaeb855d56ef5370e065f70d5e79b | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_DinoTamedInventoryComponent_Oviraptor_parameters.hpp | 54fe4dbac4b10bc360fba6c3526b59d16e353571 | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | hpp | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoTamedInventoryComponent_Oviraptor_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function DinoTamedInventoryComponent_Oviraptor.DinoTamedInventoryComponent_Oviraptor_C.ExecuteUbergraph_DinoTamedInventoryComponent_Oviraptor
struct UDinoTamedInventoryComponent_Oviraptor_C_ExecuteUbergraph_DinoTamedInventoryComponent_Oviraptor_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
68d2efc97dc810408baea04fcb6662f5584458f3 | 0ccae222bb5d73b3ad9f9c465709685f7586fdb8 | /src/dev/UniqueCreator.Graphics.Gpu.HullShaderByteCode.cpp | 445b09ce66f682ec83d64d3aef44a91407a92364 | [] | no_license | UniqueCreator/uc-graphics-winrt | c790048e8bfc768acc30d40f378a516e8214f1cc | c36e6436c9aca4ababc3ba6fa7d82b070f293656 | refs/heads/master | 2020-04-27T18:17:23.047144 | 2019-06-15T09:34:31 | 2019-06-15T09:34:31 | 174,563,143 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 750 | cpp | #include "pch.h"
#include "UniqueCreator.Graphics.Gpu.HullShaderByteCode.h"
namespace winrt::UniqueCreator::Graphics::Gpu::implementation
{
namespace
{
std::vector<uint8_t> toNative(IVector<uint8_t> const& value)
{
std::vector<uint8_t> v;
v.reserve(value.Size());
for (auto i : value)
{
v.push_back(i);
}
return v;
}
}
HullShaderByteCode::HullShaderByteCode() : m_code(std::vector<uint8_t>())
{
}
IVector<uint8_t> HullShaderByteCode::Code()
{
return m_code;
}
void HullShaderByteCode::Code(IVector<uint8_t> const& value)
{
m_code.get_container() = toNative(value);
}
Blob HullShaderByteCode::GetShaderByteCode()
{
return { &m_code.get_container()[0], m_code.get_container().size() };
}
}
| [
"stefan.dyulgerov@gmail.com"
] | stefan.dyulgerov@gmail.com |
d749af49936b9ddc150e29d74149f99394c136bc | 0090606f7f1f240674531425435d90dfa53c0552 | /codis-client/cpp/include/RoundRobinCodisPool.h | 7caca7ecf6985f04e997c0f4e92970afca536f85 | [
"BSD-3-Clause",
"MIT"
] | permissive | abigbigbird/codis | 4369079a4c31f225464fb8640d37d51e23858042 | c38433293fa02768a64d1b704af6d898b3e0ca83 | refs/heads/master | 2021-01-20T16:48:05.722578 | 2016-07-21T03:14:51 | 2016-07-21T03:14:51 | 47,390,359 | 2 | 0 | null | 2015-12-04T08:08:14 | 2015-12-04T08:08:13 | null | UTF-8 | C++ | false | false | 1,036 | h | /**
* @file
* @brief
*/
#ifndef CODIS_CLIENT_ROUNDROBINCODISPOOL_H
#define CODIS_CLIENT_ROUNDROBINCODISPOOL_H
#include "CodisClient.h"
#include <vector>
#include <zookeeper.h>
using namespace std;
namespace bfd
{
namespace codis
{
class RoundRobinCodisPool
{
public:
RoundRobinCodisPool(const string& zookeeperAddr, const string& proxyPath, const string& businessID);
~RoundRobinCodisPool();
CodisClient* GetProxy();
private:
vector<CodisClient*> m_Proxys;
int proxyIndex;
vector<pair<string, int> > m_ProxyInfos;
zhandle_t *m_Zh;
string m_ZookeeperAddr;
string m_ProxyPath;
string m_BusinessID;
pthread_mutex_t m_Mutex;
private:
void Init(zhandle_t *(&zh), const string& proxyPath);
static void proxy_watcher(zhandle_t *zh, int type, int state, const char *path, void *context);
string ZkGet(zhandle_t *(&zh), const string &path, bool watch=true);
vector<pair<string, int> > GetProxyInfos(zhandle_t *(&zh), const string& proxyPath);
void InitProxyConns(vector<pair<string, int> >& proxyInfos);
};
}
}
#endif
| [
"401379957@qq.com"
] | 401379957@qq.com |
ee9f19404207d359c1936fbacfb859ef1198b6e1 | 88080292ac6fccf651c196801a10d4d8665dd2e4 | /100-200/196 - Matrix Multiplication.cpp | ecae7788d620bd5822c72b91dcc152ca6c45e56f | [] | no_license | llalexandru00/SGU | 8c50e2cb59252631e3a8b6fe3c4f0baf989f8990 | 63d5ce299fa2758496ea97422c31a929dc55e309 | refs/heads/master | 2020-03-18T12:10:27.013828 | 2018-07-15T14:08:06 | 2018-07-15T14:08:06 | 134,712,983 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector < pair <int, int> > E;
int x, y, V[10005];
long long tot;
int main()
{
cin>>n>>m;
for (int i=1; i<=m; i++)
{
cin>>x>>y;
V[x]++; V[y]++;
E.push_back({x, y});
}
for (auto i : E)
tot += V[i.first] + V[i.second];
cout<<tot;
return 0;
}
| [
"lungualex00@gmail.com"
] | lungualex00@gmail.com |
0ce833aafa764852dac6f9c66cd9a9905523f1c0 | c28ea5bdf8f0e08cec0dd0ff862775a347cace1e | /src/FluidSim.cpp | 06026585c65d166fa8ba96fab4f09d07dbde84e8 | [] | no_license | NASGregorio/2DFluidNavierStokes | cca33fb331239aaae64c7a3e71e6baf375c1489f | 67ff54725bf34952c4bb1e757bb0bdb247de97d4 | refs/heads/master | 2020-04-23T05:03:11.925049 | 2019-02-17T23:13:03 | 2019-02-17T23:13:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,895 | cpp | #include "FluidSim.h"
#include <iostream>
#define IX(i,j) ((i)+(N+2)*(j))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define CLAMP(x, upper, lower) (MIN(upper, MAX(x, lower)))
static void set_bnd(int N, int b, float *x)
{
int i;
for (i = 1; i <= N; i++)
{
x[IX(0, i)] = b == 1 ? -x[IX(1, i)] : x[IX(1, i)];
x[IX(N + 1, i)] = b == 1 ? -x[IX(N, i)] : x[IX(N, i)];
x[IX(i, 0)] = b == 2 ? -x[IX(i, 1)] : x[IX(i, 1)];
x[IX(i, N + 1)] = b == 2 ? -x[IX(i, N)] : x[IX(i, N)];
}
x[IX(0, 0)] = 0.5f*(x[IX(1, 0)] + x[IX(0, 1)]);
x[IX(0, N + 1)] = 0.5f*(x[IX(1, N + 1)] + x[IX(0, N)]);
x[IX(N + 1, 0)] = 0.5f*(x[IX(N, 0)] + x[IX(N + 1, 1)]);
x[IX(N + 1, N + 1)] = 0.5f*(x[IX(N, N + 1)] + x[IX(N + 1, N)]);
}
static void Diffuse(int N, int b, float *x, float *x0, float diff, float dt, int gaussSeidelIter, bool systemIsClosed)
{
float a = dt * diff * N * N;
float c = 1.0f / (1 + 4 * a);
for (int k = 0; k < gaussSeidelIter; k++)
{
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
x[IX(i, j)] = c * (x0[IX(i, j)] + a * (x[IX(i - 1, j)] + x[IX(i + 1, j)] + x[IX(i, j - 1)] + x[IX(i, j + 1)]));
}
}
if (systemIsClosed) set_bnd(N, b, x);
}
}
static void Advect(int N, int b, float *d, float *d0, float *Vx, float *Vy, float dt, bool systemIsClosed)
{
int prevX, prevY, currX, currY;
float prevXf, prevYf, oneMinusDiffX, oneMinusDiffY, diffX, diffY, dt0;
dt0 = dt * N;
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
prevXf = i - dt0 * Vx[IX(i, j)];
prevYf = j - dt0 * Vy[IX(i, j)];
//x = CLAMP(x, N + 0.5f, 0.5f);
//x = fmaxf(x, 0.5f);
//x = fminf(x, N + 0.5f);
if (prevXf < 0.5f) prevXf = 0.5f;
if (prevXf > N + 0.5f) prevXf = N + 0.5f;
//y = CLAMP(x, N + 0.5f, 0.5f);
if (prevYf < 0.5f) prevYf = 0.5f;
if (prevYf > N + 0.5f) prevYf = N + 0.5f;
prevX = (int)prevXf;
currX = prevX + 1;
prevY = (int)prevYf;
currY = prevY + 1;
diffX = prevXf - prevX;
oneMinusDiffX = 1 - diffX;
diffY = prevYf - prevY;
oneMinusDiffY = 1 - diffY;
d[IX(i, j)] = oneMinusDiffX * (oneMinusDiffY*d0[IX(prevX, prevY)] + diffY * d0[IX(prevX, currY)]) +
diffX * (oneMinusDiffY*d0[IX(currX, prevY)] + diffY * d0[IX(currX, currY)]);
}
}
if (systemIsClosed) set_bnd(N, b, d);
}
static void Project(int N, float *uX, float *uY, float *vX, float *vY)
{
int i, j, k;
float h;
h = 1.0f / N;
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
vY[IX(i, j)] = -0.5f*h*(uX[IX(i + 1, j)] - uX[IX(i - 1, j)] + uY[IX(i, j + 1)] - uY[IX(i, j - 1)]);
vX[IX(i, j)] = 0;
}
}
set_bnd(N, 0, vY);
set_bnd(N, 0, vX);
for (k = 0; k < 20; k++)
{
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
vX[IX(i, j)] = (vY[IX(i, j)] + vX[IX(i - 1, j)] + vX[IX(i + 1, j)] + vX[IX(i, j - 1)] + vX[IX(i, j + 1)]) / 4;
}
}
set_bnd(N, 0, vX);
}
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
uX[IX(i, j)] -= 0.5f*(vX[IX(i + 1, j)] - vX[IX(i - 1, j)]) / h;
uY[IX(i, j)] -= 0.5f*(vX[IX(i, j + 1)] - vX[IX(i, j - 1)]) / h;
}
}
set_bnd(N, 1, uX);
set_bnd(N, 2, uY);
}
FluidSim::FluidSim(int size, float dt, int gaussSeidelIterations, float diffusion, float viscosity, bool closedSystem)
{
gridPtr = NULL;
Create(size, dt, gaussSeidelIterations, diffusion, viscosity, closedSystem);
}
FluidSim::~FluidSim()
{
Clear();
}
void FluidSim::Create(int size, float dt, int gaussSeidelIterations, float diffusion, float viscosity, bool closedSystem)
{
if (gridPtr != NULL) Clear();
FluidGrid *grid = (FluidGrid*)malloc(sizeof(*grid));
int N = (size + 2)*(size + 2);
grid->size = size;
grid->dt = dt;
grid->gaussSeidelIterations = gaussSeidelIterations;
grid->diff = diffusion;
grid->visc = viscosity;
grid->closedSystem = closedSystem;
grid->density = (float*)calloc(N, sizeof(float));
grid->Vx = (float*)calloc(N, sizeof(float));
grid->Vy = (float*)calloc(N, sizeof(float));
grid->density0 = (float*)calloc(N, sizeof(float));
grid->Vx0 = (float*)calloc(N, sizeof(float));
grid->Vy0 = (float*)calloc(N, sizeof(float));
gridPtr = grid;
}
void FluidSim::Clear()
{
if (gridPtr == NULL) return;
free(gridPtr->density);
free(gridPtr->Vx);
free(gridPtr->Vy);
free(gridPtr->density0);
free(gridPtr->Vx0);
free(gridPtr->Vy0);
free(gridPtr);
gridPtr = NULL;
}
void FluidSim::DensityStep()
{
if (gridPtr == NULL) return;
int N = gridPtr->size;
bool closedSystem = gridPtr->closedSystem;
int gaussSeidelIter = gridPtr->gaussSeidelIterations;
float *density = gridPtr->density;
float *density0 = gridPtr->density0;
float *Vx = gridPtr->Vx;
float *Vy = gridPtr->Vy;
float diff = gridPtr->diff / 1000;
float dt = gridPtr->dt;
//AddSource(density, density0);
//SWAP(x0, x);
//Diffuse(N, 0, density, density0, diff, dt);
//SWAP(x0, x);
//Advect(N, 0, density, density0, Vx, Vy, dt);
AddSource(density, density0);
Diffuse(N, 0, density0, density, diff, dt, gaussSeidelIter, closedSystem);
Advect(N, 0, density, density0, Vx, Vy, dt, closedSystem);
}
void FluidSim::VelocityStep()
{
if (gridPtr == NULL) return;
int N = gridPtr->size;
bool closedSystem = gridPtr->closedSystem;
int gaussSeidelIter = gridPtr->gaussSeidelIterations;
float *Vx = gridPtr->Vx;
float *Vy = gridPtr->Vy;
float *Vx0 = gridPtr->Vx0;
float *Vy0 = gridPtr->Vy0;
float visc = gridPtr->visc;
float dt = gridPtr->dt;
AddSource(Vx, Vx0);
AddSource(Vy, Vy0);
Diffuse(N, 1, Vx0, Vx, visc, dt, gaussSeidelIter, closedSystem);
Diffuse(N, 2, Vy0, Vy, visc, dt, gaussSeidelIter, closedSystem);
Project(N, Vx0, Vy0, Vx, Vy);
Advect(N, 1, Vx, Vx0, Vx0, Vy0, dt, closedSystem);
Advect(N, 2, Vy, Vy0, Vx0, Vy0, dt, closedSystem);
Project(N, Vx, Vy, Vx0, Vy0);
//AddSource(Vx, Vx0);
//AddSource(Vy, Vy0);
//SWAP(u0, u);
//SWAP(v0, v);
//Diffuse(N, 1, u, u0, visc, dt, 4);
//diffuse(N, 2, v, v0, visc, dt, 4);
//project(N, u, v, u0, v0);
//SWAP(u0, u);
//SWAP(v0, v);
//Advect(N, 1, u, u0, u0, v0, dt);
//Advect(N, 2, v, v0, u0, v0, dt);
//project(N, u, v, u0, v0);
}
void FluidSim::AddDensity(int x, int y, float amount)
{
if (gridPtr == NULL) return;
int index = 0;
if (TryGetIndex(x, y, index))
{
gridPtr->density[index] += amount;
//float f = gridPtr->density[index];
//gridPtr->density[index] = CLAMP(f, 1, 0);
}
}
float FluidSim::GetDensityAt(int x, int y)
{
if (gridPtr == NULL) return -1;
int index = 0;
return (TryGetIndex(x, y, index)) ? gridPtr->density[index] : -1;
}
void FluidSim::AddVelocity(int x, int y, float amountX, float amountY)
{
if (gridPtr == NULL) return;
int index = 0;
if (TryGetIndex(x, y, index))
{
gridPtr->Vx[index] += amountX;
gridPtr->Vy[index] += amountY;
}
}
float FluidSim::GetVelocityXAt(int x, int y)
{
if (gridPtr == NULL) return -1;
int index = 0;
return (TryGetIndex(x, y, index)) ? gridPtr->Vx[index] : 0;
}
float FluidSim::GetVelocityYAt(int x, int y)
{
if (gridPtr == NULL) return -1;
int index = 0;
return (TryGetIndex(x, y, index)) ? gridPtr->Vy[index] : 0;
}
void FluidSim::ZeroOutDensityBuffer()
{
if (gridPtr == NULL) return;
int N = gridPtr->size;
for (int i = 0; i < (N + 2)*(N + 2); i++)
{
gridPtr->density[i] = 0.0f;
}
}
void FluidSim::ZeroOutPreviousDensityVelocityBuffers()
{
if (gridPtr == NULL) return;
int N = gridPtr->size;
for (int i = 0; i < (N + 2)*(N + 2); i++)
{
gridPtr->Vx0[i] = gridPtr->Vy0[i] = gridPtr->density0[i] = 0.0f;
}
}
void FluidSim::AddSource(float *x, float *x0)
{
if (gridPtr == NULL) return;
int N = gridPtr->size;
float dt = gridPtr->dt;
for (int i = 0; i < (N + 2)*(N + 2); i++)
x[i] += dt * x0[i];
}
bool FluidSim::TryGetIndex(int x, int y, int &index)
{
if (gridPtr == NULL) return false;
int N = gridPtr->size;
if (x < 0 || x > N + 2 || y < 0 || y > N + 2) return false;
index = IX(x, y);
return true;
} | [
"nelson.gregorio@live.com.pt"
] | nelson.gregorio@live.com.pt |
a2e3fe9dda26e12eb2eaaa82ba56c1d24f528186 | dce9b8a0adf25b5b624dacee95614e3de1fa23ea | /poitprogram/poitprogram.ino | b35f850335a27261e213f891d306820b67fcb9f5 | [] | no_license | nikola139/poitzadanie | 5876e0f0ad66ceb475ed07c65b56ba78f04f30cc | 8e5d360e70ca07d13664ee8391a5ed8b7944e6f7 | refs/heads/master | 2022-10-01T08:34:50.273028 | 2020-06-02T21:13:17 | 2020-06-02T21:13:17 | 268,909,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 263 | ino |
#include <dht.h>
dht DHT;
#define DHT11_PIN 7
void setup(){
Serial.begin(9600);
}
void loop()
{
int chk = DHT.read11(DHT11_PIN);
Serial.print(DHT.temperature);
Serial.print(",");
Serial.print(DHT.humidity);
Serial.print("\n");
delay(5000);
}
| [
"noreply@github.com"
] | noreply@github.com |
6b882b856b6d07b3a78cd74c2c76f764b128a889 | 805311b6112c49599016e44e5ac0677975a73c12 | /source/Hero.cpp | 33883e75bac79509cff6ef46d67395ace7a3e826 | [] | no_license | KCherkasov/Coordinator | 0fa210682f4c7661ac8f8b6bf4db4e29d16ce66a | 6d29e9fd3b081deb10b83f45686a79b00f0ba587 | refs/heads/master | 2020-12-27T15:04:04.377923 | 2017-02-01T23:43:20 | 2017-02-01T23:43:20 | 68,733,708 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,243 | cpp | #include "Hero.h"
#include "Quest.h"
#include "Player.h"
size_t Hero::_id = SIZE_T_DEFAULT_VALUE;
Hero::Hero(const HeroTemplate& data, HeroClass& hero_class, Faction& faction): _own_id(data._own_id), _name(data._name), _description(data._description), _to_delete(false), _level(START_LEVEL), _faction(faction), _health(data._health), _stats(data._stats), _class(hero_class), _experience(data._experience), _personality(data._personality), _history(data._history), _equipment(data._equipment) {
if (_own_id == FREE_ID) {
_own_id = ++_id;
} else {
if (_id > _own_id) {
_id = _own_id;
}
}
if (data._level > _level) {
_level = data._level;
}
}
Hero::~Hero() {
if (_quest != NULL) {
_quest->remove_hero(this);
}
if (_guild != NULL) {
_guild->remove_hero(this);
}
}
size_t Hero::level_up() {
size_t stat_points = POINTS_PER_LEVEL;
while (true) {
size_t stat_id = roll_dice(_stats.size());
++_stats[stat_id];
--stat_points;
if (stat_points == 0) {
break;
}
}
return RC_OK;
}
size_t Hero::get_class(HeroClass& result) const {
result = _class;
return RC_OK;
}
size_t Hero::get_experience(std::vector<size_t>& result) const {
result.clear();
result = _experience;
return RC_OK;
}
size_t Hero::get_experience(const size_t& index, size_t& result) const {
if (index < _experience.size()) {
result = _experience[index];
return RC_OK;
} else {
return RC_BAD_INDEX;
}
}
size_t Hero::get_personality(std::vector<size_t>& result) const {
result.clear();
result = _personality;
return RC_OK;
}
size_t Hero::get_personality(const size_t& index, size_t& result) const {
if (index < _personality.size()) {
result = _personality[index];
return RC_OK;
} else {
return RC_BAD_INDEX;
}
}
size_t Hero::get_history(std::vector<size_t>& result) const {
result.clear();
result = _history;
return RC_OK;
}
size_t Hero::get_history(const size_t& index, size_t& result) const {
if (index < _history.size()) {
result = _history[index];
return RC_OK;
} else {
return RC_BAD_INDEX;
}
}
size_t Hero::get_equipment(Inventory*& result) const {
result = &_equipment;
return RC_OK;
}
size_t Hero::get_power() const {
size_t power = SIZE_T_DEFAULT_VALUE;
size_t limit;
if (_stats.size() > SI_DEFENSE) {
limit = SI_DEFENSE;
} else {
limit = _stats.size();
}
for (size_t i = 0; i < limit; ++i) {
size_t modifier;
size_t class_bonus;
size_t items_bonus;
_class.get_power_mods(i, modifier);
_class.get_stat_bonuses(i, class_bonus);
_equipment.get_bonuses(i, items_bonus);
power += ((_stats[i] + class_bonus + items_bonus) * modifier / PERCENT_CAP);
}
return power;
}
size_t Hero::get_power(const size_t& target_archetype_id) const {
size_t power = SIZE_T_DEFAULT_VALUE;
size_t limit;
if (_stats.size() > SI_DEFENSE) {
limit = SI_DEFENSE;
} else {
limit = _stats.size();
}
for (size_t i = 0; i < limit; ++i) {
size_t modifier;
size_t class_bonus;
size_t items_bonus;
_class.get_power_mods(i, modifier);
_class.get_stat_bonuses(i, class_bonus);
_equipment.get_bonuses(i, items_bonus);
power += ((_stats[i] + class_bonus + items_bonus) * modifier / PERCENT_CAP);
}
size_t power_mod;
_class.get_att_power_modifiers(target_archetype_id, power_mod);
power = power * power_mod / PERCENT_CAP;
return power;
}
size_t Hero::get_defense() const {
size_t defense = SIZE_T_DEFAULT_VALUE;
for (size_t i = 0; i < _stats.size(); ++i) {
size_t modifier;
size_t class_bonus;
size_t items_bonus;
_class.get_defense_mods(i, modifier);
_class.get_stat_bonuses(i, class_bonus);
_equipment.get_bonuses(i, items_bonus);
defense += ((_stats[i] + class_bonus + items_bonus) * modifier / PERCENT_CAP);
}
return defense;
}
size_t Hero::get_defense(const size_t& attacker_archetype_id) const {
size_t defense = SIZE_T_DEFAULT_VALUE;
for (size_t i = 0; i < _stats.size(); ++i) {
size_t modifier;
size_t class_bonus;
size_t items_bonus;
_class.get_defense_mods(i, modifier);
_class.get_stat_bonuses(i, class_bonus);
_equipment.get_bonuses(i, items_bonus);
defense += ((_stats[i] + class_bonus + items_bonus) * modifier / PERCENT_CAP);
}
size_t defense_mod;
_class.get_defense_modifiers(attacker_archetype_id, defense_mod);
defense = defense * defense_mod / PERCENT_CAP;
return defense;
}
size_t Hero::get_save_data(MercenaryTemplate& save_data) const {
save_data._own_id = _own_id;
save_data._name.clear()
save_data._name = _name;
save_data._description.clear();
save_data._description = _description;
save_data._level = _level;
save_data._faction_id = _faction_id;
save_data._health = _health;
save_data._stats.clear();
save_data._stats = _stats;
save_data._class_id = _class.get_own_id();
save_data._experience.clear();
save_data._experience = _experience;
save_data._personality.clear/();
save_data._personality = _personality;
save_data._history.clear();
save_data._history = _history;
_equipment.get_save_data(save_data._equipment);
return RC_OK;
}
size_t Hero::set_class(Hero& value) {
_class = value;
return RC_OK;
}
size_t Hero::set_experience(const std::vector<size_t>& value) {
if (value.empty) {
return RC_BAD_INPUT;
}
_experience.clear();
_experience = value;
return RC_OK;
}
size_t Hero::set_experience(const size_t& index, const size_t& value) {
if (index < _experience.size()) {
_experience[index] = value;
return RC_OK;
} else {
return RC_BAD_INDEX;
}
}
size_t Hero::set_personality(const std::vector<size_t>& value) {
if (value.empty()) {
return RC_BAD_INPUT;
}
_personality.clear();
_personality = value;
return RC_OK;
}
size_t Hero::set_personality(const size_t& index, const size_t& value) {
if (index < _personality.size()) {
_personality[index] = value;
return RC_OK;
} else {
return RC_BAD_INDEX;
}
}
size_t Hero::set_history(const std::vector<size_t>& value) {
if (value.empty()) {
return RC_BAD_INPUT;
}
_history.clear();
_history = value;
return RC_OK;
}
size_t Hero::set_history(const size_t& index, const size_t& value) {
if (index < _history.size()) {
_history[index] = value;
return RC_OK;
} else {
return RC_BAD_INDEX;
}
}
size_t Hero::what(std::string& result) const {
result.clear();
result += _name;
result.append(" ");
std::string buffer;
buffer.clear();
_class.short_what(buffer);
result += buffer;
buffer.clear();
result.append("\n\n");
convert_to_string(_level, buffer);
result += buffer;
buffer.clear();
result.append(" Level (");
convert_to_string(_experience[0], buffer);
result += buffer;
buffer.clear();
result.append(" / ");
convert_to_string(_experience[1], buffer);
result += buffer;
buffer.clear();
result.append(" Exp)\nHealth: ");
_dictionary->get_health_state(_health, buffer);
buffer.append("\nFaction: ");
result += buffer;
buffer.clear();
_faction.get_name(buffer);
result += buffer;
buffer.clear();
result.append("\n\nStats:\n");
std::vector<size_t> equipment_bonuses;
_equipment.get_bonuses(equipment_bonuses);
for (size_t i = 0; i < _stats.size(); ++i) {
_dictionary->get_stat_name(i, buffer);
result.append(": ");
buffer.clear();
convert_to_string(_stats[i] + equipment_bonuses[i], buffer);
result += buffer;
buffer.clear();
result.append(" (");
convert_to_string(_stats[i], buffer);
result += buffer;
buffer.clear();
convert_to_string(equipment_bonuses[i], buffer);
result.append(" + ");
result += buffer;
buffer.clear();
result.append(")\n");
}
result.apppend("History:\n");
for (size_t i = 0; i < _history.size(); ++i) {
_dictionary->get_hero_history_name(i, buffer);
result.append(": ");
buffer.clear();
convert_to_string(_history[i], buffer);
result += buffer;
buffer.clear();
result.append("\n");
}
return RC_OK;
}
size_t Hero::short_what(std::string& result) const {
result.clear();
result += _name;
result.append(" ");
std::string buffer;
buffer.clear();
_class.short_what(buffer);
result += buffer;
buffer.clear();
result.append("\n\n");
convert_to_string(_level, buffer);
result += buffer;
buffer.clear();
result.append(" Level (");
convert_to_string(_experience[0], buffer);
result += buffer;
buffer.clear();
result.append(" / ");
convert_to_string(_experience[1], buffer);
result += buffer;
buffer.clear();
result.append(" Exp)\nHealth: ");
_dictionary->get_health_state(_health, buffer);
buffer.append("\nFaction: ");
result += buffer;
buffer.clear();
_faction.short_what(buffer);
result += buffer;
buffer.clear();
return RC_OK;
}
size_t Hero::update() {
while (_experience[0] >= _experience[1]) {
level_up();
}
if (_health == CH_DEAD) {
// some code here to send suicide message
_to_delete = true;
}
if (_quest == NULL && _guild != NULL) {
// some code here to process idle activity (only for player guild members)
}
return RC_OK;
}
size_t Hero::equip(Item*& item, const size_t& slot) {
if (item != NULL) {
// check if hero is able to wear that item
if (_level < item->get_level()) {
return RC_BAD_INPUT;
}
if ()
// calculating the target slot
size_t slot = SIZE_T_DEFAULT_VALUE;
bool if_slot = BOOL_DEFAULT_VALUE;
for (size_t i = 0; i < IS_SIZE; ++i) {
item->get_slot(i, if_slot);
if (if_slot) {
slot = i;
Item* is_free = NULL;
_equipment.get_equipment(i, is_free);
if (is_free == NULL) {
break;
}
}
}
_equipment.set_equipment(slot, item);
return RC_OK;
} else {
if (slot < IS_SIZE) {
Item* in_slot = NULL;
_equipment.get_equipment(slot, in_slot);
if (in_slot != NULL) {
in_slot->set_owner_id(FREE_ID);
_equipment.set_equipment(slot, item);
return RC_OK;
} else {
return RC_OK;
}
} else {
return RC_BAD_INPUT;
}
}
}
size_t Hero::add_history(const size_t& index, const size_t& amount) {
if (index < _history.size()) {
_history[index] += amount;
return RC_OK;
} else {
return RC_BAD_INDEX;
}
}
size_t Hero::add_experience(const size_t& amount) {
_experience[0] += amount;
level_up();
return RC_OK;
}
size_t Hero::add_quest(Quest* to_add) {
if (_quest != NULL) {
return RC_ALREADY_BUSY;
}
if (to_add = NULL) {
return RC_BAD_INPUT;
}
if (to_add->get_party_size() >= MAX_HEROES_PER_QUEST) {
return RC_BAD_INPUT;
}
_quest = to_add;
_quest->add_hero(this);
return RC_OK;
}
size_t Hero::remove_quest() {
if (_quest != NULL) {
_quest->remove_hero(this);
}
_quest = NULL;
return RC_OK;
}
size_t Hero::enter_guild(Player* to_add) {
if (_guild != NULL) {
return RC_ALREADY_HIRED;
}
if (to_add == NULL) {
return RC_BAD_INPUT;
}
_guild = to_add;
return RC_OK;
}
size_t Hero::leave_guild() {
if (_guild != NULL) {
_guild->remove_hero(this);
}
_guild = NULL;
return RC_OK;
}
| [
"kvcherk@live.ru"
] | kvcherk@live.ru |
4e1f6f2524450ed0b5418535a3d594acb8dae967 | 0be5e29a1526c0470be2b288bc7f36755f7564e9 | /417. Pacific Atlantic Water Flow/solution_1.cpp | dbe161560abffc1eba0ecd24614494b5ab892513 | [] | no_license | XutongLi/Leetcode-Solution | 019e8f959f6b5b3ce4719d4415adffe730156a6c | 17434946a7117693424853f2bbd6c9c6a2d28b95 | refs/heads/master | 2021-11-04T23:25:55.265763 | 2021-11-01T14:38:49 | 2021-11-01T14:38:49 | 141,797,505 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,766 | cpp | class Solution {
private:
void dfs(const vector<vector<int>>& arr, int i, int j, vector<vector<vector<bool>>> &mem, int m, int n, int flag) {
mem[flag][i][j] = true;
for (int h = -1; h <= 1; ++ h) {
for (int v = -1; v <= 1; ++ v) {
if (h == 0 && v == 0 || h != 0 && v != 0)
continue;
int x = i + h, y = j + v;
if (x < 0 || x >= m || y < 0 || y >= n || arr[x][y] < arr[i][j] || mem[flag][x][y])
continue;
dfs(arr, x, y, mem, m, n, flag);
}
}
}
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {
int m = matrix.size(), n = m > 0 ? matrix[0].size() : 0;
vector<vector<int>> res;
if (m == 0 || n == 0)
return res;
vector<vector<vector<bool>>> mem(2, vector<vector<bool>>(m, vector<bool>(n, false))); //0 - Pac 1 - Atl
//从边缘开始,沿着非递减路径对Pac和Atl分别标记mem
for(int i = 0; i < m; ++ i) {
if (!mem[0][i][0])
dfs(matrix, i, 0, mem, m, n, 0);
if (!mem[1][i][n - 1])
dfs(matrix, i, n - 1, mem, m, n, 1);
}
for (int j = 0; j < n; ++ j) {
if (!mem[0][0][j])
dfs(matrix, 0, j, mem, m, n, 0);
if (!mem[1][m - 1][j])
dfs(matrix, m - 1, j, mem, m, n, 1);
}
for (int i = 0; i < m; ++ i) {
for (int j = 0; j < n; ++ j) {
if (mem[0][i][j] && mem[1][i][j])
res.push_back(vector<int>{i, j});
}
}
return res;
}
};
//DFS with Memoization
//time O(mn) space O(mn) | [
"brianleelxt@gmail.com"
] | brianleelxt@gmail.com |
d1bf008a5219b028b436d53abcb8f4c0ecbb5b37 | b3f3a5ac8c57d6fe96fc74df732143b36fa2479b | /chapter1/1-16/1-16.cpp | 67a6138014ef236becc0b2b18b03063eff7996ed | [] | no_license | wangzhengyang/MyC-PrimerAnswer | 19ef7064b7e48f63e86e896e914dd8c92300d49e | c86ceea1667d3bb9078c22a55ec806c098773f46 | refs/heads/master | 2022-12-09T14:58:47.218957 | 2020-09-01T09:49:15 | 2020-09-01T09:49:15 | 261,182,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 189 | cpp | #include <iostream>
int main()
{
int val = 0;
int sum = 0;
while(std::cin >> val){
sum += val;
}
std::cout << "the sum is " << sum << std::endl;
return 0;
} | [
"1484413135@qq.com"
] | 1484413135@qq.com |
f36bb3043cfedad28d8b8c8eaf4823b9f7db5fe3 | e42c817747f4d4d539dcf745dbf94b1bb9701466 | /TypeTraits.h | a2a6298908fa035a5ed4c434b37a17d503bad136 | [
"Apache-2.0"
] | permissive | nikitamikhaylov/TypeTraitsFunctorVisitor | 9d3e78665a2a4512788b12a6a95b26ad5037c9fb | 8eec9c0e966b0ee8c8b1e0dade0d4be623639168 | refs/heads/master | 2020-11-25T13:26:12.333164 | 2019-12-17T19:28:33 | 2019-12-17T19:28:33 | 228,685,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,278 | h | #pragma once
#include "TypeList.h"
namespace type_traits {
/// helpers
struct false_type
{
static constexpr bool value = false;
};
struct true_type
{
static constexpr bool value = true;
};
template <typename T>
using add_rvalue_reference_t = T&&;
template <typename T>
add_rvalue_reference_t<T> declval();
/// enable_if_t
template <bool, typename = void>
struct enable_if {};
template <typename T>
struct enable_if<true, T> {
using type = T;
};
template <bool B, typename T = void>
using enable_if_t = typename enable_if<B, T>::type;
/// is_class
namespace detail
{
template <typename T, typename = typename enable_if<!std::is_union<T>::value>::type>
std::true_type test(int T::*);
template <typename T>
std::false_type test(...);
}
template <class T>
struct is_class : decltype(detail::test<T>(nullptr))
{};
/// is_base_of
namespace detail {
template <typename Base>
true_type is_base_of_test_func(const volatile Base*);
template <typename Base>
false_type is_base_of_test_func(const volatile void*);
template <typename Base, typename Derived>
using pre_is_base_of = decltype(is_base_of_test_func<Base>(declval<Derived*>()));
template <typename Base, typename Derived, typename = void>
struct pre_is_base_of2 : public true_type { };
template <typename Base, typename Derived>
struct pre_is_base_of2<Base, Derived, std::void_t<pre_is_base_of<Base, Derived>>> :
public pre_is_base_of<Base, Derived> { };
}
template<bool B, class T, class F>
struct conditional { typedef T type; };
template<class T, class F>
struct conditional<false, T, F> { typedef F type; };
template< bool B, class T, class F >
using conditional_t = typename conditional<B,T,F>::type;
template <typename Base, typename Derived>
struct is_base_of : public conditional_t<
is_class<Base>::value && is_class<Derived>::value,
detail::pre_is_base_of2<Base, Derived>, false_type> { };
/// is_abstract
namespace detail
{
template <typename T, typename = decltype(new T[1])>
false_type is_abstract_(int);
template <typename>
true_type is_abstract_(...);
}
template <typename T>
struct is_abstract : decltype(detail::is_abstract_<T>(0)) {};
template <typename TL, template <typename> class Condition>
struct Split {
typedef typelist::EmptyList accept;
typedef typelist::EmptyList reject;
};
template <typename H, typename... T, template <typename> class Condition>
class Split<typelist::TypeList<H, T...>, Condition> {
private:
typedef typename Split<typelist::TypeList<T...>, Condition>::accept accepted_prev;
typedef typename Split<typelist::TypeList<T...>, Condition>::reject rejected_prev;
public:
typedef conditional_t<Condition<H>::value, typelist::Append<accepted_prev, H>, accepted_prev> accept;
typedef conditional_t<Condition<H>::value, rejected_prev, typelist::Append<rejected_prev, H>> reject;
};
}
| [
"mikhaylovnikitka@gmail.com"
] | mikhaylovnikitka@gmail.com |
9ab92a83a61b807607b89aa97bbe86e3c459721f | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5670465267826688_0/C++/ch11y/c.cpp | 472eed533f47fd144bc511d17f5d092a0346418c | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,180 | cpp | #include <iostream>
#include <map>
#include <vector>
#include <string>
#include <set>
#include <bitset>
#include <algorithm>
#include <numeric>
#include <queue>
#include <list>
#include <limits>
#include <stack>
#include <sstream>
#include <fstream>
#include <ctime>
#include <cstdlib>
#include <complex>
#include <cctype>
#include <iomanip>
#include <functional>
#include <cstring>
using namespace std;
typedef long long int64 ;
typedef unsigned long long uint64 ;
#define two(X) (1<<(X))
#define twoL(X) (((int64)(1))<<(X))
#define PB push_back
#define SZ(X) ((int)(X.size()))
#define LEN(X) ((int)(X.length()))
int sign [][4]={
1,1,1,1,
1,-1,1,-1,
1,-1,-1,1,
1,1,-1,-1
};
int tran[][4]={
0,1,2,3,
1,0,3,2,
2,3,0,1,
3,2,1,0
};
inline int char2int(char c){
return c-'i'+1;
}
int main (){
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
int T;
cin >> T;
for(int Cas = 1 ; Cas <= T ; ++Cas){
int64 X,L;
cin >> L >> X;
string s;
cin >> s;
int left = -1;
pair<int, int> leftcur = make_pair(1,0);
int64 leftpos = -1;
for(int i = 0 ; i < min(X,4LL); ++i){
for(int j = 0 ; j < s.length(); ++j){
leftcur.first = leftcur.first*sign[leftcur.second][char2int(s[j])];
leftcur.second = tran[leftcur.second][char2int(s[j])];
if(leftcur.first==1&&leftcur.second==1){
leftpos = i*s.length()+j+1;
break;
}
}
if(leftpos!=-1) break;
}
int rsign[4][4], rtran[4][4];
for(int i=0;i<4;++i)
for(int j=0;j<4;++j)
rsign[i][j]=sign[j][i],rtran[i][j]=tran[j][i];
pair<int,int> rightcur = make_pair(1,0);
int64 rightpos =-1;
for(int i=0; i < min(X,4LL); ++i){
for(int j=s.length()-1; j>=0; --j){
rightcur.first = rightcur.first*rsign[rightcur.second][char2int(s[j])];
rightcur.second = rtran[rightcur.second][char2int(s[j])];
if(rightcur.first==1&&rightcur.second==3){
rightpos = i*s.length()+s.length()-j;
break;
}
}
if(rightpos!=-1) break;
}
pair<int,int> cur = make_pair(1,0);
for(int i=0; i < s.length(); ++i){
cur.first = cur.first*sign[cur.second][char2int(s[i])];
cur.second = tran[cur.second][char2int(s[i])];
}
bool can = false;
int res = (X%4==0)?4:X%4;
pair<int,int> tmp=cur;
for(int i = 0 ; i < res-1; ++i){
cur.first = cur.first*tmp.first*sign[cur.second][tmp.second];
cur.second = tran[cur.second][tmp.second];
}
if(cur.first==-1&&cur.second==0)
can = true;
bool ans = true;
if( !can || leftpos==-1 || rightpos==-1 ||leftpos+rightpos > X*L)
ans = false;
cout <<"Case #"<<Cas<<": "<<(ans?"YES":"NO")<<endl;
}
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
f51872a22584c56c6ca151239ebacd89e1121215 | a794871c9be87ebfa2596cf1bbc3cca611613311 | /src/KMZLoader.cpp | 4e659243d0274f4d7f238b08dedd2b3201f4709f | [
"MIT"
] | permissive | wonlake/Direct3D11Framework | d0c0de7b1323e5a1b2cff032b1469c8e43f4e7f9 | 3f36f0cae1ac36950d732fc1cbdbeba16ee66991 | refs/heads/master | 2021-01-22T04:01:46.104244 | 2017-05-25T16:32:25 | 2017-05-25T16:32:25 | 92,422,910 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 62,235 | cpp | //
// Copyright (C) Mei Jun 2011
//
/*
#include "KMZLoader.h"
#include "Utility.h"
#include <zzip/zzip.h>
#ifdef _DEBUG
#pragma comment( lib, "dom_d.lib" )
#pragma comment( lib, "zlib_d.lib")
#pragma comment( lib, "zziplib_d.lib")
#else
#pragma comment( lib, "dom.lib" )
#pragma comment( lib, "zlib.lib" )
#pragma comment( lib, "zziplib.lib")
#endif
KMZLoader::ConstantBuffer KMZLoader::s_Buffer;
KMZLoader::PSConstantBuffer KMZLoader::s_PSBuffer;
ID3D11InputLayout* KMZLoader::m_lpInputLayout = NULL;
ID3D11VertexShader* KMZLoader::m_lpVertexShader = NULL;
ID3D11PixelShader* KMZLoader::m_lpPixelShader = NULL;
ID3D11GeometryShader* KMZLoader::m_lpGeometryShader = NULL;
ID3D11Buffer* KMZLoader::m_lpVSConstBufferWorldViewProj = NULL;
DWORD KMZLoader::m_dwShaderBytecodeSize = 0;
VOID* KMZLoader::m_lpShaderBytecodeInput = NULL;
DWORD KMZLoader::m_Reference = 0;
ID3D11InputLayout* KMZLoader::m_lpInputLayoutForNoTexture = NULL;
ID3D11VertexShader* KMZLoader::m_lpVertexShaderForNoTexture = NULL;
ID3D11PixelShader* KMZLoader::m_lpPixelShaderForNoTexture = NULL;
ID3D11GeometryShader* KMZLoader::m_lpGeometryShaderForNoTexture = NULL;
DWORD KMZLoader::m_dwShaderBytecodeSizeForNoTexture = 0;
VOID* KMZLoader::m_lpShaderBytecodeInputForNoTexture = NULL;
ID3D11Buffer* KMZLoader::m_lpPSConstBufferDiffuse = NULL;
ID3D11RasterizerState* KMZLoader::m_lpRasterizerState = NULL;
ID3D11RasterizerState* KMZLoader::m_lpRasterizerStateForNoCull = NULL;
KMZLoader::KMZLoader( ID3D11Device* lpDevice, ID3D11DeviceContext* lpDeviceContext )
{
m_lpDevice = lpDevice;
m_lpDeviceContext = lpDeviceContext;
m_pRoot = NULL;
m_fScale = 1.0f;
m_lpTexture = NULL;
m_lpResourceView = NULL;
m_lpResourceViewExchange = NULL;
m_lpVertexBuffer = NULL;
m_lpIndexBuffer = NULL;
++m_Reference;
if( m_Reference == 1 )
{
SetupShaders();
SetupShadersForNoTexture();
SetupInput();
SetupInputForNoTexture();
CreateRenderState();
}
for( int i = 0; i < 3; ++i )
{
m_Max[i] = -FLT_MAX;
m_Min[i] = FLT_MAX;
m_fCenter[i] = 0.0f;
}
m_fTranslateUnit = 1.0f;
m_pBoundingBox = NULL;
m_bShowBoundingBox = FALSE;
static XMMATRIX matIdentity = XMMatrixIdentity();
memcpy( m_matTransform, &matIdentity, sizeof(XMMATRIX) );
memcpy( m_matTranslate, &matIdentity, sizeof(XMMATRIX) );
}
KMZLoader::~KMZLoader(void)
{
DestroyPrivateResource();
--m_Reference;
if( m_Reference == 0 )
{
SAFE_RELEASE( m_lpInputLayout );
SAFE_RELEASE( m_lpVertexShader );
SAFE_RELEASE( m_lpPixelShader );
SAFE_RELEASE( m_lpGeometryShader );
SAFE_RELEASE( m_lpVSConstBufferWorldViewProj );
SAFE_DELETEARRAY( m_lpShaderBytecodeInput );
SAFE_RELEASE( m_lpInputLayoutForNoTexture );
SAFE_RELEASE( m_lpVertexShaderForNoTexture );
SAFE_RELEASE( m_lpPixelShaderForNoTexture );
SAFE_RELEASE( m_lpGeometryShaderForNoTexture );
SAFE_RELEASE( m_lpPSConstBufferDiffuse );
SAFE_DELETEARRAY( m_lpShaderBytecodeInputForNoTexture );
SAFE_RELEASE( m_lpRasterizerState );
SAFE_RELEASE( m_lpRasterizerStateForNoCull );
}
}
VOID KMZLoader::DestroyPrivateResource()
{
SAFE_DELETE( m_pRoot );
SAFE_DELETE( m_pBoundingBox );
//清除Collada模型对象链
{
std::list<KMZLoader*>::iterator iter =
m_listDaeLoaders.begin();
while( iter != m_listDaeLoaders.end() )
{
SAFE_DELETE(*iter);
++iter;
}
m_listDaeLoaders.clear();
}
//清除纹理数据
{
std::map<std::string, ID3D11ShaderResourceView*>::iterator iter =
m_mapTextures.begin();
while( iter != m_mapTextures.end() )
{
SAFE_RELEASE(iter->second);
++iter;
}
m_mapTextures.clear();
}
SAFE_RELEASE( m_lpVertexBuffer );
SAFE_RELEASE( m_lpIndexBuffer );
SAFE_RELEASE( m_lpTexture );
SAFE_RELEASE( m_lpResourceView );
//清除几何数据
{
std::vector<GEOMETRY>::iterator iter = m_vecGeometries.begin();
while( iter != m_vecGeometries.end() )
{
int numMeshes = (*iter).nNumMeshes;
for( int j= 0; j < numMeshes; j++ )
{
MESH* pMesh = &(*iter).pMeshes[j];
SAFE_RELEASE( (*iter).pMeshes[j].pVertexBuffer );
}
SAFE_DELETEARRAY( (*iter).pMeshes );
++iter;
}
}
m_fTranslateUnit = 1.0f;
for( int i = 0; i < 3; ++i )
{
m_Max[i] = -FLT_MAX;
m_Min[i] = FLT_MAX;
m_fCenter[i] = 0.0f;
}
static XMMATRIX matIdentity = XMMatrixIdentity();
memcpy( m_matTransform, &matIdentity, sizeof(XMMATRIX) );
memcpy( m_matTranslate, &matIdentity, sizeof(XMMATRIX) );
}
void KMZLoader::Render( XMMATRIX* pWorldViewMatrix, XMMATRIX* pProjMatrix )
{
ID3D11Device* lpDevice = m_lpDevice;
if( m_listDaeLoaders.size() > 0 )
{
static XMMATRIX matIdentity = XMMatrixIdentity();
std::list<KMZLoader*>::iterator iter =
m_listDaeLoaders.begin();
while( iter != m_listDaeLoaders.end() )
{
XMMATRIX matTranslate = matIdentity;
memcpy( &matTranslate, (*iter)->m_matTranslate, sizeof(XMMATRIX) );
XMMATRIX matWorldView = *pWorldViewMatrix * matTranslate;
XMMATRIX matWorldViewProj = matWorldView * *pProjMatrix;
ID3D11RasterizerState* pOrig = NULL;
if( m_lpRasterizerState )
{
m_lpDeviceContext->RSGetState( &pOrig );
m_lpDeviceContext->RSSetState( m_lpRasterizerState );
}
TraverseSceneGraphForOpaque(lpDevice, *iter, &matWorldViewProj, &matWorldView );
TraverseSceneGraphForTransparent(lpDevice, *iter, &matWorldViewProj, &matWorldView );
if( pOrig )
m_lpDeviceContext->RSSetState( pOrig );
if( m_bShowBoundingBox )
{
XMMATRIX matTransform = matIdentity;
memcpy( &matTransform, (*iter)->m_matTransform, sizeof(XMMATRIX) );
(*iter)->RenderBoundingBox( &( matTransform * matWorldViewProj) );
}
++iter;
}
}
}
void KMZLoader::RenderBoundingBox( XMMATRIX* pWorldViewProjMatrix )
{
if( m_pBoundingBox )
m_pBoundingBox->Render( pWorldViewProjMatrix );
}
void KMZLoader::TraverseSceneGraphForOpaque( ID3D11Device* lpDevice,
KMZLoader* pDaeLoader, XMMATRIX* pWorldViewProjMatrix, XMMATRIX* pWorldView )
{
std::list<scene_node_t* >::iterator iter =
pDaeLoader->m_listRenderableNodes.begin();
static XMMATRIX matIdentity = XMMatrixIdentity();
static XMVECTOR vZero = XMVectorZero();
while( iter != pDaeLoader->m_listRenderableNodes.end() )
{
XMMATRIX matTransform = matIdentity;
memcpy( &matTransform, (*iter)->_transform, sizeof(XMMATRIX) );
XMMATRIX matPTransform = matIdentity;
memcpy( &matPTransform, pDaeLoader->m_matTransform, sizeof(XMMATRIX) );
XMMATRIX WorldMatrix = matTransform * matPTransform;
int numGeos = (*iter)->_geos.size();
for( int i = 0; i < numGeos; ++i )
{
int numMeshes = (*iter)->_geos[i]->nNumMeshes;
for( int j= 0; j < numMeshes; j++ )
{
DWORD materialID = (*iter)->_geos[i]->pMeshes[j].nMaterialID;
static BOOL bComplete = FALSE;
if( materialID != 0xFFFFFFFF )
{
if( pDaeLoader->m_vecMaterials[materialID].bIsTransparent )
continue;
UINT stride = sizeof(VERTEX_DATA);
UINT offset = 0;
if( pDaeLoader->m_vecMaterials[materialID].pTexture )
{
m_lpDeviceContext->IASetInputLayout( m_lpInputLayout );
m_lpDeviceContext->IASetVertexBuffers( 0, 1, &(*iter)->_geos[i]->pMeshes[j].pVertexBuffer, &stride, &offset );
m_lpDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
memcpy( s_Buffer.matWorldViewProj, &(WorldMatrix * (*pWorldViewProjMatrix)), sizeof(XMMATRIX) );
D3D11_MAPPED_SUBRESOURCE pData;
m_lpDeviceContext->Map( m_lpVSConstBufferWorldViewProj, 0, D3D11_MAP_WRITE_DISCARD, 0, &pData );
memcpy_s( pData.pData, pData.RowPitch, (void*)( &s_Buffer ), sizeof(ConstantBuffer) );
m_lpDeviceContext->Unmap( m_lpVSConstBufferWorldViewProj, 0 );
m_lpDeviceContext->VSSetConstantBuffers( 0, 1, &m_lpVSConstBufferWorldViewProj );
m_lpDeviceContext->VSSetShader( m_lpVertexShader, NULL, 0 );
m_lpDeviceContext->PSSetShader( m_lpPixelShader, NULL, 0 );
m_lpDeviceContext->GSSetShader( m_lpGeometryShader, NULL, 0 );
m_lpDeviceContext->PSSetShaderResources( 0, 1, &pDaeLoader->m_vecMaterials[materialID].pTexture );
}
else
{
m_lpDeviceContext->IASetInputLayout( m_lpInputLayoutForNoTexture );
m_lpDeviceContext->IASetVertexBuffers( 0, 1, &(*iter)->_geos[i]->pMeshes[j].pVertexBuffer, &stride, &offset );
m_lpDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
memcpy( s_Buffer.matWorldViewProj, &(WorldMatrix * (*pWorldViewProjMatrix)), sizeof(XMMATRIX) );
memcpy( s_Buffer.matWorldView, &(WorldMatrix * *pWorldView), sizeof(XMMATRIX) );
XMVECTOR vecDeterminant = vZero;
XMMATRIX matWorldViewForNormal =
XMMatrixTranspose( XMMatrixInverse( &vecDeterminant, s_Buffer.matWorldView) );
memcpy( s_Buffer.matWorldViewForNormal, &matWorldViewForNormal, sizeof(XMMATRIX) );
D3D11_MAPPED_SUBRESOURCE pData;
m_lpDeviceContext->Map( m_lpVSConstBufferWorldViewProj, 0, D3D11_MAP_WRITE_DISCARD, 0, &pData );
memcpy_s( pData.pData, pData.RowPitch, (void*)( &s_Buffer ), sizeof(ConstantBuffer) );
m_lpDeviceContext->Unmap( m_lpVSConstBufferWorldViewProj, 0 );
m_lpDeviceContext->VSSetConstantBuffers( 0, 1, &m_lpVSConstBufferWorldViewProj );
memcpy( s_PSBuffer.color,
pDaeLoader->m_vecMaterials[materialID].Diffuse, sizeof(float) * 4 );
s_PSBuffer.tranparency =
pDaeLoader->m_vecMaterials[materialID].Transparency;
memcpy( s_PSBuffer.specular,
pDaeLoader->m_vecMaterials[materialID].Specular, sizeof(float) * 4 );
s_PSBuffer.power[0] =
pDaeLoader->m_vecMaterials[materialID].Power;
m_lpDeviceContext->Map( m_lpPSConstBufferDiffuse, 0, D3D11_MAP_WRITE_DISCARD, 0, &pData );
memcpy_s( pData.pData, pData.RowPitch, (void*)(&s_PSBuffer), sizeof(PSConstantBuffer) );
m_lpDeviceContext->Unmap( m_lpPSConstBufferDiffuse, 0 );
m_lpDeviceContext->PSSetConstantBuffers( 0, 1, &m_lpPSConstBufferDiffuse );
m_lpDeviceContext->VSSetShader( m_lpVertexShaderForNoTexture, NULL, 0 );
m_lpDeviceContext->PSSetShader( m_lpPixelShaderForNoTexture, NULL, 0 );
m_lpDeviceContext->GSSetShader( m_lpGeometryShaderForNoTexture, NULL, 0 );
}
}
else
continue;
ID3D11RasterizerState* pOrig = NULL;
if( pDaeLoader->m_vecMaterials[materialID].bDoubleSided )
{
m_lpDeviceContext->RSGetState( &pOrig );
m_lpDeviceContext->RSSetState( m_lpRasterizerStateForNoCull );
}
m_lpDeviceContext->Draw(
(*iter)->_geos[i]->pMeshes[j].nNumVertices, 0 );
if( pOrig )
m_lpDeviceContext->RSSetState( pOrig );
}
}
++iter;
}
}
void KMZLoader::TraverseSceneGraphForTransparent( ID3D11Device* lpDevice,
KMZLoader* pDaeLoader, XMMATRIX* pWorldViewProjMatrix, XMMATRIX* pWorldView )
{
std::list<scene_node_t* >::iterator iter =
pDaeLoader->m_listRenderableNodes.begin();
static XMMATRIX matIdentity = XMMatrixIdentity();
static XMVECTOR vZero = XMVectorZero();
while( iter != pDaeLoader->m_listRenderableNodes.end() )
{
XMMATRIX matTransform = matIdentity;
memcpy( &matTransform, (*iter)->_transform, sizeof(XMMATRIX) );
XMMATRIX matPTransform = matIdentity;
memcpy( &matPTransform, pDaeLoader->m_matTransform, sizeof(XMMATRIX) );
XMMATRIX WorldMatrix = matTransform * matPTransform;
int numGeos = (*iter)->_geos.size();
for( int i = 0; i < numGeos; ++i )
{
int numMeshes = (*iter)->_geos[i]->nNumMeshes;
for( int j= 0; j < numMeshes; j++ )
{
DWORD materialID = (*iter)->_geos[i]->pMeshes[j].nMaterialID;
static BOOL bComplete = FALSE;
if( materialID != 0xFFFFFFFF )
{
if( !pDaeLoader->m_vecMaterials[materialID].bIsTransparent )
continue;
UINT stride = sizeof(VERTEX_DATA);
UINT offset = 0;
if( pDaeLoader->m_vecMaterials[materialID].pTexture )
{
m_lpDeviceContext->IASetInputLayout( m_lpInputLayout );
m_lpDeviceContext->IASetVertexBuffers( 0, 1, &(*iter)->_geos[i]->pMeshes[j].pVertexBuffer, &stride, &offset );
m_lpDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
memcpy( s_Buffer.matWorldViewProj, &(WorldMatrix * (*pWorldViewProjMatrix)), sizeof(XMMATRIX) );
D3D11_MAPPED_SUBRESOURCE pData;
m_lpDeviceContext->Map( m_lpVSConstBufferWorldViewProj, 0, D3D11_MAP_WRITE_DISCARD, 0, &pData );
memcpy_s( pData.pData, pData.RowPitch, (void*)( &s_Buffer ), sizeof(ConstantBuffer) );
m_lpDeviceContext->Unmap( m_lpVSConstBufferWorldViewProj, 0 );
m_lpDeviceContext->VSSetConstantBuffers( 0, 1, &m_lpVSConstBufferWorldViewProj );
m_lpDeviceContext->VSSetShader( m_lpVertexShader, NULL, 0 );
m_lpDeviceContext->PSSetShader( m_lpPixelShader, NULL, 0 );
m_lpDeviceContext->GSSetShader( m_lpGeometryShader, NULL, 0 );
m_lpDeviceContext->PSSetShaderResources( 0, 1, &pDaeLoader->m_vecMaterials[materialID].pTexture );
}
else
{
m_lpDeviceContext->IASetInputLayout( m_lpInputLayoutForNoTexture );
m_lpDeviceContext->IASetVertexBuffers( 0, 1, &(*iter)->_geos[i]->pMeshes[j].pVertexBuffer, &stride, &offset );
m_lpDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
memcpy( s_Buffer.matWorldViewProj, &(WorldMatrix * (*pWorldViewProjMatrix)), sizeof(XMMATRIX) );
memcpy( s_Buffer.matWorldView, &(WorldMatrix * *pWorldView), sizeof(XMMATRIX) );
XMVECTOR vecDeterminant = vZero;
XMMATRIX matWorldViewForNormal =
XMMatrixTranspose( XMMatrixInverse( &vecDeterminant, s_Buffer.matWorldView) );
memcpy( s_Buffer.matWorldViewForNormal, &matWorldViewForNormal, sizeof(XMMATRIX) );
D3D11_MAPPED_SUBRESOURCE pData;
m_lpDeviceContext->Map( m_lpVSConstBufferWorldViewProj, 0, D3D11_MAP_WRITE_DISCARD, 0, &pData );
memcpy_s( pData.pData, pData.RowPitch, (void*)( &s_Buffer ), sizeof(ConstantBuffer) );
m_lpDeviceContext->Unmap( m_lpVSConstBufferWorldViewProj, 0 );
m_lpDeviceContext->VSSetConstantBuffers( 0, 1, &m_lpVSConstBufferWorldViewProj );
memcpy( s_PSBuffer.color,
pDaeLoader->m_vecMaterials[materialID].Diffuse, sizeof(float) * 4 );
s_PSBuffer.tranparency =
pDaeLoader->m_vecMaterials[materialID].Transparency;
memcpy( s_PSBuffer.specular,
pDaeLoader->m_vecMaterials[materialID].Specular, sizeof(float) * 4 );
s_PSBuffer.power[0] =
pDaeLoader->m_vecMaterials[materialID].Power;
m_lpDeviceContext->Map( m_lpPSConstBufferDiffuse, 0, D3D11_MAP_WRITE_DISCARD, 0, &pData );
memcpy_s( pData.pData, pData.RowPitch, (void*)(&s_PSBuffer), sizeof(PSConstantBuffer) );
m_lpDeviceContext->Unmap( m_lpPSConstBufferDiffuse, 0 );
m_lpDeviceContext->PSSetConstantBuffers( 0, 1, &m_lpPSConstBufferDiffuse );
m_lpDeviceContext->VSSetShader( m_lpVertexShaderForNoTexture, NULL, 0 );
m_lpDeviceContext->PSSetShader( m_lpPixelShaderForNoTexture, NULL, 0 );
m_lpDeviceContext->GSSetShader( m_lpGeometryShaderForNoTexture, NULL, 0 );
}
}
else
continue;
ID3D11RasterizerState* pOrig = NULL;
if( pDaeLoader->m_vecMaterials[materialID].bDoubleSided )
{
m_lpDeviceContext->RSGetState( &pOrig );
m_lpDeviceContext->RSSetState( m_lpRasterizerStateForNoCull );
}
m_lpDeviceContext->Draw(
(*iter)->_geos[i]->pMeshes[j].nNumVertices, 0 );
if( pOrig )
m_lpDeviceContext->RSSetState( pOrig );
}
}
++iter;
}
}
void KMZLoader::LoadColladaMeshFromKMZ( LPCTSTR lpFilename )
{
DestroyPrivateResource();
std::map<std::string, DATA_SIZE> file_stream;
std::list<std::string> dae_list;
size_t len = WideCharToMultiByte( CP_ACP, 0, lpFilename, -1, NULL, 0, NULL, NULL );
char* pFileName = new char[len];
WideCharToMultiByte( CP_ACP, 0, lpFilename, -1, pFileName, len, NULL, NULL );
ZZIP_DIR* dir = zzip_opendir( pFileName );
SAFE_DELETEARRAY( pFileName );
ZZIP_DIRENT* dirrent = NULL;
while( dirrent = zzip_readdir( dir ) )
{
size_t length = strlen(dirrent->d_name);
if( length > 0 )
{
if( dirrent->d_name[length - 1] != '\\' &&
dirrent->d_name[length - 1] != '/' )
{
ZZIP_FILE* pFile = zzip_file_open( dir, dirrent->d_name, ZZIP_CASELESS );
if( pFile != NULL )
{
ZZIP_STAT sz;
ZeroMemory( &sz, sizeof(sz) );
zzip_file_stat( pFile, &sz );
if( sz.st_size > 0 )
{
bool bDae = false;
if( length > 4 )
{
if( !stricmp(dirrent->d_name + length - 4, ".dae") )
{
dae_list.push_back( _strlwr(dirrent->d_name) );
bDae = true;
}
}
char* pBuffer = NULL;
if( bDae )
{
pBuffer = new char[sz.st_size + 1];
pBuffer[sz.st_size] = 0;
}
else
pBuffer = new char[sz.st_size];
size_t num = zzip_file_read( pFile, pBuffer, sz.st_size );
if( bDae )
{
char* p = pBuffer;
while( ++p - pBuffer < sz.st_size )
{
if( *p == 0 )
*p = 0x20;
}
}
DATA_SIZE data_size = { pBuffer, sz.st_size };
file_stream.insert( std::make_pair( _strlwr(dirrent->d_name), data_size) );
}
zzip_file_close( pFile );
}
}
}
}
zzip_closedir( dir );
//if( false )
{
std::list<std::string>::iterator iter =
dae_list.begin();
while( iter != dae_list.end() )
{
KMZLoader* pDaeLoader = new KMZLoader( m_lpDevice, m_lpDeviceContext );
pDaeLoader->LoadColladaMeshFromMemory( file_stream, iter->c_str() );
m_listDaeLoaders.push_back(pDaeLoader );
++iter;
if( pDaeLoader )
m_fTranslateUnit = pDaeLoader->m_fTranslateUnit;
}
}
{
std::map<std::string, DATA_SIZE>::iterator iter =
file_stream.begin();
while( iter != file_stream.end() )
{
SAFE_DELETEARRAY(iter->second.pData);
++iter;
}
}
}
void KMZLoader::LoadColladaMeshFromMemory( std::map<std::string, DATA_SIZE>& filelist,
LPCSTR lpDaeName )
{
std::map<std::string, DATA_SIZE>::iterator file_iter =
filelist.find(lpDaeName);
if( file_iter == filelist.end() )
return;
DAE* pDae = new DAE;
domCOLLADA* pDom = pDae->openFromMemory( std::string(lpDaeName), file_iter->second.pData );
m_fScale = 1.0f;
if( pDom->getAsset()->getUnit() )
{
m_fScale = pDom->getAsset()->getUnit()->getMeter();
}
ReadImages( pDom, filelist );
ReadEffects( pDom );
ReadMaterials( pDom );
ReadGeometries( pDom );
ReadNodes( pDom );
ReadScene( pDom );
ComputeBoundingBox();
pDae->cleanup();
SAFE_DELETE(pDae);
}
void KMZLoader::ReadImages( domCOLLADA* pDom,
std::map<std::string, DATA_SIZE>& filelist )
{
int num = pDom->getLibrary_images_array().getCount();
for( int idx = 0; idx < num; ++idx )
{
domLibrary_imagesRef lib = pDom->getLibrary_images_array()[idx];
size_t numImages = lib->getImage_array().getCount();
ID3D11Device* lpDevice = m_lpDevice;
for( size_t i = 0; i < numImages; ++i )
{
domImage* pImage = lib->getImage_array()[i];
const domImage::domInit_fromRef initFrom = pImage->getInit_from();
const char* pImageFilename = initFrom->getValue().getURI();
const char* pBaseURI = pDom->getDAE()->getBaseURI().getOriginalURI();
size_t name_len = strlen(pImageFilename);
char* pFileName = new char[name_len + 1];
memcpy( pFileName, pImageFilename, name_len + 1 );
for( size_t j = 0; j < name_len; ++j )
{
if( pFileName[j] == '\\' )
pFileName[j] = '/';
}
size_t Buffer_Len = strlen(pBaseURI) - 2;
std::map<std::string, DATA_SIZE>::iterator file_iter =
filelist.find(_strlwr(pFileName + Buffer_Len));
SAFE_DELETEARRAY( pFileName );
ID3D11ShaderResourceView* lpTexture = NULL;
//if( false )
{
if( file_iter != filelist.end() )
{
D3DX11_IMAGE_LOAD_INFO loadInfo;
ZeroMemory( &loadInfo, sizeof(D3DX11_IMAGE_LOAD_INFO) );
loadInfo.BindFlags = D3D11_BIND_SHADER_RESOURCE;
loadInfo.Format = DXGI_FORMAT_BC1_UNORM;
D3DX11CreateShaderResourceViewFromMemory( lpDevice, file_iter->second.pData,
file_iter->second.dwSize, &loadInfo, NULL, &lpTexture, NULL );
}
m_mapTextures.insert( std::make_pair(pImage->getID(), lpTexture) );
}
}
break;
}
}
void KMZLoader::ReadEffects( domCOLLADA* pDom )
{
size_t num = pDom->getLibrary_effects_array().getCount();
for( size_t idx = 0; idx < num; ++idx )
{
domLibrary_effectsRef lib = pDom->getLibrary_effects_array()[idx];
size_t numEffects = lib->getEffect_array().getCount();
for( size_t i = 0; i < numEffects; ++i )
{
domEffect* pEffect = lib->getEffect_array()[i];
const char* pEffectId = pEffect->getId();
size_t numProfiles = pEffect->getFx_profile_abstract_array().getCount();
for( size_t j = 0; j < numProfiles; ++j )
{
domFx_profile_abstract* pProfile =
pEffect->getFx_profile_abstract_array()[j];
const char* pTypeName = pProfile->getTypeName();
if( !stricmp("profile_COMMON", pTypeName) )
{
domProfile_COMMON* pCommon =
(domProfile_COMMON*)pProfile;
domProfile_COMMON::domTechniqueRef pTech = pCommon->getTechnique();
domProfile_COMMON::domTechnique::domLambert* pLambert =
pTech->getLambert();
domProfile_COMMON::domTechnique::domPhong* pPhong =
pTech->getPhong();
daeElement* pLightModel = NULL;
domCommon_color_or_texture_type_complexType::domTextureRef pTexture = NULL;
if( pLambert )
{
pLightModel = pLambert;
pTexture = pLambert->getDiffuse()->getTexture();
}
else if( pPhong )
{
pLightModel = pPhong;
pTexture = pPhong->getDiffuse()->getTexture();
}
std::pair<daeElement*, std::list<domExtraRef> > pairLightModelExtra;
pairLightModelExtra.first = pLightModel;
size_t numExtras = pCommon->getExtra_array().getCount();
for( size_t k = 0; k < numExtras; ++k )
{
domExtraRef pExtra = pCommon->getExtra_array()[k];
pairLightModelExtra.second.push_back( pExtra );
}
numExtras = pEffect->getExtra_array().getCount();
for( size_t k = 0; k < numExtras; ++k )
{
domExtraRef pExtra = pEffect->getExtra_array()[k];
pairLightModelExtra.second.push_back( pExtra );
}
m_mapEffects.insert(std::make_pair(pEffectId, pairLightModelExtra));
ID3D11ShaderResourceView* lpTexture = NULL;
if( pTexture != NULL )
{
const char* pImageId = pTexture->getTexture();
size_t numNewparams = pCommon->getNewparam_array().getCount();
for( size_t k = 0; k < numNewparams; ++k )
{
domCommon_newparam_typeRef pNewparam =
pCommon->getNewparam_array()[k];
if( !strcmp( pNewparam->getSid(), pImageId ) )
{
for( size_t l = 0; l < numNewparams; ++l )
{
domCommon_newparam_typeRef pNewparam2 =
pCommon->getNewparam_array()[l];
if( pNewparam->getSampler2D()->getSource() != NULL )
{
const char* pSourceId =
pNewparam->getSampler2D()->getSource()->getValue();
if( pSourceId != NULL )
{
if( !strcmp( pNewparam2->getSid(),
pSourceId) )
{
size_t numContents = pNewparam2->getSurface()->getContents().getCount();
for( size_t m = 0; m < numContents; ++m )
{
const char* pElemName =
pNewparam2->getSurface()->getContents()[m]->getElementName();
if( !stricmp( pElemName, "init_from" ) )
{
daeElementRef pElem = pNewparam2->getSurface()->getContents()[m];
std::string TextureId;
pElem->getCharData(TextureId);
std::map<std::string, ID3D11ShaderResourceView*>::iterator iter =
m_mapTextures.find(TextureId);
if( iter != m_mapTextures.end() )
{
lpTexture = iter->second;
}
break;
}
}
break;
}
}
}
}
break;
}
}
}
m_mapEffectTextures.insert(std::make_pair(pEffectId, lpTexture) );
}
}
}
break;
}
}
void KMZLoader::ReadMaterials( domCOLLADA* pDom )
{
size_t num = pDom->getLibrary_materials_array().getCount();
for( size_t idx = 0; idx < num; ++idx )
{
domLibrary_materialsRef lib = pDom->getLibrary_materials_array()[idx];
size_t numMaterials = lib->getMaterial_array().getCount();
m_vecMaterials.resize(numMaterials);
for( size_t i = 0; i < numMaterials; ++i )
{
domMaterial* pMaterial = lib->getMaterial_array()[i];
domInstance_effectRef pEffect = pMaterial->getInstance_effect();
const char* pEffectId = pEffect->getUrl().getOriginalURI();
std::map<std::string, std::pair<daeElement*, std::list<domExtraRef> > >::iterator iter =
m_mapEffects.find( pEffectId + 1);
std::map<std::string, ID3D11ShaderResourceView*>::iterator iter2 =
m_mapEffectTextures.find( pEffectId + 1);
MATERIAL material;
if( iter != m_mapEffects.end() )
{
float AmbientR = 1.0f;
float AmbientG = 1.0f;
float AmbientB = 1.0f;
float AmbientA = 1.0f;
float DiffuseR = 1.0f;
float DiffuseG = 1.0f;
float DiffuseB = 1.0f;
float DiffuseA = 1.0f;
float SpecularR = 0.0f;
float SpecularG = 0.0f;
float SpecularB = 0.0f;
float SpecularA = 1.0f;
float EmissionR = 0.0f;
float EmissionG = 0.0f;
float EmissionB = 0.0f;
float EmissionA = 1.0f;
float Power = 0.0f;
domProfile_COMMON::domTechnique::domLambert* pLambert = NULL;
domProfile_COMMON::domTechnique::domPhong* pPhong = NULL;
if( iter->second.first->typeID() == 743 )
{
pLambert = (domProfile_COMMON::domTechnique::domLambert*)iter->second.first;
}
if( iter->second.first->typeID() == 744 )
{
pPhong = (domProfile_COMMON::domTechnique::domPhong*)iter->second.first;
}
ZeroMemory( &material, sizeof(material));
if( pLambert )
{
if( pLambert->getAmbient() )
{
if( pLambert->getAmbient()->getColor() != NULL )
{
AmbientR = pLambert->getAmbient()->getColor()->getValue().get(0);
AmbientG = pLambert->getAmbient()->getColor()->getValue().get(1);
AmbientB = pLambert->getAmbient()->getColor()->getValue().get(2);
AmbientA = pLambert->getAmbient()->getColor()->getValue().get(3);
}
}
if( pLambert->getDiffuse() )
{
if( pLambert->getDiffuse()->getColor() != NULL )
{
DiffuseR = pLambert->getDiffuse()->getColor()->getValue().get(0);
DiffuseG = pLambert->getDiffuse()->getColor()->getValue().get(1);
DiffuseB = pLambert->getDiffuse()->getColor()->getValue().get(2);
DiffuseA = pLambert->getDiffuse()->getColor()->getValue().get(3);
}
}
if( pLambert->getEmission() )
{
if( pLambert->getEmission()->getColor() != NULL )
{
EmissionR = pLambert->getEmission()->getColor()->getValue().get(0);
EmissionG = pLambert->getEmission()->getColor()->getValue().get(1);
EmissionB = pLambert->getEmission()->getColor()->getValue().get(2);
EmissionA = pLambert->getEmission()->getColor()->getValue().get(3);
}
}
material.Ambient[0] = AmbientR;
material.Ambient[1] = AmbientG;
material.Ambient[2] = AmbientB;
material.Ambient[3] = AmbientA;
material.Diffuse[0] = DiffuseR;
material.Diffuse[1] = DiffuseG;
material.Diffuse[2] = DiffuseB;
material.Diffuse[3] = DiffuseA;
material.Specular[0] = SpecularR;
material.Specular[1] = SpecularG;
material.Specular[2] = SpecularB;
material.Specular[3] = SpecularA;
material.Emissive[0] = EmissionR;
material.Emissive[1] = EmissionB;
material.Emissive[2] = EmissionG;
material.Emissive[3] = EmissionA;
material.Power = Power;
material.pTexture = iter2->second;
material.bIsTransparent = FALSE;
if( pLambert->getTransparency() )
{
material.Transparency =
(float)pLambert->getTransparency()->getFloat()->getValue();
if( material.Transparency < 0.001f )
material.Transparency = 1.0f;
}
else
material.Transparency = 1.0f;
}
else if( pPhong )
{
if( pPhong->getAmbient() )
{
if( pPhong->getAmbient()->getColor() != NULL )
{
AmbientR = pPhong->getAmbient()->getColor()->getValue().get(0);
AmbientG = pPhong->getAmbient()->getColor()->getValue().get(1);
AmbientB = pPhong->getAmbient()->getColor()->getValue().get(2);
AmbientA = pPhong->getAmbient()->getColor()->getValue().get(3);
}
}
if( pPhong->getDiffuse() )
{
if( pPhong->getDiffuse()->getColor() != NULL )
{
DiffuseR = pPhong->getDiffuse()->getColor()->getValue().get(0);
DiffuseG = pPhong->getDiffuse()->getColor()->getValue().get(1);
DiffuseB = pPhong->getDiffuse()->getColor()->getValue().get(2);
DiffuseA = pPhong->getDiffuse()->getColor()->getValue().get(3);
}
}
if( pPhong->getSpecular() )
{
if( pPhong->getSpecular()->getColor() != NULL )
{
SpecularR = pPhong->getSpecular()->getColor()->getValue().get(0);
SpecularG = pPhong->getSpecular()->getColor()->getValue().get(1);
SpecularB = pPhong->getSpecular()->getColor()->getValue().get(2);
SpecularA = pPhong->getSpecular()->getColor()->getValue().get(3);
}
}
if( pPhong->getEmission() )
{
if( pPhong->getEmission()->getColor() != NULL )
{
EmissionR = pPhong->getEmission()->getColor()->getValue().get(0);
EmissionG = pPhong->getEmission()->getColor()->getValue().get(1);
EmissionB = pPhong->getEmission()->getColor()->getValue().get(2);
EmissionA = pPhong->getEmission()->getColor()->getValue().get(3);
}
}
if( pPhong->getShininess() )
{
Power = (float)pPhong->getShininess()->getFloat()->getValue();
}
material.Ambient[0] = AmbientR;
material.Ambient[1] = AmbientG;
material.Ambient[2] = AmbientB;
material.Ambient[3] = AmbientA;
material.Diffuse[0] = DiffuseR;
material.Diffuse[1] = DiffuseG;
material.Diffuse[2] = DiffuseB;
material.Diffuse[3] = DiffuseA;
material.Specular[0] = SpecularR;
material.Specular[1] = SpecularG;
material.Specular[2] = SpecularB;
material.Specular[3] = SpecularA;
material.Emissive[0] = EmissionR;
material.Emissive[1] = EmissionB;
material.Emissive[2] = EmissionG;
material.Emissive[3] = EmissionA;
material.Power = Power;
material.pTexture = iter2->second;
material.bIsTransparent = FALSE;
if( pPhong->getTransparency() )
{
material.Transparency =
(float)pPhong->getTransparency()->getFloat()->getValue();
if( material.Transparency < 0.001f )
material.Transparency = 1.0f;
}
else
material.Transparency = 1.0f;
}
}
if( material.Transparency < 1.0f || material.Diffuse[3] < 1.0f )
material.bIsTransparent = TRUE;
std::list<domExtraRef>::iterator iterExtra = iter->second.second.begin();
while( iterExtra != iter->second.second.end() )
{
size_t uiNumTechs = (*iterExtra)->getTechnique_array().getCount();
for( size_t l = 0; l < uiNumTechs; ++l )
{
domTechniqueRef pTech = (*iterExtra)->getTechnique_array()[l];
size_t uiNumContents = pTech->getContents().getCount();
for( size_t m = 0; m < uiNumContents; ++m )
{
daeElementRef pElem = pTech->getContents()[m];
std::string strElemName = pElem->getElementName();
if( strcmp(strElemName.c_str(), "double_sided") == 0 )
{
std::string strValue;
pElem->getCharData( strValue );
if( strcmp(strValue.c_str(), "1") == 0 )
material.bDoubleSided = TRUE;
}
}
}
++iterExtra;
}
m_vecMaterials[i] = material;
if( pMaterial->getId() )
{
m_mapMaterials[pMaterial->getId()] = i;
}
}
break;
}
}
void KMZLoader::ReadGeometries( domCOLLADA* pDom )
{
size_t num = pDom->getLibrary_geometries_array().getCount();
for( size_t idx = 0; idx < num; ++idx )
{
domLibrary_geometriesRef lib = pDom->getLibrary_geometries_array()[idx];
size_t numGeometries = lib->getGeometry_array().getCount();
m_vecGeometries.resize(numGeometries);
for( size_t i = 0; i < numGeometries; ++i )
{
domGeometryRef pGeometry = lib->getGeometry_array()[i];
domMeshRef pMesh = pGeometry->getMesh();
if( pMesh != NULL )
{
size_t numMeshes =
pMesh->getTriangles_array().getCount();
size_t numSources =
pMesh->getSource_array().getCount();
std::map<std::string, domSourceRef> mapSources;
std::map<std::string, domSourceRef> mapVertexInputs;
for( size_t j = 0; j < numSources; ++j )
{
domSourceRef pSource = pMesh->getSource_array()[j];
if( pSource->getID() != NULL )
{
mapSources.insert(
std::make_pair(pSource->getID(), pSource) );
}
}
if( pMesh->getVertices() != NULL )
{
size_t numInputs =
pMesh->getVertices()->getInput_array().getCount();
for( size_t j = 0; j < numInputs; ++j )
{
domInputLocalRef pInput =
pMesh->getVertices()->getInput_array()[j];
const char* pUri = pInput->getSource().getOriginalURI();
std::map<std::string, domSourceRef>::iterator iter =
mapSources.find(pUri + 1);
if( iter != mapSources.end() )
{
if( !stricmp( pInput->getSemantic(), "POSITION") )
{
mapVertexInputs["POSITION"] = iter->second;
}
else if( !stricmp( pInput->getSemantic(), "NORMAL"))
{
mapVertexInputs["NORMAL"] = iter->second;
}
else if( !stricmp( pInput->getSemantic(), "TEXCOORD"))
{
mapVertexInputs["TEXCOORD"] = iter->second;
}
}
}
mapSources[pMesh->getVertices()->getId()] = NULL;
}
m_vecGeometries[i].nNumMeshes = numMeshes;
m_vecGeometries[i].pMeshes = new MESH[numMeshes];
m_vecGeometries[i].type = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
m_vecGeometries[i].index = i;
for( size_t j = 0; j < numMeshes; ++j )
{
std::map<std::string, domSourceRef> mapTypeSources;
domTrianglesRef pTriangle =
pMesh->getTriangles_array()[j];
size_t numInputs =
pTriangle->getInput_array().getCount();
bool bHasNormal = false;
bool bHasTexcoord = false;
domSourceRef pNormal = NULL;
domSourceRef pTexcoord = NULL;
domSourceRef pPosition = NULL;
bool bNormalInVertex = false;
bool bTexcoordInVertex = false;
std::map<std::string, int> mapInputOrder;
size_t curOrderIndex = 0;
for( size_t k = 0; k < numInputs; ++k )
{
domInputLocalOffsetRef pInput =
pTriangle->getInput_array()[k];
const char* pUri =
pInput->getSource().getOriginalURI();
std::map<std::string, domSourceRef>::iterator iter =
mapSources.find(pUri + 1);
if( iter != mapSources.end() )
{
if( !stricmp( pInput->getSemantic(), "VERTEX" ) )
{
std::map<std::string, domSourceRef>::iterator iterPosition =
mapVertexInputs.find("POSITION");
std::map<std::string, domSourceRef>::iterator iterNormal =
mapVertexInputs.find("NORMAL");
std::map<std::string, domSourceRef>::iterator iterTexcoord =
mapVertexInputs.find("TEXCOORD");
if( iterPosition != mapVertexInputs.end() )
{
pPosition = iterPosition->second;
}
if( iterNormal != mapVertexInputs.end() )
{
bHasNormal = true;
bNormalInVertex = true;
pNormal = iterNormal->second;
}
if( iterTexcoord != mapVertexInputs.end() )
{
bHasTexcoord = true;
bTexcoordInVertex = true;
pTexcoord = iterTexcoord->second;
}
}
else if( !stricmp( pInput->getSemantic(), "NORMAL") )
{
pNormal = iter->second;
bHasNormal = true;
}
else if( !stricmp( pInput->getSemantic(), "TEXCOORD") )
{
pTexcoord = iter->second;
bHasTexcoord = true;
}
}
mapInputOrder[pInput->getSemantic()] = curOrderIndex;
++curOrderIndex;
}
domPRef pP = pTriangle->getP();
if( pP != NULL )
{
size_t numPArray = pP->getValue().getCount();
size_t indexCounter = 0;
size_t numFaces = pTriangle->getCount();
m_vecGeometries[i].pMeshes[j].bHasNormal = bHasNormal;
m_vecGeometries[i].pMeshes[j].bHasTexcoord = bHasTexcoord;
m_vecGeometries[i].pMeshes[j].nMaterialID = 0xFFFFFFFF;
m_vecGeometries[i].pMeshes[j].materialName = pTriangle->getMaterial();
m_vecGeometries[i].pMeshes[j].nNumVertices = 3 * numFaces;
m_vecGeometries[i].pMeshes[j].pVertices = new VERTEX_DATA[3 * numFaces];
if( pGeometry->getName() )
m_vecGeometries[i].pMeshes[j].name = pGeometry->getName();
int stride = 2;
if( pTexcoord )
{
domSource::domTechnique_commonRef pTech =
pTexcoord->getTechnique_common();
if( pTech )
{
domAccessorRef pAccessor = pTech->getAccessor();
if( pAccessor )
{
stride = pAccessor->getStride();
}
}
}
size_t numIndices = pP->getValue().getCount();
int offsetVertex = 0;
int offsetNormal = 0;
int offsetTexcoord = 0;
if( pPosition )
{
offsetVertex = mapInputOrder["VERTEX"];
offsetNormal = offsetVertex;
offsetTexcoord = offsetNormal;
}
for( size_t n = 0;
n < m_vecGeometries[i].pMeshes[j].nNumVertices;
n++ )
{
if( pPosition != NULL )
{
size_t index = pP->getValue()[n * numInputs + offsetVertex];
m_vecGeometries[i].pMeshes[j].pVertices[n].x =
pPosition->getFloat_array()->getValue().get(index * 3);
m_vecGeometries[i].pMeshes[j].pVertices[n].y =
pPosition->getFloat_array()->getValue().get(index * 3 + 1);
m_vecGeometries[i].pMeshes[j].pVertices[n].z =
pPosition->getFloat_array()->getValue().get(index * 3 + 2);
}
if( pNormal != NULL )
{
if( !bNormalInVertex )
offsetNormal = mapInputOrder["NORMAL"];
size_t index = pP->getValue()[n * numInputs + offsetNormal];
m_vecGeometries[i].pMeshes[j].pVertices[n].normal[0] =
pNormal->getFloat_array()->getValue().get(index * 3);
m_vecGeometries[i].pMeshes[j].pVertices[n].normal[1] =
pNormal->getFloat_array()->getValue().get(index * 3 + 1);
m_vecGeometries[i].pMeshes[j].pVertices[n].normal[2] =
pNormal->getFloat_array()->getValue().get(index * 3 + 2);
}
if( pTexcoord != NULL )
{
if( !bTexcoordInVertex )
offsetTexcoord = mapInputOrder["TEXCOORD"];
size_t index = pP->getValue()[n * numInputs + offsetTexcoord];
m_vecGeometries[i].pMeshes[j].pVertices[n].u = pTexcoord->getFloat_array()->getValue().get(index * stride);
m_vecGeometries[i].pMeshes[j].pVertices[n].v = 1.0 - pTexcoord->getFloat_array()->getValue().get(index * stride + 1);
}
}
}
}
if( pGeometry->getID() )
m_mapGeomtries[pGeometry->getID()] = &m_vecGeometries[i];
}
}
break;
}
}
void KMZLoader::TraverseAndSetupTransform( domNodeRef pNode,
scene_node_t* pSceneNode )
{
static XMMATRIX matIdentity = XMMatrixIdentity();
static XMVECTOR vZero = XMVectorZero();
if( pSceneNode != NULL )
{
memcpy( pSceneNode->_transform, &matIdentity, sizeof(XMMATRIX) );
}
if( pNode == NULL )
return;
size_t numTranslation = pNode->getTranslate_array().getCount();
size_t numRotation = pNode->getRotate_array().getCount();
size_t numScaling = pNode->getScale_array().getCount();
size_t numMatrices = pNode->getMatrix_array().getCount();
BOOL bIsTranslationExist = FALSE;
BOOL bIsRotationExist = FALSE;
BOOL bIsScalingExist = FALSE;
BOOL bIsMatrixExist = FALSE;
XMVECTOR vecTranslation;
XMVECTOR vecAxis;
FLOAT RotAngle;
XMVECTOR vecScale;
XMMATRIX matRot;
XMMATRIX matScale;
XMMATRIX matTrans;
XMMATRIX tempMatrix = matIdentity;
for( size_t i = 0; i < numRotation; ++i )
{
domRotateRef pRotation = pNode->getRotate_array()[i];
float axis_x = pRotation->getValue().get(0);
float axis_y = pRotation->getValue().get(1);
float axis_z = pRotation->getValue().get(2);
float angle = pRotation->getValue().get(3);
vecAxis = XMVectorSet(axis_x, axis_y, axis_z, 0.0f);
RotAngle = angle;
bIsRotationExist = TRUE;
}
for( size_t i = 0; i < numTranslation; ++i )
{
domTranslateRef pTranslation = pNode->getTranslate_array()[i];
float translation_x = pTranslation->getValue().get(0);
float translation_y = pTranslation->getValue().get(1);
float translation_z = pTranslation->getValue().get(2);
vecTranslation = XMVectorSet(translation_x, translation_y, translation_z, 0.0f);
bIsTranslationExist = TRUE;
}
for( size_t i = 0; i < numScaling; ++i )
{
domScaleRef pScaling = pNode->getScale_array()[i];
float scaling_x = pScaling->getValue().get(0);
float scaling_y = pScaling->getValue().get(1);
float scaling_z = pScaling->getValue().get(2);
vecScale = XMVectorSet(scaling_x, scaling_y, scaling_z, 0.0f);
bIsScalingExist = TRUE;
}
for( size_t i = 0; i < numMatrices; ++i )
{
domMatrixRef pMatrix = pNode->getMatrix_array()[i];
tempMatrix._11 = pMatrix->getValue().get(0);
tempMatrix._21 = pMatrix->getValue().get(1);
tempMatrix._31 = pMatrix->getValue().get(2);
tempMatrix._41 = pMatrix->getValue().get(3);
tempMatrix._12 = pMatrix->getValue().get(4);
tempMatrix._22 = pMatrix->getValue().get(5);
tempMatrix._32 = pMatrix->getValue().get(6);
tempMatrix._42 = pMatrix->getValue().get(7);
tempMatrix._13 = pMatrix->getValue().get(8);
tempMatrix._23 = pMatrix->getValue().get(9);
tempMatrix._33 = pMatrix->getValue().get(10);
tempMatrix._43 = pMatrix->getValue().get(11);
tempMatrix._14 = pMatrix->getValue().get(12);
tempMatrix._24 = pMatrix->getValue().get(13);
tempMatrix._34 = pMatrix->getValue().get(14);
tempMatrix._44 = pMatrix->getValue().get(15);
bIsMatrixExist = TRUE;
}
if( bIsTranslationExist )
{
matTrans = XMMatrixTranslationFromVector( vecTranslation );
XMMATRIX matNodeTransform = matIdentity;
memcpy( &matNodeTransform, pSceneNode->_transform, sizeof(XMMATRIX) );
matNodeTransform = matTrans * matNodeTransform;
memcpy( pSceneNode->_transform, &matNodeTransform, sizeof(XMMATRIX) );
}
if( bIsRotationExist )
{
matRot = XMMatrixRotationAxis( vecAxis, RotAngle );
XMMATRIX matNodeTransform = matIdentity;
memcpy( &matNodeTransform, pSceneNode->_transform, sizeof(XMMATRIX) );
matNodeTransform = matRot * matNodeTransform;
memcpy( pSceneNode->_transform, &matNodeTransform, sizeof(XMMATRIX) );
}
if( bIsScalingExist )
{
matScale = XMMatrixScalingFromVector( vecScale );
XMMATRIX matNodeTransform = matIdentity;
memcpy( &matNodeTransform, pSceneNode->_transform, sizeof(XMMATRIX) );
matNodeTransform = matScale * matNodeTransform;
memcpy( pSceneNode->_transform, &matNodeTransform, sizeof(XMMATRIX) );
}
if( bIsMatrixExist )
memcpy( pSceneNode->_transform, &tempMatrix, sizeof(XMMATRIX) );
if( pSceneNode->_pparent != NULL )
{
XMMATRIX matNodeTransform = matIdentity;
memcpy( &matNodeTransform, pSceneNode->_transform, sizeof(XMMATRIX) );
XMMATRIX matParentTransform = matIdentity;
memcpy( &matParentTransform, pSceneNode->_pparent->_transform, sizeof(XMMATRIX) );
matNodeTransform *= matParentTransform;
memcpy( pSceneNode->_transform, &matNodeTransform, sizeof(XMMATRIX) );
}
else
{
FLOAT scale = 1.0f;
XMMATRIX WorldMatrix;
XMMATRIX TransMatrix;
XMMATRIX RotMatrix, RotMatrixX, RotMatrixY;
XMMATRIX ScalingMatrix;
ScalingMatrix = XMMatrixScaling( scale, scale, scale );
TransMatrix = XMMatrixTranslation( 0.0f, 0.0f, 0.0f );
RotMatrixY = XMMatrixRotationY( 0.0f );
RotMatrixX = XMMatrixRotationX( -XM_PI / 2.0f );
RotMatrix = RotMatrixY * RotMatrixX;
WorldMatrix = ScalingMatrix * RotMatrix * TransMatrix;
XMMATRIX matNodeTransform = matIdentity;
memcpy( &matNodeTransform, pSceneNode->_transform, sizeof(XMMATRIX) );
matNodeTransform *= WorldMatrix;
memcpy( pSceneNode->_transform, &matNodeTransform, sizeof(XMMATRIX) );
}
if( !pSceneNode->_bAdded )
{
m_listRenderableNodes.push_back( pSceneNode );
pSceneNode->_bAdded = TRUE;
}
int numInstanceGeometry = pNode->getInstance_geometry_array().getCount();
for( int i = 0; i < numInstanceGeometry; ++i )
{
domInstance_geometryRef pGeometry = pNode->getInstance_geometry_array()[i];
const char* pUri = pGeometry->getUrl().getOriginalURI();
std::map<std::string, GEOMETRY*>::iterator iter =
m_mapGeomtries.find(pUri + 1);
if( iter != m_mapGeomtries.end() )
{
pSceneNode->_geos.push_back( iter->second );
domBind_materialRef pBindMaterial = pGeometry->getBind_material();
domBind_material::domTechnique_commonRef pTech =
pBindMaterial->getTechnique_common();
std::map<std::string, std::string> mapSymbolTargets;
int numInstanceMaterials =
pTech->getInstance_material_array().getCount();
for( int j = 0; j < numInstanceMaterials; ++j )
{
domInstance_materialRef pMaterial =
pTech->getInstance_material_array()[j];
if( pMaterial->getSymbol() )
mapSymbolTargets[pMaterial->getSymbol()] =
pMaterial->getTarget().getOriginalURI() + 1;
}
for( size_t j = 0; j < iter->second->nNumMeshes; ++j )
{
MESH* pMesh = &iter->second->pMeshes[j];
std::map<std::string, std::string>::iterator iterSymbol =
mapSymbolTargets.find(pMesh->materialName);
if( iterSymbol != mapSymbolTargets.end() )
{
std::map<std::string, int>::iterator iterMaterial =
m_mapMaterials.find(iterSymbol->second);
if( iterMaterial != m_mapMaterials.end() )
{
pMesh->nMaterialID = iterMaterial->second;
}
}
}
}
}
size_t numInstanceNode = pNode->getInstance_node_array().getCount();
size_t numNodes = pNode->getNode_array().getCount();
size_t numTotalNodes = numInstanceNode + numNodes;
if( numTotalNodes > 0 )
pSceneNode->_children.resize(numTotalNodes);
for( size_t i = 0; i < numInstanceNode; ++i )
{
domInstance_nodeRef pInstanceNode =
pNode->getInstance_node_array()[i];
const char* pUri = pInstanceNode->getUrl().getOriginalURI();
std::map<std::string, domNodeRef>::iterator iter =
m_mapNodes.find( pUri + 1 );
if( iter != m_mapNodes.end() )
{
domNodeRef pChildNode = iter->second;
scene_node_t pMyNode;
pMyNode._pparent = pSceneNode;
pMyNode._bAdded = FALSE;
pSceneNode->_children[i] = pMyNode;
TraverseAndSetupTransform( pChildNode, &(pSceneNode->_children[i]) );
}
}
for( size_t i = numInstanceNode; i < numTotalNodes ; ++i )
{
domNodeRef pChildNode = pNode->getNode_array()[i];
scene_node_t pMyNode;
pMyNode._pparent = pSceneNode;
pMyNode._bAdded = FALSE;
pSceneNode->_children[i] = pMyNode;
TraverseAndSetupTransform( pChildNode, &(pSceneNode->_children[i]) );
}
}
void KMZLoader::ReadNodes( domCOLLADA* pDom )
{
size_t num = pDom->getLibrary_nodes_array().getCount();
for( size_t idx = 0; idx < num; ++idx )
{
domLibrary_nodesRef lib = pDom->getLibrary_nodes_array()[idx];
size_t numNodes = lib->getNode_array().getCount();
for( size_t i = 0; i < numNodes; ++i )
{
domNodeRef pNode = lib->getNode_array()[i];
if( pNode->getId() )
{
m_mapNodes[pNode->getId()] = pNode;
}
}
break;
}
}
void KMZLoader::ReadScene( domCOLLADA* pDom )
{
m_pRoot = new scene_node_t;
m_pRoot->_pparent = NULL;
m_pRoot->_bAdded = FALSE;
domCOLLADA::domSceneRef pScene = pDom->getScene();
daeElement* pElement =
pScene->getInstance_visual_scene()->getUrl().getElement();
if( pElement != NULL )
{
domVisual_sceneRef pVisualScene = (domVisual_scene*)pElement;
size_t numNodes = pVisualScene->getNode_array().getCount();
for( size_t i = 0; i < numNodes; ++i )
{
domNodeRef pNode = pVisualScene->getNode_array()[i];
TraverseAndSetupTransform( pNode, m_pRoot );
}
}
}
BOOL KMZLoader::SetupInput()
{
D3D11_INPUT_ELEMENT_DESC elements[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = _countof( elements );
HRESULT hr = m_lpDevice->CreateInputLayout( elements, numElements,
m_lpShaderBytecodeInput,
m_dwShaderBytecodeSize,
&m_lpInputLayout );
if( FAILED( hr ) )
return FALSE;
SAFE_DELETEARRAY( m_lpShaderBytecodeInput );
return TRUE;
}
BOOL KMZLoader::SetupInputForNoTexture()
{
D3D11_INPUT_ELEMENT_DESC elements[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = _countof( elements );
HRESULT hr = m_lpDevice->CreateInputLayout( elements, numElements,
m_lpShaderBytecodeInputForNoTexture,
m_dwShaderBytecodeSizeForNoTexture,
&m_lpInputLayoutForNoTexture );
if( FAILED( hr ) )
return FALSE;
SAFE_DELETEARRAY( m_lpShaderBytecodeInputForNoTexture );
return TRUE;
}
BOOL KMZLoader::SetupShadersForNoTexture()
{
static CHAR strVS[] =
{
"cbuffer main : register(b0)\n"
"{\n"
" float4x4 matWorldViewProj;\n"
" float4x4 matWorldView;\n"
" float4x4 matWorldViewForNormal;\n"
"};\n"
"\n"
"struct VS_INPUT\n"
"{\n"
" float4 position : POSITION;\n"
" float3 normal : NORMAL;\n"
"};\n"
"\n"
"struct VS_OUTPUT\n"
"{\n"
" float4 position : SV_POSITION;\n"
" float3 normal : TEXCOORD0;\n"
"};\n"
"\n"
"void main( in VS_INPUT vert,\n"
" out VS_OUTPUT o )\n"
"{\n"
" o.position = mul( matWorldViewProj, vert.position );\n"
" float3 norm1 = normalize( mul((float3x3)matWorldViewForNormal, vert.normal) );\n"
" o.normal = norm1.xyz;\n"
"}\n"
};
static CHAR strPS[] =
{
"cbuffer main : register(b0)\n"
"{\n"
" float4 diffuse;\n"
" float4 specular;\n"
" float tranparency;\n"
" float power;\n"
"};\n"
"\n"
"struct PS_INPUT\n"
"{\n"
" float4 position : SV_POSITION;\n"
" float3 normal : TEXCOORD0;\n"
"};\n"
"\n"
"float4 main( in PS_INPUT vert ) : SV_TARGET\n"
"{\n"
" float3 vLightDir = float3(0.0f, 0.0f, -1.0f);\n"
" float fLightColor = saturate( dot(vert.normal, vLightDir) );\n"
" float fLightFactor = saturate( dot(vert.normal, normalize(float3(0.0f, 0.0f, -2.0f))));"
" float4 color = diffuse * fLightColor + specular * pow(fLightFactor, power); \n"
" color.a = diffuse.a * tranparency;\n"
" return color;\n"
"}\n"
};
HRESULT hr = S_OK;
DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
ID3D10Blob* pBlobError = NULL;
//////////////////////////////创建Vertex Shader/////////////////////////
{
ID3D10Blob* pBlobVS = NULL;
//hr = D3DX11CompileFromFile( TEXT("E:\\Projects\\Direct3D11Tutorial\\D3D11_Effect\\kmz.vsh"), NULL, NULL,
// "main", "vs_4_0", 0, 0, NULL,
// &pBlobVS, &pBlobError, NULL );
hr = D3DCompile( strVS, lstrlenA( strVS ) + 1, NULL, NULL, NULL, "main",
"vs_4_0", dwShaderFlags, 0, &pBlobVS, &pBlobError );
if( FAILED( hr ) )
{
if( pBlobError != NULL )
{
MessageBoxA( NULL, (LPCSTR)(pBlobError->GetBufferPointer()), "VertexShader", NULL );
pBlobError->Release();
}
return FALSE;
}
SAFE_RELEASE( m_lpVertexShaderForNoTexture );
hr = m_lpDevice->CreateVertexShader( pBlobVS->GetBufferPointer(), pBlobVS->GetBufferSize(),
NULL, &m_lpVertexShaderForNoTexture );
if( FAILED( hr ) )
return FALSE;
SAFE_DELETEARRAY( m_lpShaderBytecodeInputForNoTexture )
m_dwShaderBytecodeSizeForNoTexture = pBlobVS->GetBufferSize();
if( m_dwShaderBytecodeSizeForNoTexture > 0 )
{
m_lpShaderBytecodeInputForNoTexture =
new BYTE[m_dwShaderBytecodeSizeForNoTexture];
memcpy( m_lpShaderBytecodeInputForNoTexture,
pBlobVS->GetBufferPointer(),
m_dwShaderBytecodeSizeForNoTexture );
}
pBlobVS->Release();
}
//////////////////////////////创建Pixel Shader/////////////////////////
{
ID3D10Blob* pBlobPS = NULL;
//hr = D3DX11CompileFromFile( TEXT("E:\\Projects\\Direct3D11Tutorial\\D3D11_Effect\\kmz.psh"), NULL, NULL,
// "main", "ps_4_0", 0, 0, NULL,
// &pBlobPS, &pBlobError, NULL );
hr = D3DCompile( strPS, lstrlenA( strPS ) + 1, NULL, NULL, NULL, "main",
"ps_4_0", dwShaderFlags, 0, &pBlobPS, &pBlobError );
if( FAILED( hr ) )
{
if( pBlobError != NULL )
{
MessageBoxA( NULL, (LPCSTR)(pBlobError->GetBufferPointer()), "PixelShader", NULL );
pBlobError->Release();
}
return hr;
}
SAFE_RELEASE( m_lpPixelShaderForNoTexture );
hr = m_lpDevice->CreatePixelShader( pBlobPS->GetBufferPointer(), pBlobPS->GetBufferSize(),
NULL, &m_lpPixelShaderForNoTexture );
if( FAILED( hr ) )
return FALSE;
pBlobPS->Release();
}
return TRUE;
}
BOOL KMZLoader::SetupShaders()
{
static CHAR strVS[] =
{
"cbuffer main : register(b0)\n"
"{\n"
" float4x4 matWorldViewProj;\n"
"};\n"
"struct VS_INPUT\n"
"{\n"
" float4 position : POSITION;\n"
" float3 normal : NORMAL;\n"
" float2 texcoord : TEXCOORD;\n"
"};\n"
"struct VS_OUTPUT\n"
"{\n"
" float4 position : SV_POSITION;\n"
" float2 texcoord : TEXCOORD;\n"
"};\n"
"void main( in VS_INPUT vert,\n"
" out VS_OUTPUT o )\n"
"{\n"
" o.position = mul( matWorldViewProj, vert.position );\n"
" o.texcoord = vert.texcoord;\n"
"}\n"
};
static CHAR strPS[] =
{
"Texture2D testMap : register(t0);\n"
"SamplerState samLinear : register(s0);\n"
"struct PS_INPUT\n"
"{\n"
" float4 position : SV_Position;\n"
" float2 texcoord : TEXCOORD;\n"
"};\n"
"float4 main( in PS_INPUT vert ) : SV_TARGET\n"
"{\n"
" return testMap.Sample(samLinear, vert.texcoord);\n"
"}\n"
};
HRESULT hr = S_OK;
DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
ID3D10Blob* pBlobError = NULL;
//////////////////////////////创建Vertex Shader/////////////////////////
{
ID3D10Blob* pBlobVS = NULL;
hr = D3DCompile( strVS, lstrlenA( strVS ) + 1, NULL, NULL, NULL, "main",
"vs_4_0", dwShaderFlags, 0, &pBlobVS, &pBlobError );
if( pBlobError != NULL )
{
MessageBoxA( NULL, (LPCSTR)(pBlobError->GetBufferPointer()), "VertexShader", NULL );
pBlobError->Release();
}
if( FAILED( hr ) )
return FALSE;
SAFE_RELEASE(m_lpVertexShader);
hr = m_lpDevice->CreateVertexShader( pBlobVS->GetBufferPointer(), pBlobVS->GetBufferSize(),
NULL, &m_lpVertexShader );
if( FAILED( hr ) )
return FALSE;
SAFE_DELETEARRAY( m_lpShaderBytecodeInput );
m_dwShaderBytecodeSize = pBlobVS->GetBufferSize();
m_lpShaderBytecodeInput = new BYTE[m_dwShaderBytecodeSize];
memcpy( m_lpShaderBytecodeInput, pBlobVS->GetBufferPointer(), m_dwShaderBytecodeSize );
pBlobVS->Release();
}
////////////////////创建Vertex Shader常量缓冲区/////////////////////////
{
D3D11_BUFFER_DESC cb;
cb.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cb.ByteWidth = sizeof( ConstantBuffer );
cb.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cb.MiscFlags = 0;
cb.StructureByteStride = 0;
cb.Usage = D3D11_USAGE_DYNAMIC;
D3D11_SUBRESOURCE_DATA data;
data.pSysMem = &s_Buffer;
data.SysMemPitch = 0;
data.SysMemSlicePitch = 0;
hr = m_lpDevice->CreateBuffer( &cb, NULL, &m_lpVSConstBufferWorldViewProj );
if( FAILED(hr) )
return FALSE;
}
//////////////////////////////创建Pixel Shader/////////////////////////
{
ID3D10Blob* pBlobPS = NULL;
hr = D3DCompile( strPS, lstrlenA( strPS ) + 1, NULL, NULL, NULL, "main",
"ps_4_0", dwShaderFlags, 0, &pBlobPS, &pBlobError );
if( pBlobError != NULL )
{
MessageBoxA( NULL, (LPCSTR)(pBlobError->GetBufferPointer()), "PixelShader", NULL );
pBlobError->Release();
}
if( FAILED( hr ) )
return FALSE;
SAFE_RELEASE(m_lpPixelShader);
hr = m_lpDevice->CreatePixelShader( pBlobPS->GetBufferPointer(), pBlobPS->GetBufferSize(),
NULL, &m_lpPixelShader );
if( FAILED( hr ) )
return FALSE;
pBlobPS->Release();
}
////////////////////创建Pixel Shader常量缓冲区/////////////////////////
{
D3D11_BUFFER_DESC cb;
cb.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cb.ByteWidth = sizeof( PSConstantBuffer );
cb.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cb.MiscFlags = 0;
cb.StructureByteStride = 0;
cb.Usage = D3D11_USAGE_DYNAMIC;
hr = m_lpDevice->CreateBuffer( &cb, NULL, &m_lpPSConstBufferDiffuse );
if( FAILED(hr) )
return FALSE;
}
return TRUE;
}
VOID KMZLoader::ComputeBoundingBox()
{
//计算包围盒
{
std::list<scene_node_t* >::iterator iter =
m_listRenderableNodes.begin();
while( iter != m_listRenderableNodes.end() )
{
XMMATRIX WorldMatrix = (*iter)->_transform;
int numGeos = (*iter)->_geos.size();
for( int i = 0; i < numGeos; ++i )
{
size_t numMeshes = (*iter)->_geos[i]->nNumMeshes;
for( size_t j= 0; j < numMeshes; j++ )
{
for( size_t k = 0; k < (*iter)->_geos[i]->pMeshes[j].nNumVertices; ++k )
{
XMVECTOR vecIn = XMVectorSet(
(*iter)->_geos[i]->pMeshes[j].pVertices[k].x,
(*iter)->_geos[i]->pMeshes[j].pVertices[k].y,
(*iter)->_geos[i]->pMeshes[j].pVertices[k].z,
0.0f );
XMVECTOR vecOut = XMVector3Transform( vecIn, (*iter)->_transform );
FLOAT vecOutX = XMVectorGetX( vecOut );
FLOAT vecOutY = XMVectorGetY( vecOut );
FLOAT vecOutZ = XMVectorGetZ( vecOut );
if( vecOutX < m_Min[0] )
m_Min[0] = vecOutX;
if( vecOutY < m_Min[1] )
m_Min[1] = vecOutY;
if( vecOutZ < m_Min[2] )
m_Min[2] = vecOutZ;
if( vecOutX > m_Max[0] )
m_Max[0] = vecOutX;
if( vecOutY > m_Max[1] )
m_Max[1] = vecOutY;
if( vecOutZ > m_Max[2] )
m_Max[2] = vecOutZ;
}
}
}
++iter;
}
}
//创建顶点缓存
{
std::vector<GEOMETRY>::iterator iter =
m_vecGeometries.begin();
while( iter != m_vecGeometries.end() )
{
int numMeshes = (*iter).nNumMeshes;
for( int j= 0; j < numMeshes; j++ )
{
MESH* pMesh = &(*iter).pMeshes[j];
if( pMesh->nNumVertices > 0 )
{
D3D11_BUFFER_DESC bd = { 0 };
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof(VERTEX_DATA) * pMesh->nNumVertices;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
HRESULT hr = m_lpDevice->CreateBuffer( &bd, NULL,
&pMesh->pVertexBuffer );
m_lpDeviceContext->UpdateSubresource( pMesh->pVertexBuffer, 0, NULL,
pMesh->pVertices, bd.ByteWidth, 0 );
SAFE_DELETEARRAY( pMesh->pVertices );
}
else
pMesh->pVertexBuffer = NULL;
}
++iter;
}
}
//创建包围盒顶点缓存
{
VERTEX_DATA vertices[8];
vertices[0].x = m_Min[0];
vertices[0].y = m_Min[1];
vertices[0].z = m_Min[2];
vertices[1].x = m_Max[0];
vertices[1].y = m_Min[1];
vertices[1].z = m_Min[2];
vertices[2].x = m_Min[0];
vertices[2].y = m_Max[1];
vertices[2].z = m_Min[2];
vertices[3].x = m_Max[0];
vertices[3].y = m_Max[1];
vertices[3].z = m_Min[2];
vertices[4].x = m_Min[0];
vertices[4].y = m_Min[1];
vertices[4].z = m_Max[2];
vertices[5].x = m_Max[0];
vertices[5].y = m_Min[1];
vertices[5].z = m_Max[2];
vertices[6].x = m_Min[0];
vertices[6].y = m_Max[1];
vertices[6].z = m_Max[2];
vertices[7].x = m_Max[0];
vertices[7].y = m_Max[1];
vertices[7].z = m_Max[2];
WORD index[] = {
0, 1, 2, //back
2, 1, 3,
6, 2, 7, //top
7, 2, 3,
4, 6, 5, //front
5, 6, 7,
4, 5, 0, //bottom
0, 5, 1,
7, 3, 5, //right
5, 3, 1,
0, 2, 4, //left
4, 2, 6
};
m_pBoundingBox = new BoundingBox( m_lpDevice, m_lpDeviceContext );
m_pBoundingBox->SetBuffer( 36, index, sizeof(WORD), 8, vertices, sizeof(VERTEX_DATA) );
}
FLOAT Length[3];
for( int i = 0; i < 3; ++i )
{
m_fCenter[i] = (m_Min[i] + m_Max[i]) / 2.0f;
Length[i] = (m_Max[i] - m_Min[i]) / 2.0f;
}
FLOAT Radius = XMVectorGetX( XMVector3Length( XMVectorSet(Length[0], Length[1], Length[2], 0.0f) ) );
XMMATRIX matTrans;
XMMATRIX matScale;
if( Radius < 10.0f )
{
if( m_fScale > 0.0f && m_fScale < 1.0f )
m_fScale = 1.0f;
else if( m_fScale > -1.0f && m_fScale < 0.0f )
m_fScale = -1.0f;
}
matScale = XMMatrixScalingFromVector( XMVectorSet(m_fScale, m_fScale, -m_fScale, 0.0f) );
matTrans = XMMatrixTranslationFromVector( XMVectorSet(-m_fCenter[0], -m_fCenter[1], -m_fCenter[2], 0.0f) );
float fPositiveScale = fabs( m_fScale );
XMMATRIX matTransform = matTrans * matScale;
memcpy( m_matTransform, &matTransform, sizeof(XMMATRIX) );
m_fTranslateUnit = Radius * fPositiveScale / 20.0f;
XMMATRIX matTranslate = XMMatrixTranslationFromVector( XMVectorSet(0.0f, 0.0f,
Radius * (1.0f / sin(XM_PI / 8.0f) - 1.0f) * m_fScale, 0.0f) );
memcpy( m_matTranslate, &matTranslate, sizeof(XMMATRIX) );
}
void KMZLoader::ShowBoundingBox( BOOL bShow )
{
m_bShowBoundingBox = bShow;
}
float KMZLoader::GetTranslateUnit()
{
return m_fTranslateUnit;
}
BOOL KMZLoader::CreateRenderState()
{
D3D11_RASTERIZER_DESC rs_desc;
ZeroMemory( &rs_desc, sizeof(D3D11_RASTERIZER_DESC) );
rs_desc.CullMode = D3D11_CULL_FRONT;
rs_desc.FillMode = D3D11_FILL_SOLID;
rs_desc.DepthClipEnable = TRUE;
HRESULT hr = m_lpDevice->CreateRasterizerState( &rs_desc, &m_lpRasterizerState );
if( FAILED(hr) )
return FALSE;
rs_desc.CullMode = D3D11_CULL_NONE;
hr = m_lpDevice->CreateRasterizerState( &rs_desc, &m_lpRasterizerStateForNoCull );
if( FAILED(hr) )
return FALSE;
else
return TRUE;
}
*/ | [
"meijun@wonlake-pc"
] | meijun@wonlake-pc |
8f826377d6471ee4255b44199bffd17a77f39e6a | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14017/function14017_schedule_14/function14017_schedule_14_wrapper.cpp | f8f79baef8b820dc9a06ee888838457894aab2a0 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,398 | cpp | #include "Halide.h"
#include "function14017_schedule_14_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(64);
Halide::Buffer<int32_t> buf01(1024, 64);
Halide::Buffer<int32_t> buf02(512, 1024);
Halide::Buffer<int32_t> buf03(512, 64);
Halide::Buffer<int32_t> buf04(512);
Halide::Buffer<int32_t> buf05(512);
Halide::Buffer<int32_t> buf06(512);
Halide::Buffer<int32_t> buf07(64);
Halide::Buffer<int32_t> buf0(512, 1024, 64);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14017_schedule_14(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf07.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14017/function14017_schedule_14/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
5fc2d0e967d0c5ebd9a00ba3ff1a51860576dfdb | 1ac63ebf74c76714bd985b18456192f7c7406990 | /dtls.cpp | 3abaee6d6924c0da29fb976b95d4589e830aa45d | [] | no_license | vvoody/sproxy | 45731552cff29580617dfad87b76474c977c290a | 2b63d889e5f30e449153e14ee1847c899b731eeb | refs/heads/master | 2021-01-10T22:41:20.971590 | 2016-10-08T16:06:59 | 2016-10-08T16:06:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,410 | cpp | #include "dtls.h"
#include <string.h>
#include <unistd.h>
#include <math.h>
#include <arpa/inet.h>
#include <sys/time.h>
#define DTLS_BUF_LEN (4*1024*1024ull)
//#define DEBUG_DTLS
/*
* * The next routines deal with comparing 32 bit unsigned ints
* * and worry about wraparound (automatic with unsigned arithmetic).
* */
static inline int before(uint32_t seq1, uint32_t seq2)
{
return (int32_t)(seq1-seq2) < 0;
}
static inline int noafter(uint32_t seq1, uint32_t seq2)
{
return (int32_t)(seq1-seq2) <= 0;
}
#define after(seq2, seq1) before(seq1, seq2)
#define nobefore(seq2, seq1) noafter(seq1, seq2)
void TTL::add(uint32_t value) {
if(value){
data.push(std::make_pair(getmtime(), value));
sum += value;
}
}
uint32_t TTL::getsum() {
uint32_t now =getmtime();
while(!data.empty()){
if( now - data.front().first > 100){
sum -= data.front().second;
data.pop();
}else{
break;
}
}
return sum;
}
Dtls::Dtls(SSL* ssl):Ssl(ssl) {
read_seqs.push_back(std::make_pair(0,0));
tick_time = ack_time = getmtime();
write_buff = new unsigned char[DTLS_BUF_LEN];
read_buff = new unsigned char[DTLS_BUF_LEN];
}
Dtls::~Dtls(){
delete []write_buff;
delete []read_buff;
}
ssize_t Dtls::read(void* buff, size_t size) {
if(recv() < 0){
errno = EIO;
return -1;
}
if(read_seqs.begin()->first == read_seqs.begin()->second){
errno = EAGAIN;
return -1;
}
uint32_t start_pos = read_seqs.begin()->first;
if(read_seqs.begin()->second - read_seqs.begin()->first < size){
size = read_seqs.begin()->second - read_seqs.begin()->first;
}
read_seqs.begin()->first += size;
uint32_t from = start_pos &(DTLS_BUF_LEN-1);
size_t l = Min(DTLS_BUF_LEN - from, size);
memcpy(buff, read_buff + from, l);
memcpy((char *)buff + l, read_buff, size - l);
return size;
}
ssize_t Dtls::write(const void* buff, size_t size) {
if(after(write_seq + size, recv_ack + DTLS_BUF_LEN)){
if(send() < 0){
errno= EIO;
}else{
errno = EAGAIN;
}
return -1;
}
uint32_t from = write_seq &(DTLS_BUF_LEN-1);
size_t l = Min(DTLS_BUF_LEN - from, size);
memcpy(write_buff+from, buff, l);
memcpy(write_buff, (const char*)buff + l, size -l);
write_seq += size;
if(send() < 0){
errno = EIO;
return -1;
}
return size;
}
int Dtls::recv(){
assert(!read_seqs.empty());
unsigned char buff[DTLS_MTU];
uint32_t tick_recvpkg = 0;
uint32_t recv_time = 0;
int ret;
#ifdef DEBUG_DTLS
uint32_t recv_begin = 0;
uint32_t recv_end = 0;
#endif
while((ret = SSL_read(ssl, buff, DTLS_MTU)) > 0){
Dtls_head *head = (Dtls_head *)buff;
const uint32_t ack = ntohl(head->ack);
const uint32_t seq = ntohl(head->seq);
const uint32_t time = ntohl(head->time);
const uint16_t len = ret - sizeof(Dtls_head);
bucket_limit = bucket_limit*0.8 + ntohs(head->window)*0.2;
bucket_limit = Max(bucket_limit,10);
tick_recvpkg ++;
if(head->type == DTLS_TYPE_DATA){
#ifdef DEBUG_DTLS
if(recv_begin == 0){
recv_begin = seq;
}
if(recv_end && recv_end != seq){
LOG("[DTLS] %u: get pkg: %x -- %x\n", getmtime(), recv_begin, recv_end);
recv_begin = seq;
}
recv_end = seq + len;
#endif
uint32_t full_pos = read_seqs.begin()->second;
if(after(seq + len, full_pos) &&
before(seq + len , read_seqs.begin()->first + DTLS_BUF_LEN))
{
uint32_t start_pos = after(seq, full_pos)?seq:full_pos;
auto i = read_seqs.begin();
for(;i!=read_seqs.end();i++){
if(nobefore(i->first, start_pos))
break;
}
read_seqs.insert(i, std::make_pair(start_pos, seq+len));
for(auto i= read_seqs.begin(); ;){
auto pre = i++;
if(i == read_seqs.end())
break;
if(nobefore(pre->second, i->first)){
pre->second = after(pre->second, i->second)?pre->second:i->second;
read_seqs.erase(i);
i = pre;
}
}
size_t size = seq - start_pos + len;
size_t from = start_pos & (DTLS_BUF_LEN-1);
size_t l = Min(DTLS_BUF_LEN - from, size);
memcpy(read_buff+ from , (const char*)(head+1) + (start_pos-seq), l);
memcpy(read_buff , (const char*)(head+1) + (start_pos + l -seq), size - l);
}else{
#ifdef DEBUG_DTLS
LOG("[DTLS] %u: discard pkg %x -- %x (%x)\n", getmtime(), seq, seq+len, full_pos);
#endif
}
recv_time = time;
}else{
rtt_time = rtt_time * 0.8 + (getmtime()-time) * 0.2;
gap_num = 0;
uint32_t *gap_ptr = (uint32_t *)(head+1);
while((unsigned char*)gap_ptr - buff <ret){
gaps[gap_num++] = ntohl(*gap_ptr++);
}
#ifdef DEBUG_DTLS
LOG("[DTLS] %u: ack: %x window: %u rtt: %u\n",getmtime(), ack, bucket_limit, rtt_time);
#endif
}
if(after(ack, recv_ack)){
recv_ack = ack;
ack_time = time;
}
}
#ifdef DEBUG_DTLS
if(recv_end){
LOG("[DTLS] %u: get pkg: %x -- %x\n", getmtime(), recv_begin, recv_end);
}
#endif
if(ret < 0 && !BIO_should_retry(SSL_get_rbio(ssl))){
return -1;
}
recv_pkgs.add(tick_recvpkg);
send_ack(recv_time, recv_pkgs.getsum());
return send();
}
int Dtls::send() {
uint32_t recvp_num = recv_pkgs.getsum();
uint32_t now = getmtime();
uint32_t buckets;
if(bucket_limit < 50){
buckets = (now - tick_time) * sqrt(bucket_limit*100) /100;
}else{
buckets = (now - tick_time) * (bucket_limit+5) /80;
}
assert(bucket_limit>=10);
if(buckets){
if(buckets > bucket_limit){
buckets = bucket_limit;
}
if(now-ack_time >= Max(2,rtt_time*1.2) && before(recv_ack, write_seq)){
resend_pos = after(recv_ack, resend_pos)?recv_ack: resend_pos;
if(gap_num){
for(size_t i =0;i<gap_num;i+=2){
resend_pos = after(gaps[i], resend_pos)?gaps[i]:resend_pos;
#ifdef DEBUG_DTLS
uint32_t send_begin = resend_pos;
#endif
while(buckets && before(resend_pos, gaps[i+1])){
resend_pos += send_pkg(resend_pos, recvp_num, Min(DTLS_LEN, (int32_t)write_seq - (int32_t)resend_pos));
buckets--;
}
#ifdef DEBUG_DTLS
if(send_begin != resend_pos){
LOG("[DTLS] %u: send pkg: %x -- %x, left buckets: %d rtt: %d [R]\n", getmtime(),
send_begin, resend_pos, buckets, rtt_time);
}
#endif
if(buckets == 0){
break;
}
}
}else{
#ifdef DEBUG_DTLS
uint32_t send_begin = resend_pos;
#endif
while(buckets && before(resend_pos, send_pos)){
resend_pos += send_pkg(resend_pos, recvp_num, Min(DTLS_LEN, (int32_t)write_seq - (int32_t)resend_pos));
buckets--;
}
#ifdef DEBUG_DTLS
if(send_begin != resend_pos){
LOG("[DTLS] %u: send pkg: %x -- %x, left buckets: %d rtt: %d [SR]\n", getmtime(),
send_begin, resend_pos, buckets, rtt_time);
}
#endif
}
if(buckets){
resend_pos = recv_ack;
ack_time = now;
}
}
#ifdef DEBUG_DTLS
uint32_t send_begin = send_pos;
#endif
while(buckets && before(send_pos, write_seq)) {
send_pos += send_pkg(send_pos, recvp_num, Min(DTLS_LEN, (int32_t)write_seq-(int32_t)send_pos));
buckets --;
}
#ifdef DEBUG_DTLS
if(send_begin != send_pos){
LOG("[DTLS] %u: send pkg: %x -- %x, left buckets: %d rtt: %d\n",
getmtime(), send_begin, send_pos, buckets, rtt_time);
}
#endif
tick_time = now - buckets*100/bucket_limit;
}
return 0;
}
void Dtls::send_ack(uint32_t time, uint32_t window) {
if(time){
assert(window && window < 65536);
unsigned char buff[DTLS_MTU];
Dtls_head *head = (Dtls_head *)buff;
auto seq = read_seqs.begin();
head->ack = htonl(seq->second);
head->seq = 0;
head->time = htonl(time);
head->window = htons(window);
head->type = DTLS_TYPE_ACK;
uint32_t *gaps= (uint32_t *)(head+1);
decltype(seq) pre = seq;
while(1){
pre = seq++;
if(seq == read_seqs.end() ||
(size_t)((unsigned char*)gaps-buff) >= (size_t)DTLS_MTU)
break;
assert(before(pre->second, seq->first));
*(gaps++)=htonl(pre->second);
*(gaps++)=htonl(seq->first);
}
SSL_write(ssl , buff, (unsigned char*)gaps-buff);
}
}
uint32_t Dtls::send_pkg(uint32_t seq, uint32_t window, size_t len) {
assert(len && len <= DTLS_LEN);
assert(window < 65536);
unsigned char buff[DTLS_MTU];
Dtls_head *head = (Dtls_head *)buff;
head->ack = htonl(read_seqs.begin()->second);
head->seq = htonl(seq);
head->time = htonl(getmtime());
head->window = htons(window);
head->type = DTLS_TYPE_DATA;
uint32_t from = seq & (DTLS_BUF_LEN-1);
size_t l = Min(DTLS_BUF_LEN - from, len);
memcpy(head+1, write_buff + from, l);
memcpy((char *)(head+1) + l, write_buff, len - l);
int ret = SSL_write(ssl ,buff, len + sizeof(Dtls_head));
if(ret > 0){
assert((size_t)ret == len + sizeof(Dtls_head));
}else{
void(0); //TODO put some error info
}
#ifdef DEBUG_DTLS
// LOG("[DTLS] %u: send a pkg: %x -- %x\n",getmtime(), seq, seq+(uint32_t)len);
#endif
return len;
}
| [
"zhouwei400@gmail.com"
] | zhouwei400@gmail.com |
d4144b3c9d54fad50f841bdfe1c2f4d5a9b3e41a | a7119b8fbdfaf3d5181e82a8e8faef458543b1b4 | /src/wallet/walletdb.cpp | 9b276d03a61d0b17e328061cebafaf9361a59680 | [
"MIT"
] | permissive | qbic-platform/qbic | 1b58988c792866386e71607d9aca200160eb8978 | 644be839db9109cf99916142bd9eda5ffd636fb7 | refs/heads/master | 2021-09-16T01:48:21.326437 | 2018-04-12T19:16:13 | 2018-04-12T19:16:13 | 117,234,643 | 23 | 19 | MIT | 2018-04-12T19:16:14 | 2018-01-12T11:43:46 | C++ | UTF-8 | C++ | false | false | 38,016 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Qbic Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet/walletdb.h"
#include "base58.h"
#include "consensus/validation.h"
#include "main.h" // For CheckTransaction
#include "protocol.h"
#include "serialize.h"
#include "sync.h"
#include "util.h"
#include "utiltime.h"
#include "wallet/wallet.h"
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/thread.hpp>
using namespace std;
static uint64_t nAccountingEntryNumber = 0;
//
// CWalletDB
//
bool CWalletDB::WriteName(const string& strAddress, const string& strName)
{
nWalletDBUpdated++;
return Write(make_pair(string("name"), strAddress), strName);
}
bool CWalletDB::EraseName(const string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
nWalletDBUpdated++;
return Erase(make_pair(string("name"), strAddress));
}
bool CWalletDB::WritePurpose(const string& strAddress, const string& strPurpose)
{
nWalletDBUpdated++;
return Write(make_pair(string("purpose"), strAddress), strPurpose);
}
bool CWalletDB::ErasePurpose(const string& strPurpose)
{
nWalletDBUpdated++;
return Erase(make_pair(string("purpose"), strPurpose));
}
bool CWalletDB::WriteTx(uint256 hash, const CWalletTx& wtx)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("tx"), hash), wtx);
}
bool CWalletDB::EraseTx(uint256 hash)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("tx"), hash));
}
bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
{
nWalletDBUpdated++;
if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
keyMeta, false))
return false;
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + vchPrivKey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
return Write(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false);
}
bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey,
const std::vector<unsigned char>& vchCryptedSecret,
const CKeyMetadata &keyMeta)
{
const bool fEraseUnencryptedKey = true;
nWalletDBUpdated++;
if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
keyMeta))
return false;
if (!Write(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false))
return false;
if (fEraseUnencryptedKey)
{
Erase(std::make_pair(std::string("key"), vchPubKey));
Erase(std::make_pair(std::string("wkey"), vchPubKey));
}
return true;
}
bool CWalletDB::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("mkey"), nID), kMasterKey, true);
}
bool CWalletDB::WriteCScript(const uint160& hash, const CScript& redeemScript)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("cscript"), hash), *(const CScriptBase*)(&redeemScript), false);
}
bool CWalletDB::WriteWatchOnly(const CScript &dest)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("watchs"), *(const CScriptBase*)(&dest)), '1');
}
bool CWalletDB::EraseWatchOnly(const CScript &dest)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("watchs"), *(const CScriptBase*)(&dest)));
}
bool CWalletDB::WriteBestBlock(const CBlockLocator& locator)
{
nWalletDBUpdated++;
Write(std::string("bestblock"), CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan
return Write(std::string("bestblock_nomerkle"), locator);
}
bool CWalletDB::ReadBestBlock(CBlockLocator& locator)
{
if (Read(std::string("bestblock"), locator) && !locator.vHave.empty()) return true;
return Read(std::string("bestblock_nomerkle"), locator);
}
bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext)
{
nWalletDBUpdated++;
return Write(std::string("orderposnext"), nOrderPosNext);
}
bool CWalletDB::WriteDefaultKey(const CPubKey& vchPubKey)
{
nWalletDBUpdated++;
return Write(std::string("defaultkey"), vchPubKey);
}
bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool)
{
return Read(std::make_pair(std::string("pool"), nPool), keypool);
}
bool CWalletDB::WritePool(int64_t nPool, const CKeyPool& keypool)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("pool"), nPool), keypool);
}
bool CWalletDB::ErasePool(int64_t nPool)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("pool"), nPool));
}
bool CWalletDB::WriteMinVersion(int nVersion)
{
return Write(std::string("minversion"), nVersion);
}
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
{
account.SetNull();
return Read(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
{
return Write(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
{
return Write(std::make_pair(std::string("acentry"), std::make_pair(acentry.strAccount, nAccEntryNum)), acentry);
}
bool CWalletDB::WriteAccountingEntry_Backend(const CAccountingEntry& acentry)
{
return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
}
CAmount CWalletDB::GetAccountCreditDebit(const string& strAccount)
{
list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries);
CAmount nCreditDebit = 0;
BOOST_FOREACH (const CAccountingEntry& entry, entries)
nCreditDebit += entry.nCreditDebit;
return nCreditDebit;
}
void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
{
bool fAllAccounts = (strAccount == "*");
Dbc* pcursor = GetCursor();
if (!pcursor)
throw runtime_error("CWalletDB::ListAccountCreditDebit(): cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << std::make_pair(std::string("acentry"), std::make_pair((fAllAccounts ? string("") : strAccount), uint64_t(0)));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
pcursor->close();
throw runtime_error("CWalletDB::ListAccountCreditDebit(): error scanning DB");
}
// Unserialize
string strType;
ssKey >> strType;
if (strType != "acentry")
break;
CAccountingEntry acentry;
ssKey >> acentry.strAccount;
if (!fAllAccounts && acentry.strAccount != strAccount)
break;
ssValue >> acentry;
ssKey >> acentry.nEntryNo;
entries.push_back(acentry);
}
pcursor->close();
}
DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet)
{
LOCK(pwallet->cs_wallet);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64_t, TxPair > TxItems;
TxItems txByTime;
for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
}
list<CAccountingEntry> acentries;
ListAccountCreditDebit("", acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
int64_t& nOrderPosNext = pwallet->nOrderPosNext;
nOrderPosNext = 0;
std::vector<int64_t> nOrderPosOffsets;
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
if (nOrderPos == -1)
{
nOrderPos = nOrderPosNext++;
nOrderPosOffsets.push_back(nOrderPos);
if (pwtx)
{
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
}
else
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
else
{
int64_t nOrderPosOff = 0;
BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
{
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
}
nOrderPos += nOrderPosOff;
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
if (!nOrderPosOff)
continue;
// Since we're changing the order, write it back
if (pwtx)
{
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
}
else
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
}
WriteOrderPosNext(nOrderPosNext);
return DB_LOAD_OK;
}
class CWalletScanState {
public:
unsigned int nKeys;
unsigned int nCKeys;
unsigned int nKeyMeta;
bool fIsEncrypted;
bool fAnyUnordered;
int nFileVersion;
vector<uint256> vWalletUpgrade;
CWalletScanState() {
nKeys = nCKeys = nKeyMeta = 0;
fIsEncrypted = false;
fAnyUnordered = false;
nFileVersion = 0;
}
};
bool
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
CWalletScanState &wss, string& strType, string& strErr)
{
try {
// Unserialize
// Taking advantage of the fact that pair serialization
// is just the two items serialized one after the other
ssKey >> strType;
if (strType == "name")
{
string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].name;
}
else if (strType == "purpose")
{
string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].purpose;
}
else if (strType == "tx")
{
uint256 hash;
ssKey >> hash;
CWalletTx wtx;
ssValue >> wtx;
CValidationState state;
if (!(CheckTransaction(wtx, state) && (wtx.GetHash() == hash) && state.IsValid()))
return false;
// Undo serialize changes in 31600
if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
{
if (!ssValue.empty())
{
char fTmp;
char fUnused;
ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount, hash.ToString());
wtx.fTimeReceivedIsTxTime = fTmp;
}
else
{
strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString());
wtx.fTimeReceivedIsTxTime = 0;
}
wss.vWalletUpgrade.push_back(hash);
}
if (wtx.nOrderPos == -1)
wss.fAnyUnordered = true;
pwallet->AddToWallet(wtx, true, NULL);
}
else if (strType == "acentry")
{
string strAccount;
ssKey >> strAccount;
uint64_t nNumber;
ssKey >> nNumber;
if (nNumber > nAccountingEntryNumber)
nAccountingEntryNumber = nNumber;
if (!wss.fAnyUnordered)
{
CAccountingEntry acentry;
ssValue >> acentry;
if (acentry.nOrderPos == -1)
wss.fAnyUnordered = true;
}
}
else if (strType == "watchs")
{
CScript script;
ssKey >> *(CScriptBase*)(&script);
char fYes;
ssValue >> fYes;
if (fYes == '1')
pwallet->LoadWatchOnly(script);
// Watch-only addresses have no birthday information for now,
// so set the wallet birthday to the beginning of time.
pwallet->nTimeFirstKey = 1;
}
else if (strType == "key" || strType == "wkey")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
if (!vchPubKey.IsValid())
{
strErr = "Error reading wallet database: CPubKey corrupt";
return false;
}
CKey key;
CPrivKey pkey;
uint256 hash;
if (strType == "key")
{
wss.nKeys++;
ssValue >> pkey;
} else {
CWalletKey wkey;
ssValue >> wkey;
pkey = wkey.vchPrivKey;
}
// Old wallets store keys as "key" [pubkey] => [privkey]
// ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
// using EC operations as a checksum.
// Newer wallets store keys as "key"[pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
// remaining backwards-compatible.
try
{
ssValue >> hash;
}
catch (...) {}
bool fSkipCheck = false;
if (!hash.IsNull())
{
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + pkey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
if (Hash(vchKey.begin(), vchKey.end()) != hash)
{
strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
return false;
}
fSkipCheck = true;
}
if (!key.Load(pkey, vchPubKey, fSkipCheck))
{
strErr = "Error reading wallet database: CPrivKey corrupt";
return false;
}
if (!pwallet->LoadKey(key, vchPubKey))
{
strErr = "Error reading wallet database: LoadKey failed";
return false;
}
}
else if (strType == "mkey")
{
unsigned int nID;
ssKey >> nID;
CMasterKey kMasterKey;
ssValue >> kMasterKey;
if(pwallet->mapMasterKeys.count(nID) != 0)
{
strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
return false;
}
pwallet->mapMasterKeys[nID] = kMasterKey;
if (pwallet->nMasterKeyMaxID < nID)
pwallet->nMasterKeyMaxID = nID;
}
else if (strType == "ckey")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
if (!vchPubKey.IsValid())
{
strErr = "Error reading wallet database: CPubKey corrupt";
return false;
}
vector<unsigned char> vchPrivKey;
ssValue >> vchPrivKey;
wss.nCKeys++;
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
{
strErr = "Error reading wallet database: LoadCryptedKey failed";
return false;
}
wss.fIsEncrypted = true;
}
else if (strType == "keymeta")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
CKeyMetadata keyMeta;
ssValue >> keyMeta;
wss.nKeyMeta++;
pwallet->LoadKeyMetadata(vchPubKey, keyMeta);
// find earliest key creation time, as wallet birthday
if (!pwallet->nTimeFirstKey ||
(keyMeta.nCreateTime < pwallet->nTimeFirstKey))
pwallet->nTimeFirstKey = keyMeta.nCreateTime;
}
else if (strType == "defaultkey")
{
ssValue >> pwallet->vchDefaultKey;
}
else if (strType == "pool")
{
int64_t nIndex;
ssKey >> nIndex;
CKeyPool keypool;
ssValue >> keypool;
pwallet->setKeyPool.insert(nIndex);
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (pwallet->mapKeyMetadata.count(keyid) == 0)
pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
else if (strType == "version")
{
ssValue >> wss.nFileVersion;
if (wss.nFileVersion == 10300)
wss.nFileVersion = 300;
}
else if (strType == "cscript")
{
uint160 hash;
ssKey >> hash;
CScript script;
ssValue >> *(CScriptBase*)(&script);
if (!pwallet->LoadCScript(script))
{
strErr = "Error reading wallet database: LoadCScript failed";
return false;
}
}
else if (strType == "orderposnext")
{
ssValue >> pwallet->nOrderPosNext;
}
else if (strType == "destdata")
{
std::string strAddress, strKey, strValue;
ssKey >> strAddress;
ssKey >> strKey;
ssValue >> strValue;
if (!pwallet->LoadDestData(CBitcoinAddress(strAddress).Get(), strKey, strValue))
{
strErr = "Error reading wallet database: LoadDestData failed";
return false;
}
}
} catch (...)
{
return false;
}
return true;
}
static bool IsKeyType(string strType)
{
return (strType== "key" || strType == "wkey" ||
strType == "mkey" || strType == "ckey");
}
DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
{
pwallet->vchDefaultKey = CPubKey();
CWalletScanState wss;
bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK;
try {
LOCK(pwallet->cs_wallet);
int nMinVersion = 0;
if (Read((string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
// Get cursor
Dbc* pcursor = GetCursor();
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
return DB_CORRUPT;
}
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
LogPrintf("Error reading next record from wallet database\n");
return DB_CORRUPT;
}
// Try to be tolerant of single corrupt records:
string strType, strErr;
if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
{
// losing keys is considered a catastrophic error, anything else
// we assume the user can live with:
if (IsKeyType(strType))
result = DB_CORRUPT;
else
{
// Leave other errors alone, if we try to fix them we might make things worse.
fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
if (strType == "tx")
// Rescan if there is a bad transaction record:
SoftSetBoolArg("-rescan", true);
}
}
if (!strErr.empty())
LogPrintf("%s\n", strErr);
}
pcursor->close();
// Store initial pool size
pwallet->nKeysLeftSinceAutoBackup = pwallet->GetKeyPoolSize();
LogPrintf("nKeysLeftSinceAutoBackup: %d\n", pwallet->nKeysLeftSinceAutoBackup);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (...) {
result = DB_CORRUPT;
}
if (fNoncriticalErrors && result == DB_LOAD_OK)
result = DB_NONCRITICAL_ERROR;
// Any wallet corruption at all: skip any rewriting or
// upgrading, we don't want to make it worse.
if (result != DB_LOAD_OK)
return result;
LogPrintf("nFileVersion = %d\n", wss.nFileVersion);
LogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
// nTimeFirstKey is only reliable if all keys have metadata
if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta)
pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value'
BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade)
WriteTx(hash, pwallet->mapWallet[hash]);
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
return DB_NEED_REWRITE;
if (wss.nFileVersion < CLIENT_VERSION) // Update
WriteVersion(CLIENT_VERSION);
if (wss.fAnyUnordered)
result = ReorderTransactions(pwallet);
pwallet->laccentries.clear();
ListAccountCreditDebit("*", pwallet->laccentries);
BOOST_FOREACH(CAccountingEntry& entry, pwallet->laccentries) {
pwallet->wtxOrdered.insert(make_pair(entry.nOrderPos, CWallet::TxPair((CWalletTx*)0, &entry)));
}
return result;
}
DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash, vector<CWalletTx>& vWtx)
{
pwallet->vchDefaultKey = CPubKey();
bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK;
try {
LOCK(pwallet->cs_wallet);
int nMinVersion = 0;
if (Read((string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
// Get cursor
Dbc* pcursor = GetCursor();
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
return DB_CORRUPT;
}
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
LogPrintf("Error reading next record from wallet database\n");
return DB_CORRUPT;
}
string strType;
ssKey >> strType;
if (strType == "tx") {
uint256 hash;
ssKey >> hash;
CWalletTx wtx;
ssValue >> wtx;
vTxHash.push_back(hash);
vWtx.push_back(wtx);
}
}
pcursor->close();
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (...) {
result = DB_CORRUPT;
}
if (fNoncriticalErrors && result == DB_LOAD_OK)
result = DB_NONCRITICAL_ERROR;
return result;
}
DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet, vector<CWalletTx>& vWtx)
{
// build list of wallet TXs
vector<uint256> vTxHash;
DBErrors err = FindWalletTx(pwallet, vTxHash, vWtx);
if (err != DB_LOAD_OK)
return err;
// erase each wallet TX
BOOST_FOREACH (uint256& hash, vTxHash) {
if (!EraseTx(hash))
return DB_CORRUPT;
}
return DB_LOAD_OK;
}
void ThreadFlushWalletDB(const string& strFile)
{
// Make this thread recognisable as the wallet flushing thread
RenameThread("qbic-wallet");
static bool fOneThread;
if (fOneThread)
return;
fOneThread = true;
if (!GetBoolArg("-flushwallet", DEFAULT_FLUSHWALLET))
return;
unsigned int nLastSeen = nWalletDBUpdated;
unsigned int nLastFlushed = nWalletDBUpdated;
int64_t nLastWalletUpdate = GetTime();
while (true)
{
MilliSleep(500);
if (nLastSeen != nWalletDBUpdated)
{
nLastSeen = nWalletDBUpdated;
nLastWalletUpdate = GetTime();
}
if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
{
TRY_LOCK(bitdb.cs_db,lockDb);
if (lockDb)
{
// Don't do this if any databases are in use
int nRefCount = 0;
map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
while (mi != bitdb.mapFileUseCount.end())
{
nRefCount += (*mi).second;
mi++;
}
if (nRefCount == 0)
{
boost::this_thread::interruption_point();
map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
if (mi != bitdb.mapFileUseCount.end())
{
LogPrint("db", "Flushing wallet.dat\n");
nLastFlushed = nWalletDBUpdated;
int64_t nStart = GetTimeMillis();
// Flush wallet.dat so it's self contained
bitdb.CloseDb(strFile);
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(mi++);
LogPrint("db", "Flushed wallet.dat %dms\n", GetTimeMillis() - nStart);
}
}
}
}
}
}
bool BackupWallet(const CWallet& wallet, const string& strDest)
{
if (!wallet.fFileBacked)
return false;
while (true)
{
{
LOCK(bitdb.cs_db);
if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
{
// Flush log data to the dat file
bitdb.CloseDb(wallet.strWalletFile);
bitdb.CheckpointLSN(wallet.strWalletFile);
bitdb.mapFileUseCount.erase(wallet.strWalletFile);
// Copy wallet.dat
boost::filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
boost::filesystem::path pathDest(strDest);
if (boost::filesystem::is_directory(pathDest))
pathDest /= wallet.strWalletFile;
try {
#if BOOST_VERSION >= 104000
boost::filesystem::copy_file(pathSrc, pathDest, boost::filesystem::copy_option::overwrite_if_exists);
#else
boost::filesystem::copy_file(pathSrc, pathDest);
#endif
LogPrintf("copied wallet.dat to %s\n", pathDest.string());
return true;
} catch (const boost::filesystem::filesystem_error& e) {
LogPrintf("error copying wallet.dat to %s - %s\n", pathDest.string(), e.what());
return false;
}
}
}
MilliSleep(100);
}
return false;
}
// This should be called carefully:
// either supply "wallet" (if already loaded) or "strWalletFile" (if wallet wasn't loaded yet)
bool AutoBackupWallet (CWallet* wallet, std::string strWalletFile, std::string& strBackupWarning, std::string& strBackupError)
{
namespace fs = boost::filesystem;
strBackupWarning = strBackupError = "";
if(nWalletBackups > 0)
{
fs::path backupsDir = GetBackupsDir();
if (!fs::exists(backupsDir))
{
// Always create backup folder to not confuse the operating system's file browser
LogPrintf("Creating backup folder %s\n", backupsDir.string());
if(!fs::create_directories(backupsDir)) {
// smth is wrong, we shouldn't continue until it's resolved
strBackupError = strprintf(_("Wasn't able to create wallet backup folder %s!"), backupsDir.string());
LogPrintf("%s\n", strBackupError);
nWalletBackups = -1;
return false;
}
}
// Create backup of the ...
std::string dateTimeStr = DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime());
if (wallet)
{
// ... opened wallet
LOCK2(cs_main, wallet->cs_wallet);
strWalletFile = wallet->strWalletFile;
fs::path backupFile = backupsDir / (strWalletFile + dateTimeStr);
if(!BackupWallet(*wallet, backupFile.string())) {
strBackupWarning = strprintf(_("Failed to create backup %s!"), backupFile.string());
LogPrintf("%s\n", strBackupWarning);
nWalletBackups = -1;
return false;
}
// Update nKeysLeftSinceAutoBackup using current pool size
wallet->nKeysLeftSinceAutoBackup = wallet->GetKeyPoolSize();
LogPrintf("nKeysLeftSinceAutoBackup: %d\n", wallet->nKeysLeftSinceAutoBackup);
if(wallet->IsLocked(true)) {
strBackupWarning = _("Wallet is locked, can't replenish keypool! Automatic backups and mixing are disabled, please unlock your wallet to replenish keypool.");
LogPrintf("%s\n", strBackupWarning);
nWalletBackups = -2;
return false;
}
} else {
// ... strWalletFile file
fs::path sourceFile = GetDataDir() / strWalletFile;
fs::path backupFile = backupsDir / (strWalletFile + dateTimeStr);
sourceFile.make_preferred();
backupFile.make_preferred();
if (fs::exists(backupFile))
{
strBackupWarning = _("Failed to create backup, file already exists! This could happen if you restarted wallet in less than 60 seconds. You can continue if you are ok with this.");
LogPrintf("%s\n", strBackupWarning);
return false;
}
if(fs::exists(sourceFile)) {
try {
fs::copy_file(sourceFile, backupFile);
LogPrintf("Creating backup of %s -> %s\n", sourceFile.string(), backupFile.string());
} catch(fs::filesystem_error &error) {
strBackupWarning = strprintf(_("Failed to create backup, error: %s"), error.what());
LogPrintf("%s\n", strBackupWarning);
nWalletBackups = -1;
return false;
}
}
}
// Keep only the last 10 backups, including the new one of course
typedef std::multimap<std::time_t, fs::path> folder_set_t;
folder_set_t folder_set;
fs::directory_iterator end_iter;
backupsDir.make_preferred();
// Build map of backup files for current(!) wallet sorted by last write time
fs::path currentFile;
for (fs::directory_iterator dir_iter(backupsDir); dir_iter != end_iter; ++dir_iter)
{
// Only check regular files
if ( fs::is_regular_file(dir_iter->status()))
{
currentFile = dir_iter->path().filename();
// Only add the backups for the current wallet, e.g. wallet.dat.*
if(dir_iter->path().stem().string() == strWalletFile)
{
folder_set.insert(folder_set_t::value_type(fs::last_write_time(dir_iter->path()), *dir_iter));
}
}
}
// Loop backward through backup files and keep the N newest ones (1 <= N <= 10)
int counter = 0;
BOOST_REVERSE_FOREACH(PAIRTYPE(const std::time_t, fs::path) file, folder_set)
{
counter++;
if (counter > nWalletBackups)
{
// More than nWalletBackups backups: delete oldest one(s)
try {
fs::remove(file.second);
LogPrintf("Old backup deleted: %s\n", file.second);
} catch(fs::filesystem_error &error) {
strBackupWarning = strprintf(_("Failed to delete backup, error: %s"), error.what());
LogPrintf("%s\n", strBackupWarning);
return false;
}
}
}
return true;
}
LogPrintf("Automatic wallet backups are disabled!\n");
return false;
}
//
// Try to (very carefully!) recover wallet.dat if there is a problem.
//
bool CWalletDB::Recover(CDBEnv& dbenv, const std::string& filename, bool fOnlyKeys)
{
// Recovery procedure:
// move wallet.dat to wallet.timestamp.bak
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to wallet.dat
// Set -rescan so any missing transactions will be
// found.
int64_t now = GetTime();
std::string newFilename = strprintf("wallet.%d.bak", now);
int result = dbenv.dbenv->dbrename(NULL, filename.c_str(), NULL,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
LogPrintf("Renamed %s to %s\n", filename, newFilename);
else
{
LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
return false;
}
std::vector<CDBEnv::KeyValPair> salvagedData;
bool fSuccess = dbenv.Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
return false;
}
LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
boost::scoped_ptr<Db> pdbCopy(new Db(dbenv.dbenv, 0));
int ret = pdbCopy->open(NULL, // Txn pointer
filename.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0)
{
LogPrintf("Cannot create database file %s\n", filename);
return false;
}
CWallet dummyWallet;
CWalletScanState wss;
DbTxn* ptxn = dbenv.TxnBegin();
BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
{
if (fOnlyKeys)
{
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
string strType, strErr;
bool fReadOK;
{
// Required in LoadKeyMetadata():
LOCK(dummyWallet.cs_wallet);
fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
wss, strType, strErr);
}
if (!IsKeyType(strType))
continue;
if (!fReadOK)
{
LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr);
continue;
}
}
Dbt datKey(&row.first[0], row.first.size());
Dbt datValue(&row.second[0], row.second.size());
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
ptxn->commit(0);
pdbCopy->close(0);
return fSuccess;
}
bool CWalletDB::Recover(CDBEnv& dbenv, const std::string& filename)
{
return CWalletDB::Recover(dbenv, filename, false);
}
bool CWalletDB::WriteDestData(const std::string &address, const std::string &key, const std::string &value)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("destdata"), std::make_pair(address, key)), value);
}
bool CWalletDB::EraseDestData(const std::string &address, const std::string &key)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("destdata"), std::make_pair(address, key)));
}
| [
"info@misscoin.io"
] | info@misscoin.io |
7b531bd45202412487a0ea48b98c3997f97b90fa | b915b1940cb3f9a4f8b2db231ea73a75ae283513 | /List/traverse.cpp | a7b371f68fd1359ca852d738ff272a0a866ca85f | [] | no_license | hblee12294/algorithm-prc | bc3259106ec7f4fe30289146d0fa126c038502ef | 8ceaa7ac00b619f3be23e2c1dd6d90aa848c0e58 | refs/heads/master | 2021-06-08T21:12:27.516054 | 2016-12-03T14:00:02 | 2016-12-03T14:00:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | cpp | template <typename T>
void List<T>::traverse(void (*vist)(T&)) // function pointer
{
Posi(T) p = header;
while ((p = p->succ) != trailer) visit(p->data);
}
template <typename T>
template <typename VST>
void List<T>::traverse(VST &visit) // function object
{
Posi(T) p = header;
while ((p = p->succ) != trailer) visit(p->data);
} | [
"hblee12294@gmail.com"
] | hblee12294@gmail.com |
99a1b99dac4b62ed8952ccd3e12633ab5e38071c | 6656cb5738ab865adad9b5ba2129ab21ca240fd5 | /MasterFile/src/tests/test_multiple_resolution_encode.cpp | deba9e4427fc6f8455c89adef45bfe6995fb674b | [] | no_license | jamesaberry/webm.libvpx-tester-cmake | f524c5dac99d680eabd779e32a73f8843ee8e22b | ee3b0c819ea46417aa97eaf4fd14ca1fc4ab759f | refs/heads/master | 2021-07-04T14:33:39.543087 | 2017-09-25T15:35:17 | 2017-09-25T17:19:11 | 104,767,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,440 | cpp | #include "vpxt_test_declarations.h"
int test_multiple_resolution_encode(int argc,
const char** argv,
const std::string &working_dir,
const std::string sub_folder_str,
int test_type,
int delete_ivf,
int artifact_detection)
{
char *comp_out_str = "Allow Spatial Resampling";
char *test_dir = "test_multiple_resolution_encode";
int input_ver = vpxt_check_arg_input(argv[1], argc);
if (input_ver < 0)
return vpxt_test_help(argv[1], 0);
std::string input = argv[2];
int bitrate = atoi(argv[3]);
std::string enc_format = argv[4];
unsigned int width_1;
unsigned int height_1;
unsigned int width_2;
unsigned int height_2;
unsigned int width_3;
unsigned int height_3;
int speed = 0;
//////////// Formatting Test Specific directory ////////////
std::string cur_test_dir_str;
std::string file_index_str;
char main_test_dir_char[255] = "";
char file_index_output_char[255] = "";
if (initialize_test_directory(argc, argv, test_type, working_dir, test_dir,
cur_test_dir_str, file_index_str, main_test_dir_char,
file_index_output_char, sub_folder_str) == 11)
return kTestErrFileMismatch;
char width_1_char[10];
char width_2_char[10];
char width_3_char[10];
char height_1_char[10];
char height_2_char[10];
char height_3_char[10];
vpxt_get_multi_res_width_height(input.c_str(), 1, width_1, height_1);
vpxt_get_multi_res_width_height(input.c_str(), 2, width_2, height_2);
vpxt_get_multi_res_width_height(input.c_str(), 3, width_3, height_3);
vpxt_itoa_custom(width_1, width_1_char, 10);
vpxt_itoa_custom(height_1, height_1_char, 10);
vpxt_itoa_custom(width_2, width_2_char, 10);
vpxt_itoa_custom(height_2, height_2_char, 10);
vpxt_itoa_custom(width_3, width_3_char, 10);
vpxt_itoa_custom(height_3, height_3_char, 10);
std::string multi_res_enc = cur_test_dir_str + slashCharStr() + test_dir;
int multi_res_enc_1_art_det = artifact_detection;
int multi_res_enc_2_art_det = artifact_detection;
int multi_res_enc_3_art_det = artifact_detection;
std::string multi_res_enc_1 = multi_res_enc + "-" + width_1_char + "x" +
height_1_char;
vpxt_enc_format_append(multi_res_enc_1, enc_format);
std::string multi_res_enc_2 = multi_res_enc + "-" + width_2_char + "x" +
height_2_char;
vpxt_enc_format_append(multi_res_enc_2, enc_format);
std::string multi_res_enc_3 = multi_res_enc + "-" + width_3_char + "x" +
height_3_char;
vpxt_enc_format_append(multi_res_enc_3, enc_format);
///////////// Open Output File and Print Header ////////////
std::string text_file_str = cur_test_dir_str + slashCharStr() + test_dir;
FILE *fp;
vpxt_open_output_file(test_type, text_file_str, fp);
vpxt_print_header(argc, argv, main_test_dir_char, cur_test_dir_str,
test_dir, test_type);
VP8_CONFIG opt;
vpxt_default_parameters(opt);
/////////////////// Use Custom Settings ///////////////////
if(vpxt_use_custom_settings(argv, argc, input_ver, fp, file_index_str,
file_index_output_char, test_type, opt, bitrate)
== kTestIndeterminate)
return kTestIndeterminate;
opt.target_bandwidth = bitrate;
// Run Test only (Runs Test, Sets up test to be run, or skips compresion of
// files)
if (test_type == kTestOnly)
{
// This test requires no preperation before a Test Only Run
}
else
{
if (vpxt_compress_multi_resolution(input.c_str(), multi_res_enc.c_str(),
speed, bitrate, opt, comp_out_str, 1, 0, enc_format) == -1)
{
fclose(fp);
record_test_complete(file_index_str, file_index_output_char,
test_type);
return kTestIndeterminate;
}
}
// Create Compression only stop test short.
if (test_type == kCompOnly)
{
fclose(fp);
record_test_complete(file_index_str, file_index_output_char, test_type);
return kTestEncCreated;
}
double psnr_1 = vpxt_psnr(input.c_str(), multi_res_enc_1.c_str(), 0,
PRINT_BTH, 1, 0, 0, 0, NULL, multi_res_enc_1_art_det);
double psnr_2 = vpxt_psnr(input.c_str(), multi_res_enc_2.c_str(), 0,
PRINT_BTH, 1, 0, 0, 0, NULL, multi_res_enc_2_art_det);
double psnr_3 = vpxt_psnr(input.c_str(), multi_res_enc_3.c_str(), 0,
PRINT_BTH, 1, 0, 0, 0, NULL, multi_res_enc_3_art_det);
char multi_res_enc_1_file_name[256];
char multi_res_enc_2_file_name[256];
char multi_res_enc_3_file_name[256];
vpxt_file_name(multi_res_enc_1.c_str(), multi_res_enc_1_file_name, 0);
vpxt_file_name(multi_res_enc_2.c_str(), multi_res_enc_2_file_name, 0);
vpxt_file_name(multi_res_enc_3.c_str(), multi_res_enc_3_file_name, 0);
int test_state = kTestPassed;
if (psnr_1 > 25.0)
{
vpxt_formated_print(RESPRT, "%s PSNR: %.2f > 25 - Passed",
multi_res_enc_1_file_name, psnr_1);
tprintf(PRINT_BTH, "\n");
}
else
{
vpxt_formated_print(RESPRT, "%s PSNR: %.2f < 25 - Failed",
multi_res_enc_1_file_name, psnr_1);
tprintf(PRINT_BTH, "\n");
test_state = kTestFailed;
}
if (psnr_2 > 25.0)
{
vpxt_formated_print(RESPRT, "%s PSNR: %.2f > 25 - Passed",
multi_res_enc_2_file_name, psnr_2);
tprintf(PRINT_BTH, "\n");
}
else
{
vpxt_formated_print(RESPRT, "%s PSNR: %.2f < 25 - Failed",
multi_res_enc_2_file_name, psnr_2);
tprintf(PRINT_BTH, "\n");
test_state = kTestFailed;
}
if (psnr_3 > 25.0)
{
vpxt_formated_print(RESPRT, "%s PSNR: %.2f > 25 - Passed",
multi_res_enc_3_file_name, psnr_3);
tprintf(PRINT_BTH, "\n");
}
else
{
vpxt_formated_print(RESPRT, "%s PSNR: %.2f < 25 - Failed",
multi_res_enc_3_file_name, psnr_3);
tprintf(PRINT_BTH, "\n");
test_state = kTestFailed;
}
if (psnr_1 >= psnr_2 && psnr_2 >= psnr_3)
{
vpxt_formated_print(RESPRT, "%s: %.2f >= %s: %.2f >= %s: %.2f - Passed"
, multi_res_enc_1_file_name, psnr_1, multi_res_enc_2_file_name,
psnr_2, multi_res_enc_3_file_name, psnr_3);
tprintf(PRINT_BTH, "\n");
}
else
{
if(psnr_1 < psnr_2 && psnr_2 < psnr_3)
{
vpxt_formated_print(RESPRT, "%s: %.2f < %s: %.2f < %s: %.2f - "
"Failed", multi_res_enc_1_file_name, psnr_1,
multi_res_enc_2_file_name, psnr_2, multi_res_enc_3_file_name,
psnr_3);
tprintf(PRINT_BTH, "\n");
}
else if(psnr_1 < psnr_2)
{
vpxt_formated_print(RESPRT, "%s: %.2f < %s: %.2f >= %s: %.2f - "
"Failed", multi_res_enc_1_file_name, psnr_1,
multi_res_enc_2_file_name, psnr_2, multi_res_enc_3_file_name,
psnr_3);
tprintf(PRINT_BTH, "\n");
}
else if(psnr_2 < psnr_3)
{
vpxt_formated_print(RESPRT, "%s: %.2f >= %s: %.2f < %s: %.2f - "
"Failed", multi_res_enc_1_file_name, psnr_1,
multi_res_enc_2_file_name, psnr_2, multi_res_enc_3_file_name,
psnr_3);
tprintf(PRINT_BTH, "\n");
}
test_state = kTestFailed;
}
// handle possible artifact
if(multi_res_enc_1_art_det == kPossibleArtifactFound ||
multi_res_enc_2_art_det == kPossibleArtifactFound ||
multi_res_enc_3_art_det == kPossibleArtifactFound)
{
tprintf(PRINT_BTH, "\nPossible Artifact\n");
fclose(fp);
record_test_complete(file_index_str, file_index_output_char, test_type);
return kTestPossibleArtifact;
}
if (test_state == kTestPassed)
tprintf(PRINT_BTH, "\nPassed\n");
if (test_state == kTestFailed)
tprintf(PRINT_BTH, "\nFailed\n");
if (delete_ivf)
vpxt_delete_files(3, multi_res_enc_1.c_str(), multi_res_enc_2.c_str(),
multi_res_enc_3.c_str());
fclose(fp);
record_test_complete(file_index_str, file_index_output_char, test_type);
return test_state;
}
| [
"jamesberry@google.com"
] | jamesberry@google.com |
358bb48f5b87c2b1d7f4f162daab3584ae042fed | b0e74eb6a105bacaeed0219ef1c778c52faed277 | /source/FAST/Tools/OpenIGTLinkClient/main.cpp | 6d3138a1af7a2ce4269d757847c4f6dbdb945d84 | [
"BSD-2-Clause"
] | permissive | gjertmagne/FAST | 034cfc7eeb695bcacce0460e42ebb3f38062d712 | acd6f6f365b8ed9e0cedf5a5de99870669b449b0 | refs/heads/master | 2020-03-28T17:31:07.325707 | 2018-09-14T10:00:18 | 2018-09-14T10:00:18 | 148,797,490 | 0 | 0 | BSD-2-Clause | 2018-09-14T14:08:13 | 2018-09-14T14:08:13 | null | UTF-8 | C++ | false | false | 204 | cpp | #include "GUI.hpp"
using namespace fast;
int main() {
//Reporter::setGlobalReportMethod(Reporter::COUT);
GUI::pointer window = GUI::New();
window->start(STREAMING_MODE_NEWEST_FRAME_ONLY);
} | [
"ersmistad@gmail.com"
] | ersmistad@gmail.com |
fe59b00004eaf53233227155091c50152a7da35a | 142c7070d08447c2b1c6aaf43bf109f8292aa8bd | /Edaly_Projets_Template/A3_Structure.hpp | 199027811124780b838b2e2b6a0c8961744cc00b | [] | no_license | Gekloecht/Edaly_Addons | bc98ee65e58226d23945a9f3823633e0cd51ca7c | 21eabbdadc1b4231c2b89645eee1c96cf62a7e79 | refs/heads/master | 2020-03-07T14:55:01.744051 | 2018-03-31T13:08:28 | 2018-03-31T13:08:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,583 | hpp | class Edaly_A3_Structure_Stadium_p1_F : Static
{
scope = 2;
displayName = "Stadium P1";
model = "a3\structures_f_epc\Dominants\Stadium\Stadium_p1_F.p3d";
editorCategory = "EdCat_Edaly_Structure";
editorSubcategory = "EdSubcat_Edaly_Structure_Sport";
editorPreview = "\Edaly_Projets_Template\EditorPreview\Edaly_A3_Structure_Stadium_p1_F.jpg";
};
class Edaly_A3_Structure_Stadium_p2_F : Edaly_A3_Structure_Stadium_p1_F
{
scope = 2;
displayName = "Stadium P2";
model = "a3\structures_f_epc\Dominants\Stadium\Stadium_p2_F.p3d";
editorPreview = "\Edaly_Projets_Template\EditorPreview\Edaly_A3_Structure_Stadium_p2_F.jpg";
};
class Edaly_A3_Structure_Stadium_p3_F : Edaly_A3_Structure_Stadium_p1_F
{
scope = 2;
displayName = "Stadium P3";
model = "a3\structures_f_epc\Dominants\Stadium\Stadium_p3_F.p3d";
editorPreview = "\Edaly_Projets_Template\EditorPreview\Edaly_A3_Structure_Stadium_p3_F.jpg";
};
class Edaly_A3_Structure_Stadium_p4_F : Edaly_A3_Structure_Stadium_p1_F
{
scope = 2;
displayName = "Stadium P4";
model = "a3\structures_f_epc\Dominants\Stadium\Stadium_p4_F.p3d";
editorPreview = "\Edaly_Projets_Template\EditorPreview\Edaly_A3_Structure_Stadium_p4_F.jpg";
};
class Edaly_A3_Structure_Stadium_p5_F : Edaly_A3_Structure_Stadium_p1_F
{
scope = 2;
displayName = "Stadium P5";
model = "a3\structures_f_epc\Dominants\Stadium\Stadium_p5_F.p3d";
editorPreview = "\Edaly_Projets_Template\EditorPreview\Edaly_A3_Structure_Stadium_p5_F.jpg";
};
class Edaly_A3_Structure_Stadium_p6_F : Edaly_A3_Structure_Stadium_p1_F
{
scope = 2;
displayName = "Stadium P6";
model = "a3\structures_f_epc\Dominants\Stadium\Stadium_p6_F.p3d";
editorPreview = "\Edaly_Projets_Template\EditorPreview\Edaly_A3_Structure_Stadium_p6_F.jpg";
};
class Edaly_A3_Structure_Stadium_p7_F : Edaly_A3_Structure_Stadium_p1_F
{
scope = 2;
displayName = "Stadium P7";
model = "a3\structures_f_epc\Dominants\Stadium\Stadium_p7_F.p3d";
editorPreview = "\Edaly_Projets_Template\EditorPreview\Edaly_A3_Structure_Stadium_p7_F.jpg";
};
class Edaly_A3_Structure_Stadium_p8_F : Edaly_A3_Structure_Stadium_p1_F
{
scope = 2;
displayName = "Stadium P8";
model = "a3\structures_f_epc\Dominants\Stadium\Stadium_p8_F.p3d";
editorPreview = "\Edaly_Projets_Template\EditorPreview\Edaly_A3_Structure_Stadium_p8_F.jpg";
};
class Edaly_A3_Structure_Stadium_p9_F : Edaly_A3_Structure_Stadium_p1_F
{
scope = 2;
displayName = "Stadium P9";
model = "a3\structures_f_epc\Dominants\Stadium\Stadium_p9_F.p3d";
editorPreview = "\Edaly_Projets_Template\EditorPreview\Edaly_A3_Structure_Stadium_p9_F.jpg";
}; | [
"KeviinSkyline@hotmail.fr"
] | KeviinSkyline@hotmail.fr |
08c9832e830bb4580472d5553ce30ab30b35d68e | 7a5d97bb9179511310447a126df89042b9b52981 | /Client/Source/Net/Action/AcMainLogin.cpp | 5337649314e591b9de0416a0285cae0fb07f5d86 | [] | no_license | wzAdmin/buddyLocate | cf4af4663120bd164802156b28b8492cc6da3841 | 327f86ac4944bb02c9a3171ad24c9445a3a664e1 | refs/heads/master | 2016-09-05T09:46:19.620127 | 2013-05-11T15:45:06 | 2013-05-11T15:45:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 390 | cpp | #include "AcMainLogin.h"
#include "RakPeerInterface.h"
#include "Net/LoginCallBack.h"
#include "Net/MainClient.h"
namespace Net
{
void AcMainLogin::doWork()
{
Common::GetBuddies gbd;
RakNet::BitStream bst;
gbd.ToBitStream(bst);
MainClient::Instance().SendBitStream(&bst);
if(MainClient::Instance().mCallBack)
MainClient::Instance().mCallBack->OnLoginReulst(LGE_none);
}
}
| [
"wudecs2007@126.com"
] | wudecs2007@126.com |
38fc3e714549ac18015bf257ace7d4281c0d9e65 | 3a77e7ffa78b51e1be18576f0c3e99048be8734f | /be/src/vec/columns/column_struct.cpp | 78c438a5e1b678a8be486a1820a8eee2a8a41b96 | [
"OpenSSL",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-facebook-patent-rights-2",
"PSF-2.0",
"dtoa",
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-public-domain"
] | permissive | yiguolei/incubator-doris | e73e2c44c7e3a3869d379555a29abfe48f97de6c | ada01b7ba6eac5d442b7701b78cea44235ed5017 | refs/heads/master | 2023-08-18T23:28:09.915740 | 2023-08-05T05:18:18 | 2023-08-05T05:18:44 | 160,305,067 | 1 | 1 | Apache-2.0 | 2023-07-07T08:05:16 | 2018-12-04T05:43:20 | Java | UTF-8 | C++ | false | false | 12,894 | cpp | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// This file is copied from
// https://github.com/ClickHouse/ClickHouse/blob/master/src/Columns/ColumnStruct.cpp
// and modified by Doris
#include "vec/columns/column_struct.h"
#include <functional>
#include "vec/common/assert_cast.h"
#include "vec/common/typeid_cast.h"
class SipHash;
namespace doris {
namespace vectorized {
class Arena;
} // namespace vectorized
} // namespace doris
namespace doris::vectorized {
std::string ColumnStruct::get_name() const {
std::stringstream res;
res << "Struct(";
bool is_first = true;
for (const auto& column : columns) {
if (!is_first) {
res << ", ";
}
is_first = false;
res << column->get_name();
}
res << ")";
return res.str();
}
ColumnStruct::ColumnStruct(MutableColumns&& mutable_columns) {
columns.reserve(mutable_columns.size());
for (auto& column : mutable_columns) {
if (is_column_const(*column)) {
LOG(FATAL) << "ColumnStruct cannot have ColumnConst as its element";
}
columns.push_back(std::move(column));
}
}
ColumnStruct::Ptr ColumnStruct::create(const Columns& columns) {
for (const auto& column : columns) {
if (is_column_const(*column)) {
LOG(FATAL) << "ColumnStruct cannot have ColumnConst as its element";
}
}
auto column_struct = ColumnStruct::create(MutableColumns());
column_struct->columns.assign(columns.begin(), columns.end());
return column_struct;
}
ColumnStruct::Ptr ColumnStruct::create(const TupleColumns& tuple_columns) {
for (const auto& column : tuple_columns) {
if (is_column_const(*column)) {
LOG(FATAL) << "ColumnStruct cannot have ColumnConst as its element";
}
}
auto column_struct = ColumnStruct::create(MutableColumns());
column_struct->columns = tuple_columns;
return column_struct;
}
MutableColumnPtr ColumnStruct::clone_empty() const {
const size_t tuple_size = columns.size();
MutableColumns new_columns(tuple_size);
for (size_t i = 0; i < tuple_size; ++i) {
new_columns[i] = columns[i]->clone_empty();
}
return ColumnStruct::create(std::move(new_columns));
}
MutableColumnPtr ColumnStruct::clone_resized(size_t new_size) const {
const size_t tuple_size = columns.size();
MutableColumns new_columns(tuple_size);
for (size_t i = 0; i < tuple_size; ++i) {
new_columns[i] = columns[i]->clone_resized(new_size);
}
return ColumnStruct::create(std::move(new_columns));
}
Field ColumnStruct::operator[](size_t n) const {
Field res;
get(n, res);
return res;
}
void ColumnStruct::get(size_t n, Field& res) const {
const size_t tuple_size = columns.size();
res = Tuple();
Tuple& res_tuple = res.get<Tuple&>();
res_tuple.reserve(tuple_size);
for (size_t i = 0; i < tuple_size; ++i) {
res_tuple.push_back((*columns[i])[n]);
}
}
bool ColumnStruct::is_default_at(size_t n) const {
const size_t tuple_size = columns.size();
for (size_t i = 0; i < tuple_size; ++i) {
if (!columns[i]->is_default_at(n)) {
return false;
}
}
return true;
}
void ColumnStruct::insert(const Field& x) {
const auto& tuple = x.get<const Tuple&>();
const size_t tuple_size = columns.size();
if (tuple.size() != tuple_size) {
LOG(FATAL) << "Cannot insert value of different size into tuple. field tuple size"
<< tuple.size() << ", columns size " << tuple_size;
}
for (size_t i = 0; i < tuple_size; ++i) {
columns[i]->insert(tuple[i]);
}
}
void ColumnStruct::insert_from(const IColumn& src_, size_t n) {
const ColumnStruct& src = assert_cast<const ColumnStruct&>(src_);
const size_t tuple_size = columns.size();
if (src.columns.size() != tuple_size) {
LOG(FATAL) << "Cannot insert value of different size into tuple.";
}
for (size_t i = 0; i < tuple_size; ++i) {
columns[i]->insert_from(*src.columns[i], n);
}
}
void ColumnStruct::insert_default() {
for (auto& column : columns) {
column->insert_default();
}
}
void ColumnStruct::pop_back(size_t n) {
for (auto& column : columns) {
column->pop_back(n);
}
}
StringRef ColumnStruct::serialize_value_into_arena(size_t n, Arena& arena,
char const*& begin) const {
StringRef res(begin, 0);
for (const auto& column : columns) {
auto value_ref = column->serialize_value_into_arena(n, arena, begin);
res.data = value_ref.data - res.size;
res.size += value_ref.size;
}
return res;
}
const char* ColumnStruct::deserialize_and_insert_from_arena(const char* pos) {
for (auto& column : columns) {
pos = column->deserialize_and_insert_from_arena(pos);
}
return pos;
}
void ColumnStruct::update_hash_with_value(size_t n, SipHash& hash) const {
for (const auto& column : columns) {
column->update_hash_with_value(n, hash);
}
}
void ColumnStruct::update_hashes_with_value(std::vector<SipHash>& hashes,
const uint8_t* __restrict null_data) const {
SIP_HASHES_FUNCTION_COLUMN_IMPL();
}
void ColumnStruct::update_xxHash_with_value(size_t start, size_t end, uint64_t& hash,
const uint8_t* __restrict null_data) const {
for (const auto& column : columns) {
column->update_xxHash_with_value(start, end, hash, nullptr);
}
}
void ColumnStruct::update_crc_with_value(size_t start, size_t end, uint64_t& hash,
const uint8_t* __restrict null_data) const {
for (const auto& column : columns) {
column->update_crc_with_value(start, end, hash, nullptr);
}
}
void ColumnStruct::update_hashes_with_value(uint64_t* __restrict hashes,
const uint8_t* __restrict null_data) const {
for (const auto& column : columns) {
column->update_hashes_with_value(hashes, null_data);
}
}
void ColumnStruct::update_crcs_with_value(std::vector<uint64_t>& hash, PrimitiveType type,
const uint8_t* __restrict null_data) const {
for (const auto& column : columns) {
column->update_crcs_with_value(hash, type, null_data);
}
}
void ColumnStruct::insert_indices_from(const IColumn& src, const int* indices_begin,
const int* indices_end) {
const ColumnStruct& src_concrete = assert_cast<const ColumnStruct&>(src);
for (size_t i = 0; i < columns.size(); ++i) {
columns[i]->insert_indices_from(src_concrete.get_column(i), indices_begin, indices_end);
}
}
void ColumnStruct::insert_range_from(const IColumn& src, size_t start, size_t length) {
const size_t tuple_size = columns.size();
for (size_t i = 0; i < tuple_size; ++i) {
columns[i]->insert_range_from(*assert_cast<const ColumnStruct&>(src).columns[i], start,
length);
}
}
ColumnPtr ColumnStruct::filter(const Filter& filt, ssize_t result_size_hint) const {
const size_t tuple_size = columns.size();
Columns new_columns(tuple_size);
for (size_t i = 0; i < tuple_size; ++i) {
new_columns[i] = columns[i]->filter(filt, result_size_hint);
}
return ColumnStruct::create(new_columns);
}
size_t ColumnStruct::filter(const Filter& filter) {
const size_t tuple_size = columns.size();
size_t result_size = 0;
for (size_t i = 0; i < tuple_size; ++i) {
const auto this_result_size = columns[i]->filter(filter);
CHECK(result_size == 0 || result_size == this_result_size);
result_size = this_result_size;
}
return result_size;
}
Status ColumnStruct::filter_by_selector(const uint16_t* sel, size_t sel_size, IColumn* col_ptr) {
auto to = reinterpret_cast<vectorized::ColumnStruct*>(col_ptr);
const size_t tuple_size = columns.size();
DCHECK_EQ(to->tuple_size(), tuple_size);
for (size_t i = 0; i < tuple_size; ++i) {
columns[i]->filter_by_selector(sel, sel_size, &to->get_column(i));
}
return Status::OK();
}
ColumnPtr ColumnStruct::permute(const Permutation& perm, size_t limit) const {
const size_t tuple_size = columns.size();
Columns new_columns(tuple_size);
for (size_t i = 0; i < tuple_size; ++i) {
new_columns[i] = columns[i]->permute(perm, limit);
}
return ColumnStruct::create(new_columns);
}
ColumnPtr ColumnStruct::replicate(const Offsets& offsets) const {
const size_t tuple_size = columns.size();
Columns new_columns(tuple_size);
for (size_t i = 0; i < tuple_size; ++i) {
new_columns[i] = columns[i]->replicate(offsets);
}
return ColumnStruct::create(new_columns);
}
void ColumnStruct::replicate(const uint32_t* indexs, size_t target_size, IColumn& column) const {
auto& res = reinterpret_cast<ColumnStruct&>(column);
res.columns.resize(columns.size());
for (size_t i = 0; i != columns.size(); ++i) {
columns[i]->replicate(indexs, target_size, *res.columns[i]);
}
}
MutableColumns ColumnStruct::scatter(ColumnIndex num_columns, const Selector& selector) const {
const size_t tuple_size = columns.size();
std::vector<MutableColumns> scattered_tuple_elements(tuple_size);
for (size_t tuple_element_idx = 0; tuple_element_idx < tuple_size; ++tuple_element_idx) {
scattered_tuple_elements[tuple_element_idx] =
columns[tuple_element_idx]->scatter(num_columns, selector);
}
MutableColumns res(num_columns);
for (size_t scattered_idx = 0; scattered_idx < num_columns; ++scattered_idx) {
MutableColumns new_columns(tuple_size);
for (size_t tuple_element_idx = 0; tuple_element_idx < tuple_size; ++tuple_element_idx) {
new_columns[tuple_element_idx] =
std::move(scattered_tuple_elements[tuple_element_idx][scattered_idx]);
}
res[scattered_idx] = ColumnStruct::create(std::move(new_columns));
}
return res;
}
void ColumnStruct::reserve(size_t n) {
const size_t tuple_size = columns.size();
for (size_t i = 0; i < tuple_size; ++i) {
get_column(i).reserve(n);
}
}
//please check you real need size in data column, When it mixes various data types, eg: string column with int column
void ColumnStruct::resize(size_t n) {
const size_t tuple_size = columns.size();
for (size_t i = 0; i < tuple_size; ++i) {
get_column(i).resize(n);
}
}
size_t ColumnStruct::byte_size() const {
size_t res = 0;
for (const auto& column : columns) {
res += column->byte_size();
}
return res;
}
size_t ColumnStruct::allocated_bytes() const {
size_t res = 0;
for (const auto& column : columns) {
res += column->allocated_bytes();
}
return res;
}
void ColumnStruct::protect() {
for (auto& column : columns) {
column->protect();
}
}
void ColumnStruct::get_extremes(Field& min, Field& max) const {
const size_t tuple_size = columns.size();
Tuple min_tuple(tuple_size);
Tuple max_tuple(tuple_size);
for (size_t i = 0; i < tuple_size; ++i) {
columns[i]->get_extremes(min_tuple[i], max_tuple[i]);
}
min = min_tuple;
max = max_tuple;
}
void ColumnStruct::for_each_subcolumn(ColumnCallback callback) {
for (auto& column : columns) {
callback(column);
}
}
bool ColumnStruct::structure_equals(const IColumn& rhs) const {
if (const auto* rhs_tuple = typeid_cast<const ColumnStruct*>(&rhs)) {
const size_t tuple_size = columns.size();
if (tuple_size != rhs_tuple->columns.size()) {
return false;
}
for (size_t i = 0; i < tuple_size; ++i) {
if (!columns[i]->structure_equals(*rhs_tuple->columns[i])) {
return false;
}
}
return true;
} else {
return false;
}
}
} // namespace doris::vectorized
| [
"noreply@github.com"
] | noreply@github.com |
5432d3d2782911be97e65ba5024289679854e0a3 | 4c04bfa2b0dd91250e35bce2886954830299bb80 | /src/bench/checkqueue.cpp | 845a92d2d6d4825aa7ff0092e6b893aa697df101 | [
"MIT"
] | permissive | thehomosapien/dclr | 6a81a5fcd761b6fb7cf21f5d1c7e64d8d6e0c941 | dba88f2ad6359addaa66f1875792cc8c4f30d686 | refs/heads/master | 2020-07-04T03:28:50.754864 | 2019-08-13T12:27:40 | 2019-08-13T12:27:40 | 202,137,473 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,688 | cpp | // Copyright (c) 2017-2018 The Bitcoin Core developers
// Copyright (c) 2017 The Raven Core developers
// Copyright (c) 2018 The Rito Core developers
// Copyright (c) 2019 The DCLRcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bench.h"
#include "util.h"
#include "validation.h"
#include "checkqueue.h"
#include "prevector.h"
#include <vector>
#include <boost/thread/thread.hpp>
#include "random.h"
// This Benchmark tests the CheckQueue with the lightest
// weight Checks, so it should make any lock contention
// particularly visible
static const int MIN_CORES = 2;
static const size_t BATCHES = 101;
static const size_t BATCH_SIZE = 30;
static const int PREVECTOR_SIZE = 28;
static const int QUEUE_BATCH_SIZE = 128;
static void CCheckQueueSpeed(benchmark::State& state)
{
struct FakeJobNoWork {
bool operator()()
{
return true;
}
void swap(FakeJobNoWork& x){};
};
CCheckQueue<FakeJobNoWork> queue {QUEUE_BATCH_SIZE};
boost::thread_group tg;
for (auto x = 0; x < std::max(MIN_CORES, GetNumCores()); ++x) {
tg.create_thread([&]{queue.Thread();});
}
while (state.KeepRunning()) {
CCheckQueueControl<FakeJobNoWork> control(&queue);
// We call Add a number of times to simulate the behavior of adding
// a block of transactions at once.
std::vector<std::vector<FakeJobNoWork>> vBatches(BATCHES);
for (auto& vChecks : vBatches) {
vChecks.resize(BATCH_SIZE);
}
for (auto& vChecks : vBatches) {
// We can't make vChecks in the inner loop because we want to measure
// the cost of getting the memory to each thread and we might get the same
// memory
control.Add(vChecks);
}
// control waits for completion by RAII, but
// it is done explicitly here for clarity
control.Wait();
}
tg.interrupt_all();
tg.join_all();
}
// This Benchmark tests the CheckQueue with a slightly realistic workload,
// where checks all contain a prevector that is indirect 50% of the time
// and there is a little bit of work done between calls to Add.
static void CCheckQueueSpeedPrevectorJob(benchmark::State& state)
{
struct PrevectorJob {
prevector<PREVECTOR_SIZE, uint8_t> p;
PrevectorJob(){
}
explicit PrevectorJob(FastRandomContext& insecure_rand){
p.resize(insecure_rand.randrange(PREVECTOR_SIZE*2));
}
bool operator()()
{
return true;
}
void swap(PrevectorJob& x){p.swap(x.p);};
};
CCheckQueue<PrevectorJob> queue {QUEUE_BATCH_SIZE};
boost::thread_group tg;
for (auto x = 0; x < std::max(MIN_CORES, GetNumCores()); ++x) {
tg.create_thread([&]{queue.Thread();});
}
while (state.KeepRunning()) {
// Make insecure_rand here so that each iteration is identical.
FastRandomContext insecure_rand(true);
CCheckQueueControl<PrevectorJob> control(&queue);
std::vector<std::vector<PrevectorJob>> vBatches(BATCHES);
for (auto& vChecks : vBatches) {
vChecks.reserve(BATCH_SIZE);
for (size_t x = 0; x < BATCH_SIZE; ++x)
vChecks.emplace_back(insecure_rand);
control.Add(vChecks);
}
// control waits for completion by RAII, but
// it is done explicitly here for clarity
control.Wait();
}
tg.interrupt_all();
tg.join_all();
}
BENCHMARK(CCheckQueueSpeed);
BENCHMARK(CCheckQueueSpeedPrevectorJob);
| [
"rishabhshukla@opulasoft.com"
] | rishabhshukla@opulasoft.com |
7bb8981a12490f9b423f9d1f700e981a83793e5c | c20c4812ac0164c8ec2434e1126c1fdb1a2cc09e | /Source/Source/KG3DEngine/KG3DEngine/KG3DModelBatchRender.h | 027818eef2fdc245623e6e91d45bafddc4264e0b | [
"MIT"
] | permissive | uvbs/FullSource | f8673b02e10c8c749b9b88bf18018a69158e8cb9 | 07601c5f18d243fb478735b7bdcb8955598b9a90 | refs/heads/master | 2020-03-24T03:11:13.148940 | 2018-07-25T18:30:25 | 2018-07-25T18:30:25 | 142,408,505 | 2 | 2 | null | 2018-07-26T07:58:12 | 2018-07-26T07:58:12 | null | UTF-8 | C++ | false | false | 113 | h | #pragma once
class KG3DModelBatchRender
{
public:
KG3DModelBatchRender(void);
~KG3DModelBatchRender(void);
};
| [
"dark.hades.1102@GAMIL.COM"
] | dark.hades.1102@GAMIL.COM |
754ef833a69464eb32a74def59db29a220c65a01 | a13e7993275058dceae188f2101ad0750501b704 | /2021/606. Construct String from Binary Tree.cpp | 85606d43d4c441661359fbde750b6ba68ad74599 | [] | no_license | yangjufo/LeetCode | f8cf8d76e5f1e78cbc053707af8bf4df7a5d1940 | 15a4ab7ce0b92b0a774ddae0841a57974450eb79 | refs/heads/master | 2023-09-01T01:52:49.036101 | 2023-08-31T00:23:19 | 2023-08-31T00:23:19 | 126,698,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 911 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
string res;
string tree2str(TreeNode* root) {
dfs(root);
return res.substr(1, res.length() - 2);
}
void dfs(TreeNode* root) {
res += "(";
if (root != NULL) {
res += to_string(root->val);
if (root->left != NULL || root->right != NULL) {
dfs(root->left);
}
if (root->right != NULL) {
dfs(root->right);
}
}
res += ")";
}
}; | [
"yangjufo@gmail.com"
] | yangjufo@gmail.com |
fcb0a20a75a4c7977455ebc397a4a7cb8387d88d | bf6e18459f226b45fab192e7027e5ae876ee8f3a | /treeString/tstring.cc | 6b98943266548a78060babd62c44c2b524e5b4c6 | [
"MIT"
] | permissive | WeiningLi/Object_Oriented_Programming | bb6e818a52ca8eec5d9e1592c683f243e913b78d | 4ddecaa11dba7ce2fedeef47105ec31eebb1cf64 | refs/heads/master | 2020-09-16T19:42:36.497829 | 2019-11-26T06:30:51 | 2019-11-26T06:30:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,386 | cc | #include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include "tnode.h"
#include "tstring.h"
using namespace std;
TString::TString(const std::string &str) {
length = str.length();
root = new TNode{ str, length, nullptr, nullptr };
}
TString::TString(const TString &other) {
length = other.length;
root = new TNode{ "", 0, nullptr, nullptr };
*root = *(other.root);
}
void getLen(TNode *root, size_t *len) {
*len += root->size;
if (root->right) {
getLen(root->right, len);
}
}
TString::TString(TNode *r) {
size_t len = 0;
getLen(r, &len);
length = len;
root = new TNode{ "", 0, nullptr, nullptr };
*root = *r;
}
TString::~TString() {
delete root;
}
TNode *popRight(TNode * n) {
TNode *prevn = n;
while (n->right) {
prevn = n;
n = n->right;
}
prevn->right = n->left;
n->left = nullptr;
return n;
}
TString TString::operator+(const TString &other) const {
TNode* myRoot = new TNode{ *root };
if (other.length == 0) {
TString news = myRoot;
delete myRoot;
return news;
}
if (myRoot->right) {
TNode *newRoot = popRight(myRoot);
TNode right = *(other.root);
newRoot->right = &right;
newRoot->left = myRoot;
newRoot->size = length;
TString news = newRoot;
newRoot->right = nullptr;
delete newRoot;
return news;
}
else {
TNode* right = new TNode{ *(other.root) };
myRoot->right = right;
TString news = myRoot;
delete myRoot;
return news;
}
}
char & TString::operator[] (const unsigned int index) {
TNode *curr = root;
size_t cumIndex = index;
int notFound = 1;
while (notFound) {
if (cumIndex < (curr->size - (curr->data).length())) {
curr = curr->left;
}
else if (cumIndex > curr->size - 1) {
cumIndex -= curr->size;
curr = curr->right;
}
else notFound = 0;
}
if (!curr->left) {
char &c = curr->data[cumIndex];
return c;
}
else {
char &c = curr->data[cumIndex - (curr->size - (curr->data).length())];
return c;
}
}
void TString::insert(const std::string &str, const unsigned int index) {
if (str == "") return;
// originally empty
if (length == 0) {
root->data = str;
root->size = str.length();
length = str.length();
return;
}
TNode *curr = root;
size_t cumIndex = index;
size_t len = str.length();
size_t newSize;
// index is greater than string length
if (index >= length) {
TNode *curr = root;
while (curr->right) {
curr = curr->right;
}
TNode *newN = new TNode{ str, len, nullptr, nullptr };
curr->right = newN;
length += len;
return;
}
int notFound = 1;
// find node N to insert
while (notFound) {
// move left
if (cumIndex < (curr->size - (curr->data).length())) {
curr->size += len;
curr = curr->left;
}
// move right
else if (cumIndex > curr->size + 1) {
cumIndex -= curr->size;
if(curr->right) curr = curr->right;
}
else notFound = 0;
}
// before
if (cumIndex == curr->size - (curr->data).length()) {
size_t leftSize = 0;
if (curr->left) getLen(curr->left, &leftSize);
newSize = (curr->data).length() + leftSize;
TNode *newN = new TNode{ str, newSize, curr->left, nullptr };
curr->left = newN;
length += len;
}
// after
else if (cumIndex == (curr->size + 1)) {
TNode *newN = new TNode{ str, len, nullptr, curr->right };
curr->right = newN;
length += len;
}
// middle
else if (cumIndex > curr->size - (curr->data).length() && cumIndex < (curr->size + 1)) {
string ls = curr->data.substr(0, cumIndex - (curr->size - (curr->data).length()));
string rs = curr->data.substr(cumIndex - (curr->size - (curr->data).length()));
size_t leftSize;
size_t temp = 0;
if (curr->left) {
getLen(curr->left, &temp);
leftSize = temp + cumIndex - (curr->size - (curr->data).length());
}
else {
leftSize = cumIndex - (curr->size - (curr->data).length());
}
if (ls != "") {
TNode *newL = new TNode{ ls, leftSize, curr->left, nullptr };
getLen(newL, &temp);
curr->left = newL;
}
if (rs != "") {
TNode *newR = new TNode{ rs, rs.length(), nullptr, curr->right };
if (rs != "") curr->right = newR;
}
newSize = len + temp;
curr->data = str;
curr->size = newSize;
length += len;
}
}
void print(std::ostream& out, const TNode *n) {
if (n->left) print(out, n->left);
out << n->data;
if (n->right) print(out, n->right);
}
std::ostream& operator<<(std::ostream& out, const TString &t) {
print(out, t.root);
return out;
}
| [
"bill.weining.li@gmail.com"
] | bill.weining.li@gmail.com |
b71afd86bdc8cfd991d9b150e3dfbb6091f18e78 | e3d4f6d88fb3d236efbc8fbc03522db173911443 | /TheKingOfGlory/Classes/Network/ChatBox.h | ec47d5d94a0cc96c9312e5157e74f487e96d14a6 | [] | no_license | cocosproject-thekingofglory/TheKingOfGlory | ea0b84aad256924d9b819852e96eb894fc48ee1a | 9b434f358932dbe03843fb650ffe3c06ba3eb48f | refs/heads/develop | 2020-05-15T02:12:17.027852 | 2019-06-16T15:45:31 | 2019-06-16T15:45:31 | 182,043,038 | 6 | 2 | null | 2019-06-15T09:09:10 | 2019-04-18T07:57:57 | C++ | UTF-8 | C++ | false | false | 1,224 | h | #pragma once
#include "cocos2d.h"
#include "ui/CocosGUI.h"
#include "Network/Client.h"
class ChatText :public cocos2d::Sprite
{
private:
cocos2d::ui::Text* _text;
bool _isLocal;
public:
static ChatText* create(const std::string& filename, const std::string& text, bool isLocal);
bool init(const std::string& text, bool isLocal);
bool isLocal() { return _isLocal; }
};
class ChatBox :public cocos2d::Sprite
{
private:
Client* _client;
int _index;
bool _isOpen;
const int maxNum = 17;
cocos2d::ui::TextField* textInput;
cocos2d::Vector<ChatText*>_chatTextList;
cocos2d::Vector<cocos2d::ui::Button*> _buttonList;
public:
static ChatBox* create(const std::string& filename, Client* client);
bool init(Client* client);
void addChatText(ChatText* text) { _chatTextList.pushBack(text); }
void setIndex(int index) { _index = index; }
void updateLayout();
void open();
void close();
void update() { if (_isOpen)close(); else open(); _isOpen = !_isOpen; }
void up() { if (_index < _chatTextList.size() - 1) ++_index; }
void down() { if (_index > 0) --_index; }
void pgUp() { if (_index < _chatTextList.size() - maxNum) _index += maxNum; }
void pgdown() { _index -= maxNum; if (_index < 0) _index = 0; }
};
| [
"824999404@qq.com"
] | 824999404@qq.com |
591fbfe4fdd32d0a55f7a1235eb418de8235647f | eb32bca809264605597a1c112ddb8d2dcde5efb7 | /p1261.cc | d75950dc739a29a85d27edd99b320964869dfbef | [] | no_license | superweaver/leetcode | fe423beebafe2b92935ac2376af5cee6da7d55ed | 7e90a53dbbb28511053a34812bd18209d4adfb26 | refs/heads/master | 2023-06-21T20:25:08.284150 | 2023-06-19T17:48:11 | 2023-06-19T17:48:11 | 109,064,436 | 0 | 0 | null | 2020-01-23T05:44:26 | 2017-10-31T23:49:55 | C++ | UTF-8 | C++ | false | false | 856 | cc | #include "common.h"
class FindElements {
public:
FindElements(TreeNode* root) {
this->root = root;
}
bool find(int target) {
vector<int> path;
if (!target) {
return true;
}
while(target) {
path.push_back(target);
target = (target - 1) / 2;
}
path.push_back(0);
int n = path.size();
TreeNode* pre_node = root;
for (int j = n - 2; j >= 0; --j) {
if (path[j] == (2 * path[j + 1] + 1)) {
if (pre_node->left == nullptr) {
return false;
} else {
pre_node = pre_node->left;
}
} else {
if (pre_node->right == nullptr) {
return false;
} else {
pre_node = pre_node->right;
}
}
}
return true;
}
private:
TreeNode* root;
//unordered_map<int, TreeNode*> trees;
};
int main() {
Solution s;
return 0;
}
| [
"evergreenwill@gmail.com"
] | evergreenwill@gmail.com |
acd354f4a3b63694877e87c877e738108e83e44f | 534e2e3d8d8bebd2366c0fee60886d84597ee0ef | /atcoder/AGC049/pB.cpp | cbf591f1ccd00c39c8563a833960941dae831979 | [] | no_license | coldEr66/online-judge | a8844d3f35755adafd4f43a1f08ce56b6b870601 | e85ec0750d92dd00133c93284085a0f5d8a11d36 | refs/heads/master | 2021-09-07T01:58:10.634492 | 2021-07-28T16:31:13 | 2021-07-28T16:31:13 | 128,494,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,384 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
#define RST(i,n) memset(i,n,sizeof i)
#define SZ(a) (int)a.size()
#define ALL(a) a.begin(),a.end()
#define X first
#define Y second
#define eb emplace_back
#ifdef cold66
#define debug(...) do{\
fprintf(stderr,"LINE %d: (%s) = ",__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<", ";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#define IOS()
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#endif // cold66
//}
const ll MAXN=1e5+5,MAXlg=__lg(MAXN)+2;
const ll MOD=1000000007;
const ll INF=0x3f3f3f3f;
vector<ll> S,T;
signed main(){
IOS();
int n;
cin >> n;
string s,t;
cin >> s >> t;
if (s[n-1] == '0' && t[n-1] == '1') return cout << -1 << endl,0;
for (int i=0;i<n;++i) {
if (s[i] == '1') S.eb(i);
if (t[i] == '1') T.eb(i);
}
if (SZ(S) % 2 != SZ(T) % 2 || SZ(S) < SZ(T)) return cout << -1 << endl,0;
ll idx = 0, cur = SZ(S), ans = 0;
for (int i=0;i<SZ(S);++i) {
if (idx == SZ(T)) {
ans += S[i+1] - S[i];
cur -= 2;
i++;
continue;
}
if (S[i] < T[idx]) {
if (cur <= SZ(T) || i == SZ(S)-1) return cout << -1 << endl,0;
ans += S[i+1] - S[i];
cur -= 2;
i++;
}
else {
ans += S[i] - T[idx];
idx++;
}
debug(ans);
}
cout << ans << endl;
}
| [
"seal1000402@gmail.com"
] | seal1000402@gmail.com |
ebb8addf7495d62c240aae3223a12604f1303072 | e954fbbe8e469743c000c6fe469471dd11a02e18 | /ndi_pusher/IPAddressEdit/IPAddressEdit_bak.h | b4934fb004e920643c1eae2d950a3f939368556d | [] | no_license | liangzhijun1314/2019_exploit | aa06e8059ec10207159b5f506fc550817d24e917 | 7ac762f5a4b3b7a6fbe91206ab130df14c08f8a8 | refs/heads/master | 2021-06-15T02:45:29.502968 | 2021-05-19T01:22:36 | 2021-05-19T01:22:36 | 197,108,440 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | h | #ifndef MYIPADDREDIT_H
#define MYIPADDREDIT_H
#include <QFrame>
#include <QMouseEvent>
#include <QKeyEvent>
class QLineEdit;
class QLabel;
class IPPartLineEdit;
class IPAddressEdit : public QWidget
{
Q_OBJECT
public:
IPAddressEdit(QWidget* pParent = 0);
~IPAddressEdit();
void setText(const QString &text);
QString text();
void setHight(int hight);
void clear();
bool checkInlegal();
protected:
bool eventFilter(QObject *watched, QEvent *event);
signals:
void textchanged(const QString& text);
void textedited(const QString &text);
private slots:
void textchangedslot(const QString& text);
void texteditedslot(const QString &text);
private:
IPPartLineEdit *ip_part1_; //ip的四段
IPPartLineEdit *ip_part2_;
IPPartLineEdit *ip_part3_;
IPPartLineEdit *ip_part4_;
QLabel *labeldot1_; //'.'号
QLabel *labeldot2_;
QLabel *labeldot3_;
};
#endif //MYIPADDREDIT_H
| [
"liangzhijun@ctvit.com"
] | liangzhijun@ctvit.com |
b719bec0f40d54d87899d5537a0c0003196b81f3 | 9b291d036ee7d4364734caab6fcf061e0e6de147 | /Core/3dgraphics/LightIF.cpp | 97866463b7a32fc2d7be3d3af06d4ba2f7c88cf1 | [] | no_license | PSP-Archive/Rip-Off | 0227db92c34b6f084a56ba122baa4b5bd74e6e6d | 968c21162b0b44a539664400a0047ffaad4ad764 | refs/heads/main | 2023-04-13T12:52:36.275617 | 2021-04-24T15:15:23 | 2021-04-24T15:15:23 | 361,194,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 832 | cpp | #ifdef _3D
#include "LightIF.h"
LightIF::LightIF(int id):m_id(id),
m_type(OMNI),
m_position(0,0,0,1),
m_direction(0,0,0),
m_diffuse(1,1,1,1),
m_ambient(0,0,0,0),
m_specular(0,0,0,0),
m_linearAtt(0),
m_quadricAtt(0),
m_isEnabled(1)
{}
void LightIF::setAmbient(const Vector4f& ambient){
m_ambient=ambient;
}
void LightIF::setDiffuse(const Vector4f& diffuse){
m_diffuse=diffuse;
}
void LightIF::setSpecular(const Vector4f& specular){
m_specular=specular;
}
void LightIF::setCoordinates(const Vector4f& position, const Vector3f& direction){
m_position=position;
m_direction=direction;
}
void LightIF::setAttenuation(float linear, float quadric){
m_linearAtt=linear;
m_quadricAtt=quadric;
}
void LightIF::setIsEnabled(int isEnabled){
m_isEnabled=isEnabled;
}
#endif | [
"pierluigiortenzi@gmail.com"
] | pierluigiortenzi@gmail.com |
d9952441a038cf5e75209547642d2fea4a769e5c | 893a1646ac2df675a247de6c4203878c9f090abf | /TIENDIEN.cpp | f8e9cee8c43ba0df43cd7afc806d21fabfa3ea96 | [] | no_license | HauPham-Wts/Vinhdinhcoder | b6f130aebc5b1aa03aafa3fb3c6a9654dfe07a2e | 7ff91f7e96cff7ddea61f9faee4bae687bbf7e63 | refs/heads/main | 2023-05-10T08:51:36.615419 | 2021-06-15T10:10:56 | 2021-06-15T10:10:56 | 376,540,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 699 | cpp | /*
Chi nhánh điện lực Quảng Trị đưa ra hai mức tính tiền điện như sau:
- Dưới 200 Kwh mức giá 1500đ/kwh
- Từ 200 kwh trở lên mức giá là 3000đ/kwh.
Hãy giúp bạn tính tiền điện của nhà bạn Nam biết rằng tháng vừa rồi nhà bạn Nam tiêu thụ hết N (kwh).
Dữ liệu vào: N được nhập vào từ bàn phím
Kết quả: in tiền điện ra màn hình
Ràng buộc: 0 < N < 1000
*/
#include<iostream>
using namespace std;
int main() {
unsigned int n;
cin >> n;
if (n < 200) {
n *= 1500;
cout << n;
}
else {
n *= 3000;
cout << n;
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
409bf27628bc4c5b6b9135b3d41eff2ae273f9a1 | 27a869283b7a9be644e46b46f56d4fa84f7622b7 | /Source/DirectX/GameSystem/Collide.cpp | 60aae68f7065437b17f7064288d9a55c6c86803d | [] | no_license | tachikawa-syota/2D_BlushGirls | 0aa666605268703218f95ebab348de55326bad22 | a3aa19b94aadec1e5461af246543d3a872f8a8c2 | refs/heads/master | 2021-01-17T18:18:17.719989 | 2016-09-28T04:18:13 | 2016-09-28T04:18:13 | 69,417,693 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,752 | cpp |
#include "Collide.h"
/**
* @brief 矩形と矩形の当たり判定をチェックする
* @param obj - オブジェクトの位置
* @param rec - オブジェクトの当たり範囲
* @return true - 当たった、false - 当たっていない
*
* @note 使い方:obj1とrec1には同じオブジェクトのパラメータを入れる(obj2とrec2も然り)
* オブジェクトの順番は逆にしても結果は変わらない
*/
bool Collide::CheckRectAndRect(Vector2 obj1, Vector2 obj2, Rect rec1, Rect rec2)
{
float obj1left = rec1.right / 2.0f;
float obj2left = rec2.right / 2.0f;
float obj1top = rec1.bottom / 2.0f;
float obj2top = rec2.bottom / 2.0f;
if (obj2.x - obj2left + rec2.right >= obj1.x - obj1left && obj2.x - obj2left <= obj1.x - obj1left + rec1.right)
{
if ((obj2.y - obj2top) + rec2.bottom >= (obj1.y - obj1top) && (obj2.y - obj2top) <= (obj1.y - obj1top) + rec1.bottom)
{
return true;
}
}
return false;
}
/**
* @brief 重なった分だけ左右にズラす
* @param obj - オブジェクトの位置
* @param rec - オブジェクトの当たり範囲
* @param dir - オブジェクトの向き
*/
float Collide::PlayerDisplace(Vector2 obj1, Vector2 obj2, Rect rec1, Rect rec2, Dir& dir)
{
float ret;
float obj1left = rec1.right / 2.0f;
float obj2left = rec2.right / 2.0f;
// 1Pの右端と2Pの左端
if (obj1.x - obj1left + rec1.right < obj2.x - obj2left + 5.0f)
{
ret = -15.0f;
}
// 2Pの右端と1Pの左端
if (obj2.x - obj2left + rec2.right < obj1.x - obj1left + 5.0f)
{
ret = 15.0f;
}
// 重なったら
if (obj1.x == obj2.x)
{
ret = 15.0f;
}
// 例外処理
else{
// 右
if (dir == Dir::Right)
ret = -15.0f;
// 左
else
ret = 15.0f;
}
return ret;
} | [
"s.tachikawa1105@gmail.com"
] | s.tachikawa1105@gmail.com |
04cd792697bcda7569a549edad060a3a7d985646 | bb9ec7e3096671a886e83917cfee787bc48903b4 | /src-game/dumpster-dive.cpp | e847cec0edffe50519a628ce9291d42373f5ad8e | [] | no_license | jonah-chen/bears-v-babies | 8a8fabed3fcc25af472cdda37c48758d890d711d | e95dd77122f0e17d5d60723f565a58698c698fde | refs/heads/master | 2023-06-30T03:27:09.424778 | 2021-07-22T21:14:28 | 2021-07-22T21:14:28 | 385,145,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | cpp | #include "server.hpp"
unsigned char Game::dumpster_dive(unsigned int target)
{
if (int_turn > 0)
{
std::cout << "you cannot dumpster dive this turn anymore\n";
return 0;
}
auto found = dumpster.find(target);
if (found==dumpster.end())
{
std::cout << "the card you dived for cannot be found in the dumpster\n";
return 0;
}
// dumpster diving babies
switch (lut.at(target).type)
{
case (unsigned char)-LAND: case (unsigned char)-SEA: case (unsigned char)-SKY:
babies[TYPE((unsigned char)-lut.at(target).type)].push_back(*found);
dumpster.erase(found);
lut.at(*found).owner = MIDDLE;
return 19;
default:
hand[CUR_PLAYER_ZERO_INDEX].push_back(*found);
dumpster.erase(found);
lut.at(*found).owner = CUR_PLAYER;
return 19;
}
} | [
"jonah.chen@mail.utoronto.ca"
] | jonah.chen@mail.utoronto.ca |
4ed0f6ddb7d5fc51a1ff961ae01d7fc0d4617709 | 9d523c64c539d5e3c1d2bb80a7f761f60ce2c865 | /6 lab/simpleBinSearchTree.cpp | f1eac2f3f1d890c2cf953c032fcf6b2872460172 | [] | no_license | Imagination7478/ITMO-Algo-Labs-1-sem | 2b5600d9571c40ac12e30a58103c9c7d28241364 | b8a253c0592fd59bb9aaf4b609076e38505635d4 | refs/heads/master | 2020-03-31T06:01:09.377217 | 2018-12-10T05:40:00 | 2018-12-10T05:40:00 | 151,965,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,617 | cpp | #define _CRT_SECURE_NO_WARNINGS
#define strsize 20
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct vertex
{
long long val = 0;
vertex * parent = nullptr;
vertex * left = nullptr;
vertex * right = nullptr;
} vertex;
int size = 0;
void delete_root(vertex * root);
void delete_vert(vertex * root, long long val);
void insert_vert(vertex * root, long long val) {
if (size <= 0) {
root->val = val;
size = 1;
return;
}
if (val < root->val && root->left == nullptr) {
root->left = new vertex;
root->left->val = val;
root->left->parent = root;
size++;
return;
}
if (val > root->val && root->right == nullptr) {
root->right = new vertex;
root->right->val = val;
root->right->parent = root;
size++;
return;
}
vertex * parent = nullptr;
vertex * vert = root;
while (vert != nullptr) {
if (val < vert->val) {
parent = vert;
vert = vert->left;
}
else if (val > vert->val) {
parent = vert;
vert = vert->right;
}
else return;
}
vert = new vertex;
vert->val = val;
vert->parent = parent;
if (val < parent->val)
parent->left = vert;
else parent->right = vert;
size++;
}
bool exists_vert(vertex * root, long long val) {
if (size <= 0)
return false;
if (val == root->val)
return true;
vertex * vert = root;
while (vert != nullptr) {
if (val < vert->val)
vert = vert->left;
else if (val > vert->val)
vert = vert->right;
else return true;
}
return false;
}
void delete_root(vertex * root) {
vertex * vert = root;
if (size <= 0)
return;
if (vert->left == nullptr && vert->right == nullptr) {
size = 0;
return;
}
if (size == 1) {
size = 0;
return;
}
if (vert->left != nullptr && vert->right != nullptr) {
vertex * swap = vert->right;
while (swap->left != nullptr)
swap = swap->left;
long long tmp = swap->val;
delete_vert(root, swap->val);
vert->val = tmp;
return;
}
vertex * change;
if (vert->left != nullptr)
change = vert->left;
else change = vert->right;
*root = *change;
if (change->left != NULL)
change->left->parent = root;
if (change->right != NULL)
change->right->parent = root;
size--;
delete change;
}
void delete_vert(vertex * root, long long val) {
if (size <= 0)
return;
if (root->val == val) {
delete_root(root);
return;
}
vertex * vert = root;
while (vert != nullptr) {
if (val < vert->val)
vert = vert->left;
else if (val > vert->val)
vert = vert->right;
else break;
}
if (vert == nullptr)
return;
if (vert->left == nullptr && vert->right == nullptr) {
if (vert->parent->left == vert)
vert->parent->left = nullptr;
else vert->parent->right = nullptr;
delete vert;
size--;
}
else if (vert->left != nullptr && vert->right != nullptr) {
vertex * swap = vert->right;
while (swap->left != nullptr)
swap = swap->left;
long long tmp = swap->val;
delete_vert(root, swap->val);
vert->val = tmp;
}
else {
vertex * change;
if (vert->left != nullptr)
change = vert->left;
else change = vert->right;
if (vert->parent->left == vert)
vert->parent->left = change;
else vert->parent->right = change;
change->parent = vert->parent;
delete vert;
size--;
}
}
vertex * next_vert(vertex * root, long long val) {
if (size <= 0)
return nullptr;
if (size == 1) {
if (val < root->val)
return root;
else return nullptr;
}
vertex * vert = root;
while (vert != nullptr) {
if (val < vert->val)
if (vert->left != nullptr)
vert = vert->left;
else break;
else if (val > vert->val)
if (vert->right != nullptr)
vert = vert->right;
else break;
else break;
}
if (vert == nullptr)
return nullptr;
if (val < vert->val)
return vert;
if (vert->right != nullptr) {
vert = vert->right;
while (vert->left != nullptr)
vert = vert->left;
return vert;
}
vertex * check = vert;
vertex * parent = vert->parent;
while (true)
{
if (parent == nullptr)
return nullptr;
else if (check == parent->right) {
check = parent;
parent = parent->parent;
}
else if (check == parent->left)
return parent;
else return nullptr;
}
}
vertex * prev_vert(vertex * root, long long val) {
if (size <= 0)
return nullptr;
if (size == 1) {
if (val > root->val)
return root;
else return nullptr;
}
vertex * vert = root;
while (vert != nullptr) {
if (val < vert->val)
if (vert->left != nullptr)
vert = vert->left;
else break;
else if (val > vert->val)
if (vert->right != nullptr)
vert = vert->right;
else break;
else break;
}
if (vert == nullptr)
return nullptr;
if (val > vert->val)
return vert;
if (vert->left != nullptr) {
vert = vert->left;
while (vert->right != nullptr)
vert = vert->right;
return vert;
}
vertex * check = vert;
vertex * parent = vert->parent;
while (true)
{
if (parent == nullptr)
return nullptr;
else if (check == parent->left) {
check = parent;
parent = parent->parent;
}
else if (check == parent->right)
return parent;
else return nullptr;
}
}
int main() {
FILE * in = fopen("bstsimple.in", "r");
FILE * out = fopen("bstsimple.out", "w");
vertex root;
char command[strsize];
char arg[strsize];
char * pEnd;
long long val;
vertex * check = nullptr;
fscanf(in, "%s", command);
fscanf(in, "%s", arg);
val = strtoll(arg, &pEnd, 10);
while (true) {
if (strcmp(command, "insert") == 0)
insert_vert(&root, val);
else if (strcmp(command, "exists") == 0)
if (exists_vert(&root, val))
fprintf(out, "true\n");
else fprintf(out, "false\n");
else if (strcmp(command, "delete") == 0)
delete_vert(&root, val);
else if (strcmp(command, "next") == 0) {
check = next_vert(&root, val);
if (check != nullptr)
fprintf(out, "%lld\n", check->val);
else fprintf(out, "none\n");
}
else if (strcmp(command, "prev") == 0) {
check = prev_vert(&root, val);
if (check != nullptr)
fprintf(out, "%lld\n", check->val);
else fprintf(out, "none\n");
}
if (feof(in))
break;
strcpy(command, "");
fscanf(in, "%s", command);
fscanf(in, "%s", arg);
val = strtoll(arg, &pEnd, 10);
}
fclose(in);
fclose(out);
return 0;
} | [
"dimka40302010@gmail.com"
] | dimka40302010@gmail.com |
5f0ebaef26fa33f7e5476b04d4aa9c60f4aa54a5 | abad16efcf9ab6b95884ca854f916071d8d00865 | /llvm-project/llvm/lib/Transforms/ExecModel/ExecModel.cpp | 6aebc6a36f598fd2c1ee5d5e92d5ca2ea4800f19 | [] | no_license | jjiantong/LLVM-OpenCL | dd6202a7848168a1aaabc2f533a92f0091e0f05f | 111988aa990fce359958779316f4b8230c924241 | refs/heads/master | 2020-05-20T13:38:58.059967 | 2019-09-03T03:52:37 | 2019-09-03T03:52:37 | 185,603,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,318 | cpp | #define APP "TQH"
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include "llvm/Pass.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Analysis/CFG.h"
using namespace llvm;
namespace {
struct ExecModel : public ModulePass {
static char ID;
ExecModel() : ModulePass(ID) {}
bool runOnModule(Module &M) override {
// we need the results of direct prediction from ExecModel.in
// 1: NDR
// 2: SWI
// 3: NDR+C
// 4: SWI+C
int em = 0;
std::string app = APP;
std::string file = "/root/Work/llvm/apps/" + app + "/ExecModel.in";
std::ifstream fin(file);
char line[20];
fin.getline(line, sizeof(line));
std::stringstream ss(line);
ss >> em;
if(em == 1)
{
errs() << "\t\tNDR\n";
}
else if(em == 3)
{
errs() << "\t\tNDR+C\n";
}
else if(em == 4)
{
errs() << "\t\tSWI+C\n";
}
else
{
errs() << "\t\tSWI\n";
}
/*
for(Module::iterator f = M.begin(), f2 = M.end(); f!=f2; f++) // functions
{
if(f->getCallingConv() == 76)
{
k++;
int pos = findKernel(kList, kcnt, k);
// if k is in kList: find its position
if(pos != -1)
{
kList[pos].bbcnt = 0;
for(Function::iterator bb = f->begin(), e = f->end(); bb!=e; bb++) // basic blocks
{
BasicBlock *bbtmp = dyn_cast<BasicBlock>(bb); //errs() << bbtmp->getName() << '\n';
kList[pos].bbList[kList[pos].bbcnt].bb = bbtmp;
kList[pos].bbList[kList[pos].bbcnt].name = bbtmp->getName();
kList[pos].bbList[kList[pos].bbcnt].keep = true;
kList[pos].bbcnt++;
}
}
}
}
// if there are args be consider
if(arg)
{
int k = -1;
for(Module::iterator f = M.begin(), f2 = M.end(); f!=f2; f++) // functions
{
if(f->getCallingConv() == 76)
{
k++;
int acnt = -1;
for(Function::arg_iterator a = f->arg_begin(), e = f->arg_end(); a != e; a++)
{
acnt++;
// if (k, acnt) is in wgarg: get its value
int value = match(wgarg, wgacnt, k, acnt);
if(value != -1)
{
// and find the position of k
int pos = findKernel(kList, kcnt, k); //errs() << a->getName() << '\n';
for(Function::iterator bb = f->begin(), e = f->end(); bb!=e; bb++) // all basic blocks
{
for(BasicBlock::iterator i = bb->begin(), i2 = bb->end(); i!=i2; i++) // all instructions
{
std::string si = formatv("{0}",*i).str();
if(si.find(a->getName()) != std::string::npos) // find the related instructions
{
Instruction *inst = dyn_cast<Instruction>(i); //errs() << "inst: " << *i << '\n';
BasicBlock *ibb = inst->getParent();
// find the position of its parent bb
int bbpos = findBB(kList, pos, ibb);
// this inst needs to be considered only when its situation now is "true"
if(kList[pos].bbList[bbpos].keep)
{
int res = findTerminator(ibb, inst, a->getName(), value); //errs() << "parent bb: " << kList[pos].bbList[bbpos].name << '\n';//errs() << "result value: " << res << '\n';
// valid result
if(res != -100)
{
Instruction *last_inst = ibb->getTerminator();
if(BranchInst *br_inst = dyn_cast<BranchInst>(last_inst))
{
// this inst needs to be considered only when it leads to a definite branch
// it should be a conditional branch
if(br_inst->isConditional())
{
BasicBlock *dest; //errs() << "br: " << *br_inst << '\n';
if(res == 1)
{
dest = br_inst->getSuccessor(1);
}
else if(res == 0)
{
dest = br_inst->getSuccessor(0);
}
//errs() << "handle: " << dest->getName() << '\n';
handleBB(dest, ibb, kList, pos);
}
}
}
}
}
}
}
}
}
}
}
}
for(int i = 0; i < kcnt; i++)
{ //errs() << i << '\n';
int y = 0;
int n = 0;
for(int j = 0; j < kList[i].bbcnt; j++)
{ //errs() << "bb: " << kList[i].bbList[j].name << ":\t";
if(kList[i].bbList[j].keep)
{
y++; //errs() << "y\n";
}
else
{
n++; //errs() << "n\n";
}
}
// if we delete more than half of the bbs
if(n > y)
{
errs() << "\t\tYes\n";
errs() << "1\n";
return false;
}
}
errs() << "\t\tNo\n";
errs() << "0\n";
return false;
*/
}
};
} // end of anonymous namespace
char ExecModel::ID = 0;
static RegisterPass<ExecModel> X("execmodel", "direct prediction + potential evolution of swi",
false /* Only looks at CFG */,
false /* Analysis Pass */);
| [
"609705173@qq.com"
] | 609705173@qq.com |
f30cbbaeef361a829af9bc4f55f339d2ce8362cc | 6c3cbda4628f0fcff7322ca9d7e30a1a54b3be63 | /src/main.cpp | 90403e1ec48de50a962a7797bdafd40c776e0b87 | [
"MIT",
"CC-BY-3.0",
"Unlicense",
"BSL-1.0",
"Cube"
] | permissive | validolchik/comp-graphics-in-game-dev | 35f61833b2f559b05db5b88b558bc5230596c6a5 | 1b86eb168183b5604862ca605bfa7938e75ea5ca | refs/heads/main | 2023-03-06T19:13:31.728471 | 2021-02-20T10:16:14 | 2021-02-20T10:16:14 | 331,862,153 | 0 | 2 | MIT | 2021-02-20T10:16:15 | 2021-01-22T06:51:34 | C | UTF-8 | C++ | false | false | 402 | cpp | #include "renderer/renderer.h"
#include "settings.h"
#include <iostream>
int main(int argc, char** argv)
{
try
{
auto settings = cg::settings::parse_settings(argc, argv);
auto renderer = cg::renderer::make_renderer(settings);
renderer->init();
renderer->render();
renderer->destroy();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
} | [
"valik.valeevrenat@mail.ru"
] | valik.valeevrenat@mail.ru |
1d198c581e8cdeba001f79cc1466dcbcb62c691a | 9d3321ab63880183e947a372c53de572aa3ce885 | /include/jwt/impl/string_view.ipp | 34a7e118cfbe8b04a300284ca96f254c421c475c | [
"MIT"
] | permissive | qrealka/cpp-jwt | 5e224b2278ee9e4d9846e2aecfcfb54f0f62714a | 32099f6691dda31506be58e4810300e38c522d65 | refs/heads/master | 2020-03-09T12:28:19.470624 | 2018-04-07T12:25:04 | 2018-04-07T12:25:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,221 | ipp | /*
Copyright (c) 2017 Arun Muralidharan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef JWT_STRING_VIEW_IPP
#define JWT_STRING_VIEW_IPP
namespace jwt {
template <typename CharT, typename Traits>
auto basic_string_view<CharT, Traits>::find(
const CharT* str,
size_type pos,
size_type n) const noexcept -> size_type
{
assert (str);
assert (n < (len_ - pos) && "Comparison size out of bounds");
if (n == 0) {
return pos <= len_ ? pos : npos;
}
if (n <= len_) {
for (; pos <= (len_ - n); ++pos) {
if (traits_type::eq(data_[pos], str[0]) &&
traits_type::compare(data_ + pos + 1, str + 1, n - 1) == 0) {
return pos;
}
}
}
return npos;
}
template <typename CharT, typename Traits>
auto basic_string_view<CharT, Traits>::rfind(
const CharT* str,
size_type pos,
size_type n) const noexcept -> size_type
{
assert (str);
assert (pos < len_ && "Position out of bounds");
if (n <= len_) {
pos = std::min(len_ - n, pos);
do {
if (traits_type::eq(data_[pos], str[0]) &&
traits_type::compare(data_ + pos + 1, str + 1, n - 1) == 0) {
return pos;
}
} while (pos-- != 0);
}
return npos;
}
template <typename CharT, typename Traits>
auto basic_string_view<CharT, Traits>::find(
const CharT ch,
size_type pos) const noexcept -> size_type
{
if (pos < len_) {
for (size_type i = pos; i < len_; ++i) {
if (traits_type::eq(data_[i], ch)) return i;
}
}
return npos;
}
template <typename CharT, typename Traits>
auto basic_string_view<CharT, Traits>::rfind(
const CharT ch,
size_type pos) const noexcept -> size_type
{
if (pos < len_) {
do {
if (traits_type::eq(data_[pos], ch)) {
return pos;
}
} while (pos-- != 0);
}
return npos;
}
template <typename CharT, typename Traits>
auto basic_string_view<CharT, Traits>::find_first_of(
const CharT* str,
size_type pos,
size_type count) const noexcept -> size_type
{
assert (str);
for (size_type i = pos; i < len_; ++i) {
auto p = traits_type::find(str, count, data_[i]);
if (p) {
return i;
}
}
return npos;
}
template <typename CharT, typename Traits>
auto basic_string_view<CharT, Traits>::find_last_of(
const CharT* str,
size_type pos,
size_type count) const noexcept -> size_type
{
assert (str);
assert (pos < len_ && "Position must be within the bounds of the view");
size_type siz = len_;
if (siz && count) {
siz = std::min(pos, siz);
do {
auto p = traits_type::find(str, count, data_[siz]);
if (p) {
return siz;
}
} while (siz-- != 0);
}
return npos;
}
template <typename CharT, typename Traits>
auto basic_string_view<CharT, Traits>::find_first_not_of(
const CharT* str,
size_type pos,
size_type n) const noexcept -> size_type
{
assert (str);
assert (pos < len_&& "Position must be within the bounds of the view");
for (size_type i = pos; i < len_; ++i)
{
auto p = traits_type::find(str, n, data_[i]);
if (not p) return i;
}
return npos;
}
template <typename CharT, typename Traits>
auto basic_string_view<CharT, Traits>::find_last_not_of(
const CharT* str,
size_type pos,
size_type n) const noexcept -> size_type
{
assert (str);
assert (pos < len_ && "Position must be within the bounds of the view");
do {
for (size_type i = 0; i < n; ++i) {
if (not traits_type::eq(data_[pos], str[i])) return pos;
}
} while (pos-- != 0);
return npos;
}
template <typename CharT, typename Traits>
auto basic_string_view<CharT, Traits>::find_first_not_of(
CharT ch,
size_type pos) const noexcept -> size_type
{
assert (pos < len_&& "Position must be within the bounds of the view");
for (size_type i = pos; i < len_; ++i) {
if (not traits_type::eq(data_[i], ch)) return i;
}
return npos;
}
template <typename CharT, typename Traits>
auto basic_string_view<CharT, Traits>::find_last_not_of(
CharT ch,
size_type pos) const noexcept -> size_type
{
assert (pos < len_ && "Position must be within the bounds of the view");
do {
if (not traits_type::eq(data_[pos], ch)) return pos;
} while (pos-- != 0);
return npos;
}
// Comparison Operators
template <typename CharT, typename Traits>
bool operator== (basic_string_view<CharT, Traits> a,
basic_string_view<CharT, Traits> b) noexcept
{
if (a.length() != b.length()) return false;
using traits_type = typename basic_string_view<CharT, Traits>::traits_type;
using size_type = typename basic_string_view<CharT, Traits>::size_type;
for (size_type i = 0; i < a.length(); ++i) {
if (not traits_type::eq(a[i], b[i])) return false;
}
return true;
}
template <typename CharT, typename Traits>
bool operator!= (basic_string_view<CharT, Traits> a,
basic_string_view<CharT, Traits> b) noexcept
{
return not ( a == b );
}
template <typename CharT, typename Traits>
bool operator< (basic_string_view<CharT, Traits> a,
basic_string_view<CharT, Traits> b) noexcept
{
return a.compare(b) < 0;
}
template <typename CharT, typename Traits>
bool operator> (basic_string_view<CharT, Traits> a,
basic_string_view<CharT, Traits> b) noexcept
{
return a.compare(b) > 0;
}
template <typename CharT, typename Traits>
bool operator<= (basic_string_view<CharT, Traits> a,
basic_string_view<CharT, Traits> b) noexcept
{
return a.compare(b) <= 0;
}
template <typename CharT, typename Traits>
bool operator>= (basic_string_view<CharT, Traits> a,
basic_string_view<CharT, Traits> b) noexcept
{
return a.compare(b) >= 0;
}
template <typename CharT, typename Traits>
std::ostream& operator<< (std::ostream& os, basic_string_view<CharT, Traits> sv)
{
os.write(sv.data(), sv.length());
return os;
}
namespace {
/*
* Copy of gcc implementation of murmurhash
* hash_bytes.cc
*/
inline size_t
unaligned_load(const char* p)
{
std::size_t result;
std::memcpy(&result, p, sizeof(result));
return result;
}
inline size_t
hash_bytes(const void* ptr, size_t len, size_t seed)
{
const size_t m = 0x5bd1e995;
size_t hash = seed ^ len;
const char* buf = static_cast<const char*>(ptr);
// Mix 4 bytes at a time into the hash.
while(len >= 4)
{
size_t k = unaligned_load(buf);
k *= m;
k ^= k >> 24;
k *= m;
hash *= m;
hash ^= k;
buf += 4;
len -= 4;
}
// Handle the last few bytes of the input array.
switch(len)
{
case 3:
hash ^= static_cast<unsigned char>(buf[2]) << 16;
//FALLTHROUGH
case 2:
hash ^= static_cast<unsigned char>(buf[1]) << 8;
//FALLTHROUGH
case 1:
hash ^= static_cast<unsigned char>(buf[0]);
hash *= m;
};
// Do a few final mixes of the hash.
hash ^= hash >> 13;
hash *= m;
hash ^= hash >> 15;
return hash;
}
}
} // END namespace jwt
/// Provide a hash specialization
namespace std {
template <>
struct hash<jwt::string_view>
{
size_t operator()(const jwt::string_view& sv) const
{
return jwt::hash_bytes((void*)sv.data(), sv.length(), static_cast<size_t>(0xc70f6907UL));
}
};
}
#endif
| [
"arun11299@gmail.com"
] | arun11299@gmail.com |
ec0048de246d638eaf2f40e2a5960bbfec26af6c | 58f0f4c254237b00022142f3e0342cd56a6e333e | /src/modules/processes/contrib/zvrastil/LocalHistogramEqualization/LocalHistogramEqualizationInstance.cpp | 678e05d3dfc1c42baf151b24334b3d91efa22d89 | [
"LicenseRef-scancode-other-permissive"
] | permissive | cameronleger/PCL | fc7948e5a02a72c67c4b3798619d5d2b4a886add | a231a00ba8ca4a02bac6f19b6d7beae6cfe70728 | refs/heads/master | 2021-09-23T14:40:28.291908 | 2017-10-16T10:27:14 | 2017-10-16T10:27:14 | 109,534,105 | 1 | 0 | null | 2017-11-04T22:12:45 | 2017-11-04T22:12:44 | null | UTF-8 | C++ | false | false | 24,518 | cpp | // ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 02.01.07.0873
// ----------------------------------------------------------------------------
// Standard LocalHistogramEqualization Process Module Version 01.00.00.0211
// ----------------------------------------------------------------------------
// LocalHistogramEqualizationInstance.cpp - Released 2017-08-01T14:26:58Z
// ----------------------------------------------------------------------------
// This file is part of the standard LocalHistogramEqualization PixInsight module.
//
// Copyright (c) 2011-2017 Zbynek Vrastil
// Copyright (c) 2003-2017 Pleiades Astrophoto S.L.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact info@pixinsight.com.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by Pleiades Astrophoto and its contributors (http://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 PLEIADES ASTROPHOTO OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) 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 "LocalHistogramEqualizationInstance.h"
#include "LocalHistogramEqualizationParameters.h"
#include <pcl/AutoViewLock.h>
#include <pcl/Console.h>
#include <pcl/MuteStatus.h>
#include <pcl/ReferenceArray.h>
#include <pcl/StdStatus.h>
#include <pcl/Thread.h>
#include <pcl/View.h>
namespace pcl
{
// ----------------------------------------------------------------------------
LocalHistogramEqualizationInstance::LocalHistogramEqualizationInstance( const MetaProcess* m ) :
ProcessImplementation( m ),
radius( int32( TheLHERadiusParameter->DefaultValue() ) ),
histogramBins( LHEHistogramBins::Default ),
slopeLimit( TheLHESlopeLimitParameter->DefaultValue() ),
amount( TheLHEAmountParameter->DefaultValue() ),
circularKernel( TheLHECircularKernelParameter->DefaultValue() )
{
}
// ----------------------------------------------------------------------------
LocalHistogramEqualizationInstance::LocalHistogramEqualizationInstance( const LocalHistogramEqualizationInstance& x ) :
ProcessImplementation( x )
{
Assign( x );
}
// ----------------------------------------------------------------------------
void LocalHistogramEqualizationInstance::Assign( const ProcessImplementation& p )
{
const LocalHistogramEqualizationInstance* x = dynamic_cast<const LocalHistogramEqualizationInstance*>( &p );
if ( x != 0 )
{
radius = x->radius;
histogramBins = x->histogramBins;
slopeLimit = x->slopeLimit;
amount = x->amount;
circularKernel = x->circularKernel;
}
}
// ----------------------------------------------------------------------------
bool LocalHistogramEqualizationInstance::CanExecuteOn( const View& view, pcl::String& whyNot ) const
{
if ( view.Image().IsComplexSample() )
{
whyNot = "LocalHistogramEqualization cannot be executed on complex images.";
return false;
}
return true;
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
class LocalHistogramEqualizationEngine
{
public:
static void Apply( ImageVariant& image, const LocalHistogramEqualizationInstance& instance )
{
if ( image.IsFloatSample() )
switch ( image.BitsPerSample() )
{
case 32 : Apply( static_cast<Image&>( *image ), instance ); break;
case 64 : Apply( static_cast<DImage&>( *image ), instance ); break;
}
else
switch ( image.BitsPerSample() )
{
case 8 : Apply( static_cast<UInt8Image&>( *image ), instance ); break;
case 16 : Apply( static_cast<UInt16Image&>( *image ), instance ); break;
case 32 : Apply( static_cast<UInt32Image&>( *image ), instance ); break;
}
}
template <class P>
static void Apply( GenericImage<P>& image, const LocalHistogramEqualizationInstance& instance )
{
if ( image.IsColor() )
{
Image L;
image.GetLightness( L );
L.Status() = image.Status();
Apply( L, instance );
image.Status() = L.Status();
image.SetLightness( L );
return;
}
// create copy of the luminance to evaluate histogram from
GenericImage<P> imageCopy( image );
imageCopy.EnsureUnique(); // really not necessary, but we'll be safer if this is done
size_type N = image.NumberOfPixels();
int numberOfThreads = Thread::NumberOfThreads( image.Height(), 1 );
int rowsPerThread = image.Height()/numberOfThreads;
image.Status().Initialize( "CLAHE", N );
AbstractImage::ThreadData data( image, N );
// create processing threads
ReferenceArray<LocalHistogramEqualizationThread<P> > threads;
for ( int i = 0, j = 1; i < numberOfThreads; ++i, ++j )
threads.Add( new LocalHistogramEqualizationThread<P>( data,
instance,
image,
imageCopy,
i*rowsPerThread,
(j < numberOfThreads) ? j*rowsPerThread : image.Height() ) );
AbstractImage::RunThreads( threads, data );
threads.Destroy();
image.Status() = data.status;
}
private:
// Thread class, performs CLAHE on given range of lines
template <class P>
class LocalHistogramEqualizationThread : public Thread
{
public:
// constructor, accepts process instance, destination and source images and pixel range
LocalHistogramEqualizationThread( const AbstractImage::ThreadData& data,
const LocalHistogramEqualizationInstance& instance,
GenericImage<P>& imageDst,
const GenericImage<P>& imageSrc,
int firstRow,
int endRow ) :
Thread(),
m_data( data ), m_instance( instance ),
m_imageDst( imageDst ), m_imageSrc( imageSrc ), m_firstRow( firstRow ), m_endRow( endRow ),
kernelMask( 0 ), kernelFront( 0 ), kernelBack( 0 ), histogram( 0 ), clippedHistogram( 0 )
{
// extract parameters from instance
histogramSize = m_instance.GetHistogramSize();
radius = m_instance.GetRadius();
limit = m_instance.GetLimit();
factor = (double)(histogramSize-1);
// allocate histograms
histogram = new uint32[histogramSize];
clippedHistogram = new uint32[histogramSize];
// allocate and build kernel mask (square or circular)
BuildKernelMask();
}
virtual ~LocalHistogramEqualizationThread()
{
if ( kernelMask != 0 )
delete [] kernelMask, kernelMask = 0;
if ( kernelFront != 0 )
delete [] kernelFront, kernelFront = 0;
if ( kernelBack != 0 )
delete [] kernelBack, kernelBack = 0;
if ( histogram != 0 )
delete [] histogram, histogram = 0;
if ( clippedHistogram != 0 )
delete [] clippedHistogram, clippedHistogram = 0;
}
virtual void Run()
{
INIT_THREAD_MONITOR()
// get pointer to image area which we're about to process
typename P::sample* pL = m_imageDst.PixelAddress( 0, m_firstRow, 0 );
// iterate over all lines
for ( int y = m_firstRow; y < m_endRow; y++ )
{
// iterate over pixels in current line
for ( int x = 0; x < m_imageDst.Width(); x++ )
{
// get pixel luminance
RGBColorSystem::sample L;
P::FromSample( L, *pL );
// on the beginning of the line, init histogram of pixel neighborhood
if ( x == 0 )
InitHistogram( y );
// on next pixels, just shift the histogram, adding and removing required pixels
else
AdvanceHistogram( x, y );
// clip the histogram according to Contrast Limit parameter
ClipHistogram();
// transform pixel luminance using Cumulative Distribution Function of clipped histogram
RGBColorSystem::sample outL = ComputeCDF( L );
// blend with original luminance according to Amount parameter
outL = m_instance.GetAmount()*outL + (1 - m_instance.GetAmount())*L;
// set new pixel color and go to next pixel
*pL++ = P::ToSample( outL );
UPDATE_THREAD_MONITOR( 65536 )
}
}
}
private:
// allocates and builds kernel mask - 2D array of bool values whether
// corresponding pixel belongs to kernel or not
void BuildKernelMask()
{
// compute size of the kernel
kernelSize = radius * 2 -1;
// allocated square kernel mask
kernelMask = new bool[kernelSize*kernelSize];
// allocate list of pixels on the front (right) and back (left) part of the kernel
// these lists are used to advance the histogram to next pixels
kernelFront = new int[kernelSize];
kernelBack = new int[kernelSize];
// fill in the mask
for (int y = 0; y < kernelSize; y++)
{
bool firstValid = false;
for (int x = 0; x < kernelSize; x++)
{
// compute index in kernel mask array
int i = y*kernelSize+x;
// for circular kernel, compute distance of the pixel from center and compare
// to kernel radius
if (m_instance.IsCircular())
{
int dx = x - radius + 1;
int dy = y - radius + 1;
double dist = Sqrt( (double)( dx * dx + dy * dy ) );
kernelMask[i] = dist <= (double)(radius-1)+1e-6;
}
// for square kernel, all pixels belong to mask
else kernelMask[i] = true;
//update kernel front and back indices for this kernel row
if (!firstValid && kernelMask[i])
{
firstValid = true;
kernelFront[y] = x-radius+1;
kernelBack[y] = x-radius+1;
}
else if (firstValid && kernelMask[i])
{
kernelFront[y] = x-radius+1;
}
}
}
}
// computes the histogram for the neighborhood of the pixel at the beginning of given line
// kernel mask is used to determine which pixels contribute to the histogram
// image is mirorred on the boundaries in order to keep histogram size constant
void InitHistogram(int y)
{
// zero histogram
::memset( histogram, 0, histogramSize * sizeof(uint32) );
valuesInHistogram = 0;
// get pointer to image pixels
const typename P::sample* pL = m_imageSrc[0];
int r = radius-1;
// kernel mask is placed with center on the processed pixel
// iterate through kernel mask with indices relative to center
for (int ky = -r; ky <= r; ky++)
{
// compute y position of the kernel point in the image
int yy = y+ky;
// mirror it on boundaries
if (yy < 0) yy = -yy;
if (yy >= m_imageSrc.Height()) yy = 2*m_imageSrc.Height()-yy;
// make sanity check (for images smaller than kernel size)
if (yy >= 0 && yy < m_imageSrc.Height())
{
// compute offset of the processed line in the image
int offset = yy*m_imageSrc.Width();
// iterate through kernel mask row with indices relative to center
for (int kx = -r; kx <= r; kx++)
{
// compute y position of the kernel point in the image
int xx = kx;
// mirror it on left boundary (that's where we are in this method)
if (xx < 0) xx = -xx;
// make sanity check (for images smaller than kernel size)
if (xx >= 0 && xx < m_imageSrc.Width())
{
// if the current pixel is part of the kernel
if (kernelMask[(ky+r)*kernelSize+kx+r])
{
// get pixel luminance
RGBColorSystem::sample L;
P::FromSample( L, *(pL+offset+xx) );
// sample it to current histogram resolution
uint32 value = Range((uint32)(L*factor), (uint32)0, (uint32)(histogramSize-1));
// add it to the histogram
histogram[value]++;
valuesInHistogram++;
}
}
}
}
}
}
// shifts the histogram from position (x-1, y) to (x, y)
// it does it by removing pixels on the left of the kernel and adding pixels on the right of the kernel
// image is mirorred on the boundaries in order to keep histogram size constant
void AdvanceHistogram(int x, int y)
{
// get pointer to image pixels
const typename P::sample* pL = m_imageSrc[0];
int r = radius-1;
// iterate through kernel mask rows with indices relative to center
for (int ky = -r; ky <= r; ky++)
{
// compute y position of the kernel point in the image
int yy = y+ky;
// mirror it on boundaries
if (yy < 0) yy = -yy;
if (yy >= m_imageSrc.Height()) yy = 2*m_imageSrc.Height()-yy;
// make sanity check (for images smaller than kernel size)
if (yy >= 0 && yy < m_imageSrc.Height())
{
// compute offset of the processed line in the image
int offset = yy*m_imageSrc.Width();
// remove kernel back from histogram, using stored index on this row
// get x position of the back (left) pixel in the kernel on this row
int kx = kernelBack[ky+r];
// compute x position of the kernel point in the image (shifted one pixel to the left)
int xx = x+kx-1;
// mirror it on boundaries
if (xx < 0) xx = -xx;
if (xx >= m_imageSrc.Width()) xx = 2*m_imageSrc.Height()-xx;
// make sanity check (for images smaller than kernel size)
if (xx >= 0 && xx < m_imageSrc.Width())
{
// get pixel luminance
RGBColorSystem::sample L;
P::FromSample( L, *(pL+offset+xx) );
// sample it to current histogram resolution
uint32 value = Range((uint32)(L*factor), (uint32)0, (uint32)(histogramSize-1));
// remove it from the histogram
histogram[value]--;
valuesInHistogram--;
}
// add kernel front to the histogram
// get x position of the front (right) pixel in the kernel on this row
kx = kernelFront[ky+r];
// compute x position of the kernel point in the image
xx = x+kx;
// mirror it on boundaries
if (xx < 0) xx = -xx;
if (xx >= m_imageSrc.Width()) xx = 2*m_imageSrc.Height()-xx;
// make sanity check (for images smaller than kernel size)
if (xx >= 0 && xx < m_imageSrc.Width())
{
// get pixel luminance
RGBColorSystem::sample L;
P::FromSample( L, *(pL+offset+xx) );
// sample it to current histogram resolution
uint32 value = Range((uint32)(L*factor), (uint32)0, (uint32)(histogramSize-1));
// add it to the histogram
histogram[value]++;
valuesInHistogram++;
}
}
}
}
// creates clipped version of the histogram
// the histogram is clipped to ensure maximal required slope of its cumulative distribution function
// it is done by clipping each value in histogram and redistributing clipped values uniformly over
// the histogram
void ClipHistogram()
{
// copy current histogram to clipped histogram
memcpy( clippedHistogram, histogram, histogramSize * sizeof(uint32) );
int clippedValues = 0;
int clippedValuesBefore;
// compute maximal limit for one histogram value from required slope
int histLimit = ( int )( limit * valuesInHistogram / (histogramSize-1) + 0.5f );
if (histLimit == 0) histLimit = 1;
int iterations = 0;
// start iterative clipping
do
{
clippedValuesBefore = clippedValues;
clippedValues = 0;
// clip all values over limit, accumulate amount of clipped values
for ( uint32 i = 0; i < histogramSize; i++ )
{
int32 d = (int32)clippedHistogram[i] - histLimit;
if ( d > 0 )
{
clippedValues += d;
clippedHistogram[i] = histLimit;
}
}
// number of clipped values should be less then in previous iteration
if ( iterations == 0 || clippedValues < clippedValuesBefore )
{
// compute amount to deliver to each value and rest
int32 d = clippedValues / histogramSize;
int32 m = clippedValues % histogramSize;
if ( d != 0 )
{
// distribute clipped values to whole histogram
for ( uint32 i = 0; i < histogramSize; i++ )
clippedHistogram[i] += d;
}
if ( m != 0 )
{
// distribute uniformly the rest
int s = (histogramSize - 1) / m;
for ( uint32 i = 0; i < histogramSize; i += s )
clippedHistogram[i]++;
}
}
iterations++;
}
// continue iterations as long as number of clipped values goes down
while ( iterations == 1 || clippedValues < clippedValuesBefore );
}
// compute new lightness value from old one, using cumulative distribution function
// of clipped histogram
RGBColorSystem::sample ComputeCDF( RGBColorSystem::sample L )
{
// sample value to current histogram resolution
uint32 value = Range((uint32)(L*factor), (uint32)0, (uint32)(histogramSize-1));
// find first nonzero value in histogram
uint32 cdfMin = 0;
for (uint32 i = 0; i < histogramSize; i++)
{
if (clippedHistogram[i] != 0)
{
cdfMin = clippedHistogram[i];
break;
}
}
// compute new value (value of cumulative distribution function for the original luminance value)
uint32 cdf = 0;
for (uint32 i = 0; i <= value; i++)
cdf += clippedHistogram[i];
// compute total sum of histogram
uint32 cdfMax = cdf;
for (uint32 i = value+1; i < histogramSize; i++)
cdfMax += clippedHistogram[i];
// rescale result to range of CDF
return (RGBColorSystem::sample)(cdf-cdfMin)/(RGBColorSystem::sample)(cdfMax-cdfMin);
}
const AbstractImage::ThreadData& m_data;
const LocalHistogramEqualizationInstance& m_instance;
GenericImage<P>& m_imageDst;
const GenericImage<P>& m_imageSrc;
int m_firstRow, m_endRow;
int kernelSize;
bool* kernelMask;
int* kernelFront;
int* kernelBack;
uint32 histogramSize;
uint32* histogram;
uint32* clippedHistogram;
uint32 valuesInHistogram;
int radius;
double limit;
double factor;
};
};
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
void LocalHistogramEqualizationInstance::Preview( UInt16Image& image ) const
{
MuteStatus status;
image.SetStatusCallback( &status );
LocalHistogramEqualizationEngine::Apply( image, *this );
image.ResetSelections();
}
// ----------------------------------------------------------------------------
bool LocalHistogramEqualizationInstance::ExecuteOn( View& view )
{
AutoViewLock lock( view );
ImageVariant image = view.Image();
if ( image.IsComplexSample() )
return false;
Console().EnableAbort();
StandardStatus status;
image->SetStatusCallback( &status );
LocalHistogramEqualizationEngine::Apply( image, *this );
return true;
}
// ----------------------------------------------------------------------------
void* LocalHistogramEqualizationInstance::LockParameter( const MetaParameter* p, size_type /*tableRow*/ )
{
if ( p == TheLHERadiusParameter )
return &radius;
if ( p == TheLHEHistogramBinsParameter )
return &histogramBins;
if ( p == TheLHESlopeLimitParameter )
return &slopeLimit;
if ( p == TheLHECircularKernelParameter )
return &circularKernel;
if ( p == TheLHEAmountParameter )
return &amount;
return 0;
}
// ----------------------------------------------------------------------------
int LocalHistogramEqualizationInstance::GetHistogramSize() const
{
switch (histogramBins)
{
default:
case LHEHistogramBins::Bit8: return 1 << 8;
case LHEHistogramBins::Bit10: return 1 << 10;
case LHEHistogramBins::Bit12: return 1 << 12;
}
}
// ----------------------------------------------------------------------------
} // pcl
// ----------------------------------------------------------------------------
// EOF LocalHistogramEqualizationInstance.cpp - Released 2017-08-01T14:26:58Z
| [
"juan.conejero@pixinsight.com"
] | juan.conejero@pixinsight.com |
d1aa00f1cfb407bb783f284a206a9698c00ba7b2 | b4ecc53688d1f9442d135cd6f0de2a4a7938c876 | /task1/mainwindow.h | cae397d257138a925063d27c152e17b20055af6c | [] | no_license | unn16/geekclass | 9297760fa67ba342ef232c917fbb0558bf78da98 | c721f2980844dfe440f40d3a15300172ea908afc | refs/heads/master | 2020-04-07T03:05:20.699642 | 2018-12-29T13:28:26 | 2018-12-29T13:28:26 | 158,001,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 356 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void frases();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"noreply@github.com"
] | noreply@github.com |
ab0d651e573b267cb062bbd2f7d85d4e3fb3ac60 | 9226b8f148dd5971dbef40fe359ed9aa276ac2d3 | /tests/test-math-frustum.hpp | 771bddbfa3cb69f8ade571344f445dda8fb82355 | [] | no_license | asdlei99/gearoenix | ff7fdd875c5ab3ebe9443473837e44df3e8e085e | 1be747da5d17f7f412deffff3497ed61db6c05ed | refs/heads/master | 2021-01-02T18:49:00.069672 | 2020-02-08T05:58:25 | 2020-02-08T05:58:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,428 | hpp | #include <gearoenix/math/math-aabb.hpp>
#include <gearoenix/math/math-frustum.hpp>
#include <gearoenix/math/math-projector-frustum.hpp>
#include <gearoenix/math/math-sphere.hpp>
BOOST_AUTO_TEST_CASE(math_frustum_test)
{
namespace gxm = gearoenix::math;
const gxm::Mat4x4 identity;
const gxm::Frustum f({
gxm::Plane(gxm::Vec3(-1.0f, -1.0f, -1.0f), gxm::Vec3(1.0f, 0.0f, 0.0f)),
gxm::Plane(gxm::Vec3(-1.0f, -1.0f, -1.0f), gxm::Vec3(0.0f, 1.0f, 0.0f)),
gxm::Plane(gxm::Vec3(-1.0f, -1.0f, -1.0f), gxm::Vec3(0.0f, 0.0f, 1.0f)),
gxm::Plane(gxm::Vec3(1.0f, 1.0f, 1.0f), gxm::Vec3(-1.0f, 0.0f, 0.0f)),
gxm::Plane(gxm::Vec3(1.0f, 1.0f, 1.0f), gxm::Vec3(0.0f, -1.0f, 0.0f)),
gxm::Plane(gxm::Vec3(1.0f, 1.0f, 1.0f), gxm::Vec3(0.0f, 0.0f, -1.0f)),
});
BOOST_CHECK_EQUAL(f.check_intersection(gxm::Sphere(gxm::Vec3(0.0f, 0.0f, 0.0f), 0.9999f)), gxm::IntersectionStatus::In);
BOOST_CHECK_EQUAL(f.check_intersection(gxm::Sphere(gxm::Vec3(1.0f, 1.0f, 1.0f), 1.0f)), gxm::IntersectionStatus::Cut);
BOOST_CHECK_EQUAL(f.check_intersection(gxm::Sphere(gxm::Vec3(1.5f, 1.5f, 1.5f), 1.0f)), gxm::IntersectionStatus::Cut);
BOOST_CHECK_EQUAL(f.check_intersection(gxm::Sphere(gxm::Vec3(1.6f, 1.6f, 1.6f), 1.0f)), gxm::IntersectionStatus::Cut);
BOOST_CHECK_EQUAL(f.check_intersection(gxm::Sphere(gxm::Vec3(1.7f, 1.7f, 1.7f), 1.0f)), gxm::IntersectionStatus::Cut);
BOOST_CHECK_EQUAL(f.check_intersection(gxm::Sphere(gxm::Vec3(2.001f, 2.001f, 2.001f), 1.0f)), gxm::IntersectionStatus::Out);
const gxm::ProjectorFrustum pf(identity);
BOOST_CHECK_EQUAL(pf.check_intersection(gxm::Aabb3(gxm::Vec3(0.999f, 0.999f, 0.999f), gxm::Vec3(-0.999f, -0.999f, -0.999f))), gxm::IntersectionStatus::In);
BOOST_CHECK_EQUAL(pf.check_intersection(gxm::Aabb3(gxm::Vec3(2.0f, 2.0f, 2.0f), gxm::Vec3(0.0f, 0.0f, 0.0f))), gxm::IntersectionStatus::Cut);
BOOST_CHECK_EQUAL(pf.check_intersection(gxm::Aabb3(gxm::Vec3(2.0f, 2.0f, 2.0f), gxm::Vec3(1.0f, 1.0f, 1.0f))), gxm::IntersectionStatus::Out);
BOOST_CHECK_EQUAL(pf.check_intersection(gxm::Sphere(gxm::Vec3(0.0f, 0.0f, 0.0f), 0.999f)), gxm::IntersectionStatus::In);
BOOST_CHECK_EQUAL(pf.check_intersection(gxm::Sphere(gxm::Vec3(2.0f, 0.0f, 0.0f), 3.0f)), gxm::IntersectionStatus::Cut);
BOOST_CHECK_EQUAL(pf.check_intersection(gxm::Sphere(gxm::Vec3(2.0f, 0.0f, 0.0f), 0.999f)), gxm::IntersectionStatus::Out);
} | [
"hossein.noroozpour@gmail.com"
] | hossein.noroozpour@gmail.com |
07e0317443117571c1e10b9b496439c7a365ab17 | 266e0b9ea45f319fa8efb6f4190f81a81bee4b77 | /Geometry/Mahmoud and Ehab and the MEX.cpp | 71e35b8e8b0becc355a8ad2d77daef6792171bff | [] | no_license | Salsabil007/programming | 8667fef904335676134c0a7d877c5fb155a6aad0 | 88bc3be9f5d1bdf71c071235670fa7ee05852bba | refs/heads/master | 2020-04-01T07:54:52.038427 | 2018-10-14T19:17:47 | 2018-10-14T19:17:47 | 153,009,516 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,x,i,j,k,l,sum=0,mex;
cin>>n>>x;
int arr[n];
for(i=0;i<n;i++)
{
cin>>arr[i];
}
sort(arr,arr+n);
for(i=0;i<n;i++)
{
if(arr[i]==x) {cout<<1;return 0;}
}
int pp=0;
for(i=0;i<n;i++)
{
if(arr[i]==pp) {pp++;}
else if(arr[i]!=pp) {mex=pp;break;}
}
if(mex==x) {cout<<0;return 0;}
else if(mex > x)
{
cout<<1<<endl;
return 0;
}
else if(mex < x)
{
for(i=0;i<n;i++)
{
if(arr[i]>x) break;
sum++;
}
cout<<x-sum;
}
else
{
}
}
| [
"salsabilarabishusmi007@gmail.com"
] | salsabilarabishusmi007@gmail.com |
cefaa6c9be38c7d713f02c51fa8b7580ad455304 | 59746b1d4afdc28ba4db5d0144a68737153baaa7 | /leetcode/罗马数字转整数/4.cpp | db461e2ee7b06ccc4e7e98c03a1ab342d148e8b4 | [] | no_license | LoveBettygirl/code-practice | 6072006e65be242a1b34524433667a4c2a8c597c | 09450e9e2202630f7d775f3d1a293a4d79018d98 | refs/heads/master | 2023-03-29T01:31:14.885529 | 2021-02-14T02:39:42 | 2021-02-14T02:39:42 | 279,858,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 917 | cpp | #include <string>
#include <iostream>
using namespace std;
class Solution
{
private:
int getValue(char s)
{
switch (s)
{
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
public:
int romanToInt(string s)
{
int sum = 0, size = s.length();
int prev = getValue(s[0]), curr;
for (int i = 1; i < size; i++)
{
curr = getValue(s[i]);
if (prev < curr)
sum -= prev;
else
sum += prev;
prev = curr;
}
sum += prev;
return sum;
}
};
int main()
{
return 0;
} | [
"bettycyygirl@163.com"
] | bettycyygirl@163.com |
fdb3dd3ae008f05dd4e8acabb2e65979cabfa91f | e239c73c6ef72bf2ab1f33d6fcdfd5221ca45712 | /HowDoWeTurnThisOn/include/sprite.h | 2ccf745752d42fd92968651ba1c797c96d02bdce | [] | no_license | OlmoPrietoDev/HowDoWeTurnThisOn | bd588c3f643f4a7e37d3fe5f723c0139c2019895 | 0ac7aa469ddebd2f675bb024e552f70dc2c18049 | refs/heads/master | 2016-09-06T16:21:33.842123 | 2015-07-31T17:29:52 | 2015-07-31T17:29:52 | 39,510,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,482 | h | #ifndef __SPRITE_H__
#define __SPRITE_H__
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <iostream>
#include "drawable_element.h"
#include "utils.h"
class Sprite : public DrawableElement {
public:
Sprite();
Sprite(Sprite *other);
Sprite(char *path);
Sprite(std::string path);
Sprite(const sf::Texture &other);
~Sprite();
void setTextureFromFile(char *path);
void setTextureFromTexture(const sf::Texture &other);
void setBoundingBox(float width, float height);
void setBoundingBox(const Rect &box);
void setPosition(float x, float y);
void setPosition(const Vec2 &pos);
void setRotation(float angle);
void setScale(float scale_x, float scale_y);
void setScale(const Vec2 &scales);
void setOrigin(float x, float y); // local to the sprite
void setOrigin(const Vec2 &origin);
const Rect &getBoundingBox() const;
const Vec2 &getPosition() const;
const float getRotation() const;
const Vec2 &getScale() const;
const Vec2 &getOrigin() const;
void moveBy(float off_x, float off_y);
void moveBy(const Vec2 &offset);
void rotate(float angle);
void scale(float scale_x, float scale_y);
void scale(const Vec2 &scales);
sf::Sprite getDrawable();
sf::Sprite *getDrawableAddress();
private:
sf::Sprite *m_pSprite;
float m_fXPos;
float m_fYPos;
float m_fWidth;
float m_fHeight;
};
#endif // __SPRITE_H__
| [
"gbarcomu@alumnos.unex.es"
] | gbarcomu@alumnos.unex.es |
2f30ec6af9f0b58bef5b8b901851df40027360ef | b52e09b14f1b85af7f32e51849288a2d972ccf37 | /CocosNet/CCNetDelegate.cpp | b338723b55781e96f8cd378ee0ad0e9a6c5a7f23 | [
"MIT"
] | permissive | LingJiJian/Tui-x | 9bd80b801d9eba7b67223b16f1bad6ecebd20690 | e00e79109db466143ed2b399a8991be4e5fea28f | refs/heads/master | 2016-09-05T14:07:49.984373 | 2016-01-25T10:01:37 | 2016-01-25T10:01:37 | 19,667,247 | 68 | 36 | null | null | null | null | UTF-8 | C++ | false | false | 8,167 | cpp | /****************************************************************************
Copyright (c) 2014 Lijunlin - Jason lee
Created by Lijunlin - Jason lee on 2014
jason.lee.c@foxmail.com
http://www.cocos2d-x.org
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 "CCNetDelegate.h"
NS_CC_BEGIN
CNetDelegate::CNetDelegate()
: m_fSoTimeout(SOCKET_SOTIMEOUT)
, m_eStatus(eSocketIoClosed)
, m_fConnectingDuration(0.0f)
, m_bRunSchedule(false)
{
}
CNetDelegate::~CNetDelegate()
{
m_oSocket.ccClose();
while(!m_lSendBuffers.empty())
{
CC_SAFE_DELETE_ARRAY(m_lSendBuffers.front().pBuffer);
m_lSendBuffers.pop_front();
}
}
void CNetDelegate::setInetAddress(const CInetAddress& oInetAddress)
{
m_oInetAddress = oInetAddress;
}
const CInetAddress& CNetDelegate::getInetAddress() const
{
return m_oInetAddress;
}
void CNetDelegate::setSoTimeout(float fSoTimeout)
{
m_fSoTimeout = fSoTimeout;
}
float CNetDelegate::getSoTimeout() const
{
return m_fSoTimeout;
}
void CNetDelegate::send(char* pBuffer, unsigned int uLen)
{
if( !pBuffer || uLen == 0 || !isConnected() )
return;
#if USING_PACKAGE_HEAD_LENGTH
CBuffer* pBuf = new CBuffer(pBuffer, uLen);
pBuf->autorelease();
send(pBuf);
#else
char* pTemp = new char[uLen];
memcpy(pTemp, pBuffer, uLen);
_SENDBUFFER tBuf;
tBuf.pBuffer = pTemp;
tBuf.nLength = (int)uLen;
tBuf.nOffset = 0;
m_lSendBuffers.push_back(tBuf);
#endif
}
void CNetDelegate::send(CBuffer* pBuffer)
{
if( pBuffer->empty() || !isConnected() )
return;
#if USING_PACKAGE_HEAD_LENGTH
unsigned int u_len = pBuffer->length();
pBuffer->moveRight(sizeof(unsigned int));
pBuffer->moveWriterIndexToFront();
pBuffer->writeUInt(u_len);
#endif
pBuffer->moveReaderIndexToFront();
char* pData = pBuffer->readWholeData();
int nLength = (int)pBuffer->length();
pBuffer->moveReaderIndexToFront();
_SENDBUFFER tBuf;
tBuf.pBuffer = pData;
tBuf.nLength = nLength;
tBuf.nOffset = 0;
m_lSendBuffers.push_back(tBuf);
}
bool CNetDelegate::isConnected()
{
return m_eStatus == eSocketConnected;
}
bool CNetDelegate::connect()
{
if( m_eStatus != eSocketConnected && m_eStatus != eSocketConnecting )
{
m_oSocket.setInetAddress(m_oInetAddress);
if( m_oSocket.ccConnect() )
{
registerScheduler();
m_eStatus = eSocketConnecting;
return true;
}
}
return false;
}
void CNetDelegate::disconnect()
{
if( m_eStatus == eSocketConnected )
{
unregisterScheduler();
m_oSocket.ccDisconnect();
m_eStatus = eSocketDisconnected;
onDisconnected();
}
}
void CNetDelegate::close()
{
if( m_eStatus == eSocketConnected )
{
unregisterScheduler();
m_oSocket.ccClose();
m_eStatus = eSocketIoClosed;
onDisconnected();
}
}
void CNetDelegate::runSchedule(float dt)
{
switch( m_eStatus )
{
case eSocketConnecting:
{
switch( m_oSocket.ccIsConnected() )
{
case eSocketConnected:
{
m_eStatus = eSocketConnected;
onConnected();
}
break;
case eSocketConnectFailed:
{
unregisterScheduler();
m_oSocket.ccClose();
m_eStatus = eSocketConnectFailed;
onExceptionCaught(eSocketConnectFailed);
}
break;
case eSocketConnecting:
{
if( m_fConnectingDuration > m_fSoTimeout )
{
unregisterScheduler();
m_oSocket.ccDisconnect();
m_eStatus = eSocketDisconnected;
onConnectTimeout();
m_fConnectingDuration = 0.0f;
}
else
{
m_fConnectingDuration += dt;
}
}
break;
default:
break;
}
}
break;
case eSocketConnected:
{
#if HANDLE_ON_SINGLE_FRAME
while( m_oSocket.ccIsReadable() )
#else
if( m_oSocket.ccIsReadable() )
#endif
{
if( this->runRead() ) return;
}
#if HANDLE_ON_SINGLE_FRAME
while( m_oSocket.ccIsWritable() && !m_lSendBuffers.empty() )
#else
if( m_oSocket.ccIsWritable() && !m_lSendBuffers.empty() )
#endif
{
if( this->runWrite() ) return;
}
}
break;
default:
break;
}
}
bool CNetDelegate::runRead()
{
int nRet = m_oSocket.ccRead(m_pReadBuffer, SOCKET_READ_BUFFER_SIZE);
if( nRet == eSocketIoError || nRet == eSocketIoClosed )
{
unregisterScheduler();
m_oSocket.ccClose();
m_eStatus = eSocketIoClosed;
onDisconnected();
return true;
}
else
{
#if 1
CCLOG("CCSOCKET READ %d", nRet);
#endif
m_oReadBuffer.writeData(m_pReadBuffer, (unsigned int)nRet);
#if USING_PACKAGE_HEAD_LENGTH
while( m_oReadBuffer.isReadable(sizeof(int)) )
{
m_oReadBuffer.moveReaderIndexToFront();
int n_head_len = m_oReadBuffer.readInt();
if( n_head_len <= 0 )
{
CCLOGERROR("invalidate head length");
m_oReadBuffer.moveLeft(sizeof(int));
}
int n_content_len = (int)m_oReadBuffer.length();
if( n_content_len - (int)(sizeof(int)) >= n_head_len )
{
m_oReadBuffer.moveLeft(sizeof(unsigned int));
CBuffer* pData = m_oReadBuffer.readData(n_head_len);
m_oReadBuffer.moveLeft(n_head_len);
m_oReadBuffer.moveReaderIndexToFront();
m_oReadBuffer.moveWriterIndexToBack();
onMessageReceived(*pData);
#if USING_LUA
executeOnMessageReceivedScriptHandler(pData);
#endif
}else{
break;
}
}
#else
CBuffer* pData = (CBuffer*) m_oReadBuffer.copy();
pData->autorelease();
m_oReadBuffer.clear();
onMessageReceived(*pData);
#if USING_LUA
executeOnMessageReceivedScripHandler(pData);
#endif
#endif
}
return false;
}
bool CNetDelegate::runWrite()
{
_SENDBUFFER& tBuffer = m_lSendBuffers.front();
int nRet = m_oSocket.ccWrite(tBuffer.pBuffer + tBuffer.nOffset, tBuffer.nLength - tBuffer.nOffset);
#if 1
CCLOG("CCSOCKET WRITE %d", nRet);
#endif
if( nRet == eSocketIoError )
{
unregisterScheduler();
m_oSocket.ccClose();
m_eStatus = eSocketIoClosed;
onDisconnected();
return true;
}
else if( nRet == tBuffer.nLength - tBuffer.nOffset )
{
CC_SAFE_DELETE_ARRAY(tBuffer.pBuffer);
m_lSendBuffers.pop_front();
}
else
{
tBuffer.nOffset += nRet;
}
return false;
}
void CNetDelegate::registerScheduler()
{
if( m_bRunSchedule )
return;
Director::getInstance()->getScheduler()->schedule(
schedule_selector(CNetDelegate::runSchedule),
this,
0.0f,
false
);
m_bRunSchedule = true;
}
void CNetDelegate::unregisterScheduler()
{
if( !m_bRunSchedule )
return;
Director::getInstance()->getScheduler()->unschedule(
schedule_selector(CNetDelegate::runSchedule),
this
);
m_bRunSchedule = false;
}
#if USING_LUA
void CNetDelegate::executeOnMessageReceivedScriptHandler(CBuffer *oBuffer)
{
if (m_nMessageReceivedScriptHandler != 0)
{
LuaEngine* pEngine = LuaEngine::getInstance();
LuaStack* pStack = pEngine->getLuaStack();
pStack->pushObject(oBuffer, "CBuffer");
pStack->executeFunctionByHandler(m_nMessageReceivedScriptHandler, 1);
pStack->clean();
}
}
void CNetDelegate::executeOnExceptionCaughtScriptHandler(CCSocketStatus eStatus)
{
if (m_nExceptionCaughtScriptHandler != 0)
{
LuaEngine* pEngine = LuaEngine::getInstance();
LuaStack* pStack = pEngine->getLuaStack();
pStack->pushInt((int)eStatus);
pStack->executeFunctionByHandler(m_nExceptionCaughtScriptHandler, 1);
pStack->clean();
}
}
#endif
NS_CC_END
| [
"342854406@qq.com"
] | 342854406@qq.com |
32e608c563d87bcb65bf1c1bc984c548df6c66f1 | 17dd5b165700f7128ee3a174dc67d5b68c4bd139 | /CHESS-0.3-hess-pp-qt-40/Source/Kernel/Classes/AdMH.h | 26b686393eeb1d8e9c944033f76fa683a80368bf | [] | no_license | Bayesian-Omics/CHESS | f3da2714431268287cc882172bc47f91ed89deb2 | c9b884004b57220e301d416d5d4f83f0937bccaa | refs/heads/master | 2016-09-11T02:15:27.690918 | 2014-12-02T22:29:57 | 2014-12-02T22:29:57 | 27,103,199 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,105 | h | /* This file is part of CHESS.
* Copyright (c) Habib Saadi (h.saadi@imperial.ac.uk)
* 2013
*
* The file is copied from AdMH.h in the ESS++ program
* Copyright (c) Marc Chadeau (m.chadeau@imperial.ac.uk)
* Leonardo Bottolo (l.bottolo@imperial.ac.uk)
* David Hastie (d.hastie@imperial.ac.uk)
* 2010
*
* CHESS 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.
*
* CHESS 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 CHESS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef AdMH_H
#define AdMH_H
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_sort_vector.h>
#include <math.h>
#include "../Routines/matrix_handling.h"
#include <gsl/gsl_statistics_double.h>
#include <vector>
#include <algorithm>
#include "../Classes/Move_monitor.h"
using namespace std;
class AdMH
{
public:
AdMH();
~AdMH(){};
unsigned int n_batch;
double optimal;
double ls;
double delta_n;
unsigned int tilda_accept;
unsigned int tilda_accept_ins;
unsigned int tilda_n_sweep;
unsigned int tilda_n_sweep_ins;
vector < double > M;
vector < double > Ls;
void set_AdMH(int g_sample,
unsigned int n_batch_from_read,
double AdMH_optimal_from_read,
double AdMH_ls_from_read,
unsigned int pX,
unsigned int burn_in,
double M_min_input,
double M_max_input);
void display_AdMH();
void Adapt_AdMH_ESS(unsigned int sweep, Move_monitor *My_Move_monitor);
double Adapt_AdMH(unsigned int sweep);
};
#endif /* !defined AdMH_H */
| [
"saadi@crans.org"
] | saadi@crans.org |
400ddf1df8cbea13fc8ae9ae4078079c2774534e | 5fa16413faaa39c6d756fc6a5e107e0e3f1eb715 | /C++/Ass1-CTDL_GT/Ass1-CTDL_GT/SparseMatrix.h | c7f071f9be6f92b91a7ba32aa152de637e31c770 | [] | no_license | quang2415/Working-Environment | ce2c46e4c84d8bc524f26e38535fe6ea89fe7fe5 | 6632a7383866f1162743a8932e66678ebda30771 | refs/heads/master | 2022-05-24T17:52:13.172937 | 2020-04-26T13:58:09 | 2020-04-26T13:58:09 | 217,666,902 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,790 | h | #pragma once
#include"Element.h"
class SparseMatrix {
private:
// data member for dynamic array
Element* storage;
unsigned size;
unsigned capacity;
unsigned int nrow, ncol; // the size of matrix is nrow x ncol
void rangeCheck(unsigned row, unsigned col) const{
if(row < 0 || row >= nrow || col < 0 || col >=ncol)
throw "MatrixSubscriptOutOfBoundsException";
}
void setCapacity(unsigned newCapacity) {
Element *newStorage = new Element[newCapacity];
memcpy(newStorage, storage, sizeof(Element) * size);
capacity = newCapacity;
delete[] storage;
storage = newStorage;
}
void ensureCapacity(unsigned minCapacity) {
if (minCapacity > capacity) {
unsigned newCapacity = (capacity * 3) / 2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
setCapacity(newCapacity);
}
}
void pack() {
if (size <= capacity / 2) {
int newCapacity = (size * 3) / 2 + 1;
setCapacity(newCapacity);
}
}
void trim() {
int newCapacity = size;
setCapacity(newCapacity);
}
void insertAt(int index, Element val) {
ensureCapacity(size + 1);
memmove(storage + index + 1, storage + index, sizeof(Element)*(size - index));
storage[index] = val;
size++;
}
void add(Element val) {
ensureCapacity(size + 1);
storage[size] = val;
size++;
}
void removeAt(int index) {
memmove(storage + index, storage + index + 1, sizeof(Element)*(size - index - 1));
size--;
pack();
}
public:
SparseMatrix(unsigned int nr = 1, unsigned int nc = 1) {
nrow = nr;
ncol = nc;
capacity = 10;
size = 0;
storage = new Element[capacity];
}
SparseMatrix(const SparseMatrix& a) {
nrow = a.nrow;
ncol = a.ncol;
capacity = a.capacity;
size = a.size;
storage = new Element[capacity];
memcpy(storage, a.storage, sizeof(Element)*size);
}
SparseMatrix& operator=(const SparseMatrix& a) {
if (&a == this)
return *this;
if (storage != NULL) delete storage;
nrow = a.nrow;
ncol = a.ncol;
capacity = a.capacity;
size = a.size;
storage = new Element[capacity];
memcpy(storage, a.storage, sizeof(Element)*size);
return (*this);
}
~SparseMatrix() {
if (storage != NULL) {
delete[] storage;
storage = NULL;
}
size = 0;
}
public:
void printFull() {
for (unsigned i = 0; i < nrow; i++) {
for (unsigned j = 0; j < ncol; j++) {
cout << getAt(i, j) << " ";
}
cout << endl;
}
}
// Your tasks: complete the implementation of the below methods
// in SparseMatrix.cpp
void setAt(unsigned row, unsigned col, double val);
double getAt(unsigned row, unsigned col);
SparseMatrix* transpose();
double trace();
SparseMatrix* add(const SparseMatrix& b);
SparseMatrix* multiplyPointWise(const SparseMatrix& b);
friend ostream& operator<<(ostream& os, const SparseMatrix& a);
};
| [
"34291933+quang2415@users.noreply.github.com"
] | 34291933+quang2415@users.noreply.github.com |
e12fc335b7527ff423a7336fa1971a33d7ee59b8 | fe94014ab341d2f5493dabd5dba57b4e3f52ca10 | /01/Solution0.91/my_lib.cpp | 2941e4509fac5d2c59c42d1906d1a9e65ca07e31 | [] | no_license | DaveMSU/Machine-Graphics | 6ce3944fc90cebd661a85e6ff04c155b73b7a43c | d19c9338392bfdd98fc98fb2cb455bbf2235cb9a | refs/heads/master | 2021-04-23T20:28:33.292810 | 2020-04-05T20:51:46 | 2020-04-05T20:51:46 | 249,996,660 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,762 | cpp | #include <cmath>
#include <iostream>
#include <fstream>
#include <vector>
#include "geometry.h" // Кастомная библиотека для работы с геометрическими объектами посредством законов алгебры.
#include "my_lib.h" // Основная библ-ка, в кот-ой нах-ся описания и справки всех функций.
#include "bitmap.h" // Шаблон для записи картинка в .bmp формате.
Vec3f reflect( const Vec3f& vec, const Vec3f& normal ){ // Отражаем вектор vec относительно нормали normal.
return normal * 2 * std::max(0.f, ((-vec)*normal)) + vec;
}
// Для нахождения OY, по OX и normal в Chessdesk.get_material().
//
Vec3f vector_product( const Vec3f& v1, const Vec3f& v2 ){
float x = v1[1]*v2[2] - v1[2]*v2[1];
float y = v1[2]*v2[0] - v1[0]*v2[2];
float z = v1[0]*v2[1] - v1[1]*v2[0];
return Vec3f(x,y,z);
}
std::pair<size_t, float> scene_intersect( const Vec3f& orig,
const Vec3f& dir,
const std::vector <Object*>& objects ){
static float dist; // Расстояние до текущего объекта.
static float min_dist; // Расстояние до ближайшего объекта.
static size_t min_index; // Индекс ближайшего объекта.
dist = -1;
min_dist = -1;
min_index = -1;
for( size_t i = 0; i < objects.size(); ++i ){
dist = objects[i]->ray_intersect( orig, dir );
if( min_index == -1 && dist != -1 ){
min_dist = dist;
min_index = i;
}
else
if( dist != -1 )
if( min_dist > dist ){
min_dist = dist;
min_index = i;
}
}
return std::pair<size_t, float>(min_index, min_dist);
}
Vec3f cast_ray( const Vec3f& orig,
const Vec3f& dir, // Соглашение: вектор должен приходить нормализованным.
const std::vector <Object*>& objects, // spheres/chessdesk
const std::vector <Light>& lights,
size_t depth ){
if( fabs(dir.length() - 1.f) > 1E-5 ){ // Соглашение: dir пришел не нормированным - бросаем исключение.
std::string exc = "\n*****\nFunction: cast_ray()\n";
exc += "dir пришел не нормализованным.\ncurrent depth: ";
exc += std::to_string(depth) + "\n*****";
throw std::logic_error(exc);
}
static std::pair<size_t, float> index_dist;
static size_t min_index;
static float min_dist;
index_dist = scene_intersect( orig, dir, objects );
min_index = index_dist.first;
min_dist = index_dist.second;
if( min_index != -1 ){
static Vec3f point; // Радиус вектор этой точки.
static Vec3f normal; // Нормаль к этой точке.
static Vec3f light_dir; // Вектор исходящий из источника в эту точку.
static Vec3f spec_dir; // Свет источника, отраженный от объекта.
static float diff_coef; // Коэф. диффузной освещенности.
static float spec_coef; // Коэф. бликовой (отражающей) освещенности.
static float cos; // Переменная в кот-ой хранится cos неко-ых 2ух векторов.
static float distance; // Расстояние от источника света до точки.
static float shadow_coef; // Степень 'тени', если луч источника не достигает точки.
static float light_to_indx_point; // Расстояние от источника света до рассм-емой точки.
static float fin_intensity; // Цвет точки на объекте.
shadow_coef = 0;
fin_intensity = objects[min_index]->get_material(point).backg_coef;
point = orig + dir.normalize()*min_dist; // Нормализуем, т.к. по дефолту не нор-о в рекурсии.
normal = objects[min_index]->get_normal(point);
Material this_material = objects[min_index]->get_material(point);
for( size_t i = 0; i < lights.size(); ++i ){
// Диффузный цвет:
//
light_dir = lights[i].position - point;
cos = (normal * light_dir) / light_dir.length();
distance = 4*pi * (light_dir * light_dir);
diff_coef = lights[i].intensity * cos / distance;
diff_coef = std::max(0.f, diff_coef);
// Бликовый цвет:
//
spec_dir = reflect(-light_dir, normal);
spec_coef = (-point).normalize() * spec_dir.normalize();
spec_coef = pow(std::max(0.f, spec_coef), 100);
// Тени:
//
Vec3f cur_point;
for( size_t indx = 0; indx < objects.size(); ++indx ){
if( indx == min_index ) continue;
light_to_indx_point = objects[indx]
->ray_intersect( lights[i].position, -light_dir.normalize() );
if( (light_to_indx_point > 0) && (light_to_indx_point < light_dir.length()) )
shadow_coef += 0.08;
}
fin_intensity += diff_coef*objects[min_index]->get_material(point).diff_coef;
fin_intensity += spec_coef*objects[min_index]->get_material(point).spec_coef;
fin_intensity *= std::max(0.f, 1 - shadow_coef);
}
this_material.color *= fin_intensity;
// Зеркало:
//
static float n2;
n2 = objects[min_index]->get_material(point).refr_coef;
if( objects[min_index]->get_material(point).mirror == true ){
if( n2 > 0 ){
float R = ((Sphere*)objects[min_index])->get_radius();
float cosA = (-point).normalize()*normal;
float cosB = sqrt( 1 - (1/(1000*n2*n2)) * (1-cosA*cosA) );
float sinA = sqrt(1 - cosA*cosA);
float sinB = sqrt(1 - cosB*cosB);
float ABs = 2*R*cosB*cosB;
Vec3f ABv = -normal;
float BCs = sinB*2*R*cosB;
Vec3f BCv = (point.normalize() + normal*cosA)*(1/sinA);
Vec3f in_vec = ABv*ABs + BCv*BCs;
Vec3f tmp_vec = (-normal)*R - in_vec*0.5;
Vec3f out_vec = reflect(in_vec, BCv).normalize();
if( depth > 0 ){
Vec3f tmp = cast_ray( point+in_vec,
out_vec,
objects,
lights,
depth-1 );
if( tmp == background )
tmp *= 1.05;
return tmp * fin_intensity;
}
}
else
if( depth > 0 ){
normal = normal.normalize();
Vec3f tmp = cast_ray( point,
reflect(dir, normal),
objects,
lights,
depth-1 );
if( tmp == background )
tmp *= 1.05;
return tmp * fin_intensity;
}
}
return objects[min_index]->get_material(point).color * fin_intensity;
}
return background;
}
// Рисуем композицию - если луч пересекает объект, то ставим соотв. цвету объекта пиксель с учетом падения света.
//
void render( const std::vector <Object*>& objects,
const std::vector <Light>& lights,
const std::string outFilePath ){
const int width = 1024*1;
const int height = 768*1;
std::vector<Vec3f> framebuffer( width * height );
for ( size_t j = 0; j < height; j++ )
for ( size_t i = 0; i < width; i++ ){
float x = (width/(float)height)*(i - float(width)/2)/float(width);
float y = (j - float(height)/2)/float(height);
Vec3f dir = Vec3f(x,y, 1).normalize(); // +x = направо, +y = вверх, +z = вдаль.
framebuffer[i+j*width] = cast_ray( Vec3f(0,0,-15), dir, objects, lights, MAX_DEPTH );
}
SaveBMP( outFilePath, framebuffer, width, height );
}
//----------------------------------------Light:-------------------------------------------------------
Light::Light( const Vec3f& p, const float& i ) : position(p), intensity(i) {}
//----------------------------------------Material:-----------------------------------------------------
Material::Material( const Vec3f& color,
const float bg,
const float df,
const float sc,
const bool flag,
const float rf ) :
color(color),
backg_coef(bg),
diff_coef(df),
spec_coef(sc),
mirror(flag),
refr_coef(rf){}// Реализовать зн. по умолчанию!!!!!!!
//----------------------------------------Sphere:-------------------------------------------------------
Sphere::Sphere( const Vec3f& c, const float& r, const Material& m ): center(c), radius(r), material(m) {}
// >0 - растояние до пересечения, -1 - не пересекает. (подробней см. my_lib.h)
//
float Sphere::ray_intersect( const Vec3f& orig, const Vec3f& dir ) const {
if( fabs(dir.length() - 1.f) > 1E-5 ){ // Соглашение: dir пришел не нормированным - бросаем исключение.
std::string exc = "\n*****\nFunction: Sphere::ray_intersect()\n";
exc += "dir пришел не нормализованным.\n*****";
throw std::logic_error(exc);
}
static Vec3f L;
static float cosFI;
static float r2;
static float d2;
static float dist_to_center2;
static float dist_d;
static float d;
L = center - orig;
cosFI = L.normalize()*dir.normalize();// cos(dir,радиус-вектор ц/c).
r2 = radius*radius;
d2 = L*L*(1 - cosFI*cosFI);
if( d2 > r2 )
return -1; // Расстояние до ПРЯМОЙ больше радуса.
if( cosFI < 0 )
return -1; // 'Смотрят' в разные полупространства (стороны).
dist_to_center2 = L*L; // Квадрат расстояния от источника света до центра сферы.
dist_d = sqrt(dist_to_center2 + d2); // 'почти' Расстояние до сферы.
d = sqrt(r2 - d2); // То самое 'почти'.
return dist_d - d;
}
Material Sphere::get_material( const Vec3f& point ) const {
return material;
}
Vec3f Sphere::get_normal( const Vec3f& point ) const {
return (point - center).normalize();
}
float Sphere::get_radius() const {
return radius;
}
//--------------------------------------Chessdesk:-----------------------------------------------------
Chessdesk::Chessdesk( const Vec3f& n,
const float& b,
const float& size,
const Material& m1,
const Material& m2 ):
normal(n.normalize()),
bias(b / n.length()),
call_size(size),
first_material(m1),
second_material(m2) {
/* Вычисляем некоторую условную точку O - начало координат. */
O = Vec3f(0,0,0);
size_t i;
for( i = 0; !normal[i]; ++i );
O[i] = -bias / normal[i];
// По 3dtmp вычисляем 2dtmp - вектор, но в координатах плоскости.
//
c1 = Vec3f(0,0,0);
c2 = Vec3f(0,0,0);
Vec3f tmp_vec(0,0,0);
tmp_vec[(i+2)%3] = normal[i] / fabs(normal[i]);
c1 = normal*(bias+normal*tmp_vec)/(normal*normal) + tmp_vec;
c1 = c1 - O;
c2 = vector_product(c1,normal); // Векторное произведение.
}
float Chessdesk::ray_intersect( const Vec3f& orig, const Vec3f& dir ) const {
if( fabs(dir.length() - 1.f) > 1E-5 ){ // Соглашение: dir пришел не нормированным - бросаем исключение.
std::string exc = "\n*****\nFunction: Chessdesk::ray_intersect()\n";
exc += "dir пришел не нормализованным.\n*****";
throw std::logic_error(exc);
}
if( (orig*normal-bias) * (dir*normal) < 0 )
return (normal*orig+bias)/(dir*normal);
return -1;
}
Material Chessdesk::get_material( const Vec3f& point ) const {
Vec3f tmp3d = point - O; // Вектор точки point расматриваемый относительно плоскости.
Vec3f tmp2d(tmp3d*c1, tmp3d*c2, 0);
static bool xd;
static bool yd;
xd = (tmp2d[0] - floor(tmp2d[0]/(call_size*2))*2*call_size) < call_size;
yd = (tmp2d[1] - floor(tmp2d[1]/(call_size*2))*2*call_size) < call_size;
if( xd == yd )
return first_material;
else
return second_material;
}
Vec3f Chessdesk::get_normal( const Vec3f& point ) const {
return normal;
}
| [
"noreply@github.com"
] | noreply@github.com |
7f754316021e063696658571857f4b9963d94ad2 | 2822073b241218f9a33abe9a1dae6f79c9f7e66c | /include/Odom.h | 4afa382fa769fa79af2549c3c76e143dc68b0f31 | [] | no_license | aboufama/changeup2020 | 2fc92e1d8f06c71f4aefad38aea3b7be3c8a989b | 2c9efd193871a94510a1fc8caa191c401395779a | refs/heads/main | 2023-02-15T10:33:51.898237 | 2021-01-15T19:14:04 | 2021-01-15T19:14:04 | 329,996,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37 | h | using namespace vex;
void OdomRun(); | [
"andre@Andres-MacBook-Pro.local"
] | andre@Andres-MacBook-Pro.local |
5ecc8dec78c31d23831c12f803b0e0564749686e | d393a50a3b261c79994dc0c51fe590447696813d | /HLT_SingleMu_Jared/SetHLT.h | 228c8d3d358af8a8b405ec2b219adaf1775f3d79 | [] | no_license | stuli/TriggerEfficiencyAnalyzerPbPb2018 | cdfcbe4ebdcb5d554c85922f22d6b62d6733f528 | b627415b90846d41aaab9fbfd00b611525dcb834 | refs/heads/master | 2020-03-27T16:28:45.103282 | 2018-09-05T22:16:26 | 2018-09-05T22:16:26 | 146,785,565 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,965 | h | #ifndef SetHLT_C
#define SetHLT_C
#include <TF1.h>
#include <TCut.h>
#include <TChain.h>
#include <TGraphAsymmErrors.h>
#include <TCanvas.h>
#include <TNtuple.h>
#include <iostream>
#include <TLine.h>
#include <TMath.h>
#include <TTree.h>
#include <math.h>
#include <TVector3.h>
#include <TLorentzVector.h>
#include <TROOT.h>
#include <TClonesArray.h>
#include <TFile.h>
#include <TH1D.h>
#include <TH2D.h>
#include <TLegend.h>
struct ParticleMass { double JPsi, Psi2S, Y1S, Y2S, Y3S, Z, PiPlus, KaPlus; };
ParticleMass pdgMass = {3.096, 3.686, 9.460, 10.023, 10.355, 91.188, 0.139570, 0.49367 };
struct TriggerList { int HLT_HIL1DoubleMu0_v1, HLT_HIL2DoubleMu0_v1, HLT_HIL3DoubleMu0_v2, HLT_L1DoubleMu0_v1, HLT_L1SingleMuOpen_v1, HLT_L1SingleMu3_v1, HLT_L1SingleMu5_v1, HLT_L1SingleMu7_v1, HLT_HIL2Mu7_v1, HLT_HIL3Mu3_v1, HLT_HIL3Mu5_v1, HLT_HIL3Mu7_v2; };
struct TriggerBranch { TBranch *b_HLT_HIL1DoubleMu0_v1, *b_HLT_HIL2DoubleMu0_v1, *b_HLT_HIL3DoubleMu0_v2, *b_HLT_L1DoubleMu0_v1, *b_HLT_L1SingleMuOpen_v1, *b_HLT_L1SingleMu3_v1, *b_HLT_L1SingleMu5_v1, *b_HLT_L1SingleMu7_v1, *b_HLT_HIL2Mu7_v1, *b_HLT_HIL3Mu3_v1, *b_HLT_HIL3Mu5_v1, *b_HLT_HIL3Mu7_v2; };
int kPromptJpsiLowPt = 0;
int kPromptJpsiHighPt = 1;
int kNonPromptJpsi = 2;
int kUpsione = 3;
int kSingleMu = 4;
int kZboson = 5;
int kXeXe=6;
const int Ntrig = 11;
/*
vector<string> trigname={
"HLT_HIL1DoubleMuOpen_v1",
"HLT_HIL1DoubleMuOpen_OS_v1",
"HLT_HIL1DoubleMuOpen_SS_v1",
"HLT_HIL1DoubleMuOpen_BptxAND_v1",
"HLT_HIL1DoubleMuOpen_OS_BptxAND_v1",
"HLT_HIL1DoubleMuOpen_SS_BptxAND_v1",
"HLT_HIL1DoubleMuOpen_Cent10100_BptxAND_v1",
"HLT_HIL1DoubleMuOpen_Cent50100_BptxAND_v1",
"HLT_HIL1DoubleMu0_v1",
"HLT_HIL1DoubleMu0_BptxAND_v1",
"HLT_HIL1DoubleMu0_Cent10100_BptxAND_v1",
"HLT_HIL1DoubleMu0_Cent30100_BptxAND_v1",
"HLT_HIL1DoubleMu0_Cent50100_BptxAND_v1",
"HLT_HIL2DoubleMu0_v1",
"HLT_HIL3DoubleMu0_v2",
"HLT_L1DoubleMu0_v1",
"HLT_L1SingleMuOpen_v1",
"HLT_L1SingleMu3_v1",
"HLT_L1SingleMu5_v1",
"HLT_L1SingleMu7_v1",
"HLT_HIL2Mu7_v1",
"HLT_HIL3Mu3_v1",
"HLT_HIL3Mu5_v1",
"HLT_HIL3Mu7_v2",
"HLT_HIL3Mu12_v1",
"HLT_HIL3Mu15_v1",
"HLT_HIL3Mu20_v1"
};
*/
vector<string> trigname={
"HLT_HIL1DoubleMu0_v1",
"HLT_HIL2DoubleMu0_v1",
"HLT_HIL3DoubleMu0_v2",
"HLT_L1DoubleMu0_v1",
"HLT_L1SingleMuOpen_v1",
"HLT_L1SingleMu3_v1",
"HLT_L1SingleMu5_v1",
"HLT_L1SingleMu7_v1",
"HLT_HIL2Mu7_v1",
"HLT_HIL3Mu3_v1",
"HLT_HIL3Mu5_v1",
"HLT_HIL3Mu7_v2",
};
TString getSampleID( int sampleID ) {
if ( sampleID == kPromptJpsiLowPt ) return "PR_Jpsi_lowPt";
else if ( sampleID == kPromptJpsiHighPt ) return "PR_Jpsi_highPt";
else if ( sampleID == kNonPromptJpsi ) return "NP_Jpsi";
else if ( sampleID == kUpsione) return "Upsione";
else if ( sampleID == kSingleMu) return "SingleMuGun";
else if ( sampleID == kZboson) return "Z_Boson";
else if ( sampleID == kXeXe) return "Z_Boson";
else return "none";
}
#endif
| [
"jsjay@ucdavis.edu"
] | jsjay@ucdavis.edu |
85ac7502c0594462562a73ddf2ce38345530ce1f | 58d012e191990922d7e4f0bffde1263ca3347ed7 | /Code/Simulations/Full_Assembly_Model/build/src/compile_time.cc | 4113e92c858812b3cda314593e11a9e8b541c2fd | [] | no_license | OreUxio/Ecological_Mechanisms_Constraining_Attack_Rates | 33a8e903903640737f665dddd7509ca221e5d840 | 15628830602a208a4025c271798f38da04e42f18 | refs/heads/master | 2023-04-14T22:41:33.783714 | 2021-04-28T06:56:49 | 2021-04-28T06:56:49 | 293,066,906 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | cc | //$Id: compile_time.cc 2502 2017-02-27 17:35:59Z axel $
#include <string>
std::string compilation_time(__DATE__ ", " __TIME__);
| [
"ore@Ore.(none)"
] | ore@Ore.(none) |
10a87c5c072f17d0b316ee31d2ee5a71f87badd6 | 419ef403aa8fee77b0b3ec8d8fabe4b76a1e55ff | /Light/src/rendering/shader.cpp | 6f3d66e22b2b259d8f87a628fd6a6998a293c9b7 | [
"MIT"
] | permissive | Anon258/Light | 05387e5afc670849e2a77f2fb1187bf0d5537bb9 | 4531de6a14d796e8795d73e426e5aa31027d6e20 | refs/heads/main | 2023-05-04T01:53:13.280930 | 2021-05-17T11:57:44 | 2021-05-17T11:57:44 | 368,149,630 | 0 | 0 | MIT | 2021-05-17T10:45:31 | 2021-05-17T10:45:31 | null | UTF-8 | C++ | false | false | 1,039 | cpp | #include "rendering/shader.hpp"
namespace Light
{
void ShaderLibrary::add(const std::shared_ptr<Shader>& shader)
{
auto& name = shader->getName();
add(name, shader);
}
void ShaderLibrary::add(const std::string& name, const std::shared_ptr<Shader>& shader)
{
if(shaders.find(name) != shaders.end())
{
std::cerr << "Shader already exists!" << std::endl;
exit(1);
}
shaders[name] = shader;
}
std::shared_ptr<Shader> ShaderLibrary::load(const std::string& filepath)
{
std::shared_ptr<Shader> shader = Shader::create(filepath.c_str());
add(shader);
return shader;
}
std::shared_ptr<Shader> ShaderLibrary::load(const std::string& name, const std::string& filepath)
{
std::shared_ptr<Shader> shader = Shader::create(filepath.c_str());
add(name, shader);
return shader;
}
std::shared_ptr<Shader> ShaderLibrary::get(const std::string& name)
{
if(shaders.find(name) == shaders.end())
{
std::cerr << "Shader does not exist!" << std::endl;
exit(1);
}
return shaders[name];
}
} | [
"rwitaban0001@gmail.com"
] | rwitaban0001@gmail.com |
9a0a817161db5880fbe205e1e096c70fa3a2ea7c | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/locale/src/shared/ids.cpp | 99945f4c45cc3c3c81ea7a966df575b70525b1fe | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,681 | cpp | //
// Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#define BOOST_LOCALE_SOURCE
#include <sstd/boost/locale/boundary.hpp>
#include <sstd/boost/locale/collator.hpp>
#include <sstd/boost/locale/conversion.hpp>
#include <sstd/boost/locale/date_time_facet.hpp>
#include <sstd/boost/locale/message.hpp>
#include <sstd/boost/locale/info.hpp>
namespace boost {
namespace locale {
std::locale::id info::id;
std::locale::id calendar_facet::id;
std::locale::id converter<char>::id;
std::locale::id base_message_format<char>::id;
std::locale::id converter<wchar_t>::id;
std::locale::id base_message_format<wchar_t>::id;
#ifdef BOOST_LOCALE_ENABLE_CHAR16_T
std::locale::id converter<char16_t>::id;
std::locale::id base_message_format<char16_t>::id;
#endif
#ifdef BOOST_LOCALE_ENABLE_CHAR32_T
std::locale::id converter<char32_t>::id;
std::locale::id base_message_format<char32_t>::id;
#endif
namespace boundary {
std::locale::id boundary_indexing<char>::id;
std::locale::id boundary_indexing<wchar_t>::id;
#ifdef BOOST_LOCALE_ENABLE_CHAR16_T
std::locale::id boundary_indexing<char16_t>::id;
#endif
#ifdef BOOST_LOCALE_ENABLE_CHAR32_T
std::locale::id boundary_indexing<char32_t>::id;
#endif
}
namespace {
struct install_all {
install_all()
{
std::locale l = std::locale::classic();
install_by<char>();
install_by<wchar_t>();
#ifdef BOOST_LOCALE_ENABLE_CHAR16_T
install_by<char16_t>();
#endif
#ifdef BOOST_LOCALE_ENABLE_CHAR32_T
install_by<char32_t>();
#endif
std::has_facet<info>(l);
std::has_facet<calendar_facet>(l);
}
template<typename Char>
void install_by()
{
std::locale l = std::locale::classic();
std::has_facet<boundary::boundary_indexing<Char> >(l);
std::has_facet<converter<Char> >(l);
std::has_facet<base_message_format<Char> >(l);
}
} installer;
}
}
}
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
c7090a539b9e3425d8d1a263bb72c08bb1906100 | bf1f44544244f32c4b1cb80fac0e1a0e540720d8 | /Framework-EGC-master/Source/Laboratoare/Tema1/Tema1.cpp | 5da7fc45bdc45c56a509deb10f18d74ecb824b59 | [] | no_license | razvandorobantu98/EGC-Tema1 | b750bdc79665c60d5d6865a9e00a3b217add57d1 | 97f3296893094b2de2468f93dcd3f53c0fd69cdf | refs/heads/master | 2023-03-14T00:17:55.985862 | 2021-02-25T11:32:33 | 2021-02-25T11:32:33 | 342,220,850 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,868 | cpp | //Dorobantu Razvan-Florin, 335CB
#include "Tema1.h"
#include <vector>
#include <iostream>
#include <string>
#include <Core/Engine.h>
#include "Transformari2D.h"
#include "Obiecte2D.h"
using namespace std;
Tema1::Tema1() {
}
Tema1::~Tema1() {
}
void Tema1::Init() {
//seteaza camera
glm::ivec2 resolution = window->GetResolution();
auto camera = GetSceneCamera();
camera->SetOrthographic(0, (float)resolution.x, 0, (float)resolution.y, 0.01f, 400);
camera->SetPosition(glm::vec3(0, 0, 50));
camera->SetRotation(glm::vec3(0, 0, 0));
camera->Update();
GetCameraInput()->SetActive(false);
//construieste meshurile pasare
Mesh* head = Obiecte2D::CreateCircle("head", glm::vec3(0.95, 0.75, 0));
AddMeshToList(head);
Mesh* body = Obiecte2D::CreateCircle("body", glm::vec3(0.95, 0.75, 0));
AddMeshToList(body);
Mesh* eye = Obiecte2D::CreateCircle("eye", glm::vec3(0, 0, 0));
AddMeshToList(eye);
Mesh* beak = Obiecte2D::CreateTriangle("beak", glm::vec3(1, 0, 0));
AddMeshToList(beak);
Mesh* tail = Obiecte2D::CreateTriangle("tail", glm::vec3(0.95, 0.75, 0));
AddMeshToList(tail);
//construieste meshurile obstacole
string meshNames[] = { "pipeGreen", "pipeBlue", "pipeRed", "pipeYellow", "pipePurple" };
glm::vec3 meshColors[] = { glm::vec3(0, 1, 0), glm::vec3(0, 0, 1), glm::vec3(1, 0, 0), glm::vec3(1, 1, 0), glm::vec3(1, 0, 1) };
for (int i = 0; i < 5; i++) {
Mesh* mesh = Obiecte2D::CreateSquare(meshNames[i], meshColors[i]);
AddMeshToList(mesh);
}
string meshNames2[] = { "pipeGreen2", "pipeBlue2", "pipeRed2", "pipeYellow2", "pipePurple2" };
glm::vec3 meshColors2[] = { glm::vec3(0, 0.5, 0), glm::vec3(0, 0, 0.5), glm::vec3(0.5, 0, 0), glm::vec3(1, 0.5, 0), glm::vec3(0.5, 0, 0.5) };
for (int i = 0; i < 5; i++) {
Mesh* mesh = Obiecte2D::CreateSquare(meshNames2[i], meshColors2[i]);
AddMeshToList(mesh);
}
//seteaza valorile initiale
windowHeight = 720;
windowWidth = 1280;
birdInitialX = windowWidth / 5;
birdInitialY = windowHeight / 2;
sectionWidth = 320;
firstStart = true;
scoreMax = 0;
printf("Press SPACE to start the game!\n");
}
void Tema1::startGame() {
//toate variabilele sut setate la valorile initiale
speed = 0;
position = 0;
listSections = { 0, 0, 0, 0, 0 };
listColors = { 0, 0, 0, 0, 0 };
listMoving = { 0, 0, 0, 0, 0 };
levelPosition = 200;
pipeDirection = true;
gameSpeed = 0;
score = 0;
passed = false;
//porneste jocul
gameRunning = true;
printf("Start Game!\n\n");
}
void Tema1::endGame() {
//se opreste jocul si se afiseaza scorul
gameRunning = false;
if(scoreMax < score)
scoreMax = score;
printf("Game Over!\n");
printf("Your score is: %d. Best score: %d.\n", score, scoreMax);
printf("Press Space to try again.\n\n");
}
void Tema1::FrameStart() {
glClearColor(0.4, 0.7, 1, 0.5); //seteaza culoarea
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::ivec2 resolution = window->GetResolution();
glViewport(0, 0, resolution.x, resolution.y);
}
void Tema1::Update(float deltaTimeSeconds) {
glm::ivec2 resolution = window->GetResolution();
//creeaza matricea de rotatie
rotationMatrix = glm::mat3(1);
if (speed > 0) {
rotationMatrix *= Transformari2D::Translate(birdInitialX - 20, birdInitialY) * Transformari2D::Rotate(0.5) * Transformari2D::Translate(-birdInitialX + 20, -birdInitialY);
}
else if (speed < 0) {
rotationMatrix *= Transformari2D::Translate(birdInitialX - 20, birdInitialY) * Transformari2D::Rotate(-0.5) * Transformari2D::Translate(-birdInitialX + 20, -birdInitialY);
}
//transformari ochi
modelMatrix = glm::mat3(1);
modelMatrix *= Transformari2D::Translate(0, position);
modelMatrix *= rotationMatrix;
modelMatrix *= Transformari2D::Translate(birdInitialX - 5, birdInitialY);
modelMatrix *= Transformari2D::Scale(3, 3);
RenderMesh2D(meshes["eye"], shaders["VertexColor"], modelMatrix);
//transformari cap
modelMatrix = glm::mat3(1);
modelMatrix *= Transformari2D::Translate(0, position);
modelMatrix *= rotationMatrix;
modelMatrix *= Transformari2D::Translate(birdInitialX - 10, birdInitialY);
modelMatrix *= Transformari2D::Scale(15, 15);
RenderMesh2D(meshes["head"], shaders["VertexColor"], modelMatrix);
//transformari corp
modelMatrix = glm::mat3(1);
modelMatrix *= Transformari2D::Translate(0, position);
modelMatrix *= rotationMatrix;
modelMatrix *= Transformari2D::Translate(birdInitialX - 30, birdInitialY);
modelMatrix *= Transformari2D::Scale(20, 20);
RenderMesh2D(meshes["body"], shaders["VertexColor"], modelMatrix);
//transformari cioc
modelMatrix = glm::mat3(1);
modelMatrix *= Transformari2D::Translate(0, position);
modelMatrix *= rotationMatrix;
modelMatrix *= Transformari2D::Translate(birdInitialX, birdInitialY);
modelMatrix *= Transformari2D::Scale(20, 20);
RenderMesh2D(meshes["beak"], shaders["VertexColor"], modelMatrix);
//transformari coada
modelMatrix = glm::mat3(1);
modelMatrix *= Transformari2D::Translate(0, position);
modelMatrix *= rotationMatrix;
modelMatrix *= Transformari2D::Translate(birdInitialX - 60, birdInitialY);
modelMatrix *= Transformari2D::Scale(20, 20);
RenderMesh2D(meshes["tail"], shaders["VertexColor"], modelMatrix);
if (gameRunning == true) {
//modifica factorul de translatie
position += speed * deltaTimeSeconds;
//daca ajung in marginea de sus a ecranului, nu mai sar
if (position > windowHeight - birdInitialY - 20) {
position = windowHeight - birdInitialY - 20;
}
//daca am cazut sub marginea de jos a ecranului, jocul se termina
else if (position < -birdInitialY + 15) {
endGame();
}
//scade viteza
speed -= 850 * deltaTimeSeconds;
//modifica pozitia obstacolelor
levelPosition -= (300 + gameSpeed) * deltaTimeSeconds;
//daca primul obstacol din stanga a iesit din ecran
if (levelPosition + 75 < 0) {
//creeaza un nou obstacol cu o noua dimensiue
levelPosition += sectionWidth;
listSections.pop_front();
int i = rand() % ((int)(windowHeight / 2));
listSections.push_back(i);
//creeaza culoarea obstacolului
listColors.pop_front();
i = rand() % 5;
listColors.push_back(i);
//creeaza obstacol glisant
listMoving.pop_front();
i = rand() % 2;
listMoving.push_back(i);
//creste scorul
passed = false;
}
//calculeaza factorul de translatie pentru obstacolele glisante
if(pipeDirection == true) {
if (deltaYpipe < -25)
pipeDirection = false;
else
deltaYpipe -= 50 * deltaTimeSeconds;
}
else {
if (deltaYpipe > 25)
pipeDirection = true;
else
deltaYpipe += 50 * deltaTimeSeconds;
}
}
//copiaza listele in vectori pentru a accesa mai usor elementele
std::copy(listSections.begin(), listSections.end(), dimensions);
std::copy(listColors.begin(), listColors.end(), colors);
std::copy(listMoving.begin(), listMoving.end(), moving);
//transformari obstacole
for (int i = 0; i < listSections.size(); i++) {
//daca exista obstacol (inaltimea diferita de 0)
if (dimensions[i] != 0) {
//alege culoarea obstacolului
numePipe = "pipe";
if (colors[i] == 0)
numePipe.append("Green");
else if (colors[i] == 1)
numePipe.append("Blue");
else if (colors[i] == 2)
numePipe.append("Red");
else if (colors[i] == 3)
numePipe.append("Yellow");
else if (colors[i] == 4)
numePipe.append("Purple");
numePipe2 = numePipe;
numePipe2.append("2");
//daca obstacolul e glisant, retine factorul de translatie
delta = 0;
if(moving[i] == 1)
delta = deltaYpipe;
//creeaza marginea obstacolului de sus (capacul)
modelMatrix = glm::mat3(1);
modelMatrix *= Transformari2D::Translate(levelPosition + sectionWidth * i - 5, windowHeight - dimensions[i] + 15 + delta);
modelMatrix *= Transformari2D::Scale(85, -15);
RenderMesh2D(meshes[numePipe2], shaders["VertexColor"], modelMatrix);
//creeaza obstacolul de sus
modelMatrix = glm::mat3(1);
modelMatrix *= Transformari2D::Translate(levelPosition + sectionWidth * i, windowHeight);
modelMatrix *= Transformari2D::Scale(75, -dimensions[i] + delta);
RenderMesh2D(meshes[numePipe], shaders["VertexColor"], modelMatrix);
//creeaza marginea obstacolului de jos (capacul)
modelMatrix = glm::mat3(1);
modelMatrix *= Transformari2D::Translate(levelPosition + sectionWidth * i - 5, windowHeight / 2 - dimensions[i] + 15 - delta);
modelMatrix *= Transformari2D::Scale(85, -15);
RenderMesh2D(meshes[numePipe2], shaders["VertexColor"], modelMatrix);
//creeaza obstacolul de jos cu complementul dimensiunii
modelMatrix = glm::mat3(1);
modelMatrix *= Transformari2D::Translate(levelPosition + sectionWidth * i, 0);
modelMatrix *= Transformari2D::Scale(75, windowHeight / 2 - dimensions[i] - delta);
RenderMesh2D(meshes[numePipe], shaders["VertexColor"], modelMatrix);
}
}
if (gameRunning == true) {
//detecteaza coliziunea (daca primul obstacol are dimensiunea diferita de 0)
if(dimensions[0] != 0) {
//verifica daca obstacolul e glisant si retine factorl de translatie
delta = 0;
if (moving[0] == 1)
delta = deltaYpipe;
//verifica daca obstacolul a ajuns in dreptul pasarii (pe aza OY)
if (levelPosition < birdInitialX && levelPosition + 75 > birdInitialX - 60) {
//daca pasarea se loveste de obstacolul de sus, jocul se termina
if (birdInitialY + position > windowHeight - dimensions[0] - 20 + delta)
endGame();
//daca pasarea se loveste de obstacolul de jos, jocul se termina
else if (birdInitialY + position < windowHeight / 2 - dimensions[0] + 20 - delta)
endGame();
}
}
//daca pasarea trece de un obstacol, creste scorul si viteza jocului
if(passed == false && levelPosition + 75 < birdInitialX - 60 && dimensions[0] != 0) {
score++;
passed = true; //retine ca am crescut deja scorul
printf("Score: %d\n", score);
gameSpeed = 5 * score;
if (gameSpeed > 150)
gameSpeed == 150; //viteza creste pana la o limita
}
}
}
void Tema1::FrameEnd() {
}
void Tema1::OnInputUpdate(float deltaTime, int mods) {
}
void Tema1::OnKeyRelease(int key, int mods) {
}
void Tema1::OnKeyPress(int key, int mods) {
if (key == GLFW_KEY_SPACE) {
//daca abia am deschis jocul, acesta incepe la apasarea tastei space
if (firstStart == true) {
startGame();
firstStart = false;
}
//daca jocul ruleaza deja, pasarea sare
else if (gameRunning == true) {
speed = 350;
}
//daca jocul s-a terminat, incepe din nou la apasarea tastei space
else {
startGame();
}
}
}
void Tema1::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY) {
}
void Tema1::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods) {
}
void Tema1::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods) {
}
void Tema1::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY) {
}
void Tema1::OnWindowResize(int width, int height) {
}
| [
"68380239+razvandorobantu98@users.noreply.github.com"
] | 68380239+razvandorobantu98@users.noreply.github.com |
6663cf1e2ff3148184ab2f96693a01694827cd95 | a1f8c89e7bae66563ffd4300d7d46fc6e4bc2625 | /Lab4/Shapes/Shapes/CShape.h | 6db04306a074e7607d01c69700486fc86534b8c3 | [] | no_license | Reywam/OOP | b3078d2a2ebefbf935615d9126ead554dfb4b7c5 | 1c5e7446a8acc6e80eb0b832f04d194f555b876a | refs/heads/master | 2021-01-13T07:49:24.642059 | 2017-01-19T07:22:45 | 2017-01-19T07:22:45 | 71,701,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 377 | h | #pragma once
#include <string>
#include "IShape.h"
class CShape : public virtual IShape
{
public:
CShape() = default;
CShape(std::string color);
~CShape() = default;
virtual double GetArea()const = 0;
virtual double GetPerimeter()const = 0;
virtual std::string ToString()const = 0;
virtual std::string GetOutlineColor()const;
private:
std::string m_outlineColor;
}; | [
"reywam@mail.ru"
] | reywam@mail.ru |
61728db5e0d3df4ef611e642537bfe3bcb9f0564 | d2de4a06e65dae51dcb2d9cf445f6138cab9ba27 | /src/Spgrwise.cpp | 310864a1ddc844e773773a6e34aa69ee8949afa9 | [] | no_license | wangx23/Spgr | e44a8e84777fcf66f4bb145f38f2c2a80444c298 | 29f984fb6d46c9bd9f5ab82306b1e50616083527 | refs/heads/master | 2022-05-01T16:18:51.656476 | 2022-03-15T02:58:51 | 2022-03-15T02:58:51 | 130,878,830 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,791 | cpp | #include <RcppArmadillo.h>
#include "functions.hpp"
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
Rcpp::List Spgrwise_lasso(arma::vec &y, arma::mat &z, arma::mat &x,
arma::vec &weights, arma::mat &betam0,
double nu = 1 , double lam = 0.5 ,
int maxiter = 1000, double tolabs = 1e-4, double tolrel = 1e-2)
{
int n = x.n_rows;
int p = x.n_cols;
int n0 = n*p;
int npair = n*(n-1)/2;
arma::mat Ip = eye(p,p);
arma::sp_mat Dmat = Dfun(n);
arma::mat ztz = inv(z.t() * z) * z.t();
arma::vec Xty = reshape(trans(x.each_col() % y -
x.each_col() %(z*ztz *y)), n0 , 1);
arma::mat Xinv = inverse(x,z,nu);
arma::mat reg1 = Xinv * Xty;
// initial deltam
arma::mat deltam(p,npair);
arma::mat deltamold(p, npair);
arma::mat betadiff(p,npair);
arma::mat vm = zeros(p,npair);
deltamold = trans(Dmat * betam0);
// define some varaibles
arma::vec temp = zeros<vec>(n0);
arma::vec betanew = zeros<vec>(n0);
arma::mat betam = zeros(n,p);
arma::vec normbd(2);
arma::umat group(n,p);
int flag = 0;
double rm = 1;
double sm = 1;
double tolpri;
double toldual;
int m = 0;
for( m = 0; m < maxiter; m++)
{
temp = reshape((deltamold - 1/nu * vm)*Dmat,n0,1);
betanew = reg1 + nu*Xinv * temp;
betam = trans(reshape(betanew, p, n));
betadiff = trans(Dmat * betam);
deltam = betadiff + (1/nu) * vm;
// update deltam
for(int i = 0; i < npair; i++)
{
for(int l = 0; l < p; l++)
{
deltam(l,i) = nsfun(deltam(l,i),weights(i)*lam);
}
}
vm = vm + nu * (betadiff - deltam);
normbd(0) = norm(betadiff,"fro");
normbd(1) = norm(deltam,"fro");
tolpri = tolabs*sqrt(npair*p) + tolrel*max(normbd);
toldual = tolabs*sqrt(n * p) + tolrel * norm(vm * Dmat, "fro");
rm = norm(betadiff - deltam, "fro");
sm = nu * norm((deltam - deltamold)*Dmat, "fro");
deltamold = deltam;
if(rm <= tolpri & sm <= toldual)
break;
}
if(m == maxiter) {flag = 1;}
arma::vec yhat = sum(x % betam,1);
arma::vec eta = ztz * (y - yhat);
// change deltam
deltam = deltam.t();
for(int l=0;l <p; l++)
{
group.col(l) = ngetgroup(deltam.col(l),n,tolabs);
}
double sig2 = sum(square(y - z * eta - yhat))/n;
return Rcpp::List::create(Named("beta") = betam,
Named("eta") = eta,
Named("sig2") = sig2,
Named("group") = group,
Named("deltam") = deltam,
Named("flag") = flag,
Named("rm") = rm,
Named("sm") = sm,
Named("tolpri") = tolpri,
Named("toldual") = toldual,
Named("niteration") = m);
}
// [[Rcpp::export]]
Rcpp::List Spgrwise_scad(arma::vec &y, arma::mat &z, arma::mat &x,
arma::vec &weights, arma::mat &betam0,
double nu = 1, double gam =3 , double lam = 0.5 ,
int maxiter = 1000, double tolabs = 1e-4, double tolrel = 1e-2)
{
int n = x.n_rows;
int p = x.n_cols;
int n0 = n*p;
int npair = n*(n-1)/2;
arma::mat Ip = eye(p,p);
arma::sp_mat Dmat = Dfun(n);
arma::mat ztz = inv(z.t() * z) * z.t();
arma::vec Xty = reshape(trans(x.each_col() % y -
x.each_col() %(z*ztz *y)), n0 , 1);
arma::mat Xinv = inverse(x,z,nu);
arma::mat reg1 = Xinv * Xty;
// initial deltam
arma::mat deltam(p,npair);
arma::mat deltamold(p, npair);
arma::mat betadiff(p,npair);
arma::mat vm = zeros(p,npair);
deltamold = trans(Dmat * betam0);
// define some varaibles
arma::vec temp = zeros<vec>(n0);
arma::vec betanew = zeros<vec>(n0);
arma::mat betam = zeros(n,p);
arma::vec normbd(2);
arma::umat group(n,p);
int flag = 0;
double rm = 1;
double sm = 1;
double tolpri;
double toldual;
int m = 0;
for( m = 0; m < maxiter; m++)
{
temp = reshape((deltamold - 1/nu * vm)*Dmat,n0,1);
betanew = reg1 + nu*Xinv * temp;
betam = trans(reshape(betanew, p, n));
betadiff = trans(Dmat * betam);
deltam = betadiff + (1/nu) * vm;
// update deltam
for(int i = 0; i < npair; i++)
{
for(int l = 0; l < p; l++)
{
deltam(l,i) = nscad(deltam(l,i),weights(i)*lam,nu,gam);
}
}
vm = vm + nu * (betadiff - deltam);
normbd(0) = norm(betadiff,"fro");
normbd(1) = norm(deltam,"fro");
tolpri = tolabs*sqrt(npair*p) + tolrel*max(normbd);
toldual = tolabs*sqrt(n * p) + tolrel * norm(vm * Dmat, "fro");
rm = norm(betadiff - deltam, "fro");
sm = nu * norm((deltam - deltamold)*Dmat, "fro");
deltamold = deltam;
if(rm <= tolpri & sm <= toldual)
break;
}
if(m == maxiter) {flag = 1;}
arma::vec yhat = sum(x % betam,1);
arma::vec eta = ztz * (y - yhat);
// change deltam
deltam = deltam.t();
for(int l=0;l <p; l++)
{
group.col(l) = ngetgroup(deltam.col(l),n,tolabs);
}
double sig2 = sum(square(y - z * eta - yhat))/n;
return Rcpp::List::create(Named("beta") = betam,
Named("eta") = eta,
Named("sig2") = sig2,
Named("group") = group,
Named("deltam") = deltam,
Named("flag") = flag,
Named("rm") = rm,
Named("sm") = sm,
Named("tolpri") = tolpri,
Named("toldual") = toldual,
Named("niteration") = m);
}
| [
"wangx172@STAXWang172MBP2.local"
] | wangx172@STAXWang172MBP2.local |
5ee2347a6588a79bfe795511da6f1bcc70f8ddce | 48222f972068733466e932b3043e81f060555a0d | /nachos-3.4/code/userprog/addrspace.cc | 1f79a115af74ea9347ab043a6d9b04b2f92da910 | [
"MIT-Modern-Variant"
] | permissive | ThanhHuong98/NachosProject | 7ff87f11ab661b525a15f9ce36c9a36625d0359c | 3ca9aa6e7017c4f01c04c6ea865cc173edb86edc | refs/heads/master | 2020-04-04T11:53:32.559510 | 2018-11-16T15:56:13 | 2018-11-16T15:56:13 | 155,906,903 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,016 | cc | // addrspace.cc
// Routines to manage address spaces (executing user programs).
//
// In order to run a user program, you must:
//
// 1. link with the -N -T 0 option
// 2. run coff2noff to convert the object file to Nachos format
// (Nachos object code format is essentially just a simpler
// version of the UNIX executable object code format)
// 3. load the NOFF file into the Nachos file system
// (if you haven't implemented the file system yet, you
// don't need to do this last step)
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#include "system.h"
#include "addrspace.h"
#include "noff.h"
#ifdef HOST_SPARC
#include <strings.h>
#endif
//----------------------------------------------------------------------
// SwapHeader
// Do little endian to big endian conversion on the bytes in the
// object file header, in case the file was generated on a little
// endian machine, and we're now running on a big endian machine.
//----------------------------------------------------------------------
static void
SwapHeader (NoffHeader *noffH)
{
noffH->noffMagic = WordToHost(noffH->noffMagic);
noffH->code.size = WordToHost(noffH->code.size);
noffH->code.virtualAddr = WordToHost(noffH->code.virtualAddr);
noffH->code.inFileAddr = WordToHost(noffH->code.inFileAddr);
noffH->initData.size = WordToHost(noffH->initData.size);
noffH->initData.virtualAddr = WordToHost(noffH->initData.virtualAddr);
noffH->initData.inFileAddr = WordToHost(noffH->initData.inFileAddr);
noffH->uninitData.size = WordToHost(noffH->uninitData.size);
noffH->uninitData.virtualAddr = WordToHost(noffH->uninitData.virtualAddr);
noffH->uninitData.inFileAddr = WordToHost(noffH->uninitData.inFileAddr);
}
//----------------------------------------------------------------------
// AddrSpace::AddrSpace
// Create an address space to run a user program.
// Load the program from a file "executable", and set everything
// up so that we can start executing user instructions.
//
// Assumes that the object code file is in NOFF format.
//
// First, set up the translation from program memory to physical
// memory. For now, this is really simple (1:1), since we are
// only uniprogramming, and we have a single unsegmented page table
//
// "executable" is the file containing the object code to load into memory
//----------------------------------------------------------------------
AddrSpace::AddrSpace(OpenFile *executable)
{
NoffHeader noffH;
unsigned int i, size;
executable->ReadAt((char *)&noffH, sizeof(noffH), 0);
if ((noffH.noffMagic != NOFFMAGIC) &&
(WordToHost(noffH.noffMagic) == NOFFMAGIC))
SwapHeader(&noffH);
ASSERT(noffH.noffMagic == NOFFMAGIC);
// how big is address space?
size = noffH.code.size + noffH.initData.size + noffH.uninitData.size
+ UserStackSize; // we need to increase the size
// to leave room for the stack
numPages = divRoundUp(size, PageSize);
size = numPages * PageSize;
ASSERT(numPages <= NumPhysPages); // check we're not trying
// to run anything too big --
// at least until we have
// virtual memory
DEBUG('a', "Initializing address space, num pages %d, size %d\n",
numPages, size);
// first, set up the translation
pageTable = new TranslationEntry[numPages];
for (i = 0; i < numPages; i++) {
pageTable[i].virtualPage = i; // for now, virtual page # = phys page #
pageTable[i].physicalPage = i;
pageTable[i].valid = TRUE;
pageTable[i].use = FALSE;
pageTable[i].dirty = FALSE;
pageTable[i].readOnly = FALSE; // if the code segment was entirely on
// a separate page, we could set its
// pages to be read-only
}
// zero out the entire address space, to zero the unitialized data segment
// and the stack segment
bzero(machine->mainMemory, size);
// then, copy in the code and data segments into memory
if (noffH.code.size > 0) {
DEBUG('a', "Initializing code segment, at 0x%x, size %d\n",
noffH.code.virtualAddr, noffH.code.size);
executable->ReadAt(&(machine->mainMemory[noffH.code.virtualAddr]),
noffH.code.size, noffH.code.inFileAddr);
}
if (noffH.initData.size > 0) {
DEBUG('a', "Initializing data segment, at 0x%x, size %d\n",
noffH.initData.virtualAddr, noffH.initData.size);
executable->ReadAt(&(machine->mainMemory[noffH.initData.virtualAddr]),
noffH.initData.size, noffH.initData.inFileAddr);
}
}
//----------------------------------------------------------------------
// AddrSpace::~AddrSpace
// Dealloate an address space. Nothing for now!
//----------------------------------------------------------------------
AddrSpace::~AddrSpace()
{
delete pageTable;
}
//----------------------------------------------------------------------
// AddrSpace::InitRegisters
// Set the initial values for the user-level register set.
//
// We write these directly into the "machine" registers, so
// that we can immediately jump to user code. Note that these
// will be saved/restored into the currentThread->userRegisters
// when this thread is context switched out.
//----------------------------------------------------------------------
void
AddrSpace::InitRegisters()
{
int i;
for (i = 0; i < NumTotalRegs; i++)
machine->WriteRegister(i, 0);
// Initial program counter -- must be location of "Start"
machine->WriteRegister(PCReg, 0);
// Need to also tell MIPS where next instruction is, because
// of branch delay possibility
machine->WriteRegister(NextPCReg, 4);
// Set the stack register to the end of the address space, where we
// allocated the stack; but subtract off a bit, to make sure we don't
// accidentally reference off the end!
machine->WriteRegister(StackReg, numPages * PageSize - 16);
DEBUG('a', "Initializing stack register to %d\n", numPages * PageSize - 16);
}
//----------------------------------------------------------------------
// AddrSpace::SaveState
// On a context switch, save any machine state, specific
// to this address space, that needs saving.
//
// For now, nothing!
//----------------------------------------------------------------------
void AddrSpace::SaveState()
{}
//----------------------------------------------------------------------
// AddrSpace::RestoreState
// On a context switch, restore the machine state so that
// this address space can run.
//
// For now, tell the machine where to find the page table.
//----------------------------------------------------------------------
void AddrSpace::RestoreState()
{
machine->pageTable = pageTable;
machine->pageTableSize = numPages;
}
| [
"nguyenkhacnguyenkhang@gmail.com"
] | nguyenkhacnguyenkhang@gmail.com |
0ede071db067a2dc115abf44f8c0b8b2eb28f7cf | f9cdbdfc77950fc83d346c242500ed70d2fe196a | /Binary_search/ceil_value_of_ele.cpp | f341c8727a3f801c797ab2b1cd77bfbe1c7c50d9 | [] | no_license | Aarti002/First-git-project | 38c63df1765d7100a90c8f7372125f1557b38f4a | 34c2888ceb5d6841559f3b273b481875ace02afa | refs/heads/master | 2023-02-08T08:28:53.406049 | 2020-12-31T07:09:10 | 2020-12-31T07:09:10 | 295,241,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 539 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <bits/stdc++.h>
using namespace std;
int binaryscr_floor(int a[],int n,int x)
{
int mid,st=0,end=n-1;
int mx=INT_MAX;
while(st<=end)
{
mid=(st+end)/2;
if(a[mid]==x)
return a[mid];
else if(a[mid]>x){
mx=min(a[mid],mx);
end=mid-1;}
else{
st=mid+1;}
}
return mx;
}
int main()
{
int n,i;
cin>>n;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
int ele;
cin>>ele;
int ans=binaryscr_floor(a,n,ele);
cout<<ans<<endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
fe217fd31fb1acbc542ab20de0fd3aa0dd3f0ca7 | 3de68f5ae52ac02c8ec5bcaef78772e295ec0c8c | /external/chromium/net/disk_cache/stat_hub_api.cc | 0dd47039a4c390e420b9bdcd2ee74e53d2bb5a8e | [
"BSD-3-Clause"
] | permissive | abgoyal-archive/OT_996_ICS_20130220 | af9a005b81e072d2f6645ab342ed86765892ad1f | 133bec8851e9ef588398b04adcb69c79a3e9cbd7 | refs/heads/master | 2022-04-05T17:43:05.284149 | 2015-02-08T00:19:33 | 2015-02-08T00:19:33 | 30,475,398 | 0 | 2 | null | 2020-03-07T00:30:34 | 2015-02-08T00:18:52 | C | UTF-8 | C++ | false | false | 12,020 | cc | /** ---------------------------------------------------------------------------
Copyright (c) 2011, Code Aurora Forum. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Code Aurora Forum, Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
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 <unistd.h>
#include <string>
#include <cutils/properties.h>
#include "build/build_config.h"
#include "googleurl/src/gurl.h"
#include "base/compiler_specific.h"
#include "base/task.h"
#include "base/memory/ref_counted.h"
#include "base/threading/thread.h"
#include "net/base/completion_callback.h"
#include "net/base/net_log.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/base/load_flags.h"
#include "net/base/io_buffer.h"
#include "net/disk_cache/hash.h"
#if defined(STAT_HUB_PRECONNECT_ENABLED)
#include "net/http/preconnect.h"
#endif //defined(STAT_HUB_PRECONNECT_ENABLED)
#include "net/http/http_cache_transaction.h"
#include "net/http/http_request_info.h"
#include "net/http/http_request_headers.h"
#include "stat_hub.h"
#include "stat_hub_api.h"
#define READ_BUF_SIZE (50*1024)
class FetchRequest {
public:
explicit FetchRequest(std::string& dest, std::string& headers):
dest_(dest),
headers_(headers),
ALLOW_THIS_IN_INITIALIZER_LIST(start_callback_(this, &FetchRequest::OnStartComplete)),
ALLOW_THIS_IN_INITIALIZER_LIST(read_callback_(this, &FetchRequest::OnReadComplete)),
read_in_progress_(false),
buf_(NULL){
}
void StartFetch(net::HttpCache* cache){
request_info_.reset(new net::HttpRequestInfo());
if(StatHubIsVerboseEnabled()) {
LOG(INFO) << "Fetch: " << dest_.spec().c_str();
}
request_info_->url = dest_;
request_info_->motivation = net::HttpRequestInfo::PRECONNECT_MOTIVATED;
request_info_->priority = net::LOWEST;
request_info_->method = net::HttpRequestHeaders::kGetMethod;
request_info_->load_flags |= net::LOAD_PREFETCH;
request_info_->extra_headers.AddHeadersFromString(headers_);
int rv = cache->CreateTransaction(&trans_);
rv = trans_->Start(request_info_.get(), &start_callback_, net::BoundNetLog());
if (rv != net::ERR_IO_PENDING) {
delete this;
}
}
private:
virtual ~FetchRequest() {
}
void Read() {
int rv = trans_->Read(buf_, READ_BUF_SIZE, &read_callback_);
if (rv >= 0) {
delete this;
}
else {
if (rv == net::ERR_IO_PENDING) {
read_in_progress_ = true;
}
else {
LOG(INFO) << "FetchRequest::Read : ERROR " << rv << ":" << dest_.spec().c_str();
delete this;
}
}
}
void OnStartComplete(int error_code) {
if (error_code == net::OK) {
buf_ = new net::IOBuffer(READ_BUF_SIZE);
Read();
}
else {
LOG(INFO) << "FetchRequest::OnStartComplete : ERROR " << error_code << ":" << dest_.spec().c_str();
delete this;
}
}
void OnReadComplete(int error_code) {
read_in_progress_ = false;
if (error_code == net::OK) {
delete this;
}
else {
Read();
}
}
GURL dest_;
std::string headers_;
scoped_ptr<net::HttpRequestInfo> request_info_;
scoped_ptr<net::HttpTransaction> trans_;
net::CompletionCallbackImpl<FetchRequest> start_callback_;
net::CompletionCallbackImpl<FetchRequest> read_callback_;
bool read_in_progress_;
scoped_refptr<net::IOBuffer> buf_;
DISALLOW_COPY_AND_ASSIGN(FetchRequest);
};
static void DoPreconnect(net::HttpCache* cache, std::string* dest, uint32 count) {
if(StatHubIsVerboseEnabled()) {
LOG(INFO) << "Preconnect: " << dest->c_str() << " : " << count;
}
if (NULL!=cache) {
net::HttpNetworkSession* session = cache->GetSession();
if (NULL!=session) {
#if defined(STAT_HUB_PRECONNECT_ENABLED)
net::Preconnect::DoPreconnect(session, GURL(*dest), count);
#endif //defined(STAT_HUB_PRECONNECT_ENABLED)
}
}
delete dest;
}
static void DoFetch(net::HttpCache* cache, std::string* dest, std::string* headers) {
FetchRequest* fetch = new FetchRequest(*dest, *headers);
fetch->StartFetch(cache);
delete dest;
delete headers;
}
// ======================================= Exports ==============================================
bool StatHubIsVerboseEnabled() {
return stat_hub::StatHub::GetInstance()->IsVerboseEnabled();
}
StatHubVerboseLevel StatHubGetVerboseLevel() {
return stat_hub::StatHub::GetInstance()->GetVerboseLevel();
}
base::Time StatHubGetSystemTime() {
return base::Time::NowFromSystemTime();
}
int StatHubGetTimeDeltaInMs(const base::Time& start_time, const base::Time& finish_time) {
base::TimeDelta delta = finish_time - start_time;
return (int)delta.InMilliseconds(); //int64
}
const char* StatHubGetHostFromUrl(std::string& url, std::string& host) {
GURL dest(url);
host = dest.GetOrigin().spec();
return host.c_str();
}
unsigned int StatHubHash(const char* str) {
return disk_cache::Hash(str, strlen(str));
}
void StatHubPreconnect(MessageLoop* message_loop, net::HttpCache* cache, const char* url, uint32 count) {
message_loop->PostTask(FROM_HERE, NewRunnableFunction(&DoPreconnect, cache, new std::string(url), count));
}
void StatHubFetch(MessageLoop* message_loop, net::HttpCache* cache, const char* url, const char* headers) {
message_loop->PostTask(FROM_HERE, NewRunnableFunction(&DoFetch, cache, new std::string(url), new std::string(headers)));
}
bool StatHubGetDBmetaData(const char* key, std::string& val) {
return stat_hub::StatHub::GetInstance()->GetDBmetaData(key, val);
}
bool StatHubSetDBmetaData(const char* key, const char* val) {
return stat_hub::StatHub::GetInstance()->SetDBmetaData(key, val);
}
net::HttpCache* StatHubGetHttpCache() {
return stat_hub::StatHub::GetInstance()->GetHttpCache();
}
// ================================ StatHub SQL Interface ====================================
bool StatHubBeginTransaction(sql::Connection* db) {
return db->BeginTransaction();
}
bool StatHubCommitTransaction(sql::Connection* db) {
return db->CommitTransaction();
}
bool StatHubDoesTableExist(sql::Connection* db, const char* table_name) {
return db->DoesTableExist(table_name);
}
bool StatHubExecute(sql::Connection* db, const char* sql) {
return db->Execute(sql);
}
sql::Statement* StatHubGetStatement(sql::Connection* db, const sql::StatementID& id, const char* sql) {
if(NULL!=db && NULL!=sql) {
return new sql::Statement(db->GetCachedStatement(id, sql));
}
return NULL;
}
void StatHubReleaseStatement(sql::Statement* st) {
if (NULL!=st) {
delete st;
}
}
bool StatHubStatementStep(sql::Statement* st) {
if (NULL!=st) {
return st->Step();
}
return false;
}
bool StatHubStatementRun(sql::Statement* st) {
if (NULL!=st) {
return st->Run();
}
return false;
}
void StatHubStatementReset(sql::Statement* st) {
if (NULL!=st) {
st->Reset();
}
}
int StatHubStatementColumnInt(sql::Statement* st, int col) {
if (NULL!=st) {
return st->ColumnInt(col);
}
return 0;
}
int64 StatHubStatementColumnInt64(sql::Statement* st, int col) {
if (NULL!=st) {
return st->ColumnInt64(col);
}
return 0;
}
bool StatHubStatementColumnBool(sql::Statement* st, int col) {
if (NULL!=st) {
return st->ColumnBool(col);
}
return false;
}
std::string StatHubStatementColumnString(sql::Statement* st, int col) {
if (NULL!=st) {
return st->ColumnString(col);
}
return std::string("");
}
bool StatHubStatementBindInt(sql::Statement* st, int col, int val) {
if (NULL!=st) {
return st->BindInt(col, val);
}
return false;
}
bool StatHubStatementBindInt64(sql::Statement* st, int col, int64 val) {
if (NULL!=st) {
return st->BindInt64(col, val);
}
return false;
}
bool StatHubStatementBindBool(sql::Statement* st, int col, bool val) {
if (NULL!=st) {
return st->BindBool(col, val);
}
return false;
}
bool StatHubStatementBindCString(sql::Statement* st, int col, const char* val) {
if (NULL!=st) {
return st->BindCString(col, val);
}
return false;
}
// ============================ StatHub Functional Interface Proxies ===============================
void CmdProxy(StatHubTimeStamp timestamp, unsigned short cmd, void* param1, int sizeofparam1, void* param2, int sizeofparam2) {
stat_hub::StatHub::GetInstance()->Cmd(timestamp, cmd, param1, sizeofparam1, param2, sizeofparam2);
if (sizeofparam1) {
delete (char*)param1;
}
if (sizeofparam2) {
delete (char*)param2;
}
}
// ================================ StatHub Functional Interface ====================================
void StatHubCmd(unsigned short cmd, void* param1, int sizeofparam1, void* param2, int sizeofparam2){
unsigned int cmd_mask = stat_hub::StatHub::GetInstance()->GetCmdMask();
if (cmd>INPUT_CMD_USER_DEFINED || (cmd_mask&(1<<cmd))) {
// create persistence storage to safely pass data to another thread
char* tmp_param1 = (char*)param1;
char* tmp_param2 = (char*)param2;
if (sizeofparam1) {
tmp_param1 = new char[sizeofparam1];
memcpy(tmp_param1, param1, sizeofparam1);
}
if (sizeofparam2) {
tmp_param2 = new char[sizeofparam2];
memcpy(tmp_param2, param2, sizeofparam2);
}
if (stat_hub::StatHub::GetInstance()->IsReady()) {
stat_hub::StatHub::GetInstance()->GetThread()->message_loop()->PostTask( FROM_HERE, NewRunnableFunction(
&CmdProxy, base::Time::NowFromSystemTime(), cmd, (void*)tmp_param1, sizeofparam1, (void*)tmp_param2, sizeofparam2));
}
}
}
void StatHubUpdateMainUrl(const char* url) {
if(NULL!=url) {
StatHubCmd(INPUT_CMD_WK_MAIN_URL, (void*)url, strlen(url)+1, NULL, 0);
}
}
void StatHubUpdateSubUrl(const char* main_url, const char* sub_url) {
if(NULL!=main_url && NULL!=sub_url) {
StatHubCmd(INPUT_CMD_WK_SUB_URL_REQUEST, (void*)main_url, strlen(main_url)+1, (void*)sub_url, strlen(sub_url)+1);
}
}
void StatHubMainUrlLoaded(const char* url) {
if(NULL!=url) {
StatHubCmd(INPUT_CMD_WK_MAIN_URL_LOADED, (void*)url, strlen(url)+1, NULL, 0);
}
}
| [
"abgoyal@gmail.com"
] | abgoyal@gmail.com |
8740ed0aed8672e592fa4fdad8a2a9553ace004a | d985e64e82fb3a843cfa971d160ad7aa99819b99 | /Medusa_libraries/SdFat_Branch/IridiumSBD/src/IridiumSBD.cpp | 71ca1a7fc27229605769b90e14fec462bd789480 | [] | no_license | loggerhead-instruments/libraries | 8b106c812d905a0d9b135dd5f7278337a16afa81 | 1164cccfc35a2d9ba072e9f5e2989ad211cb3333 | refs/heads/master | 2022-09-15T17:55:30.098815 | 2022-08-22T20:19:51 | 2022-08-22T20:19:51 | 78,224,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,535 | cpp | /*
IridiumSBD - An Arduino library for Iridium SBD ("Short Burst Data") Communications
Suggested and generously supported by Rock Seven Location Technology
(http://rock7mobile.com), makers of the brilliant RockBLOCK satellite modem.
Copyright (C) 2013-2017 Mikal Hart
All rights reserved.
The latest version of this library is available at http://arduiniana.org.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TimeLib.h>
#include "IridiumSBD.h"
// Power on the RockBLOCK or return from sleep
int IridiumSBD::begin()
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalBegin();
this->reentrant = false;
// Absent a successful startup, keep the device turned off
if (ret != ISBD_SUCCESS)
power(false);
return ret;
}
// Transmit a binary message
int IridiumSBD::sendSBDBinary(const uint8_t *txData, size_t txDataSize)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalSendReceiveSBD(NULL, txData, txDataSize, NULL, NULL);
this->reentrant = false;
return ret;
}
// Transmit and receive a binary message
int IridiumSBD::sendReceiveSBDBinary(const uint8_t *txData, size_t txDataSize, uint8_t *rxBuffer, size_t &rxBufferSize)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalSendReceiveSBD(NULL, txData, txDataSize, rxBuffer, &rxBufferSize);
this->reentrant = false;
return ret;
}
// Transmit a text message
int IridiumSBD::sendSBDText(const char *message)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalSendReceiveSBD(message, NULL, 0, NULL, NULL);
this->reentrant = false;
return ret;
}
// Transmit a text message and receive reply
int IridiumSBD::sendReceiveSBDText(const char *message, uint8_t *rxBuffer, size_t &rxBufferSize)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalSendReceiveSBD(message, NULL, 0, rxBuffer, &rxBufferSize);
this->reentrant = false;
return ret;
}
// High-level wrapper for AT+CSQ
int IridiumSBD::getSignalQuality(int &quality)
{
if (this->reentrant)
return ISBD_REENTRANT;
this->reentrant = true;
int ret = internalGetSignalQuality(quality);
this->reentrant = false;
return ret;
}
// Gracefully put device to lower power mode (if sleep pin provided)
int IridiumSBD::sleep()
{
if (this->reentrant)
return ISBD_REENTRANT;
if (this->sleepPin == -1)
return ISBD_NO_SLEEP_PIN;
this->reentrant = true;
int ret = internalSleep();
this->reentrant = false;
if (ret == ISBD_SUCCESS)
power(false); // power off
return ret;
}
// Return sleep state
bool IridiumSBD::isAsleep()
{
return this->asleep;
}
// Return number of pending messages
int IridiumSBD::getWaitingMessageCount()
{
return this->remainingMessages;
}
// Define capacitor recharge times
void IridiumSBD::setPowerProfile(POWERPROFILE profile) // 0 = direct connect (default), 1 = USB
{
switch(profile)
{
case DEFAULT_POWER_PROFILE:
this->sbdixInterval = ISBD_DEFAULT_SBDIX_INTERVAL;
break;
case USB_POWER_PROFILE:
this->sbdixInterval = ISBD_USB_SBDIX_INTERVAL;
break;
}
}
// Tweak AT timeout
void IridiumSBD::adjustATTimeout(int seconds)
{
this->atTimeout = seconds;
}
// Tweak Send/Receive SBDIX process timeout
void IridiumSBD::adjustSendReceiveTimeout(int seconds)
{
this->sendReceiveTimeout = seconds;
}
void IridiumSBD::useMSSTMWorkaround(bool useWorkAround) // true to use workaround from Iridium Alert 5/7
{
this->msstmWorkaroundRequested = useWorkAround;
}
void IridiumSBD::enableRingAlerts(bool enable) // true to enable SBDRING alerts and RING signal pin
{
this->ringAlertsEnabled = enable;
if (enable)
this->ringAsserted = false;
}
bool IridiumSBD::hasRingAsserted()
{
if (!ringAlertsEnabled)
return false;
if (!reentrant)
{
// It's possible that the SBDRING message comes while we're not doing anything
filterSBDRING();
}
bool ret = ringAsserted;
ringAsserted = false;
return ret;
}
/*
int IridiumSBD::getSystemTime(struct tm &tm)
{
char msstmResponseBuf[24];
send(F("AT-MSSTM\r"));
if (!waitForATResponse(msstmResponseBuf, sizeof(msstmResponseBuf), "-MSSTM: "))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
if (!isxdigit(msstmResponseBuf[0]))
return ISBD_NO_NETWORK;
// Latest epoch began at May 11, 2014, at 14:23:55 UTC.
struct tm epoch_start;
epoch_start.tm_year = 2014 - 1900;
epoch_start.tm_mon = 5 - 1;
epoch_start.tm_mday = 11;
epoch_start.tm_hour = 14;
epoch_start.tm_min = 23;
epoch_start.tm_sec = 55;
unsigned long ticks_since_epoch = strtoul(msstmResponseBuf, NULL, 16);
unsigned long secs_since_epoch = (ticks_since_epoch / 1000) * 90;
unsigned long small_ticks = ticks_since_epoch - (secs_since_epoch / 90) * 1000;
secs_since_epoch += small_ticks * 90 / 1000;
time_t epoch_time = mktime(&epoch_start);
time_t now = epoch_time + secs_since_epoch;
memcpy(&tm, localtime(&now), sizeof tm);
return ISBD_SUCCESS;
}
*/
int IridiumSBD::getFirmwareVersion(char *version, size_t bufferSize)
{
if (bufferSize < 8)
return ISBD_RX_OVERFLOW;
send(F("AT+CGMR\r"));
if (!waitForATResponse(version, bufferSize, "Call Processor Version: "))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
return ISBD_SUCCESS;
}
/*
Private interface
*/
int IridiumSBD::internalBegin()
{
diagprint(F("Calling internalBegin\r\n"));
if (!this->asleep)
return ISBD_ALREADY_AWAKE;
power(true); // power on
bool modemAlive = false;
unsigned long startupTime = 500; //ms
for (unsigned long start = millis(); millis() - start < startupTime;)
if (cancelled())
return ISBD_CANCELLED;
// Turn on modem and wait for a response from "AT" command to begin
for (unsigned long start = millis(); !modemAlive && millis() - start < 1000UL * ISBD_STARTUP_MAX_TIME;)
{
send(F("AT\r"));
modemAlive = waitForATResponse();
if (cancelled())
return ISBD_CANCELLED;
}
if (!modemAlive)
{
diagprint(F("No modem detected.\r\n"));
return ISBD_NO_MODEM_DETECTED;
}
// The usual initialization sequence
FlashString strings[3] = { F("ATE1\r"), F("AT&D0\r"), F("AT&K0\r") };
for (int i=0; i<3; ++i)
{
send(strings[i]);
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
}
// Enable or disable RING alerts as requested by user
// By default they are on if a RING pin was supplied on constructor
diagprint(F("Ring alerts are")); diagprint(ringAlertsEnabled ? F("") : F(" NOT")); diagprint(F(" enabled.\r\n"));
send(ringAlertsEnabled ? F("AT+SBDMTA=1\r") : F("AT+SBDMTA=0\r"));
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
// Decide whether the internal MSSTM workaround should be enforced on TX/RX
// By default it is unless the firmware rev is >= TA13001
char version[8];
int ret = getFirmwareVersion(version, sizeof(version));
if (ret != ISBD_SUCCESS)
{
diagprint(F("Unknown FW version\r\n"));
msstmWorkaroundRequested = true;
}
else
{
diagprint(F("Firmware version is ")); diagprint(version); diagprint(F("\r\n"));
if (version[0] == 'T' && version[1] == 'A')
{
unsigned long ver = strtoul(version + 2, NULL, 10);
msstmWorkaroundRequested = ver < ISBD_MSSTM_WORKAROUND_FW_VER;
}
}
diagprint(F("MSSTM workaround is")); diagprint(msstmWorkaroundRequested ? F("") : F(" NOT")); diagprint(F(" enforced.\r\n"));
// Done!
diagprint(F("InternalBegin: success!\r\n"));
return ISBD_SUCCESS;
}
int IridiumSBD::internalSendReceiveSBD(const char *txTxtMessage, const uint8_t *txData, size_t txDataSize, uint8_t *rxBuffer, size_t *prxBufferSize)
{
diagprint(F("internalSendReceive\r\n"));
if (this->asleep)
return ISBD_IS_ASLEEP;
// Binary transmission?
if (txData && txDataSize)
{
if (txDataSize > ISBD_MAX_MESSAGE_LENGTH)
return ISBD_MSG_TOO_LONG;
send(F("AT+SBDWB="), true, false);
send(txDataSize);
send(F("\r"), false);
if (!waitForATResponse(NULL, 0, NULL, "READY\r\n"))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
uint16_t checksum = 0;
for (size_t i=0; i<txDataSize; ++i)
{
stream.write(txData[i]);
checksum += (uint16_t)txData[i];
}
consoleprint(F("["));
consoleprint((uint16_t)txDataSize);
consoleprint(F(" bytes]"));
diagprint(F("Checksum:"));
diagprint(checksum);
diagprint(F("\r\n"));
stream.write(checksum >> 8);
stream.write(checksum & 0xFF);
if (!waitForATResponse(NULL, 0, NULL, "0\r\n\r\nOK\r\n"))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
}
else // Text transmission
{
#if true // use long string implementation
if (txTxtMessage == NULL) // It's ok to have a NULL txtTxtMessage if the transaction is RX only
{
send(F("AT+SBDWT=\r"));
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
}
else
{
// remove any embedded \r
char *p = strchr(txTxtMessage, '\r');
if (p) *p = 0;
if (strlen(txTxtMessage) > ISBD_MAX_MESSAGE_LENGTH)
return ISBD_MSG_TOO_LONG;
send(F("AT+SBDWT\r"));
if (!waitForATResponse(NULL, 0, NULL, "READY\r\n"))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
send(txTxtMessage);
send("\r");
if (!waitForATResponse(NULL, 0, NULL, "0\r\n\r\nOK\r\n"))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
}
#else
send(F("AT+SBDWT="), true, false);
if (txTxtMessage != NULL) // It's ok to have a NULL txtTxtMessage if the transaction is RX only
send(txTxtMessage);
send(F("\r"), false);
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
#endif
}
// Long SBDIX loop begins here
for (unsigned long start = millis(); millis() - start < 1000UL * this->sendReceiveTimeout;)
{
bool okToProceed = true;
if (this->msstmWorkaroundRequested)
{
okToProceed = false;
int ret = internalMSSTMWorkaround(okToProceed);
if (ret != ISBD_SUCCESS)
return ret;
}
if (okToProceed)
{
uint16_t moCode = 0, moMSN = 0, mtCode = 0, mtMSN = 0, mtLen = 0, mtRemaining = 0;
int ret = doSBDIX(moCode, moMSN, mtCode, mtMSN, mtLen, mtRemaining);
if (ret != ISBD_SUCCESS)
return ret;
diagprint(F("SBDIX MO code: "));
diagprint(moCode);
diagprint(F("\r\n"));
if (moCode >= 0 && moCode <= 4) // this range indicates successful return!
{
diagprint(F("SBDIX success!\r\n"));
this->remainingMessages = mtRemaining;
if (mtCode == 1 && rxBuffer) // retrieved 1 message
{
diagprint(F("Incoming message!\r\n"));
return doSBDRB(rxBuffer, prxBufferSize);
}
else
{
// No data returned
if (prxBufferSize)
*prxBufferSize = 0;
}
return ISBD_SUCCESS;
}
else if (moCode == 12 || moCode == 14 || moCode == 16) // fatal failure: no retry
{
diagprint(F("SBDIX fatal!\r\n"));
return ISBD_SBDIX_FATAL_ERROR;
}
else // retry
{
diagprint(F("Waiting for SBDIX retry...\r\n"));
if (!noBlockWait(sbdixInterval))
return ISBD_CANCELLED;
}
}
else // MSSTM check fail
{
diagprint(F("Waiting for MSSTM retry...\r\n"));
if (!noBlockWait(ISBD_MSSTM_RETRY_INTERVAL))
return ISBD_CANCELLED;
}
} // big wait loop
diagprint(F("SBDIX timeout!\r\n"));
return ISBD_SENDRECEIVE_TIMEOUT;
}
int IridiumSBD::internalGetSignalQuality(int &quality)
{
if (this->asleep)
return ISBD_IS_ASLEEP;
char csqResponseBuf[2];
send(F("AT+CSQ\r"));
if (!waitForATResponse(csqResponseBuf, sizeof(csqResponseBuf), "+CSQ:"))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
if (isdigit(csqResponseBuf[0]))
{
quality = atoi(csqResponseBuf);
return ISBD_SUCCESS;
}
return ISBD_PROTOCOL_ERROR;
}
int IridiumSBD::internalMSSTMWorkaround(bool &okToProceed)
{
/*
According to Iridium 9602 Product Bulletin of 7 May 2013, to overcome a system erratum:
"Before attempting any of the following commands: +SBDDET, +SBDREG, +SBDI, +SBDIX, +SBDIXA the field application
should issue the AT command AT-MSSTM to the transceiver and evaluate the response to determine if it is valid or not:
Valid Response: "-MSSTM: XXXXXXXX" where XXXXXXXX is an eight-digit hexadecimal number.
Invalid Response: "-MSSTM: no network service"
If the response is invalid, the field application should wait and recheck system time until a valid response is
obtained before proceeding.
This will ensure that the Iridium SBD transceiver has received a valid system time before attempting SBD communication.
The Iridium SBD transceiver will receive the valid system time from the Iridium network when it has a good link to the
satellite. Ensuring that the received signal strength reported in response to AT command +CSQ and +CIER is above 2-3 bars
before attempting SBD communication will protect against lockout.
*/
char msstmResponseBuf[24];
send(F("AT-MSSTM\r"));
if (!waitForATResponse(msstmResponseBuf, sizeof(msstmResponseBuf), "-MSSTM: "))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
// Response buf now contains either an 8-digit number or the string "no network service"
okToProceed = isxdigit(msstmResponseBuf[0]);
return ISBD_SUCCESS;
}
int IridiumSBD::internalSleep()
{
if (this->asleep)
return ISBD_IS_ASLEEP;
#if false // recent research suggest this is not what you should do when just sleeping
// Best Practices Guide suggests this before shutdown
send(F("AT*F\r"));
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
#endif
return ISBD_SUCCESS;
}
bool IridiumSBD::noBlockWait(int seconds)
{
for (unsigned long start=millis(); millis() - start < 1000UL * seconds;)
if (cancelled())
return false;
return true;
}
// Wait for response from previous AT command. This process terminates when "terminator" string is seen or upon timeout.
// If "prompt" string is provided (example "+CSQ:"), then all characters following prompt up to the next CRLF are
// stored in response buffer for later parsing by caller.
bool IridiumSBD::waitForATResponse(char *response, int responseSize, const char *prompt, const char *terminator)
{
diagprint(F("Waiting for response "));
diagprint(terminator);
diagprint(F("\r\n"));
if (response)
memset(response, 0, responseSize);
int matchPromptPos = 0; // Matches chars in prompt
int matchTerminatorPos = 0; // Matches chars in terminator
enum {LOOKING_FOR_PROMPT, GATHERING_RESPONSE, LOOKING_FOR_TERMINATOR};
int promptState = prompt ? LOOKING_FOR_PROMPT : LOOKING_FOR_TERMINATOR;
consoleprint(F("<< "));
for (unsigned long start=millis(); millis() - start < 1000UL * atTimeout;)
{
if (cancelled())
return false;
while (filteredavailable() > 0)
{
char c = filteredread();
if (prompt)
{
switch (promptState)
{
case LOOKING_FOR_PROMPT:
if (c == prompt[matchPromptPos])
{
++matchPromptPos;
if (prompt[matchPromptPos] == '\0')
promptState = GATHERING_RESPONSE;
}
else
{
matchPromptPos = c == prompt[0] ? 1 : 0;
}
break;
case GATHERING_RESPONSE: // gathering response from end of prompt to first \r
if (response)
{
if (c == '\r' || responseSize < 2)
{
promptState = LOOKING_FOR_TERMINATOR;
}
else
{
*response++ = c;
responseSize--;
}
}
break;
}
}
if (c == terminator[matchTerminatorPos])
{
++matchTerminatorPos;
if (terminator[matchTerminatorPos] == '\0')
return true;
}
else
{
matchTerminatorPos = c == terminator[0] ? 1 : 0;
}
} // while (stream.available() > 0)
} // timer loop
return false;
}
bool IridiumSBD::cancelled()
{
if (ringPin != -1 && digitalRead(ringPin) == LOW) // Active low per guide
ringAsserted = true;
if (ISBDCallback != NULL)
return !ISBDCallback();
return false;
}
int IridiumSBD::doSBDIX(uint16_t &moCode, uint16_t &moMSN, uint16_t &mtCode, uint16_t &mtMSN, uint16_t &mtLen, uint16_t &mtRemaining)
{
// Returns xx,xxxxx,xx,xxxxx,xx,xxx
char sbdixResponseBuf[32];
send(F("AT+SBDIX\r"));
if (!waitForATResponse(sbdixResponseBuf, sizeof(sbdixResponseBuf), "+SBDIX: "))
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
uint16_t *values[6] = { &moCode, &moMSN, &mtCode, &mtMSN, &mtLen, &mtRemaining };
for (int i=0; i<6; ++i)
{
char *p = strtok(i == 0 ? sbdixResponseBuf : NULL, ", ");
if (p == NULL)
return ISBD_PROTOCOL_ERROR;
*values[i] = atol(p);
}
return ISBD_SUCCESS;
}
int IridiumSBD::doSBDRB(uint8_t *rxBuffer, size_t *prxBufferSize)
{
bool rxOverflow = false;
send(F("AT+SBDRB\r"));
if (!waitForATResponse(NULL, 0, NULL, "AT+SBDRB\r")) // waits for its own echo
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
// Time to read the binary data: size[2], body[size], checksum[2]
unsigned long start = millis();
while (millis() - start < 1000UL * atTimeout)
{
if (cancelled())
return ISBD_CANCELLED;
if (stream.available() >= 2)
break;
}
if (stream.available() < 2)
return ISBD_SENDRECEIVE_TIMEOUT;
uint16_t size = 256 * stream.read() + stream.read();
consoleprint(F("[Binary size:"));
consoleprint(size);
consoleprint(F("]"));
for (uint16_t bytesRead = 0; bytesRead < size;)
{
if (cancelled())
return ISBD_CANCELLED;
if (stream.available())
{
uint8_t c = stream.read();
bytesRead++;
if (rxBuffer && prxBufferSize)
{
if (*prxBufferSize > 0)
{
*rxBuffer++ = c;
(*prxBufferSize)--;
}
else
{
rxOverflow = true;
}
}
}
if (millis() - start >= 1000UL * atTimeout)
return ISBD_SENDRECEIVE_TIMEOUT;
}
while (millis() - start < 1000UL * atTimeout)
{
if (cancelled())
return ISBD_CANCELLED;
if (stream.available() >= 2)
break;
}
if (stream.available() < 2)
return ISBD_SENDRECEIVE_TIMEOUT;
uint16_t checksum = 256 * stream.read() + stream.read();
consoleprint(F("[csum:"));
consoleprint(checksum);
consoleprint(F("]"));
// Return actual size of returned buffer
if (prxBufferSize)
*prxBufferSize = (size_t)size;
// Wait for final OK
if (!waitForATResponse())
return cancelled() ? ISBD_CANCELLED : ISBD_PROTOCOL_ERROR;
return rxOverflow ? ISBD_RX_OVERFLOW : ISBD_SUCCESS;
}
void IridiumSBD::power(bool on)
{
this->asleep = !on;
if (this->sleepPin == -1)
return;
pinMode(this->sleepPin, OUTPUT);
if (on)
{
diagprint(F("Powering on modem...\r\n"));
digitalWrite(this->sleepPin, HIGH); // HIGH = awake
lastPowerOnTime = millis();
}
else
{
// Best Practices Guide suggests waiting at least 2 seconds
// before powering off again
unsigned long elapsed = millis() - lastPowerOnTime;
if (elapsed < 2000UL)
delay(2000UL - elapsed);
diagprint(F("Powering off modem...\r\n"));
digitalWrite(this->sleepPin, LOW); // LOW = asleep
}
}
void IridiumSBD::send(FlashString str, bool beginLine, bool endLine)
{
if (beginLine)
consoleprint(F(">> "));
consoleprint(str);
if (endLine)
consoleprint(F("\r\n"));
stream.print(str);
}
void IridiumSBD::send(const char *str)
{
consoleprint(F(">> "));
consoleprint(str);
consoleprint(F("\r\n"));
stream.print(str);
}
void IridiumSBD::send(uint16_t n)
{
consoleprint(n);
stream.print(n);
}
void IridiumSBD::diagprint(FlashString str)
{
PGM_P p = reinterpret_cast<PGM_P>(str);
while (1)
{
char c = pgm_read_byte(p++);
if (c == 0) break;
ISBDDiagsCallback(this, c);
}
}
void IridiumSBD::diagprint(const char *str)
{
while (*str)
ISBDDiagsCallback(this, *str++);
}
void IridiumSBD::diagprint(uint16_t n)
{
char str[10];
sprintf(str, "%u", n);
diagprint(str);
}
void IridiumSBD::consoleprint(FlashString str)
{
PGM_P p = reinterpret_cast<PGM_P>(str);
while (1)
{
char c = pgm_read_byte(p++);
if (c == 0) break;
ISBDConsoleCallback(this, c);
}
}
void IridiumSBD::consoleprint(const char *str)
{
while (*str)
ISBDConsoleCallback(this, *str++);
}
void IridiumSBD::consoleprint(uint16_t n)
{
char str[10];
sprintf(str, "%u", n);
consoleprint(str);
}
void IridiumSBD::consoleprint(char c)
{
ISBDConsoleCallback(this, c);
}
void IridiumSBD::SBDRINGSeen()
{
ringAsserted = true;
diagprint(F("SBDRING alert seen!\r\n"));
}
// Read characters until we find one that doesn't match SBDRING
// If nextChar is -1 it means we are still entertaining a possible
// match with SBDRING\r\n. Once we find a mismatch, stuff it into
// nextChar.
void IridiumSBD::filterSBDRING()
{
while (stream.available() > 0 && nextChar == -1)
{
char c = stream.read();
consoleprint(c);
if (*head != 0 && c == *head)
{
++head;
if (*head == 0)
{
SBDRINGSeen();
head = tail = SBDRING;
}
else
{
// Delay no more than 10 milliseconds waiting for next char in SBDRING
for (unsigned long start = millis(); stream.available() == 0 && millis() - start < FILTERTIMEOUT; );
// If there isn't one, assume this ISN'T an unsolicited SBDRING
if (stream.available() == 0) // pop the character back into nextChar
{
--head;
nextChar = c;
}
}
}
else
{
nextChar = c;
}
}
}
const char IridiumSBD::SBDRING[] = "SBDRING\r\n";
int IridiumSBD::filteredavailable()
{
filterSBDRING();
return head - tail + (nextChar != -1 ? 1 : 0);
}
int IridiumSBD::filteredread()
{
filterSBDRING();
// Use up the queue first
if (head > tail)
{
char c = *tail++;
if (head == tail)
head = tail = SBDRING;
return c;
}
// Then the "extra" char
else if (nextChar != -1)
{
char c = (char)nextChar;
nextChar = -1;
return c;
}
return -1;
}
| [
"dmann@loggerhead.com"
] | dmann@loggerhead.com |
f5afa55ce5a4734cf998d57a60505afd3f216bde | d2874e001ad8dc4b06c050b4df76dc770f04fc2a | /app/musicdao.cpp | 95a9221501b94a299af5da00f14227371dfa3855 | [] | no_license | oamates/MusicPlayer | 065b8d0a321d62b612bbe2299617c09712f8c413 | 57dbe40058684cab39b7b6a1bf87a6ce6ecc51a8 | refs/heads/master | 2022-10-28T15:00:11.649881 | 2020-06-12T16:34:57 | 2020-06-12T16:34:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,387 | cpp | #include "musicdao.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QStringList>
#include <QDebug>
MusicDAO::MusicDAO(QSqlDatabase &database)
: AbstractDAO(database)
{
}
MusicDAO::~MusicDAO()
{
}
void MusicDAO::init()
{
if (!m_database.tables().contains(tableName())) {
QSqlQuery query(m_database);
QString queryString = QStringLiteral
("create table %1 (id integer primary key, path text unique)")
.arg(tableName());
if (!query.exec(queryString))
qDebug() << "Creation of table failed:" << query.lastError().text();
}
updateCache();
int maxId = -1;
for (const auto &music : m_music) {
if (maxId < music.id)
maxId = music.id;
}
m_idCounter = maxId + 1;
}
void MusicDAO::reset()
{
if (m_database.tables().contains(tableName())) {
QSqlQuery query(m_database);
QString queryString = QStringLiteral("drop table %1")
.arg(tableName());
query.exec(queryString);
}
}
QString MusicDAO::tableName()
{
return "music";
}
const std::vector<Music> &MusicDAO::getAll()
{
updateCache();
return m_music;
}
const Music &MusicDAO::getMusic(int id)
{
return *std::find_if(m_music.cbegin(), m_music.cend(),
[&id] (const Music &music)
{
return music.id == id;
});
}
int MusicDAO::findByPath(const QUrl &path) const
{
return std::find_if(m_music.cbegin(), m_music.cend(),
[&path] (const Music &music)
{
return music.path == path;
})->id;
}
int MusicDAO::createMusic(const QUrl &path)
{
if (!path.isValid())
throw invalid_input();
QSqlQuery query(m_database);
QString queryString = QStringLiteral
("insert into %1 (id, path) values (%2, '%3')")
.arg(tableName())
.arg(m_idCounter)
.arg(path.url());
if (!query.exec(queryString)) {
queryString = QStringLiteral("select id from %1 where path = '%2'")
.arg(tableName())
.arg(path.url());
query.exec(queryString);
query.next();
return query.value(0).toInt();
}
m_music.emplace_back(Music{ m_idCounter, path });
return m_idCounter++;
}
void MusicDAO::updateMusic(const Music &music)
{
if (music.id < 0 || music.path.isEmpty())
throw invalid_input();
QSqlQuery query(m_database);
QString queryString = QStringLiteral
("update %1 set path = '%2' where id = %3")
.arg(tableName())
.arg(music.path.url())
.arg(music.id);
query.exec(queryString);
m_dirty = true;
}
void MusicDAO::deleteMusic(int id)
{
if (id < 0)
throw std::out_of_range("PlaylistDAO::deletePlaylist: invalid id");
QSqlQuery query(m_database);
QString queryString = QStringLiteral("delete from %1 where id = %2")
.arg(tableName())
.arg(id);
query.exec(queryString);
m_dirty = true;
}
void MusicDAO::updateCache()
{
if (!m_dirty)
return;
QSqlQuery result = m_database.exec("select id, path from " + tableName());
m_music.clear();
while (result.next()) {
m_music.emplace_back(Music{ result.value(0).toInt(),
result.value(1).toString() });
}
m_dirty = false;
}
| [
"tokhirovdoniyor@gmail.com"
] | tokhirovdoniyor@gmail.com |
647ff1b90d33d3e1e6cbd58245dc95d21598a855 | 6ab3e3b9f379c06b3347c28254287ecf0ffe01f0 | /2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 2/02 Programs/Direction/TestDirection.cpp | 6ed3a8427bdf53fd5593f4d085ae18b3e1a34df9 | [
"MIT"
] | permissive | Fantendo2001/FORKED---CourseMaterials | 2e7a4cb4ee8e71997b78791d9ddc4090799ece89 | f2799f004f4353b5f35226158c8fd9f71818810e | refs/heads/master | 2022-01-11T10:02:14.547606 | 2019-06-19T09:00:11 | 2019-06-19T09:00:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 561 | cpp | /*
* File: TestDirection.cpp
* -----------------------
* This file tests the Direction definition and functions as they
* appear in the text.
*/
#include <iostream>
#include "direction.h"
using namespace std;
int main() {
for (Direction dir = NORTH; dir <= WEST; dir = Direction(dir + 1)) {
cout << "leftFrom(" << directionToString(dir) << ") -> "
<< directionToString(leftFrom(dir)) << endl;
cout << "rightFrom(" << directionToString(dir) << ") -> "
<< directionToString(rightFrom(dir)) << endl;
}
return 0;
}
| [
"117010285@Link.cuhk.edu.cn"
] | 117010285@Link.cuhk.edu.cn |
536024983e6d2ae0d8b8b472a11e32f6a7b8d13a | 4fc1ce96a543069e73f11f75c5ca0c238676b2b3 | /cpp/AA3DCoordinate.h | cbc76343f91c96960b1f5c4ba910c08177853e1f | [] | no_license | tzengyuxio/gonghe | e25a7203ecd56545aa9c574f25a3c56e9cc7c0d2 | dd99c7a4dd8e39ccf0aadf183574891286a5f654 | refs/heads/master | 2021-05-04T15:51:36.704754 | 2018-02-05T02:46:38 | 2018-02-05T02:46:38 | 120,239,308 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,486 | h | /*
Module : AA3DCoordinate.h
Purpose: Implementation for the simple class to encapsulate a three dimensional coordinate
Created: PJN / 29-12-2003
Copyright (c) 2003 - 2018 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com)
All rights reserved.
Copyright / Usage Details:
You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
when your product is released in binary form. You are allowed to modify the source code in any way you want
except you cannot modify the copyright details at the top of each module. If you want to distribute source
code with your application, then you are only allowed to distribute versions released by the author. This is
to maintain a single distribution point for the source code.
*/
/////////////////////// Macros / Defines //////////////////////////////////////
#if _MSC_VER > 1000
#pragma once
#endif //#if _MSC_VER > 1000
#ifndef __AA3DCOORDINATE_H__
#define __AA3DCOORDINATE_H__
#ifndef AAPLUS_EXT_CLASS
#define AAPLUS_EXT_CLASS
#endif //#ifndef AAPLUS_EXT_CLASS
/////////////////////// Classes ///////////////////////////////////////////////
class AAPLUS_EXT_CLASS CAA3DCoordinate
{
public:
//Constructors / Destructors
CAA3DCoordinate() : X(0),
Y(0),
Z(0)
{
};
//member variables
double X;
double Y;
double Z;
};
#endif //#ifndef __AA3DCOORDINATE_H__
| [
"tzengyuxio@gmail.com"
] | tzengyuxio@gmail.com |
775df9fb6c18078310b5dce770eda562d59597f9 | 88ae8695987ada722184307301e221e1ba3cc2fa | /chrome/browser/ui/webui/ash/edu_account_login_handler.h | 5d425d5ac5da619aea6fcf13eefce593cf5eaa3a | [
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 7,153 | h | // Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_WEBUI_ASH_EDU_ACCOUNT_LOGIN_HANDLER_H_
#define CHROME_BROWSER_UI_WEBUI_ASH_EDU_ACCOUNT_LOGIN_HANDLER_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/ash/login/network_state_informer.h"
#include "components/image_fetcher/core/image_fetcher.h"
#include "components/signin/public/identity_manager/access_token_info.h"
#include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h"
#include "components/supervised_user/core/browser/kids_external_fetcher.h"
#include "components/supervised_user/core/browser/proto/kidschromemanagement_messages.pb.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "google_apis/gaia/gaia_auth_consumer.h"
#include "google_apis/gaia/gaia_auth_fetcher.h"
namespace ash {
// Handler for EDU account login flow.
class EduAccountLoginHandler : public content::WebUIMessageHandler,
public GaiaAuthConsumer {
public:
explicit EduAccountLoginHandler(
const base::RepeatingClosure& close_dialog_closure);
~EduAccountLoginHandler() override;
EduAccountLoginHandler(const EduAccountLoginHandler&) = delete;
EduAccountLoginHandler& operator=(const EduAccountLoginHandler&) = delete;
private:
class ProfileImageFetcher {
public:
// Create a new instance to fetch a set of images.
// |profile_image_urls| is a map from obfuscated Gaia id to profile image
// url. After all images are fetched, |callback| will be resolved with a
// map from obfuscated Gaia id to gfx::Image. If image cannot be fetched
// an empty gfx::Image() will be returned.
ProfileImageFetcher(
image_fetcher::ImageFetcher* image_fetcher,
const std::map<std::string, GURL>& profile_image_urls,
base::OnceCallback<
void(std::map<std::string, gfx::Image> profile_images)> callback);
ProfileImageFetcher(const ProfileImageFetcher&) = delete;
ProfileImageFetcher& operator=(const ProfileImageFetcher&) = delete;
~ProfileImageFetcher();
// Start fetching profile images.
void FetchProfileImages();
private:
FRIEND_TEST_ALL_PREFIXES(EduAccountLoginHandlerTest,
ProfileImageFetcherTest);
// Called for each profile provided in |profile_image_urls_|. If
// |profile_image_url| is valid - fetches the image. Otherwise calls
// |OnImageFetched| with an empty image.
void FetchProfileImage(const std::string& obfuscated_gaia_id,
const GURL& profile_image_url);
// Called for each profile provided in |profile_image_urls_|. After all
// images are fetched resolves |callback_| with profile images.
void OnImageFetched(const std::string& obfuscated_gaia_id,
const gfx::Image& image,
const image_fetcher::RequestMetadata& metadata);
raw_ptr<image_fetcher::ImageFetcher, ExperimentalAsh> image_fetcher_ =
nullptr;
const std::map<std::string, GURL> profile_image_urls_;
base::OnceCallback<void(std::map<std::string, gfx::Image> profile_images)>
callback_;
std::map<std::string, gfx::Image> fetched_profile_images_;
base::WeakPtrFactory<ProfileImageFetcher> weak_ptr_factory_{this};
};
FRIEND_TEST_ALL_PREFIXES(EduAccountLoginHandlerTest, HandleGetParentsSuccess);
FRIEND_TEST_ALL_PREFIXES(EduAccountLoginHandlerTest, HandleGetParentsFailure);
FRIEND_TEST_ALL_PREFIXES(EduAccountLoginHandlerTest,
HandleParentSigninSuccess);
FRIEND_TEST_ALL_PREFIXES(EduAccountLoginHandlerTest,
HandleParentSigninAccessTokenFailure);
FRIEND_TEST_ALL_PREFIXES(EduAccountLoginHandlerTest,
HandleParentSigninReAuthProofTokenFailure);
FRIEND_TEST_ALL_PREFIXES(EduAccountLoginHandlerTest, ProfileImageFetcherTest);
FRIEND_TEST_ALL_PREFIXES(EduAccountLoginHandlerTest,
HandleIsNetworkReadyOnline);
FRIEND_TEST_ALL_PREFIXES(EduAccountLoginHandlerTest,
HandleIsNetworkReadyOffline);
// content::WebUIMessageHandler:
void RegisterMessages() override;
void OnJavascriptDisallowed() override;
void HandleIsNetworkReady(const base::Value::List& args);
void HandleGetParents(const base::Value::List& args);
void HandleParentSignin(const base::Value::List& args);
virtual void FetchFamilyMembers();
virtual void FetchParentImages(
base::Value::List parents,
std::map<std::string, GURL> profile_image_urls);
virtual void FetchAccessToken(const std::string& obfuscated_gaia_id,
const std::string& password);
virtual void FetchReAuthProofTokenForParent(
const std::string& child_oauth_access_token,
const std::string& parent_obfuscated_gaia_id,
const std::string& parent_credential);
// ListFamilyMembers fetch handlers.
void OnListFamilyMembersResponse(
KidsExternalFetcherStatus status,
std::unique_ptr<kids_chrome_management::ListFamilyMembersResponse>
response);
void OnListFamilyMembersSuccess(
const kids_chrome_management::ListFamilyMembersResponse& response);
void OnListFamilyMembersFailure(KidsExternalFetcherStatus status);
// ProfileImageFetcher callback
void OnParentProfileImagesFetched(
base::Value::List parents,
std::map<std::string, gfx::Image> profile_images);
// signin::PrimaryAccountAccessTokenFetcher callback
void CreateReAuthProofTokenForParent(
const std::string& parent_obfuscated_gaia_id,
const std::string& parent_credential,
GoogleServiceAuthError error,
signin::AccessTokenInfo access_token_info);
// GaiaAuthConsumer overrides.
void OnReAuthProofTokenSuccess(
const std::string& reauth_proof_token) override;
void OnReAuthProofTokenFailure(
const GaiaAuthConsumer::ReAuthProofTokenStatus error) override;
// Used for getting parent RAPT token.
std::unique_ptr<GaiaAuthFetcher> gaia_auth_fetcher_;
// Used for getting child access token.
std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher>
access_token_fetcher_;
base::RepeatingClosure close_dialog_closure_;
// Reference to NetworkStateInformer that handles changes in network
// state.
scoped_refptr<NetworkStateInformer> network_state_informer_;
std::unique_ptr<
KidsExternalFetcher<kids_chrome_management::ListFamilyMembersRequest,
kids_chrome_management::ListFamilyMembersResponse>>
list_family_members_fetcher_;
std::unique_ptr<ProfileImageFetcher> profile_image_fetcher_;
std::string get_parents_callback_id_;
std::string parent_signin_callback_id_;
};
} // namespace ash
#endif // CHROME_BROWSER_UI_WEBUI_ASH_EDU_ACCOUNT_LOGIN_HANDLER_H_
| [
"jengelh@inai.de"
] | jengelh@inai.de |
da560c15fd72a55567c9b19f8bab504f4f7d6e06 | 921a8611ec0dc1d670b327fce53911340d2c703d | /04/04/fn45186_prob4_vc.cpp | d21c77314966e90e2a7820437c60a0bdc2e7e13e | [] | no_license | Georgi-Radev/UP-homework-1 | c18152082a3ac89232d4a78d395925f384ea9be5 | d1875795bec48e6021f07cbf70db5ae57aa2d778 | refs/heads/master | 2021-01-11T20:33:56.619942 | 2017-01-16T17:59:33 | 2017-01-16T17:59:33 | 79,144,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,225 | cpp | /**
*
* Solution to homework task
* Introduction to programming course
* Faculty of Mathematics and Informatics of Sofia University
* Winter semester 2016/2017
*
* @author Georgi Radev
* @idnumber 45186
* @task 4
* @compiler VC
*
*/
#include <iostream>
#include <cmath>
using namespace std;
int main() {
char figureX, kingX, figureType;
int figureY, kingY;
//cout << "Enter the type of the attacking figure: \n"
// << "Q - Queen;\n"
// << "R - Rook;\n"
// << "B - Bishop.\n"
// << "N - kNight;\n";
cin >> figureType;
//cout << "Enter the coordinates of the attacking figure (delimited by space)\n";
cin >> figureX
>> figureY;
//cout << "Enter the coordinates of the king (delimited by space)\n";
cin >> kingX
>> kingY;
figureX -= 96; // Convert ASCII codes to useful numbers:
kingX -= 96; // a => 1, b => 2, ... , h => 8
if (figureX <= 0 || figureX >= 9 || figureY <= 0 || figureY >= 9) {
cout << "Invalid figure coordinates!";
return 1;
}
if (kingX <= 0 || kingX >= 9 || kingY <= 0 || kingY >= 9) {
cout << "Invalid king coordinates!";
return 1;
}
switch (figureType) {
case 'Q': // Queen
if (figureX - figureY == kingX - kingY || // same "straight" diagonal
figureX + figureY == kingX + kingY || // same "reverse" diagonal
figureX == kingX || // same X coord
figureY == kingY) { // same Y coord
cout << "Yes\n";
}
else {
cout << "No\n";
}
break;
case 'R': // Rook
if (figureX == kingX || // same X coord
figureY == kingY) { // same Y coord
cout << "Yes\n";
}
else {
cout << "No\n";
}
break;
case 'B': // Bishop
if (figureX - figureY == kingX - kingY || // same "straight" diagonal
figureX + figureY == kingX + kingY) { // same "reverse" diagonal
cout << "Yes\n";
}
else {
cout << "No\n";
}
break;
case 'N': // kNight
if ((abs(figureX - kingX) == 1 && abs(figureY - kingY) == 2) || // (1)
(abs(figureX - kingX) == 2 && abs(figureY - kingY) == 1)) { // (2)
cout << "Yes\n";
}
// (1) x x (1)
// (2) x x (2)
// |N|
// (2) x x (2)
// (1) x x (1)
else {
cout << "No\n";
}
break;
default:
cout << "Invalid figure!\n";
return 1;
}
return 0;
} | [
"gradev@melontech.com"
] | gradev@melontech.com |
6d1f15b259ca409d23796d82cb9d3a22e03d16ed | af283dd3fbbbf04dc0efa84896b4aa37dd35a7a8 | /src/util.cpp | 6ab0001d84dedace7330152c6b9feaea632b134d | [] | no_license | enetheru/smf_tools | 2cbbe2209b23ea6e0756ccf68d3d176abdf6cb40 | 03f6bce9c0a4cda8f0f53ef2285290ceade4ca44 | refs/heads/master | 2021-01-21T04:54:18.164757 | 2016-05-26T08:47:59 | 2016-05-26T08:47:59 | 13,128,266 | 3 | 0 | null | 2015-11-23T01:03:54 | 2013-09-26T16:42:22 | C++ | UTF-8 | C++ | false | false | 9,384 | cpp | #include <chrono>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <list>
#include <OpenImageIO/imagebuf.h>
#include <OpenImageIO/imagebufalgo.h>
#include <elog.h>
#include "util.h"
std::pair< uint32_t, uint32_t >
valxval( const std::string input )
{
std::pair< uint32_t, uint32_t> result;
auto d = input.find_first_of( 'x', 0 );
if( d ) result.first = std::stoi( input.substr( 0, d ) );
else result.first = 0;
if( d == input.size() - 1 ) result.second = 0;
else result.second = std::stoi( input.substr( d + 1, std::string::npos) );
return result;
}
std::vector< uint32_t >
expandString( const char *s )
{
std::vector< uint32_t > result;
int start = 0;
bool sequence = false, fail = false;
const char *begin;
do {
begin = s;
while( *s != ',' && *s != '\n' && *s != '-' && *s ) s++;
if( begin == s) continue;
if( sequence ){
for( int i = start; i < std::stoi( std::string( begin, s ) ); ++i )
result.push_back( i );
}
if( *(s) == '-' ){
sequence = true;
try {
start = std::stoi( std::string( begin, s ) );
}
catch( std::invalid_argument ){
fail = true;
}
} else {
sequence = false;
try {
result.push_back( std::stoi( std::string( begin, s ) ) );
}
catch( std::invalid_argument ){
fail = true;
}
}
}
while( *s++ != '\0' );
if( fail ){
LOG( WARN ) << "Possible Parse Error while spliting filter string";
}
return result;
}
std::unique_ptr< OpenImageIO::ImageBuf >
fix_channels(
std::unique_ptr< OpenImageIO::ImageBuf> && inBuf,
const OpenImageIO::ImageSpec &spec )
{
OIIO_NAMESPACE_USING;
int map[] = { 0, 1, 2, 3 };
static const float fill[] = { 0, 0, 0, 1.0 };
CHECK( inBuf ) << "nullptr passed to fix_channels()";
// return a copy of the original if its the correct size.
if( inBuf->spec().nchannels == spec.nchannels ) return std::move( inBuf );
if( inBuf->spec().nchannels < 4 ) map[3] = -1;
if( inBuf->spec().nchannels < 3 ) map[2] = -1;
if( inBuf->spec().nchannels < 2 ) map[1] = -1;
// Otherwise update channels to spec channels
std::unique_ptr< OpenImageIO::ImageBuf > outBuf( new OpenImageIO::ImageBuf );
ImageBufAlgo::channels( *outBuf, *inBuf, spec.nchannels, map, fill );
return outBuf;
}
void
channels( OpenImageIO::ImageBuf *&sourceBuf, OpenImageIO::ImageSpec spec )
{
OIIO_NAMESPACE_USING;
int map[] = { 0, 1, 2, 3 };
float fill[] = { 0, 0, 0, 1.0 };
CHECK( sourceBuf ) << "nullptr passed to channels()";
// return a copy of the original if its the correct size.
if( sourceBuf->spec().nchannels == spec.nchannels ) return;
if( sourceBuf->spec().nchannels < 4 ) map[3] = -1;
if( sourceBuf->spec().nchannels < 3 ) map[2] = -1;
if( sourceBuf->spec().nchannels < 2 ) map[1] = -1;
// Otherwise update channels to spec channels
ImageBuf *tempBuf = new ImageBuf;
ImageBufAlgo::channels( *tempBuf, *sourceBuf, spec.nchannels, map, fill );
sourceBuf->clear();
delete sourceBuf;
sourceBuf = tempBuf;
}
std::unique_ptr< OpenImageIO::ImageBuf >
fix_scale(
std::unique_ptr< OpenImageIO::ImageBuf> && inBuf,
const OpenImageIO::ImageSpec &spec )
{
OIIO_NAMESPACE_USING;
using std::unique_ptr;
CHECK( inBuf ) << "nullptr passed to fix_scale()";
// return the inBuf if no change is required.
if( (inBuf->spec().width == spec.width )
&& (inBuf->spec().height == spec.height) ){
DLOG( INFO ) << "no scale required";
return std::move( inBuf );
}
// Otherwise scale
ROI roi(0, spec.width, 0, spec.height, 0, 1, 0, inBuf->spec().nchannels );
unique_ptr< ImageBuf > outBuf( new ImageBuf );
// BUG with workaround
// resample is faster but creates black outlines when scaling up, so only
// use it for scaling down.
if( (spec.width < inBuf->spec().width )
&& (spec.height < inBuf->spec().height) ){
ImageBufAlgo::resample( *outBuf, *inBuf, false, roi );
}
else {
ImageBufAlgo::resize( *outBuf, *inBuf, "", false, roi );
}
return outBuf;
}
//REMOVE
void
scale( OpenImageIO::ImageBuf *&sourceBuf, OpenImageIO::ImageSpec spec )
{
OIIO_NAMESPACE_USING;
const OpenImageIO::ImageSpec srcSpec = sourceBuf->spec();
CHECK( sourceBuf ) << "nullptr passed to scale()";
// do nothing if the original if its the correct size.
if( srcSpec.width == spec.width && srcSpec.height == spec.height ){
return;
}
// Otherwise scale
ROI roi(0, spec.width, 0, spec.height, 0, 1, 0, srcSpec.nchannels );
ImageBuf *tempBuf = new ImageBuf;
// resmple is faster but creates black outlines when scaling up, so only
// use it for scaling down.
if( spec.width < srcSpec.width && spec.height < srcSpec.height ){
ImageBufAlgo::resample( *tempBuf, *sourceBuf, false, roi );
}
else {
ImageBufAlgo::resize( *tempBuf, *sourceBuf, "", false, roi );
}
sourceBuf->clear();
delete sourceBuf;
sourceBuf = tempBuf;
}
void
progressBar( std::string header, float goal, float current )
{
static uint32_t seconds;
static uint32_t minutes;
static uint32_t hours;
static uint32_t average;
static float ratio;
static int progress;
static int remainder;
static int last_current = 0;
ratio = current / goal;
static std::list< uint32_t > history;
if( history.size() >= 30) history.pop_front();
using namespace std::chrono;
static duration< double > time_span;
static steady_clock::time_point last;
static steady_clock::time_point now;
now = steady_clock::now();
time_span = duration_cast< duration< double > >(now - last);
if( time_span.count() < 0.5 && ratio < 1 )return;
last = now;
progress = current - last_current;
last_current = current;
remainder = goal - current;
history.push_back( progress );
average = 0;
for( auto i : history ) average += i;
average = average / history.size();
seconds = remainder / average;
hours = seconds / 3600;
minutes = (seconds % 3600 ) / 60;
seconds = seconds % 60;
//construct the footer
std::stringstream footer;
footer << "[";
if( hours ) footer << hours << ":"; // hours
if( minutes ) footer << std::setfill('0') << std::setw(2) << minutes << ":"; //minutes
footer << std::setfill('0') << std::setw(2) << seconds << "]"; // seconds
footer << "[" << (int)(ratio * 100) << "%]"; // percentage complete
// calculate formatting factors
std::stringstream text;
uint32_t columns = getenv( "COLUMNS" ) ? atoi( getenv( "COLUMNS" ) ) : 80;
uint32_t barSize = columns - header.size() - footer.str().size();
//construct the bar
text << "\033[0G\033[2K"; // clear the current line and set the cursor position at the beginning
for( uint32_t i = 0; i < columns; ++i) text << "-"; //fill the output with a single dotten line
text << "\033[G"; // reset the cursor position;
text << header; // put the header on
for( uint32_t i = 0; i < ratio * barSize; ++i) text << "#"; // fill in current progress
text << ">\033[" << columns - footer.str().size() + 1 << "G" << footer.str(); // put the end cap on
if( ratio < 1.0f ) text << "\033[F"; // if were not done, move the cursor back up.
std::cout << text.str() << std::endl;
}
std::string
image_to_hex( const uint8_t *data, int width, int height, int type ){
// type 0 = UINT8
// type 1 = DXT1
// for now lets just do the red channel
std::stringstream ss;
if( type == 0 ){//RGBA8
for( int j = 0; j < height; ++j ){
for( int i = 0; i < width; ++i ){
ss << std::hex << std::setfill( '0' ) << std::setw( 2 )
<< +(uint8_t)data[ (j * width + i) * 4 ];
}
ss << "\n";
}
}
if( type == 1 ){ //DXT1
//in DXT1 each 4x4 block of pixels are represented by 64 bits
//i'm really only concerned if the data exist rather than how to
//represent it in characters.
//i want to put the dxt1 blocks over 2 lines like:
//ABCD ABCD ABCD ABCD
//DEFG DEFG DEFG DEFG
//
//ABCD etc.
//DEFG etc.
//so we have to 2nd half of the bytes until a second iteration through the material
//we treat each 4x4 block as a separate element
width = width / 4;
height = height / 4;
for( int j = 0; j < height; ++j ){// rows
for( int q = 0; q < 4; ++q ){ // sub rows
for( int i = 0; i < width; ++i ){ // columns
int datapos = (j * width + i) * 8 + q*2; // every 64 bits
ss << std::hex << std::setfill( '0' ) << std::setw( 2 )
<< +(uint8_t)data[ datapos ]
<< std::hex << std::setfill( '0' ) << std::setw( 2 )
<< +(uint8_t)data[ datapos + 1 ] << " ";
}
ss << '\n';
}
ss << '\n';
}
}
return ss.str();
}
| [
"nicholas.samuel@gmail.com"
] | nicholas.samuel@gmail.com |
26eeac021e109bfe4723cb3d9fb4ec2f0e361ae3 | aca4f00c884e1d0e6b2978512e4e08e52eebd6e9 | /2011/contest/ZOJMAUG/proP.cpp | 7f9341793694c327fad0cf7307aafcb1911beb7a | [] | no_license | jki14/competitive-programming | 2d28f1ac8c7de62e5e82105ae1eac2b62434e2a4 | ba80bee7827521520eb16a2d151fc0c3ca1f7454 | refs/heads/master | 2023-08-07T19:07:22.894480 | 2023-07-30T12:18:36 | 2023-07-30T12:18:36 | 166,743,930 | 2 | 0 | null | 2021-09-04T09:25:40 | 2019-01-21T03:40:47 | C++ | UTF-8 | C++ | false | false | 1,591 | cpp | #include<iostream>
#include<sstream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<ctime>
#include<climits>
#include<algorithm>
#include<vector>
#include<string>
#include<queue>
#include<deque>
#include<set>
#include<map>
using namespace std;
#define N 510
#define K 260
#define S 2100
#define NUM 260
int n,m,q,num;
int a[NUM];
int f[K],g[K];
int min(const int &i,const int &j){ return (i<j)?i:j; }
int max(const int &i,const int &j){ return (i>j)?i:j; }
int Call(const int &i,const int &x1,const int &y1,const int &x2,const int &y2){
int ret=0,k,tmp;
// ---
k=0;if(i>=x1 && i<=x2)k++;if(i!=n-i-1 && n-i-1 >= x1 && n-i-1<=x2)k++;
if(k){
tmp=min(m-i-1,y2)-max(i ,y1)+1;
if(tmp<0)tmp=0;
ret+=tmp*k;
}
// |||
k=0;if(i>=y1 && i<=y2)k++;if(i!=m-i-1 && m-i-1 >= y1 && m-i-1<=y2)k++;
if(k){
tmp=min(n-i-2,x2)-max(i+1,x1)+1;
if(tmp<0)tmp=0;
ret+=tmp*k;
}
return ret;
}
void work(){
int i,k;
num=(min(n,m)+1)>>1;
for(i=0;i<num;i++)scanf("%d",&a[i]);
memset(g,0x7f,sizeof(g));
scanf("%d",&q);
while(q--){
int x1,y1,x2,y2;
int kid,idx,val;
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
if(x1>x2)swap(x1,x2);if(y1>y2)swap(y1,y2);
kid=idx=val=0;
for(i=0;i<num;i++){
k=Call(i,x1,y1,x2,y2);
if(!k)continue;
//printf("%d+=%d g[%d]=%d\n",a[i],k,a[i],g[a[i]]);
if(g[a[i]]!=q){ g[a[i]]=q;f[a[i]]=0;kid++; }
f[a[i]]+=k;
if(f[a[i]]>val || (f[a[i]]==val && a[i]<idx)){
val=f[a[i]];
idx=a[i];
}
}
printf("%d %d %d\n",kid,idx,val);
}
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF)
work();
return 0;
}
| [
"jki14wz@gmail.com"
] | jki14wz@gmail.com |
5cae8de558f84462d733097c805d2ad5ea25ad46 | 827a7b6f440cbeffc040f8db6f5030fb98932963 | /.localhistory/1529060744$IngressoNidoCellini.ino | a9e1b0d81da6281621e575b3cbe341c8b0642cfa | [] | no_license | SenzaNome78/IngressoNidoCellini | 4715e47a74e407037c64ccc24c4fb4c767b00a7b | f9dfd45889e895d69ac1505dd0c2586864cf0f29 | refs/heads/master | 2020-03-18T16:38:33.649675 | 2018-07-04T06:47:06 | 2018-07-04T06:47:06 | 134,977,774 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 13,781 | ino | #include <Arduino.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include "LettoreRfid.h"
#include "IngressiNidoHelper.h"
#include <ESP8266WebServer.h>
// Istanza della classe LettoreRfid
LettoreRfid rfid;
// Mandiamo al server il seriale e il ruolo (bambino, educatore..) del badge
int SendDataToWebServer(String userSerial, String ruolo, bool entrata);
// Funzione che scrive i dati passati dal server su un nuovo badge
bool AttivaModScrittura();
// instanza per gestire l'lcd
LiquidCrystal_I2C lcd(0x27, 20, 4);
// Pausa per il testo dell'lcd
const int lcdPause = 4000;
// Costanti contenenti gli ssid e password per il wifi
const char ssidSTA[] = "DHouse"; //ssid della rete
const char passwordSTA[] = "dav050315"; //password della rete
WiFiServer webServer(80); // Usiamo questo server per registrare nuovi bambini o educatori
WiFiClient client; // client che usiamo per rilevare una connessione proveniente dal server
WiFiClient clientPres; // client per le presenze
HTTPClient httpC; // Usiamo il client http per comunicare le presente al server
ESP8266WebServer wServer(80);
String NuovoUtenteHeader; // stringa che contiene l'header del messagio get in caso di nuovo badge
// Variabili per scrittura badge se uso Delay
long tempoAttesaBadgeXScrittura;
const long tempoTotaleAttesaBadgeXScrittura = 5000; // RITARDO DI 3 SECONDO PER MINUTO
String nome_nuovo_badge;
String ruolo_nuovo_badge;
String sesso_nuovo_badge;
bool modScrittura = false;
int idPresenza; // id della presenza, temporaneo per registrarlo nell'array della classe LettoreRfid
void setup()
{
//Serial.begin(9600); // Prepariamo la seriale
Serial.begin(115200); // Prepariamo la seriale
// ******Init Variabili tempo*******
// ******Init Variabili tempo*******
tempoAttesaBadgeXScrittura = tempoTotaleAttesaBadgeXScrittura;
// **********Init RFID**************
SPI.begin(); // Init SPI bus
// **********Init RFID**************
// **********Init LCD**************
lcd.init(); //inizializiamo l'lcd
lcd.backlight(); // Accendiamo la luce di sfondo dell'lcd
// **********Init LCD**************
// **********Init WIFI STATION**************
Serial.println("");
Serial.print("Connecting to ");
Serial.println(ssidSTA);
WiFi.mode(WiFiMode::WIFI_STA);
WiFi.begin(ssidSTA, passwordSTA);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
//httpC.setReuse(true);
//httpC.setReuse();
Serial.println("\nConnected.");
Serial.println(WiFi.localIP());
wServer.on("/NewBadge.html", HTTPMethod::HTTP_ANY, NewBadgeOnIn, NewBadgeOnOut);
wServer.on("/RegEntry.html", HTTPMethod::HTTP_ANY, NewBadgeOnIn, NewBadgeOnOut);
wServer.begin();
Serial.println("SERVER BEGIN!!");
//webServer.begin();
// **********Init WIFI STATION**************
}
void RegEntryOnIn()
{
Serial.println("In RegEntryOnIn");
Serial.println(wServer.args());
for (int i = 0; i < wServer.args(); i++)
{
Serial.print(wServer.argName(i));
Serial.print(": ");
Serial.println(wServer.arg(i));
}
wServer.sendContent("RegEntryOnIn");
}
void RegEntryOnOut()
{
Serial.println("In RegEntryOnOut");
}
void NewBadgeOnIn()
{
Serial.println("In NewBadgeOnIn");
Serial.println(wServer.args());
for (int i = 0; i < wServer.args(); i++)
{
Serial.print(wServer.argName(i));
Serial.print(": ");
Serial.println(wServer.arg(i));
}
wServer.sendContent("TEST");
}
void NewBadgeOnOut()
{
Serial.println("In NewBadgeOnOut");
}
void loop()
{
wServer.handleClient();
//*********** INIZIO MOD SCRITTURA ***********************************
// Se abbiamo attivatò la modalità scrittura, ci occupiamo di scrivere il nuovo badge
// Blocco che rimane in ascolto di un eventuale richiesta per un nuovo
// badge dal server web
//client = webServer.available();
//if (client)
//{
// Serial.println("\n[Client connected]");
// if (client.connected() && modScrittura == false)
// {
// NuovoUtenteHeader = client.readStringUntil('\r');
// nome_nuovo_badge = NuovoUtenteHeader.substring(NuovoUtenteHeader.indexOf("nome=") + 5, NuovoUtenteHeader.indexOf('&'));
// nome_nuovo_badge.trim();
// ruolo_nuovo_badge = NuovoUtenteHeader.substring(NuovoUtenteHeader.indexOf("ruolo=") + 6, NuovoUtenteHeader.indexOf("ruolo=") + 7);
// ruolo_nuovo_badge = ruolo_nuovo_badge.substring(0, 1);
// sesso_nuovo_badge = NuovoUtenteHeader.substring(NuovoUtenteHeader.indexOf("sesso=") + 6, NuovoUtenteHeader.indexOf("sesso=") + 7);
// sesso_nuovo_badge = sesso_nuovo_badge.substring(0, 1);
// if (nome_nuovo_badge != "" && ruolo_nuovo_badge != "" && sesso_nuovo_badge != "")
// {
// // i campi nuovo nome, ruolo e sesso contengono qualcosa, attiviamo la
// // modalità scrittura e usciamo dal loop
// modScrittura = true;
// AttivaModScrittura();
// return;
// }
// }
//}
//*********** FINE MOD SCRITTURA ***********************************
//*********** INIZIO MOD LETTURA ***********************************
if (rfid.BadgeRilevato()) // Un badge è stato avvicinato al lettore
{
if (rfid.GetBadgeDaRegistrare())
{
LcdPrintCentered("Il badge non e'", 0, true, lcd);
LcdPrintCentered("stato registrato.", 1, true, lcd);
LcdPrintCentered("Per favore contatti", 2, true, lcd);
LcdPrintCentered("l'amministratore.", 3, true, lcd);
PlayBuzzer(); // Riproduce un suono
delay(lcdPause);
return;
}
String tmpSesso = "";
String tmpRuolo = "";
if (rfid.isNuovaRilevazione()) // NUOVA entrata rilevata
{
PlayBuzzer(); // Riproduce un suono
//if (rfid.getSessoUser() == "M")
//{
// tmpSesso = "stato inserito";
//}
//else if (rfid.getSessoUser() == "F")
//{
// tmpSesso = "stata inserita";
//}
idPresenza = SendDataToWebServer(rfid.getSeriale(), rfid.getRuoloUser(), true);
if (idPresenza > 0)
{
LcdPrintCentered("L'entrata di", 0, true, lcd);
LcdPrintCentered(rfid.getNomeUser(), 1, true, lcd);
LcdPrintCentered("e' stata registrata", 2, true, lcd);
LcdPrintCentered("Buona giornata", 3, true, lcd);
}
else
{
rfid.CancellaSerialeOggi(rfid.getSeriale());
LcdPrintCentered("Errore comunicazione", 0, true, lcd);
LcdPrintCentered("col server. Per fa-", 1, true, lcd);
LcdPrintCentered("vore contattare", 2, true, lcd);
LcdPrintCentered("l'amministratore", 3, true, lcd);
}
delay(lcdPause);
}
else // Se il badge era già stato rilevato in questa sessione, visualizza un messaggio ed esce
{
PlayBuzzer(); // Riproduce un suono
//if (rfid.getSessoUser() == "M")
//{
// tmpSesso = "stato inserito";
//}
//else if (rfid.getSessoUser() == "F")
//{
// tmpSesso = "stata inserita";
//}
//LcdPrintCentered(rfid.getNomeUser(), 0, true, lcd);
//LcdPrintCentered("era " + tmpSesso + ".", 1, true, lcd);
//LcdPrintCentered("Grazie e", 2, true, lcd);
//LcdPrintCentered("Buona giornata.", 3, true, lcd);
if (rfid.getSessoUser() == "M")
{
tmpSesso = "stato inserito";
}
else if (rfid.getSessoUser() == "F")
{
tmpSesso = "stata inserita";
}
if (rfid.getRuoloUser() == "B")
{
tmpRuolo = "stato inserito";
}
else if (rfid.getRuoloUser() == "E")
{
tmpRuolo = "stata inserita";
}
if (!SendDataToWebServer(rfid.getSeriale(), rfid.getRuoloUser(), false))
{
rfid.CancellaSerialeOggi(rfid.getSeriale());
LcdPrintCentered("Errore comunicazione", 0, true, lcd);
LcdPrintCentered("col server. Per fa-", 1, true, lcd);
LcdPrintCentered("vore contattare", 2, true, lcd);
LcdPrintCentered("l'amministratore", 3, true, lcd);
}
else
{
rfid.CancellaSerialeOggi(rfid.getSeriale());
LcdPrintCentered("Ciao", 0, true, lcd);
LcdPrintCentered(rfid.getNomeUser(), 1, true, lcd);
LcdPrintCentered("A presto e", 2, true, lcd);
LcdPrintCentered("buona giornata!", 3, true, lcd);
}
delay(lcdPause);
}
//*********** FINE MOD LETTURA ***********************************
}
else // Se nessun badge viene avvicinato visualizza un messaggio ed esci dal loop
{
LcdPrintCentered("Buongiorno!", 0, true, lcd);
LcdPrintCentered("Per favore", 1, true, lcd);
LcdPrintCentered("Avvicini il badge", 2, true, lcd);
LcdPrintCentered("Grazie!", 3, true, lcd);
return;
}
}
/*
Invia il seriale al web server che si occuperà di registrarne l'entrata nel database
userSerial: il seriale da inviare
ruolo: il ruolo dell'utente (B: Bambino, E:Educatore)
entrata: indica se si tratta di un entrata (true) o un'uscita (false)
La funzione restituisce l'id della presenze registrata o '0' se non è riuscito a registrarla
*/
int SendDataToWebServer(String userSerial, String ruolo, bool entrata)
{
int httpCode; // Ci serve per verificare che l'invio sia andato a buon fine
userSerial.trim(); // Eliminiamo eventuali spazi esterni della stringa
// *************** Usare GET ********************************************************
String entr = String(entrata);
String tmpStr = "http://192.168.0.2/NidoCellini/src/php/RegEntry.php?seriale=" + userSerial + "&ruolo=" + ruolo + "&entrata=" + entr;
//String tmpStr = "http://192.168.0.2/NidoCellini/src/php/RegEntry.php";
//WiFiClient tmpClient = wServer.client();
//Serial.println(tmpClient.connect('http://192.168.0.2/', 80));
httpC.begin(tmpStr); // Apriamo una connessione http verso il server
wServer.stop();
httpCode = httpC.GET();
// httpCode sarà negativo se c'e' stato un errore
if (httpCode > 0)
{
// Se il server
if (httpCode == HTTP_CODE_OK)
{
// Se tutto è andato bene restituiamo true
Serial.print("tmpStr: ");
Serial.println(tmpStr);
Serial.print("httpCode: ");
Serial.println(httpCode);
//httpC.setReused();
//String header;
//
//clientPres = webServer.available();
//while (!clientPres.connected())
//{
// Serial.println("InWhile");
// header = clientPres.readStringUntil('\r');
//}
//Serial.println(header);
//clientPres.flush();
//clientPres.stop();
httpC.end();
wServer.on("/NewBadge.html", HTTPMethod::HTTP_ANY, NewBadgeOnIn, NewBadgeOnOut);
wServer.on("/RegEntry.html", HTTPMethod::HTTP_ANY, NewBadgeOnIn, NewBadgeOnOut);
wServer.begin();
return true;
}
// Altrimenti false
httpC.end();
return 0;
}
else
{
// Se c'e' stato un errore lo stampiamo sulla seriale
Serial.printf("[HTTP] GET... fallito. Errore: %s\n",
httpC.errorToString(httpCode).c_str());
httpC.end();
return 0;
}
httpC.end();
}
bool AttivaModScrittura()
{
WiFiClient clientInterr;
String stopParam = "";
String stopHeader = "";
bool scritturaBadgeRiuscita = false;
String msgDiRitorno = ""; // Stringa contenente il messaggio da ritornare al server
if (modScrittura)
{
Serial.println("MODALITA' scrittura Attivata");
while (tempoAttesaBadgeXScrittura > 0)
{
if (rfid.BadgeRilevato())
{
PlayBuzzer();
scritturaBadgeRiuscita = rfid.ScriviNuovoBadge(nome_nuovo_badge, ruolo_nuovo_badge, sesso_nuovo_badge);//
if (scritturaBadgeRiuscita)
{
Serial.println(rfid.getSeriale());
msgDiRitorno = String("&S=Registrato&seriale=") + rfid.getSeriale();
client.print(msgDiRitorno);
delay(200);
client.flush();
client.stop();
LcdPrintCentered("Badge registrato.", 0, true, lcd);
LcdPrintCentered("Allontanarlo dal", 1, true, lcd);
LcdPrintCentered("lettore. Grazie e", 2, true, lcd);
LcdPrintCentered("buona giornata. ", 3, true, lcd);
delay(lcdPause);
}
else
{
msgDiRitorno = "&F=ScriviNuovoBadge";
client.print(msgDiRitorno);
delay(50);
client.flush();
client.stop();
LcdPrintCentered("Errore registrazione", 0, true, lcd);
LcdPrintCentered("del badge.", 1, true, lcd);
LcdPrintCentered("Contattare", 2, true, lcd);
LcdPrintCentered("l'amministratore.", 3, true, lcd);
delay(lcdPause);
}
break;
}
LcdPrintCentered("Avvicinare il badge", 0, true, lcd);
LcdPrintCentered("da registrare", 1, true, lcd);
LcdPrintCentered("entro un minuto.", 2, true, lcd);
LcdPrintCentered("Grazie.", 3, true, lcd);
tempoAttesaBadgeXScrittura -= 500;
delay(500);
clientInterr = webServer.available();
if (clientInterr.available())
{
stopHeader = clientInterr.readStringUntil('\r');
if (stopHeader.indexOf("command=stop") != -1)
{
delay(50);
clientInterr.stop();
msgDiRitorno = "&F=Stop";
client.print(msgDiRitorno); // Interrotto dall'utente
delay(50);
client.flush();
client.stop();
LcdPrintCentered("Registrazione badge", 0, true, lcd);
LcdPrintCentered("interrotta", 1, true, lcd);
LcdPrintCentered("dall'utente.", 2, true, lcd);
LcdPrintCentered(" ", 3, true, lcd);
delay(lcdPause);
break;
}
else
Serial.println("NON CANCELLARE!");
delay(10);
}
}
// Se il tempo per registrare il badge è finito
if (msgDiRitorno == "")
{
msgDiRitorno = "&F=Timeout";
client.print(msgDiRitorno); // Interruzione per scadenza tempo
delay(50);
client.flush();
client.stop();
LcdPrintCentered("Tempo per registrare", 0, true, lcd);
LcdPrintCentered("il badge esaurito.", 1, true, lcd);
LcdPrintCentered("Si prega ritentare.", 2, true, lcd);
LcdPrintCentered("Grazie. ", 3, true, lcd);
delay(lcdPause);
}
tempoAttesaBadgeXScrittura = tempoTotaleAttesaBadgeXScrittura;
nome_nuovo_badge = "";
ruolo_nuovo_badge = "";
sesso_nuovo_badge = "";
rfid.CancellaSerialeOggi(rfid.getSeriale());
modScrittura = false;
return scritturaBadgeRiuscita;
}
client.flush();
client.stop();
clientInterr.flush();
clientInterr.stop();
} | [
"36788151+SenzaNome78@users.noreply.github.com"
] | 36788151+SenzaNome78@users.noreply.github.com |
ee33517446438ce6144b0cf54d333876f4990a8b | a238ac1ac22b5b3684f7b0f326be66c75e05d4a3 | /WateringUnitConfig.cpp | f78df0837c92a7487578aa1b83aba5fe079fc3b2 | [] | no_license | pikapalasokeri/autowater | 36ed8f051cc9d52e001609fbe267bced48264598 | deddf6efcc9bdd4564acf3a8c01f887820dfd0fe | refs/heads/master | 2020-04-20T16:51:28.995239 | 2017-06-26T18:15:16 | 2019-02-03T10:39:21 | 168,970,830 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,343 | cpp | #include "WateringUnitConfig.hpp"
#include <iostream>
WateringUnitConfig::WateringUnitConfig(char pumpAdress,
int pumpPin,
char sensorAdress,
int sensorPin,
double humidityThreshold,
int interval,
int waitIterations,
const std::string& name,
const std::string& logFilePath)
: pumpAdress_(pumpAdress),
pumpPin_(pumpPin),
sensorAdress_(sensorAdress),
sensorPin_(sensorPin),
humidityThreshold_(humidityThreshold),
interval_(interval),
waitIterations_(waitIterations),
name_(name),
logFilePath_(logFilePath)
{}
std::ostream& operator<<(std::ostream& stream, const WateringUnitConfig& config)
{
stream << "Name: " << config.inqName() << std::endl
<< "Log file path: " << config.inqLogFilePath() << std::endl
<< "Pump adress: " << std::hex << int(config.inqPumpAdress()) << std::dec << std::endl
<< "Pump pin: " << config.inqPumpPin() << std::endl
<< "Sensor adress: " << std::hex << int(config.inqSensorAdress()) << std::dec << std::endl
<< "Sensor pin: " << config.inqSensorPin() << std::endl
<< "Humidity threshold: " << config.inqHumidityThreshold() << std::endl
<< "Interval: " << config.inqInterval() << std::endl
<< "Wait iterations: " << config.inqWaitIterations() << std::endl;
return stream;
}
| [
"noemail"
] | noemail |
284e4758a9fc375270b0b66a865c74d45dd64c74 | 158bd75e211b4cc9628a295e16e76eaecc74ce61 | /core/src/impl/DenseVector/Cuda/Morpheus_Convert_Impl.hpp | ce39df99e4a3d9e25c4e721bd9372c65f1858fb2 | [
"Apache-2.0"
] | permissive | morpheus-org/morpheus | 30733393fc60569859e838ecd942f1174767a87b | 026e9fe7ac17e27c92db98ae50b834889f192cf1 | refs/heads/develop | 2023-07-20T10:20:26.074095 | 2023-07-16T10:03:45 | 2023-07-16T10:03:45 | 272,454,646 | 12 | 0 | Apache-2.0 | 2022-12-30T15:09:13 | 2020-06-15T14:04:25 | C++ | UTF-8 | C++ | false | false | 1,862 | hpp | /**
* Morpheus_Convert_Impl.hpp
*
* EPCC, The University of Edinburgh
*
* (c) 2021 - 2023 The University of Edinburgh
*
* Contributing Authors:
* Christodoulos Stylianou (c.stylianou@ed.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
*
* 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 MORPHEUS_DENSEVECTOR_CUDA_CONVERT_IMPL_HPP
#define MORPHEUS_DENSEVECTOR_CUDA_CONVERT_IMPL_HPP
#include <Morpheus_Macros.hpp>
#if defined(MORPHEUS_ENABLE_CUDA)
#include <Morpheus_Exceptions.hpp>
#include <Morpheus_SpaceTraits.hpp>
#include <Morpheus_FormatTraits.hpp>
#include <Morpheus_FormatTags.hpp>
#include <Morpheus_Spaces.hpp>
namespace Morpheus {
namespace Impl {
template <typename ExecSpace, typename SourceType, typename DestinationType>
void convert(
const SourceType&, DestinationType&,
typename std::enable_if<
Morpheus::is_dense_vector_format_container_v<SourceType> &&
Morpheus::is_dense_vector_format_container_v<DestinationType> &&
Morpheus::has_custom_backend_v<ExecSpace> &&
Morpheus::has_cuda_execution_space_v<ExecSpace> &&
Morpheus::has_access_v<ExecSpace, SourceType, DestinationType>>::type* =
nullptr) {
throw Morpheus::NotImplementedException("convert<Kokkos::Cuda>");
}
} // namespace Impl
} // namespace Morpheus
#endif // MORPHEUS_ENABLE_CUDA
#endif // MORPHEUS_DENSEVECTOR_CUDA_CONVERT_IMPL_HPP | [
"cstyl16@gmail.com"
] | cstyl16@gmail.com |
a54220de09e6b8e9898f18724f6257b83f699b85 | 1a8eb812a6da07c98fbdc28e677d8a54ca1b8d4e | /Node.hpp | 9ca0a75e9b704089b0c1503ef27b779b0754a4a0 | [] | no_license | BryanR-SNHU/CS260-BinarySearchTree | 796ab250d59dbdd28ebdf9251e50aaafb31a3e7d | e5f30165dd841b07818754a74dc0f650becbd58b | refs/heads/master | 2023-07-15T06:23:12.315957 | 2021-08-21T20:53:30 | 2021-08-21T20:53:30 | 398,428,379 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 146 | hpp | #pragma once
#include "Bid.hpp"
/**
* Define nodes to place in the tree structure.
*/
struct Node {
Bid* bid;
Node* left;
Node* right;
};
| [
"bryan.rykowski@gmail.com"
] | bryan.rykowski@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.