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
5de6c3e8daf3c398e2b565c30e1236537be0e86f
95bc37d087ee384a461d9f82348802fc29a44e07
/casper/src/app.cpp
ad4fb9c6570c4be4e8bb623d756c580e317a0cb2
[ "Apache-2.0" ]
permissive
karanvivekbhargava/phantom
272bf42a625197166dc76d93b6361102fb1d8060
35accd85cbbfd793b9c2988af27b6cf3a8d0c76f
refs/heads/master
2020-04-27T20:02:56.461992
2019-04-13T19:19:18
2019-04-13T19:19:18
174,643,980
0
0
null
null
null
null
UTF-8
C++
false
false
1,528
cpp
#include "phantom/phantom.hpp" #include "imgui.h" #include <glm/vec3.hpp> // glm::vec3 #include <glm/vec4.hpp> // glm::vec4 #include <glm/mat4x4.hpp> // glm::mat4 #include <glm/ext/matrix_transform.hpp> // glm::translate, glm::rotate, glm::scale #include <glm/ext/matrix_clip_space.hpp> // glm::perspective //#include <glm/ext/constants.hpp> // glm::pi glm::mat4 camera(float Translate, glm::vec2 const& Rotate) { glm::mat4 Projection = glm::perspective(glm::pi<float>() * 0.25f, 4.0f / 3.0f, 0.1f, 100.f); glm::mat4 View = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -Translate)); View = glm::rotate(View, Rotate.y, glm::vec3(-1.0f, 0.0f, 0.0f)); View = glm::rotate(View, Rotate.x, glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 Model = glm::scale(glm::mat4(1.0f), glm::vec3(0.5f)); return Projection * View * Model; } class ExampleLayer : public Phantom::Layer { public: ExampleLayer() : Layer("Example") { auto cam = camera(5.0f, {0.5f, 0.6f}); } virtual void OnImGuiRender() override { ImGui::Begin("Test"); ImGui::Text("Hello World"); ImGui::End(); } void OnEvent(Phantom::Event& event) override { // PHTM_CLIENT_TRACE("{0}", event); } }; class Casper : public Phantom::Application { public: Casper() { PushLayer(new ExampleLayer); PushOverlay(new Phantom::ImGuiLayer()); } ~Casper() { } }; Phantom::Application* Phantom::CreateApplication() { return new Casper(); }
[ "karanb@umd.edu" ]
karanb@umd.edu
5730cf31858c8117f1e189694a9ef71a79f4a2a6
addf488ba98b8d09b0c430779ebd2649d29a3fea
/kdepim/knotes/knotebutton.cpp
37251001020a6a79a84261cb8789ab3b7900b8d9
[]
no_license
iegor/kdesktop
3d014d51a1fafaec18be2826ca3aa17597af9c07
d5dccbe01eeb7c0e82ac5647cf2bc2d4c7beda0b
refs/heads/master
2020-05-16T08:17:14.972852
2013-02-19T21:47:05
2013-02-19T21:47:05
9,459,573
1
0
null
null
null
null
UTF-8
C++
false
false
3,168
cpp
/******************************************************************* KNotes -- Notes for the KDE project Copyright (c) 2002-2004, The KNotes Developers This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *******************************************************************/ #include <qstyle.h> #include <qpainter.h> #include <qiconset.h> #include <qsizepolicy.h> #include <kglobal.h> #include <kicontheme.h> #include <kiconloader.h> #include "knotebutton.h" KNoteButton::KNoteButton( const QString& icon, QWidget *parent, const char *name ) : QPushButton( parent, name ) { setFocusPolicy( NoFocus ); setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) ); m_flat = true; if ( !icon.isEmpty() ) setIconSet( KGlobal::iconLoader()->loadIconSet( icon, KIcon::Small, 10 ) ); } KNoteButton::~KNoteButton() { } void KNoteButton::enterEvent( QEvent * ) { m_flat = false; repaint( false ); } void KNoteButton::leaveEvent( QEvent * ) { m_flat = true; repaint(); } QSize KNoteButton::sizeHint() const { return QSize( QPushButton::sizeHint().height(), QPushButton::sizeHint().height() ); } void KNoteButton::drawButton( QPainter* p ) { QStyle::SFlags flags = QStyle::Style_Default; if ( isEnabled() ) flags |= QStyle::Style_Enabled; if ( isDown() ) flags |= QStyle::Style_Down; if ( isOn() ) flags |= QStyle::Style_On; if ( !isFlat() && !isDown() ) flags |= QStyle::Style_Raised; if ( !m_flat ) flags |= QStyle::Style_MouseOver; style().drawPrimitive( QStyle::PE_ButtonTool, p, rect(), colorGroup(), flags ); drawButtonLabel( p ); } void KNoteButton::drawButtonLabel( QPainter* p ) { if ( iconSet() && !iconSet()->isNull() ) { QIconSet::Mode mode = QIconSet::Disabled; QIconSet::State state = QIconSet::Off; if ( isEnabled() ) mode = hasFocus() ? QIconSet::Active : QIconSet::Normal; if ( isToggleButton() && isOn() ) state = QIconSet::On; QPixmap pix = iconSet()->pixmap( QIconSet::Small, mode, state ); int dx = ( width() - pix.width() ) / 2; int dy = ( height() - pix.height() ) / 2; // Shift button contents if pushed. if ( isOn() || isDown() ) { dx += style().pixelMetric( QStyle::PM_ButtonShiftHorizontal, this ); dy += style().pixelMetric( QStyle::PM_ButtonShiftVertical, this ); } p->drawPixmap( dx, dy, pix ); } }
[ "rmtdev@gmail.com" ]
rmtdev@gmail.com
37d43d70aa5bb429815f05726fa37106531a33b3
56d1226dfefc93768a5f60ce15d1d7ca9bd58a08
/ddraw/Versions/IDirect3DDevice.h
9c27612705c14bf3c3af232b417cbdaea02baf7d
[ "Zlib", "GPL-1.0-or-later" ]
permissive
elishacloud/dxwrapper
ef6e047a6c49b98b74bf0adcff80740e8c0fff42
258bc970a72c7a4bd89449527a537e6912acbfb3
refs/heads/master
2023-08-17T06:13:06.649077
2023-08-16T21:17:18
2023-08-16T21:17:18
81,271,358
968
83
Zlib
2023-08-22T19:56:05
2017-02-08T00:58:26
C
UTF-8
C++
false
false
1,941
h
#pragma once class m_IDirect3DDevice : public IDirect3DDevice, public AddressLookupTableDdrawObject { private: m_IDirect3DDeviceX *ProxyInterface; IDirect3DDevice *RealInterface; REFIID WrapperID = IID_IDirect3DDevice; const DWORD DirectXVersion = 1; public: m_IDirect3DDevice(IDirect3DDevice *aOriginal, m_IDirect3DDeviceX *Interface) : RealInterface(aOriginal), ProxyInterface(Interface) { ProxyAddressLookupTable.SaveAddress(this, (RealInterface) ? RealInterface : (void*)ProxyInterface); } ~m_IDirect3DDevice() { ProxyAddressLookupTable.DeleteAddress(this); } /*** IUnknown methods ***/ STDMETHOD(QueryInterface)(THIS_ REFIID riid, LPVOID * ppvObj); STDMETHOD_(ULONG, AddRef)(THIS); STDMETHOD_(ULONG, Release)(THIS); /*** IDirect3DDevice methods ***/ STDMETHOD(Initialize)(THIS_ LPDIRECT3D, LPGUID, LPD3DDEVICEDESC); STDMETHOD(GetCaps)(THIS_ LPD3DDEVICEDESC, LPD3DDEVICEDESC); STDMETHOD(SwapTextureHandles)(THIS_ LPDIRECT3DTEXTURE, LPDIRECT3DTEXTURE); STDMETHOD(CreateExecuteBuffer)(THIS_ LPD3DEXECUTEBUFFERDESC, LPDIRECT3DEXECUTEBUFFER*, IUnknown*); STDMETHOD(GetStats)(THIS_ LPD3DSTATS); STDMETHOD(Execute)(THIS_ LPDIRECT3DEXECUTEBUFFER, LPDIRECT3DVIEWPORT, DWORD); STDMETHOD(AddViewport)(THIS_ LPDIRECT3DVIEWPORT); STDMETHOD(DeleteViewport)(THIS_ LPDIRECT3DVIEWPORT); STDMETHOD(NextViewport)(THIS_ LPDIRECT3DVIEWPORT, LPDIRECT3DVIEWPORT*, DWORD); STDMETHOD(Pick)(THIS_ LPDIRECT3DEXECUTEBUFFER, LPDIRECT3DVIEWPORT, DWORD, LPD3DRECT); STDMETHOD(GetPickRecords)(THIS_ LPDWORD, LPD3DPICKRECORD); STDMETHOD(EnumTextureFormats)(THIS_ LPD3DENUMTEXTUREFORMATSCALLBACK, LPVOID); STDMETHOD(CreateMatrix)(THIS_ LPD3DMATRIXHANDLE); STDMETHOD(SetMatrix)(THIS_ D3DMATRIXHANDLE, const LPD3DMATRIX); STDMETHOD(GetMatrix)(THIS_ D3DMATRIXHANDLE, LPD3DMATRIX); STDMETHOD(DeleteMatrix)(THIS_ D3DMATRIXHANDLE); STDMETHOD(BeginScene)(THIS); STDMETHOD(EndScene)(THIS); STDMETHOD(GetDirect3D)(THIS_ LPDIRECT3D*); };
[ "elisha@novicemail.com" ]
elisha@novicemail.com
7cdfa0c841809d54cca0479f31112fd3b0db52c4
8f4391979d5a457cd88c249c6c49df98308b636b
/CF-236A.cpp
1b067c6758cff9e4567d9bb00f61bcfd677d20f9
[]
no_license
yangyuyi/CodeForces
efedd0307e6efa14280722b915df99d489881cf4
047eebc2b87901a7284e332dee4fb167ba5b85c4
refs/heads/master
2022-12-14T15:18:34.395410
2020-09-07T13:13:15
2020-09-07T13:13:15
293,265,582
0
0
null
null
null
null
UTF-8
C++
false
false
361
cpp
// // Created by Taro Young on 2020/9/7. // #include <iostream> #include <string> using namespace std; int a[30]; int main() { string s; cin >> s; int num = 0; for (char ch:s) a[ch - 'a']++; for (int i = 0; i < 26; i++) if (a[i] != 0) num++; if (num % 2 == 0) cout << "CHAT WITH HER!"; else cout << "IGNORE HIM!"; return 0; }
[ "TaroYoung2000@gmail.com" ]
TaroYoung2000@gmail.com
be7b9277715c525ec91e3bd9d352a6e3400409d9
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_5/WRW+WR+pooncerelease+poreleaseacquire+Release.c.cbmc.cpp
84eb738c22803ec448654120ae0cde3d4b051424
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
35,463
cpp
// Global variabls: // 0:vars:2 // 2:atom_1_X0_1:1 // 3:atom_2_X1_0:1 // Local global variabls: // 0:thr0:1 // 1:thr1:1 // 2:thr2:1 #define ADDRSIZE 4 #define LOCALADDRSIZE 3 #define NTHREAD 4 #define NCONTEXT 5 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // Declare arrays for intial value version in contexts int local_mem[LOCALADDRSIZE]; // Dumping initializations local_mem[0+0] = 0; local_mem[1+0] = 0; local_mem[2+0] = 0; int cstart[NTHREAD]; int creturn[NTHREAD]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NTHREAD*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NTHREAD*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NTHREAD*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NTHREAD*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NTHREAD*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NTHREAD*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NTHREAD*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NTHREAD*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NTHREAD*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NTHREAD]; int cdy[NTHREAD]; int cds[NTHREAD]; int cdl[NTHREAD]; int cisb[NTHREAD]; int caddr[NTHREAD]; int cctrl[NTHREAD]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(2+0,0) = 0; mem(3+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; mem(0,1) = meminit(0,1); co(0,1) = coinit(0,1); delta(0,1) = deltainit(0,1); mem(0,2) = meminit(0,2); co(0,2) = coinit(0,2); delta(0,2) = deltainit(0,2); mem(0,3) = meminit(0,3); co(0,3) = coinit(0,3); delta(0,3) = deltainit(0,3); mem(0,4) = meminit(0,4); co(0,4) = coinit(0,4); delta(0,4) = deltainit(0,4); co(1,0) = 0; delta(1,0) = -1; mem(1,1) = meminit(1,1); co(1,1) = coinit(1,1); delta(1,1) = deltainit(1,1); mem(1,2) = meminit(1,2); co(1,2) = coinit(1,2); delta(1,2) = deltainit(1,2); mem(1,3) = meminit(1,3); co(1,3) = coinit(1,3); delta(1,3) = deltainit(1,3); mem(1,4) = meminit(1,4); co(1,4) = coinit(1,4); delta(1,4) = deltainit(1,4); co(2,0) = 0; delta(2,0) = -1; mem(2,1) = meminit(2,1); co(2,1) = coinit(2,1); delta(2,1) = deltainit(2,1); mem(2,2) = meminit(2,2); co(2,2) = coinit(2,2); delta(2,2) = deltainit(2,2); mem(2,3) = meminit(2,3); co(2,3) = coinit(2,3); delta(2,3) = deltainit(2,3); mem(2,4) = meminit(2,4); co(2,4) = coinit(2,4); delta(2,4) = deltainit(2,4); co(3,0) = 0; delta(3,0) = -1; mem(3,1) = meminit(3,1); co(3,1) = coinit(3,1); delta(3,1) = deltainit(3,1); mem(3,2) = meminit(3,2); co(3,2) = coinit(3,2); delta(3,2) = deltainit(3,2); mem(3,3) = meminit(3,3); co(3,3) = coinit(3,3); delta(3,3) = deltainit(3,3); mem(3,4) = meminit(3,4); co(3,4) = coinit(3,4); delta(3,4) = deltainit(3,4); // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !36, metadata !DIExpression()), !dbg !42 // br label %label_1, !dbg !43 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !41), !dbg !44 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !37, metadata !DIExpression()), !dbg !45 // call void @llvm.dbg.value(metadata i64 1, metadata !40, metadata !DIExpression()), !dbg !45 // store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !46 // ST: Guess // : Release iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l20_c3 old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l20_c3 // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); ASSUME(cw(1,0) >= cr(1,0+0)); ASSUME(cw(1,0) >= cr(1,0+1)); ASSUME(cw(1,0) >= cr(1,2+0)); ASSUME(cw(1,0) >= cr(1,3+0)); ASSUME(cw(1,0) >= cw(1,0+0)); ASSUME(cw(1,0) >= cw(1,0+1)); ASSUME(cw(1,0) >= cw(1,2+0)); ASSUME(cw(1,0) >= cw(1,3+0)); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 1; mem(0,cw(1,0)) = 1; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; is(1,0) = iw(1,0); cs(1,0) = cw(1,0); ASSUME(creturn[1] >= cw(1,0)); // ret i8* null, !dbg !47 ret_thread_1 = (- 1); goto T1BLOCK_END; T1BLOCK_END: // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !50, metadata !DIExpression()), !dbg !60 // br label %label_2, !dbg !48 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !59), !dbg !62 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !52, metadata !DIExpression()), !dbg !63 // %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !51 // LD: Guess old_cr = cr(2,0); cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l26_c15 // Check ASSUME(active[cr(2,0)] == 2); ASSUME(cr(2,0) >= iw(2,0)); ASSUME(cr(2,0) >= 0); ASSUME(cr(2,0) >= cdy[2]); ASSUME(cr(2,0) >= cisb[2]); ASSUME(cr(2,0) >= cdl[2]); ASSUME(cr(2,0) >= cl[2]); // Update creg_r0 = cr(2,0); crmax(2,0) = max(crmax(2,0),cr(2,0)); caddr[2] = max(caddr[2],0); if(cr(2,0) < cw(2,0)) { r0 = buff(2,0); ASSUME((!(( (cw(2,0) < 1) && (1 < crmax(2,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(2,0) < 2) && (2 < crmax(2,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(2,0) < 3) && (3 < crmax(2,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(2,0) < 4) && (4 < crmax(2,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(2,0) != co(0,cr(2,0))) { ASSUME(cr(2,0) >= old_cr); } pw(2,0) = co(0,cr(2,0)); r0 = mem(0,cr(2,0)); } ASSUME(creturn[2] >= cr(2,0)); // call void @llvm.dbg.value(metadata i64 %0, metadata !54, metadata !DIExpression()), !dbg !63 // %conv = trunc i64 %0 to i32, !dbg !52 // call void @llvm.dbg.value(metadata i32 %conv, metadata !51, metadata !DIExpression()), !dbg !60 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !55, metadata !DIExpression()), !dbg !66 // call void @llvm.dbg.value(metadata i64 1, metadata !57, metadata !DIExpression()), !dbg !66 // store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !54 // ST: Guess // : Release iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l27_c3 old_cw = cw(2,0+1*1); cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l27_c3 // Check ASSUME(active[iw(2,0+1*1)] == 2); ASSUME(active[cw(2,0+1*1)] == 2); ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(cw(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cw(2,0+1*1) >= old_cw); ASSUME(cw(2,0+1*1) >= cr(2,0+1*1)); ASSUME(cw(2,0+1*1) >= cl[2]); ASSUME(cw(2,0+1*1) >= cisb[2]); ASSUME(cw(2,0+1*1) >= cdy[2]); ASSUME(cw(2,0+1*1) >= cdl[2]); ASSUME(cw(2,0+1*1) >= cds[2]); ASSUME(cw(2,0+1*1) >= cctrl[2]); ASSUME(cw(2,0+1*1) >= caddr[2]); ASSUME(cw(2,0+1*1) >= cr(2,0+0)); ASSUME(cw(2,0+1*1) >= cr(2,0+1)); ASSUME(cw(2,0+1*1) >= cr(2,2+0)); ASSUME(cw(2,0+1*1) >= cr(2,3+0)); ASSUME(cw(2,0+1*1) >= cw(2,0+0)); ASSUME(cw(2,0+1*1) >= cw(2,0+1)); ASSUME(cw(2,0+1*1) >= cw(2,2+0)); ASSUME(cw(2,0+1*1) >= cw(2,3+0)); // Update caddr[2] = max(caddr[2],0); buff(2,0+1*1) = 1; mem(0+1*1,cw(2,0+1*1)) = 1; co(0+1*1,cw(2,0+1*1))+=1; delta(0+1*1,cw(2,0+1*1)) = -1; is(2,0+1*1) = iw(2,0+1*1); cs(2,0+1*1) = cw(2,0+1*1); ASSUME(creturn[2] >= cw(2,0+1*1)); // %cmp = icmp eq i32 %conv, 1, !dbg !55 creg__r0__1_ = max(0,creg_r0); // %conv1 = zext i1 %cmp to i32, !dbg !55 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !58, metadata !DIExpression()), !dbg !60 // store i32 %conv1, i32* @atom_1_X0_1, align 4, !dbg !56, !tbaa !57 // ST: Guess iw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l29_c15 old_cw = cw(2,2); cw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l29_c15 // Check ASSUME(active[iw(2,2)] == 2); ASSUME(active[cw(2,2)] == 2); ASSUME(sforbid(2,cw(2,2))== 0); ASSUME(iw(2,2) >= creg__r0__1_); ASSUME(iw(2,2) >= 0); ASSUME(cw(2,2) >= iw(2,2)); ASSUME(cw(2,2) >= old_cw); ASSUME(cw(2,2) >= cr(2,2)); ASSUME(cw(2,2) >= cl[2]); ASSUME(cw(2,2) >= cisb[2]); ASSUME(cw(2,2) >= cdy[2]); ASSUME(cw(2,2) >= cdl[2]); ASSUME(cw(2,2) >= cds[2]); ASSUME(cw(2,2) >= cctrl[2]); ASSUME(cw(2,2) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,2) = (r0==1); mem(2,cw(2,2)) = (r0==1); co(2,cw(2,2))+=1; delta(2,cw(2,2)) = -1; ASSUME(creturn[2] >= cw(2,2)); // ret i8* null, !dbg !61 ret_thread_2 = (- 1); goto T2BLOCK_END; T2BLOCK_END: // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !77, metadata !DIExpression()), !dbg !87 // br label %label_3, !dbg !48 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !86), !dbg !89 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !78, metadata !DIExpression()), !dbg !90 // call void @llvm.dbg.value(metadata i64 2, metadata !80, metadata !DIExpression()), !dbg !90 // store atomic i64 2, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !51 // ST: Guess // : Release iw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l35_c3 old_cw = cw(3,0+1*1); cw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l35_c3 // Check ASSUME(active[iw(3,0+1*1)] == 3); ASSUME(active[cw(3,0+1*1)] == 3); ASSUME(sforbid(0+1*1,cw(3,0+1*1))== 0); ASSUME(iw(3,0+1*1) >= 0); ASSUME(iw(3,0+1*1) >= 0); ASSUME(cw(3,0+1*1) >= iw(3,0+1*1)); ASSUME(cw(3,0+1*1) >= old_cw); ASSUME(cw(3,0+1*1) >= cr(3,0+1*1)); ASSUME(cw(3,0+1*1) >= cl[3]); ASSUME(cw(3,0+1*1) >= cisb[3]); ASSUME(cw(3,0+1*1) >= cdy[3]); ASSUME(cw(3,0+1*1) >= cdl[3]); ASSUME(cw(3,0+1*1) >= cds[3]); ASSUME(cw(3,0+1*1) >= cctrl[3]); ASSUME(cw(3,0+1*1) >= caddr[3]); ASSUME(cw(3,0+1*1) >= cr(3,0+0)); ASSUME(cw(3,0+1*1) >= cr(3,0+1)); ASSUME(cw(3,0+1*1) >= cr(3,2+0)); ASSUME(cw(3,0+1*1) >= cr(3,3+0)); ASSUME(cw(3,0+1*1) >= cw(3,0+0)); ASSUME(cw(3,0+1*1) >= cw(3,0+1)); ASSUME(cw(3,0+1*1) >= cw(3,2+0)); ASSUME(cw(3,0+1*1) >= cw(3,3+0)); // Update caddr[3] = max(caddr[3],0); buff(3,0+1*1) = 2; mem(0+1*1,cw(3,0+1*1)) = 2; co(0+1*1,cw(3,0+1*1))+=1; delta(0+1*1,cw(3,0+1*1)) = -1; is(3,0+1*1) = iw(3,0+1*1); cs(3,0+1*1) = cw(3,0+1*1); ASSUME(creturn[3] >= cw(3,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !82, metadata !DIExpression()), !dbg !92 // %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) acquire, align 8, !dbg !53 // LD: Guess // : Acquire old_cr = cr(3,0); cr(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l36_c15 // Check ASSUME(active[cr(3,0)] == 3); ASSUME(cr(3,0) >= iw(3,0)); ASSUME(cr(3,0) >= 0); ASSUME(cr(3,0) >= cdy[3]); ASSUME(cr(3,0) >= cisb[3]); ASSUME(cr(3,0) >= cdl[3]); ASSUME(cr(3,0) >= cl[3]); ASSUME(cr(3,0) >= cx(3,0)); ASSUME(cr(3,0) >= cs(3,0+0)); ASSUME(cr(3,0) >= cs(3,0+1)); ASSUME(cr(3,0) >= cs(3,2+0)); ASSUME(cr(3,0) >= cs(3,3+0)); // Update creg_r1 = cr(3,0); crmax(3,0) = max(crmax(3,0),cr(3,0)); caddr[3] = max(caddr[3],0); if(cr(3,0) < cw(3,0)) { r1 = buff(3,0); ASSUME((!(( (cw(3,0) < 1) && (1 < crmax(3,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(3,0) < 2) && (2 < crmax(3,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(3,0) < 3) && (3 < crmax(3,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(3,0) < 4) && (4 < crmax(3,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(3,0) != co(0,cr(3,0))) { ASSUME(cr(3,0) >= old_cr); } pw(3,0) = co(0,cr(3,0)); r1 = mem(0,cr(3,0)); } cl[3] = max(cl[3],cr(3,0)); ASSUME(creturn[3] >= cr(3,0)); // call void @llvm.dbg.value(metadata i64 %0, metadata !84, metadata !DIExpression()), !dbg !92 // %conv = trunc i64 %0 to i32, !dbg !54 // call void @llvm.dbg.value(metadata i32 %conv, metadata !81, metadata !DIExpression()), !dbg !87 // %cmp = icmp eq i32 %conv, 0, !dbg !55 creg__r1__0_ = max(0,creg_r1); // %conv1 = zext i1 %cmp to i32, !dbg !55 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !85, metadata !DIExpression()), !dbg !87 // store i32 %conv1, i32* @atom_2_X1_0, align 4, !dbg !56, !tbaa !57 // ST: Guess iw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l38_c15 old_cw = cw(3,3); cw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l38_c15 // Check ASSUME(active[iw(3,3)] == 3); ASSUME(active[cw(3,3)] == 3); ASSUME(sforbid(3,cw(3,3))== 0); ASSUME(iw(3,3) >= creg__r1__0_); ASSUME(iw(3,3) >= 0); ASSUME(cw(3,3) >= iw(3,3)); ASSUME(cw(3,3) >= old_cw); ASSUME(cw(3,3) >= cr(3,3)); ASSUME(cw(3,3) >= cl[3]); ASSUME(cw(3,3) >= cisb[3]); ASSUME(cw(3,3) >= cdy[3]); ASSUME(cw(3,3) >= cdl[3]); ASSUME(cw(3,3) >= cds[3]); ASSUME(cw(3,3) >= cctrl[3]); ASSUME(cw(3,3) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,3) = (r1==0); mem(3,cw(3,3)) = (r1==0); co(3,cw(3,3))+=1; delta(3,cw(3,3)) = -1; ASSUME(creturn[3] >= cw(3,3)); // ret i8* null, !dbg !61 ret_thread_3 = (- 1); goto T3BLOCK_END; T3BLOCK_END: // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !105, metadata !DIExpression()), !dbg !128 // call void @llvm.dbg.value(metadata i8** %argv, metadata !106, metadata !DIExpression()), !dbg !128 // %0 = bitcast i64* %thr0 to i8*, !dbg !64 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !64 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !107, metadata !DIExpression()), !dbg !130 // %1 = bitcast i64* %thr1 to i8*, !dbg !66 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !66 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !111, metadata !DIExpression()), !dbg !132 // %2 = bitcast i64* %thr2 to i8*, !dbg !68 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !68 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !112, metadata !DIExpression()), !dbg !134 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !113, metadata !DIExpression()), !dbg !135 // call void @llvm.dbg.value(metadata i64 0, metadata !115, metadata !DIExpression()), !dbg !135 // store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !71 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l47_c3 old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l47_c3 // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !116, metadata !DIExpression()), !dbg !137 // call void @llvm.dbg.value(metadata i64 0, metadata !118, metadata !DIExpression()), !dbg !137 // store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !73 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l48_c3 old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l48_c3 // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // store i32 0, i32* @atom_1_X0_1, align 4, !dbg !74, !tbaa !75 // ST: Guess iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l49_c15 old_cw = cw(0,2); cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l49_c15 // Check ASSUME(active[iw(0,2)] == 0); ASSUME(active[cw(0,2)] == 0); ASSUME(sforbid(2,cw(0,2))== 0); ASSUME(iw(0,2) >= 0); ASSUME(iw(0,2) >= 0); ASSUME(cw(0,2) >= iw(0,2)); ASSUME(cw(0,2) >= old_cw); ASSUME(cw(0,2) >= cr(0,2)); ASSUME(cw(0,2) >= cl[0]); ASSUME(cw(0,2) >= cisb[0]); ASSUME(cw(0,2) >= cdy[0]); ASSUME(cw(0,2) >= cdl[0]); ASSUME(cw(0,2) >= cds[0]); ASSUME(cw(0,2) >= cctrl[0]); ASSUME(cw(0,2) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,2) = 0; mem(2,cw(0,2)) = 0; co(2,cw(0,2))+=1; delta(2,cw(0,2)) = -1; ASSUME(creturn[0] >= cw(0,2)); // store i32 0, i32* @atom_2_X1_0, align 4, !dbg !79, !tbaa !75 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l50_c15 old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l50_c15 // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !80 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call3 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !81 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call4 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !82 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !83, !tbaa !84 r3 = local_mem[0]; // %call5 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !86 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !87, !tbaa !84 r4 = local_mem[1]; // %call6 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !88 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !89, !tbaa !84 r5 = local_mem[2]; // %call7 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !90 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !120, metadata !DIExpression()), !dbg !152 // %6 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !92 // LD: Guess old_cr = cr(0,0+1*1); cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l60_c12 // Check ASSUME(active[cr(0,0+1*1)] == 0); ASSUME(cr(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cr(0,0+1*1) >= 0); ASSUME(cr(0,0+1*1) >= cdy[0]); ASSUME(cr(0,0+1*1) >= cisb[0]); ASSUME(cr(0,0+1*1) >= cdl[0]); ASSUME(cr(0,0+1*1) >= cl[0]); // Update creg_r6 = cr(0,0+1*1); crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+1*1) < cw(0,0+1*1)) { r6 = buff(0,0+1*1); ASSUME((!(( (cw(0,0+1*1) < 1) && (1 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,1)> 0)); ASSUME((!(( (cw(0,0+1*1) < 2) && (2 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,2)> 0)); ASSUME((!(( (cw(0,0+1*1) < 3) && (3 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,3)> 0)); ASSUME((!(( (cw(0,0+1*1) < 4) && (4 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,4)> 0)); } else { if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) { ASSUME(cr(0,0+1*1) >= old_cr); } pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1)); r6 = mem(0+1*1,cr(0,0+1*1)); } ASSUME(creturn[0] >= cr(0,0+1*1)); // call void @llvm.dbg.value(metadata i64 %6, metadata !122, metadata !DIExpression()), !dbg !152 // %conv = trunc i64 %6 to i32, !dbg !93 // call void @llvm.dbg.value(metadata i32 %conv, metadata !119, metadata !DIExpression()), !dbg !128 // %cmp = icmp eq i32 %conv, 2, !dbg !94 creg__r6__2_ = max(0,creg_r6); // %conv8 = zext i1 %cmp to i32, !dbg !94 // call void @llvm.dbg.value(metadata i32 %conv8, metadata !123, metadata !DIExpression()), !dbg !128 // %7 = load i32, i32* @atom_1_X0_1, align 4, !dbg !95, !tbaa !75 // LD: Guess old_cr = cr(0,2); cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l62_c12 // Check ASSUME(active[cr(0,2)] == 0); ASSUME(cr(0,2) >= iw(0,2)); ASSUME(cr(0,2) >= 0); ASSUME(cr(0,2) >= cdy[0]); ASSUME(cr(0,2) >= cisb[0]); ASSUME(cr(0,2) >= cdl[0]); ASSUME(cr(0,2) >= cl[0]); // Update creg_r7 = cr(0,2); crmax(0,2) = max(crmax(0,2),cr(0,2)); caddr[0] = max(caddr[0],0); if(cr(0,2) < cw(0,2)) { r7 = buff(0,2); ASSUME((!(( (cw(0,2) < 1) && (1 < crmax(0,2)) )))||(sforbid(2,1)> 0)); ASSUME((!(( (cw(0,2) < 2) && (2 < crmax(0,2)) )))||(sforbid(2,2)> 0)); ASSUME((!(( (cw(0,2) < 3) && (3 < crmax(0,2)) )))||(sforbid(2,3)> 0)); ASSUME((!(( (cw(0,2) < 4) && (4 < crmax(0,2)) )))||(sforbid(2,4)> 0)); } else { if(pw(0,2) != co(2,cr(0,2))) { ASSUME(cr(0,2) >= old_cr); } pw(0,2) = co(2,cr(0,2)); r7 = mem(2,cr(0,2)); } ASSUME(creturn[0] >= cr(0,2)); // call void @llvm.dbg.value(metadata i32 %7, metadata !124, metadata !DIExpression()), !dbg !128 // %8 = load i32, i32* @atom_2_X1_0, align 4, !dbg !96, !tbaa !75 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l63_c13 // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r8 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r8 = buff(0,3); ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0)); ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0)); ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0)); ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0)); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r8 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i32 %8, metadata !125, metadata !DIExpression()), !dbg !128 // %and = and i32 %7, %8, !dbg !97 creg_r9 = max(creg_r7,creg_r8); r9 = r7 & r8; // call void @llvm.dbg.value(metadata i32 %and, metadata !126, metadata !DIExpression()), !dbg !128 // %and9 = and i32 %conv8, %and, !dbg !98 creg_r10 = max(creg__r6__2_,creg_r9); r10 = (r6==2) & r9; // call void @llvm.dbg.value(metadata i32 %and9, metadata !127, metadata !DIExpression()), !dbg !128 // %cmp10 = icmp eq i32 %and9, 1, !dbg !99 creg__r10__1_ = max(0,creg_r10); // br i1 %cmp10, label %if.then, label %if.end, !dbg !101 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg__r10__1_); if((r10==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([130 x i8], [130 x i8]* @.str.1, i64 0, i64 0), i32 noundef 66, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !102 // unreachable, !dbg !102 r11 = 1; goto T0BLOCK_END; T0BLOCK2: // %9 = bitcast i64* %thr2 to i8*, !dbg !105 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !105 // %10 = bitcast i64* %thr1 to i8*, !dbg !105 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !105 // %11 = bitcast i64* %thr0 to i8*, !dbg !105 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !105 // ret i32 0, !dbg !106 ret_thread_0 = 0; goto T0BLOCK_END; T0BLOCK_END: ASSUME(meminit(0,1) == mem(0,0)); ASSUME(coinit(0,1) == co(0,0)); ASSUME(deltainit(0,1) == delta(0,0)); ASSUME(meminit(0,2) == mem(0,1)); ASSUME(coinit(0,2) == co(0,1)); ASSUME(deltainit(0,2) == delta(0,1)); ASSUME(meminit(0,3) == mem(0,2)); ASSUME(coinit(0,3) == co(0,2)); ASSUME(deltainit(0,3) == delta(0,2)); ASSUME(meminit(0,4) == mem(0,3)); ASSUME(coinit(0,4) == co(0,3)); ASSUME(deltainit(0,4) == delta(0,3)); ASSUME(meminit(1,1) == mem(1,0)); ASSUME(coinit(1,1) == co(1,0)); ASSUME(deltainit(1,1) == delta(1,0)); ASSUME(meminit(1,2) == mem(1,1)); ASSUME(coinit(1,2) == co(1,1)); ASSUME(deltainit(1,2) == delta(1,1)); ASSUME(meminit(1,3) == mem(1,2)); ASSUME(coinit(1,3) == co(1,2)); ASSUME(deltainit(1,3) == delta(1,2)); ASSUME(meminit(1,4) == mem(1,3)); ASSUME(coinit(1,4) == co(1,3)); ASSUME(deltainit(1,4) == delta(1,3)); ASSUME(meminit(2,1) == mem(2,0)); ASSUME(coinit(2,1) == co(2,0)); ASSUME(deltainit(2,1) == delta(2,0)); ASSUME(meminit(2,2) == mem(2,1)); ASSUME(coinit(2,2) == co(2,1)); ASSUME(deltainit(2,2) == delta(2,1)); ASSUME(meminit(2,3) == mem(2,2)); ASSUME(coinit(2,3) == co(2,2)); ASSUME(deltainit(2,3) == delta(2,2)); ASSUME(meminit(2,4) == mem(2,3)); ASSUME(coinit(2,4) == co(2,3)); ASSUME(deltainit(2,4) == delta(2,3)); ASSUME(meminit(3,1) == mem(3,0)); ASSUME(coinit(3,1) == co(3,0)); ASSUME(deltainit(3,1) == delta(3,0)); ASSUME(meminit(3,2) == mem(3,1)); ASSUME(coinit(3,2) == co(3,1)); ASSUME(deltainit(3,2) == delta(3,1)); ASSUME(meminit(3,3) == mem(3,2)); ASSUME(coinit(3,3) == co(3,2)); ASSUME(deltainit(3,3) == delta(3,2)); ASSUME(meminit(3,4) == mem(3,3)); ASSUME(coinit(3,4) == co(3,3)); ASSUME(deltainit(3,4) == delta(3,3)); ASSERT(r11== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
285ab902323daa435e953e6d2d28a0d762903269
758a13f9debcd78cd548cc7cc79843d421d809f3
/devel/electron12/files/patch-ui_views_controls_label.cc
5a1e9b7a98be7f864dfc4c5b8683fd8876188588
[ "BSD-2-Clause" ]
permissive
DentonGentry/FreeBSD-ports
5fbb8d96afcb47a1d26518bb11cc58dcf61dcfe2
8cf43fc967a5ba15ef1177fd62f14ef027e455b1
refs/heads/main
2023-08-06T01:43:17.261186
2021-08-28T13:08:05
2021-08-29T00:26:12
400,921,743
2
2
NOASSERTION
2021-08-29T01:01:27
2021-08-29T01:01:27
null
UTF-8
C++
false
false
1,020
cc
--- ui/views/controls/label.cc.orig 2021-04-14 01:09:40 UTC +++ ui/views/controls/label.cc @@ -806,7 +806,7 @@ bool Label::OnMousePressed(const ui::MouseEvent& event // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch // of lacros-chrome is complete. -#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) || defined(OS_BSD) if (event.IsOnlyMiddleMouseButton() && GetFocusManager() && !had_focus) GetFocusManager()->SetFocusedView(this); #endif @@ -995,7 +995,7 @@ bool Label::PasteSelectionClipboard() { void Label::UpdateSelectionClipboard() { // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch // of lacros-chrome is complete. -#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) +#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) || defined(OS_BSD) if (!GetObscured()) { ui::ScopedClipboardWriter(ui::ClipboardBuffer::kSelection) .WriteText(GetSelectedText());
[ "tagattie@FreeBSD.org" ]
tagattie@FreeBSD.org
0265d99d0809777fb980a81122099f4bc47f043a
15f0514701a78e12750f68ba09d68095172493ee
/C++/83.cpp
9057ebff243f1ce1df2d4cc667170d6d7145760a
[ "MIT" ]
permissive
strengthen/LeetCode
5e38c8c9d3e8f27109b9124ae17ef8a4139a1518
3ffa6dcbeb787a6128641402081a4ff70093bb61
refs/heads/master
2022-12-04T21:35:17.872212
2022-11-30T06:23:24
2022-11-30T06:23:24
155,958,163
936
365
MIT
2021-11-15T04:02:45
2018-11-03T06:47:38
null
UTF-8
C++
false
false
1,283
cpp
__________________________________________________________________________________________________ 12ms class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode *cur = head; while (cur && cur->next) { if (cur->val == cur->next->val) { cur->next = cur->next->next; } else { cur = cur->next; } } return head; } }; __________________________________________________________________________________________________ 8980 kb /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* p = head; if (p == nullptr) return head; ListNode* q = p->next; unordered_set<int> s; while (q != nullptr) { if (q->val == p->val) { q = q->next; p->next = q; } else { p = q; q = q->next; } } return head; } }; __________________________________________________________________________________________________
[ "strengthen@users.noreply.github.com" ]
strengthen@users.noreply.github.com
6e04db9c89197f56fc2ab561645f12f6b8270f3b
e1693e396a7f69b79b3fdbba315535576f332e77
/ArduinoGameOfLife.ino
01f46027f7b4340e63b1e94bd875c73f0276ef00
[]
no_license
ReconditeRose/ArduinoGameOfLife
cb5aca0dfd41f0569cb6c1c315d7346ac4d63649
4079ec078389db366744e48e240a9c92476967d2
refs/heads/master
2021-01-19T22:29:45.344898
2015-04-18T21:04:57
2015-04-18T21:04:57
34,158,922
0
0
null
null
null
null
UTF-8
C++
false
false
3,355
ino
#include "Configuration.h" #include "preDefinedArrays.h" #include "GameOfLifeExecution.h" /* ---------------Setup and main loop--------------- Main setup function for initializing input pins and main loop */ //Array that holds the current state of the cells byte cell_Array[504]; void setup(void) { LCDInit(); //Init the LCD loadArray(gliderGun); //Arbitrary starting position //Configure pins pinMode(PIN_SWITCH_DISPLAY, INPUT); pinMode(PIN_LIGHT_SWITCH, INPUT); pinMode(PIN_LIGHT, OUTPUT); //Turn backlight on digitalWrite(PIN_LIGHT, HIGH); } void loop(void) { int i; handleInput(); for (i = 0; i < (CellArray); i++) { LCDWrite(LCD_DATA, cell_Array[i]); } stepOfLife(cell_Array); } /* ---------------Input handling--------------- Two buttons are present that needed to be checked for input. Both buttons should not be pressed together, so the light is prioritized. The inputs are one shotted. Debouncing is unnecessary since the event loop takes so long to execute, you would have to hold the button for a very long time. */ byte pressed = 0; byte displayLoop = 0; byte light = 1; int resetCountdown = 0; void handleInput(void){ if (digitalRead(PIN_LIGHT_SWITCH) == 1) { if (pressed == 0) { if (light == 1) { digitalWrite(PIN_LIGHT, HIGH); light = 0; } else { digitalWrite(PIN_LIGHT, LOW); light = 1; } } pressed = 1; } else if (digitalRead(PIN_SWITCH_DISPLAY) == 1) { if (pressed == 0){ switch(displayLoop){ case 0: randomize(); resetCountdown = 0; break; case 1: loadArray(gliderGun); break; case 2: loadArray(oscillators); break; case 3: loadArray(oscillate144); break; } displayLoop = (displayLoop+1)%4; pressed = 1; } } else { pressed = 0; } if(displayLoop==0){ resetCountdown++; if(resetCountdown == RANDOM_RESET){ randomize(); resetCountdown = 0; } } } /* ---------------Pre-defined cell Arrangements--------------- Handles updating the cell array to set new cell configurations. */ void loadArray(prog_char * e){ int i; for(i=0;i<CellArray;i++){ cell_Array[i] = pgm_read_byte_near(e+i); } } void randomize(void) { int i; //Seed randomization randomSeed((int) millis()); for (i = 0; i < LCD_X * LCD_Y / 8; i++) { //Randomize each byte cell_Array[i] = random(32767); } } /* ---------------LCD Drivers--------------- */ void LCDInit(void) { //Initialize pins pinMode(PIN_SCE, OUTPUT); pinMode(PIN_RESET, OUTPUT); pinMode(PIN_DC, OUTPUT); pinMode(PIN_SDIN, OUTPUT); pinMode(PIN_SCLK, OUTPUT); //Reset the LCD digitalWrite(PIN_RESET, LOW); digitalWrite(PIN_RESET, HIGH); //Initialize the LCD LCDWrite(LCD_COMMAND, 0x21); LCDWrite(LCD_COMMAND, 0x90); LCDWrite(LCD_COMMAND, 0x04); LCDWrite(LCD_COMMAND, 0x14); LCDWrite(LCD_COMMAND, 0x0C); LCDWrite(LCD_COMMAND, 0x20); LCDWrite(LCD_COMMAND, 0x0C); } void LCDWrite(byte data_or_command, byte data) { //Indicate the type of data being sent digitalWrite(PIN_DC, data_or_command); //Send the data digitalWrite(PIN_SCE, LOW); shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data); digitalWrite(PIN_SCE, HIGH); }
[ "wizieldaguy@gmail.com" ]
wizieldaguy@gmail.com
f7260be52ae7ca17f3c73b1f286a31f0b4ad7bc8
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5709773144064000_0/C++/venco5/B-small.cpp
2ff2b735e025d222559031eb21ffa30c40305385
[]
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
2,077
cpp
#include <string> #include <vector> #include <list> #include <map> #include <set> #include <cmath> #include <numeric> #include <algorithm> #include <functional> #include <cctype> #include <sstream> #include <cstring> #include <iostream> #include <iomanip> #include <gmp.h> #ifdef HOME_RUN # include <debug.hpp> # include <dump.hpp> # include <cassert> #else # define TR(x) do{}while(0) # ifdef assert # indef assert # endif # define assert(x) do{}while(0) #endif using namespace std; #define ALL(C) (C).begin(), (C).end() #define forIter(I,C) for(auto I=(C).begin(); I!=(C).end(); ++I) #define forNF(I,S,C) for(int I=(S); I<int(C); ++I) #define forN(I,C) forNF(I,0,C) #define forEach(I,C) forN(I,(C).size()) typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; typedef long long i64; typedef unsigned long long u64; inline istream& skip_endl(istream& in) { string s; getline(in, s); forIter( i, s ) assert(isspace(*i)); return in; } inline string get_str() { string ret; getline(cin, ret); return ret; } map<string, int> str_index; int get_index(const string& s) { return str_index.insert(make_pair(s, str_index.size())).first->second; } int get_str_index() { return get_index(get_str()); } ///////////////////////////////////////////////////////////////////////////// int num_cases = 1, part_cases = 0; int main(int argc, const char** argv) { //NTR = 1000; cin >> num_cases >> skip_endl; if ( argc == 2 ) part_cases = atoi(argv[1]); forN ( nc, num_cases ) { // parse input double C, F, X; cin >> C >> F >> X >> skip_endl; // error check if ( !cin ) { cout << "Error parsing input" << endl; return 1; } // main code double ret = X/2; double t0 = 0; for ( unsigned k = 1; ; ++k ) { t0 += C/(2+(k-1)*F); double t = t0+X/(2+k*F); if ( t > ret ) break; ret = t; } // output cout << "Case #"<<nc+1<<": "; cout << fixed << setprecision(7) << ret; cout << endl; } }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
d1eda80f7d1b933068320d61d6a54c972dfcbef0
1cd965da612f3f0e4d458935cc60023de942b3a6
/experiments/cpp/tpch_util/s3utils.cpp
42665a49f6354f53d91f8dc0fd558732cdb8013e
[ "Apache-2.0" ]
permissive
weld-project/clamor
ad42d001078ceb9e74a4a9389050dc819bf6cdc3
72e7a75e608bb3407ab6f7ee47f24f707932b71a
refs/heads/master
2023-09-03T12:56:48.623120
2021-11-04T18:00:46
2021-11-04T18:00:46
424,517,465
5
0
null
null
null
null
UTF-8
C++
false
false
6,894
cpp
#include <cstdlib> #include <string> #include <cstdio> #include <sstream> #include "s3utils.h" #define BUF_SIZE 4096 using namespace std; bool load_sf(int argc, char** argv, int& SF) { for (int i=1; i<argc; i++) { if (i+1 != argc) { if (strcmp(argv[i], "-sf") == 0) { SF = atoi(argv[i+1]); return true; } } } return false; } int binary_search(int* arr, int len, int e) { int first = 0; int last = len - 1; int middle = (first+last)/2; while (first <= last) { if (arr[middle] < e) first = middle + 1; else if (arr[middle] == e) { return middle; } else last = middle - 1; middle = (first + last)/2; } return -1; } int parse_date(const char* d) { const char z = '0'; int year = (d[3] - z) + (d[2] - z)*10 + (d[1]-z)*100 + (d[0]-z)*1000; int month = (d[6] - z) + (d[5] - z)*10; int day = (d[9] - z) + (d[8] - z)*10; return day + month * 100 + year * 10000; } void load_orders(Order* orders, FILE* tbl, int partition, int num_parts, int sf) { char buf[BUF_SIZE]; if (!tbl) { perror("couldn't open orders file"); } int index = (partition * ORDERS_PER_SF * sf) / num_parts; while (fgets(buf, BUF_SIZE, tbl)) { char* line = buf; char* token; int column = 0; while (column < 8 && (token = strsep(&line, "|")) != NULL) { switch (column) { case 0: orders[index].orderkey= atoi(token); break; case 1: orders[index].custkey= atoi(token); break; case 4: orders[index].orderdate= parse_date(token); break; case 5: orders[index].orderpriority= token[0] - '0'; break; case 7: orders[index].shippriority= atoi(token); break; default: break; } column++; } index++; } } int load_lineitems(Lineitem* lineitems, char* tbl, int offset) { if (!tbl) { perror("couldn't open lineitems file"); } string tmp(tbl); istringstream iss(tmp); int index = 0; string sline; while (getline(iss, sline)) { char* line = &sline[0]; char* token; int column = 0; int commitdate, shipdate, receiptdate; while ((token = strsep(&line, "|")) != NULL) { switch (column) { case 0: lineitems[index].orderkey = atoi(token); break; case 1: lineitems[index].partkey= atoi(token); break; case 2: lineitems[index].suppkey = atoi(token); break; case 4: lineitems[index].quantity= atoi(token); break; case 5: lineitems[index].extendedprice= atof(token); break; case 6: lineitems[index].discount= atof(token); break; case 7: lineitems[index].tax= atof(token); break; case 8: if (token[0] == 'N') lineitems[index].returnflag= 0; else if (token[0] == 'R') lineitems[index].returnflag= 1; else lineitems[index].returnflag= 2; break; case 9: if (token[0] == 'O') lineitems[index].linestatus= 0; else lineitems[index].linestatus= 1; break; case 10: lineitems[index].shipdate= parse_date(token); break; case 11: lineitems[index].commitdate= parse_date(token); break; case 12: lineitems[index].receiptdate= parse_date(token); break; case 13: if(strcmp(token, "DELIVER IN PERSON") == 0) lineitems[index].shipinstruct= 1; else if(strcmp(token, "TAKE BACK RETURN") == 0) lineitems[index].shipinstruct= 2; else if(strcmp(token, "COLLECT COD") == 0) lineitems[index].shipinstruct= 3; else if(strcmp(token, "NONE") == 0) lineitems[index].shipinstruct= 4; else lineitems[index].shipinstruct= 0; break; case 14: if (strcmp(token, "MAIL") == 0) lineitems[index].shipmode= 1; else if (strcmp(token, "AIR") == 0) lineitems[index].shipmode= 2; else if (strcmp(token, "AIR REG") == 0) lineitems[index].shipmode= 3; else lineitems[index].shipmode= 0; break; default: break; } column++; } index++; } return index; } void load_customers(Customer* c, FILE* tbl, int partition, int num_parts, int sf) { char buf[BUF_SIZE]; if (!tbl) { perror("couldn't open customers file"); } int index = (partition * CUSTOMERS_PER_SF * sf) / num_parts; int count = 0; while (fgets(buf, BUF_SIZE, tbl)) { char* line = buf; char* token; int column = 0; while ((token = strsep(&line, "|")) != NULL) { if (column == 6) { if (strcmp(token, "MACHINERY") == 0) { count++; c[index].mktsegment = 1; } else c[index].mktsegment = 0; } column++; } index++; } } void load_parts(Part* parts, FILE* tbl, int offset) { char buf[BUF_SIZE]; if (!tbl) { perror("couldn't open parts file"); } int index = offset; while (fgets(buf, BUF_SIZE, tbl)) { char* line = buf; char* token; int column = 0; while ((token = strsep(&line, "|")) != NULL) { switch (column) { case 0: parts[index].partkey= atoi(token); break; case 3: int brand; sscanf(token, "Brand#%d", &brand); parts[index].brand= brand; break; case 4: int promostr; if (strncmp(token, "PROMO", 5) == 0) { promostr = 1; } else { promostr = 0; } parts[index].promo_str= promostr; case 5: parts[index].size= atoi(token); break; case 6: char case_type[10]; char case_size[10]; int type; int size; sscanf(token, "%s %s", case_size, case_type); if(strcmp(case_type, "CASE") == 0) type = 1; else if(strcmp(case_type, "DRUM") == 0) type = 2; else if(strcmp(case_type, "PKG") == 0) type = 3; else if(strcmp(case_type, "BAG") == 0) type = 4; else if(strcmp(case_type, "CAN") == 0) type = 5; else if(strcmp(case_type, "BOX") == 0) type = 6; else if(strcmp(case_type, "PACK") == 0) type = 7; else if(strcmp(case_type, "JAR") == 0) type = 8; else type = 0; if(strcmp(case_size, "SM") == 0) size = 10; else if(strcmp(case_size, "MED") == 0) size = 20; else if(strcmp(case_size, "LG") == 0) size = 30; else if(strcmp(case_size, "JUMBO") == 0) size = 40; else if(strcmp(case_size, "WRAP") == 0) size = 50; else size = 0; parts[index].container= type + size; break; default: break; } column++; } index++; } }
[ "ubuntu@ip-172-31-11-211.ec2.internal" ]
ubuntu@ip-172-31-11-211.ec2.internal
f2d980d347e3f23081dff7534168ab4b3f5238c4
62426493025bff2bdd773bcb3c3506c25e3b3af5
/图和树/二叉树着色.cpp
c8cc6ff71b1cb91bc2df557eb6e9d61b7028d8f9
[ "Apache-2.0" ]
permissive
nju-rookie/LeetCode
e225d3e682192088914bf8b6427cc51fdbf7892b
43971db4784384da17610c78eaed149a3a5d574f
refs/heads/master
2022-06-26T04:54:11.554148
2020-05-07T15:08:09
2020-05-07T15:08:09
240,482,363
0
0
null
null
null
null
UTF-8
C++
false
false
2,389
cpp
/** 有两位极客玩家参与了一场「二叉树着色」的游戏。游戏中,给出二叉树的根节点 root,树上总共有 n 个节点,且 n 为奇数,其中每个节点上的值从 1 到 n 各不相同。   游戏从「一号」玩家开始(「一号」玩家为红色,「二号」玩家为蓝色),最开始时, 「一号」玩家从 [1, n] 中取一个值 x(1 <= x <= n); 「二号」玩家也从 [1, n] 中取一个值 y(1 <= y <= n)且 y != x。 「一号」玩家给值为 x 的节点染上红色,而「二号」玩家给值为 y 的节点染上蓝色。   之后两位玩家轮流进行操作,每一回合,玩家选择一个他之前涂好颜色的节点,将所选节点一个 未着色 的邻节点(即左右子节点、或父节点)进行染色。 如果当前玩家无法找到这样的节点来染色时,他的回合就会被跳过。 若两个玩家都没有可以染色的节点时,游戏结束。着色节点最多的那位玩家获得胜利 ✌️。   现在,假设你是「二号」玩家,根据所给出的输入,假如存在一个 y 值可以确保你赢得这场游戏,则返回 true;若无法获胜,就请返回 false。   * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ int t; TreeNode *ta; void search(TreeNode* p); int count(TreeNode* p); class Solution { public: bool btreeGameWinningMove(TreeNode* root, int n, int x) { t = x; search(root); int left = 0,right = 0; if(ta -> left != NULL) { left = count(ta-> left) ; if(left > n/2) return true; } if(ta -> right != NULL) { right = count(ta->right) ; if(right > n/2) return true; } if(left + right + 1 <= n/2) return true; return false; } }; int count(TreeNode* p) { if(p == NULL) return 0; else return 1 + count(p -> left) + count(p -> right); } void search(TreeNode* p) { if(p -> val == t) ta = p; else{ if(p -> left != NULL) search(p -> left); if(p -> right != NULL) search(p -> right); } }
[ "xieyu@promote.cache-dns.local" ]
xieyu@promote.cache-dns.local
76324692c87e74f91e0f9cad564d91746dd21ac4
545d1aa7075c423ac22d5057684d444c72d9a8c2
/codes/1576-Replace-All 's-to-Avoid-Consecutive-Repeating-Characters/cpp/main1.cpp
62d660aaa3c16bd13d77a5f24bc6bf02f603f348
[]
no_license
Stackingrule/LeetCode-Solutions
da9420953b0e56bb76f026f5c1a4a48cd404641d
3f7d22dd94eef4e47f3c19c436b00c40891dc03b
refs/heads/main
2023-08-28T00:43:37.871877
2021-10-14T02:55:42
2021-10-14T02:55:42
207,331,384
0
0
null
null
null
null
UTF-8
C++
false
false
821
cpp
class Solution { public: string modifyString(string s) { for (int i = 0; i < s.size(); ++i) { if (s[i] == '?') { //前面一个字符 如果当前是第0个的话 字符就为‘ ’ char ahead = i == 0 ? ' ' : s[i - 1]; //后面一个字符 如果当前是最后一个的话 字符就为‘ ’ char behind = i == s.size() - 1 ? ' ' : s[i + 1]; //从a开始比较 如果等于前面或者后面的话 就+1 char temp = 'a'; while (temp == ahead || temp == behind) { temp++; } //找到目标字符后 做替换 s[i] = temp; } } return s; } };
[ "38368554+Stackingrule@users.noreply.github.com" ]
38368554+Stackingrule@users.noreply.github.com
782ca1c0a55dcbf1ae68a4aff38d551a94f1a69f
7d366a6bcf5e1b9b49925f08c0233194d023daea
/ConsoleApplication2/arvore.cpp
fb1f840b807eea808cc32170073b05a2e3e74134
[]
no_license
GabrielAC17/C-Binary-Tree
ca2e8773ecc23dde5b999caa7c152feedaef954a
2b8170867443ebd4b29461e333175b8b6f7462e4
refs/heads/master
2020-06-15T05:37:27.406382
2016-12-01T18:59:36
2016-12-01T18:59:36
75,322,995
1
0
null
null
null
null
ISO-8859-1
C++
false
false
8,997
cpp
#include "arvore.h" #include <malloc.h> #include <stdio.h> #include <stdbool.h> void iniciar(struct NoArvore **raiz) { *raiz = 0; } void inserir(int valor, struct NoArvore **raiz) { struct NoArvore *aux = (struct NoArvore*)malloc(sizeof(struct NoArvore)); aux->info = valor; aux->esq = 0; aux->dir = 0; if (*raiz == 0) *raiz = aux; else { struct NoArvore *aux2 = *raiz; while (aux2 != 0) { if (aux->info > aux2->info) if (aux2->dir == 0) { aux2->dir = aux; aux2 = 0; } else aux2 = aux2->dir; else { if (aux2->esq == 0) { aux2->esq = aux; aux2 = 0; } else aux2 = aux2->esq; } } } } bool remover(int valor, struct NoArvore **raiz) { //procura e guarda informação a remover struct NoArvore *aux = *raiz; //procura e guarda informação do nó pai (ou busca o menor valor no nó da direita no caso 2 de remoção) struct NoArvore *aux2 = NULL; //guarda a origem do nó filho (esquerda ou direita) do pai bool isRight = true; while (aux != NULL) { //Se encontrou valor if (aux->info == valor) { //se não houver filhos (raiz checked) if (aux->dir == NULL && aux->esq == NULL) { aux2 = NULL; free(aux); return true; } //Se houver dois filhos (raiz checked) else if (aux->dir != NULL && aux->esq != NULL) { aux2 = aux->dir; struct NoArvore * smallestValue = aux2; while (aux2 != NULL) { if (aux2->info < smallestValue->info) { smallestValue = aux2; } aux2 = aux->esq; } aux->info = smallestValue->info; free(smallestValue); return true; } //Se houver apenas um filho (raiz fixed) else if (aux->dir != NULL || aux->esq != NULL) { if (aux->dir != NULL && aux2 != NULL) { if (isRight) aux2->dir = aux->dir; else aux2->esq = aux->dir; } else if (aux->esq != NULL && aux2 != NULL){ if (isRight) aux2->dir = aux->esq; else aux2->esq = aux->esq; } else { if (aux->dir != NULL) *raiz = aux->dir; else *raiz = aux->esq; } free(aux); return true; } } //Se o valor procurado for maior do que o atual if (aux->info < valor) { isRight = true; aux2 = aux; aux = aux->dir; } //se o valor atual for menor ou igual ao atual else { isRight = false; aux2 = aux; aux = aux->esq; } } return false; } int * buscar(int valor, struct NoArvore *raiz, int * cont) { //1 - Esquerda //2 - Direita //0 - Raiz //Ponteiro nulo - Erro int * elem = 0; *cont = 0; if (valor == raiz->info) { elem = (int *)malloc(sizeof(int)); (*elem) = 0; return elem; } struct NoArvore *aux = raiz; while (aux != 0) { if (aux->info < valor) { elem = (int*)realloc(elem, sizeof(int) * (*cont+1)); elem[(*cont)] = 2; (*cont)++; aux = aux->dir; } else { elem = (int*)realloc(elem, sizeof(int) * (*cont+1)); elem[(*cont)] = 1; (*cont)++; aux = aux->esq; } if (aux == NULL) continue; if (aux->info == valor) { return elem; } } return NULL; } //Listagem de números por vetor (erro!) /* void listarPre(struct NoArvore * raiz, int * qtde, int * lista) { //1 - Adiciona a lista //2 - Adiciona o nó a esquerda (se houver) //3 - Adiciona o nó a direita (se houver) // NÃO SE ESQUEÇA DE ZERAR AS VARIAVEIS AO IMPRIMIR NOVAMENTE A LISTA! if (raiz == NULL) return; lista = (int *)realloc(lista, sizeof(int)* ((*qtde)+1)); lista[*qtde] = raiz->info; qtde++; listarPre(raiz->esq,qtde,lista); listarPre(raiz->dir,qtde,lista); } void listarIn(struct NoArvore * raiz, int * qtde, int * lista) { //1 - Adiciona o nó a esquerda (se houver) //2 - Adiciona a lista //3 - Adiciona o nó a direita (se houver) // NÃO SE ESQUEÇA DE ZERAR AS VARIAVEIS AO IMPRIMIR NOVAMENTE A LISTA! if (raiz == NULL) return; listarPre(raiz->esq, qtde, lista); lista = (int *)realloc(lista, sizeof(int)* ((*qtde) + 1)); lista[*qtde] = raiz->info; qtde++; listarPre(raiz->dir, qtde, lista); } void listarPos(struct NoArvore * raiz, int * qtde, int * lista) { //1 - Adiciona o nó a esquerda (se houver) //2 - Adiciona o nó a direita (se houver) //3 - Adiciona a lista // NÃO SE ESQUEÇA DE ZERAR AS VARIAVEIS AO IMPRIMIR NOVAMENTE A LISTA! if (raiz == NULL) return; listarPre(raiz->esq, qtde, lista); listarPre(raiz->dir, qtde, lista); lista = (int *)realloc(lista, sizeof(int)* ((*qtde) + 1)); lista[*qtde] = raiz->info; qtde++; } */ void listarPre(struct NoArvore * raiz) { //1 - Imprime //2 - Adiciona o nó a esquerda (se houver) //3 - Adiciona o nó a direita (se houver) // NÃO SE ESQUEÇA DE ZERAR AS VARIAVEIS AO IMPRIMIR NOVAMENTE A LISTA! if (raiz == NULL) return; printf("%d ",raiz->info); listarPre(raiz->esq); listarPre(raiz->dir); } void listarIn(struct NoArvore * raiz) { //1 - Adiciona o nó a esquerda (se houver) //2 - Imprime //3 - Adiciona o nó a direita (se houver) // NÃO SE ESQUEÇA DE ZERAR AS VARIAVEIS AO IMPRIMIR NOVAMENTE A LISTA! if (raiz == NULL) return; listarPre(raiz->esq); printf("%d ", raiz->info); listarPre(raiz->dir); } void listarPos(struct NoArvore * raiz) { //1 - Adiciona o nó a esquerda (se houver) //2 - Adiciona o nó a direita (se houver) //3 - Imprime // NÃO SE ESQUEÇA DE ZERAR AS VARIAVEIS AO IMPRIMIR NOVAMENTE A LISTA! if (raiz == NULL) return; listarPre(raiz->esq); listarPre(raiz->dir); printf("%d ", raiz->info); } bool AVL(struct NoArvore ** raiz) { //Se os filhos da raiz forem nulos então nem continua if ((*raiz)->dir == NULL && (*raiz)->esq == NULL) { return false; } //fator de balanceamento = (altura do nó esquerdo) - (altura do nó direito) int fator = height((*raiz)->esq) - height((*raiz)->dir); struct NoArvore *aux; struct NoArvore *aux2; struct NoArvore *aux3; struct NoArvore *aux4; //Se a altura do nó esquerdo for maior if (fator > 1) { aux = (*raiz)->esq; aux3 = (*raiz); while (aux != NULL) { //rotação direita if (aux->esq != NULL && aux->esq->esq != NULL && aux->esq->dir == NULL) { aux2 = aux->esq; aux3->esq = aux2; aux2->dir = aux; aux->esq = NULL; return true; } //rotação esquerda else if (aux->dir != NULL && aux->dir->dir != NULL && aux->dir->esq == NULL) { aux2 = aux->dir; aux3->esq = aux2; aux2->esq = aux; aux->dir = NULL; return true; } //rotação esquerda-direita else if (aux->esq != NULL && aux->esq->dir != NULL && aux->esq->dir->esq == NULL && aux->esq->dir->dir == NULL) { aux2 = aux->esq; aux4 = aux->esq->dir; aux->esq = aux4; aux4->esq = aux2; aux3->esq = aux4; aux4->dir = aux; aux->esq = NULL; aux2->dir = NULL; return true; } //rotação direita-esquerda else if (aux->dir != NULL && aux->dir->esq != NULL && aux->dir->esq->esq == NULL && aux->dir->esq->dir == NULL) { aux2 = aux->dir; aux4 = aux->dir->esq; aux->dir = aux4; aux4->dir = aux2; aux3->esq = aux4; aux4->esq = aux; aux->dir = NULL; aux2->esq = NULL; return true; } //Se falhar, tentar com o próximo nó da esquerda else { aux = aux->esq; aux3 = aux3->esq; } } } //Se a altura do nó direito for maior else if (fator < -1) { aux = (*raiz)->dir; aux3 = (*raiz); while (aux != NULL) { //rotação direita if (aux->esq != NULL && aux->esq->esq != NULL && aux->esq->dir == NULL) { aux2 = aux->esq; aux3->esq = aux2; aux2->dir = aux; aux->esq = NULL; return true; } //rotação esquerda else if (aux->dir != NULL && aux->dir->dir != NULL && aux->dir->esq == NULL) { aux2 = aux->dir; aux3->esq = aux2; aux2->esq = aux; aux->dir = NULL; return true; } //rotação esquerda-direita else if (aux->esq != NULL && aux->esq->dir != NULL && aux->esq->dir->esq == NULL && aux->esq->dir->dir == NULL) { aux2 = aux->esq; aux4 = aux->esq->dir; aux->esq = aux4; aux4->esq = aux2; aux3->esq = aux4; aux4->dir = aux; aux->esq = NULL; aux2->dir = NULL; return true; } //rotação direita-esquerda else if (aux->dir != NULL && aux->dir->esq != NULL && aux->dir->esq->esq == NULL && aux->dir->esq->dir == NULL) { aux2 = aux->dir; aux4 = aux->dir->esq; aux->dir = aux4; aux4->dir = aux2; aux3->esq = aux4; aux4->esq = aux; aux->dir = NULL; aux2->esq = NULL; return true; } //se falhar, tentar com o próximo nó da direita else { aux = aux->dir; aux3 = aux3->dir; } } } //Se a altura estiver ok ou não conseguir balancear return false; } int height(struct NoArvore * raiz) { //Se nó for nulo retorna -1 if (raiz == NULL) { return -1; } //verifica a altura dos nós seguintes recursivamente int esqh = height(raiz->esq); int dirh = height(raiz->dir); //retorna altura obtida + ajuste dos nós inválidos; if (esqh > dirh) return (esqh + 1); else return (dirh + 1); }
[ "gabriel.de.ac@hotmail.com" ]
gabriel.de.ac@hotmail.com
4ea399380bb179b88785f7e9caacfe7da2f2bbd7
4612e46be4ccd2c05c67baa6359b7d0281fd5f1a
/platform/atomic_word_test.cpp
76d9634c3aea580b4d7b167bb5943cb2cda45edc
[ "Apache-2.0" ]
permissive
RedBeard0531/mongo_utils
eed1e06c18cf6ff0e6f076fdfc8a71d5791bb95c
402c2023df7d67609ce9da8e405bf13cdd270e20
refs/heads/master
2021-03-31T01:03:41.719260
2018-06-03T11:27:47
2018-06-03T11:27:47
124,802,061
1
0
null
null
null
null
UTF-8
C++
false
false
7,033
cpp
/* Copyright 2012 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mongo/platform/basic.h" #include <iostream> #include "mongo/platform/atomic_word.h" #include "mongo/unittest/unittest.h" namespace mongo { namespace { template <typename _AtomicWordType> void testAtomicWordBasicOperations() { typedef typename _AtomicWordType::WordType WordType; _AtomicWordType w; ASSERT_EQUALS(WordType(0), w.load()); w.store(1); ASSERT_EQUALS(WordType(1), w.load()); ASSERT_EQUALS(WordType(1), w.swap(2)); ASSERT_EQUALS(WordType(2), w.load()); ASSERT_EQUALS(WordType(2), w.compareAndSwap(0, 1)); ASSERT_EQUALS(WordType(2), w.load()); ASSERT_EQUALS(WordType(2), w.compareAndSwap(2, 1)); ASSERT_EQUALS(WordType(1), w.load()); ASSERT_EQUALS(WordType(1), w.fetchAndAdd(14)); ASSERT_EQUALS(WordType(17), w.addAndFetch(2)); ASSERT_EQUALS(WordType(16), w.subtractAndFetch(1)); ASSERT_EQUALS(WordType(16), w.fetchAndSubtract(1)); ASSERT_EQUALS(WordType(15), w.compareAndSwap(15, 0)); ASSERT_EQUALS(WordType(0), w.load()); } TEST(AtomicWordTests, BasicOperationsUnsigned32Bit) { typedef AtomicUInt32::WordType WordType; testAtomicWordBasicOperations<AtomicUInt32>(); AtomicUInt32 w(0xdeadbeef); ASSERT_EQUALS(WordType(0xdeadbeef), w.compareAndSwap(0, 1)); ASSERT_EQUALS(WordType(0xdeadbeef), w.compareAndSwap(0xdeadbeef, 0xcafe1234)); ASSERT_EQUALS(WordType(0xcafe1234), w.fetchAndAdd(0xf000)); ASSERT_EQUALS(WordType(0xcaff0234), w.swap(0)); ASSERT_EQUALS(WordType(0), w.load()); } TEST(AtomicWordTests, BasicOperationsUnsigned64Bit) { typedef AtomicUInt64::WordType WordType; testAtomicWordBasicOperations<AtomicUInt64>(); AtomicUInt64 w(0xdeadbeefcafe1234ULL); ASSERT_EQUALS(WordType(0xdeadbeefcafe1234ULL), w.compareAndSwap(0, 1)); ASSERT_EQUALS(WordType(0xdeadbeefcafe1234ULL), w.compareAndSwap(0xdeadbeefcafe1234ULL, 0xfedcba9876543210ULL)); ASSERT_EQUALS(WordType(0xfedcba9876543210ULL), w.fetchAndAdd(0xf0000000ULL)); ASSERT_EQUALS(WordType(0xfedcba9966543210ULL), w.swap(0)); ASSERT_EQUALS(WordType(0), w.load()); } TEST(AtomicWordTests, BasicOperationsSigned32Bit) { typedef AtomicInt32::WordType WordType; testAtomicWordBasicOperations<AtomicInt32>(); AtomicInt32 w(0xdeadbeef); ASSERT_EQUALS(WordType(0xdeadbeef), w.compareAndSwap(0, 1)); ASSERT_EQUALS(WordType(0xdeadbeef), w.compareAndSwap(0xdeadbeef, 0xcafe1234)); ASSERT_EQUALS(WordType(0xcafe1234), w.fetchAndAdd(0xf000)); ASSERT_EQUALS(WordType(0xcaff0234), w.swap(0)); ASSERT_EQUALS(WordType(0), w.load()); } TEST(AtomicWordTests, BasicOperationsSigned64Bit) { typedef AtomicInt64::WordType WordType; testAtomicWordBasicOperations<AtomicInt64>(); AtomicInt64 w(0xdeadbeefcafe1234ULL); ASSERT_EQUALS(WordType(0xdeadbeefcafe1234LL), w.compareAndSwap(0, 1)); ASSERT_EQUALS(WordType(0xdeadbeefcafe1234LL), w.compareAndSwap(0xdeadbeefcafe1234LL, 0xfedcba9876543210LL)); ASSERT_EQUALS(WordType(0xfedcba9876543210LL), w.fetchAndAdd(0xf0000000LL)); ASSERT_EQUALS(WordType(0xfedcba9966543210LL), w.swap(0)); ASSERT_EQUALS(WordType(0), w.load()); } TEST(AtomicWordTests, BasicOperationsFloat) { typedef AtomicWord<float>::WordType WordType; AtomicWord<float> w; ASSERT_EQUALS(WordType(0), w.load()); w.store(1); ASSERT_EQUALS(WordType(1), w.load()); ASSERT_EQUALS(WordType(1), w.swap(2)); ASSERT_EQUALS(WordType(2), w.load()); ASSERT_EQUALS(WordType(2), w.compareAndSwap(0, 1)); ASSERT_EQUALS(WordType(2), w.load()); ASSERT_EQUALS(WordType(2), w.compareAndSwap(2, 1)); ASSERT_EQUALS(WordType(1), w.load()); w.store(15); ASSERT_EQUALS(WordType(15), w.compareAndSwap(15, 0)); ASSERT_EQUALS(WordType(0), w.load()); } struct Chars { static constexpr size_t kLength = 6; Chars(const char* chars = "") { invariant(std::strlen(chars) < kLength); std::strncpy(_storage.data(), chars, sizeof(_storage)); } std::array<char, 6> _storage = {}; friend bool operator==(const Chars& lhs, const Chars& rhs) { return lhs._storage == rhs._storage; } friend bool operator!=(const Chars& lhs, const Chars& rhs) { return !(lhs == rhs); } }; std::ostream& operator<<(std::ostream& os, const Chars& chars) { return (os << chars._storage.data()); } TEST(AtomicWordTests, BasicOperationsComplex) { using WordType = Chars; AtomicWord<WordType> checkZero(AtomicWord<WordType>::ZeroInitTag{}); ASSERT_EQUALS(WordType(""), checkZero.load()); AtomicWord<WordType> w; ASSERT_EQUALS(WordType(), w.load()); w.store("b"); ASSERT_EQUALS(WordType("b"), w.load()); ASSERT_EQUALS(WordType("b"), w.swap("c")); ASSERT_EQUALS(WordType("c"), w.load()); ASSERT_EQUALS(WordType("c"), w.compareAndSwap("a", "b")); ASSERT_EQUALS(WordType("c"), w.load()); ASSERT_EQUALS(WordType("c"), w.compareAndSwap("c", "b")); ASSERT_EQUALS(WordType("b"), w.load()); w.store("foo"); ASSERT_EQUALS(WordType("foo"), w.compareAndSwap("foo", "bar")); ASSERT_EQUALS(WordType("bar"), w.load()); } template <typename T> void verifyAtomicityHelper() { ASSERT(std::atomic<T>{}.is_lock_free()); // NOLINT ASSERT(std::atomic<typename std::make_signed<T>::type>{}.is_lock_free()); // NOLINT ASSERT(std::atomic<typename std::make_unsigned<T>::type>{}.is_lock_free()); // NOLINT } template <typename... Types> void verifyAtomicity() { using expander = int[]; (void)expander{(verifyAtomicityHelper<Types>(), 0)...}; } TEST(AtomicWordTests, StdAtomicOfIntegralIsLockFree) { // 2 means that they're always atomic. Instead of 1, that means sometimes, and 0, which means // never. ASSERT_EQUALS(2, ATOMIC_CHAR_LOCK_FREE); ASSERT_EQUALS(2, ATOMIC_CHAR16_T_LOCK_FREE); ASSERT_EQUALS(2, ATOMIC_CHAR32_T_LOCK_FREE); ASSERT_EQUALS(2, ATOMIC_WCHAR_T_LOCK_FREE); ASSERT_EQUALS(2, ATOMIC_SHORT_LOCK_FREE); ASSERT_EQUALS(2, ATOMIC_INT_LOCK_FREE); ASSERT_EQUALS(2, ATOMIC_LONG_LOCK_FREE); ASSERT_EQUALS(2, ATOMIC_LLONG_LOCK_FREE); ASSERT_EQUALS(2, ATOMIC_POINTER_LOCK_FREE); verifyAtomicity<char, char16_t, char32_t, wchar_t, short, int, long, long long>(); ASSERT(std::atomic<bool>{}.is_lock_free()); // NOLINT } } // namespace } // namespace mongo
[ "redbeard0531@gmail.com" ]
redbeard0531@gmail.com
d4b7d042ece43777f572aba91c0424bf7cfff9d0
1a3d5cf11c5c9df4bd58b3dedcebe5c01863bd96
/Project_2/masses.h
555f39de173521c66971d144a4ecc8e78af66259
[]
no_license
sus-calderon/Programming_Projects
4a88147f5c5d0c32a3f18ea789b07c3d5d07e3eb
1d0ed6c4b07e36856c5a1b9f35868de4751b4e50
refs/heads/master
2023-04-06T23:33:24.974791
2021-04-14T05:17:20
2021-04-14T05:17:20
192,372,247
0
0
null
null
null
null
UTF-8
C++
false
false
981
h
//Rewritten by Susana Calderon on June 11, 2019 // #include <iostream> #include <string> #include <fstream> #include <iomanip> double masses[] = { 0.000000, 1.007825, 4.002603, 7.016003, 9.012183, 11.009305, 12.000000, 14.003074, 15.994914, 18.998403, 19.992440, 19.992440, 22.989769, 23.985042, 26.981538, 27.976926, 30.973762, 31.972071, 34.968853, 39.962383, 38.963706, 39.962591, 44.955908, 47.867000, 50.941500, 51.996100, 54.938044, 55.934936, 58.933194, 58.693400, 63.546000, 65.926033, 69.723000, 72.630000, 74.921594, 78.971000, 79.901000, 83.798000, 85.467800, 87.620000, 88.905840, 91.224000, 92.906373, 95.950000, 97.907212, 101.070000, 102.905498, 106.420000, 107.868200, 112.414000, 114.818000, 121.760000, 127.600000, 126.904472, 131.293000, };
[ "scalderon@vt.edu" ]
scalderon@vt.edu
ece420416f8c5927a597079e20462a824a67770d
c6b920f08a4615a7471d026005c2ecc3267ddd71
/adapters/Lammps/src/Glue/LammpsLatticeSQ.cpp
61025a89e7fd2d3aeca4d21a8457259d4ac52c80
[]
no_license
etomica/legacy-api
bcbb285395f27aa9685f02cc7905ab75f87b017c
defcfb6650960bf6bf0a3e55cb5ffabb40d76d8b
refs/heads/master
2021-01-20T14:07:57.547442
2010-04-22T21:19:19
2010-04-22T21:19:19
82,740,861
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
/* * LammpsLatticeSQ.cpp * API Glue * */ #include "library.h" #include "LammpsLatticeSQ.h" #include "LammpsSimulation.h" namespace lammpswrappers { const char *const LammpsLatticeSQ::LATTICE_NAME = "sq"; LammpsLatticeSQ::LammpsLatticeSQ(IAPISimulation *sim, double sc) : LammpsLattice(sim, sc, LATTICE_NAME) { } }
[ "rrassler@buffalo.edu" ]
rrassler@buffalo.edu
6e9cab6ab4ce823de4870d4fde2a7fb3b6ea00d8
c3acf1faf34e39e9bf510cab88042625d477fa86
/recursion/1AscendingAndDescendingRecursion.cpp
1e1d243c7c1849ded3d60dffc4b6c9f2a0fc588b
[]
no_license
neeraj-satyaki/dsa_daily_dose
3068bfdf918b0488ca5ceebb362a305e7cbfcc20
0058cf2a9e17771b7da5732ad411ec8a5b758bbc
refs/heads/master
2023-06-04T23:48:56.594764
2021-06-26T20:50:02
2021-06-26T20:50:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
//WAP to show ascending, descending recursion #include <iostream> using namespace std; // Recursion in Ascending order void fun1(int a){ if(a>0){ fun1(a-1); cout<<a<<" "; } } // Recursion in Descending order void fun2(int a){ if(a>0){ cout<<a<<" "; fun1(a-1); } } int main() { cout<<"Recursion in Ascending order.\n"; fun1(5); cout<<"\nRecursion in Descending order.\n"; fun2(5); return 0; }
[ "56729866+sambit221@users.noreply.github.com" ]
56729866+sambit221@users.noreply.github.com
837824c3441d3a69fff14c16395cc31a61c73079
5edb43d47325a36ecfe4abcc91b654db2d2db35a
/Wallstedt/patch.cpp
5c81672c3670e09f879132d984db0583376b6115
[ "LicenseRef-scancode-public-domain" ]
permissive
hoomanzarreh/simple-mpm
f65414a95759f135bb589146e1267ea3ffb50b45
fdb059cf45ca0fd7b817b2c4996f036e8367be4d
refs/heads/master
2021-01-17T22:33:13.831742
2013-04-05T04:57:50
2013-04-05T04:57:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,667
cpp
// Philip Wallstedt 2004-2009 #include "patch.h" using namespace std; // Cycle through each managed array and resize it void patch::resizeParts(int s){ for(unsigned v=0;v<parts.size();v+=1)parts[v]->resize(s); numberOfParts=s; } // Cycle through each managed array and resize it void patch::resizeNodes(int s){ for(unsigned v=0;v<nodes.size();v+=1)nodes[v]->resize(s); numberOfNodes=s; } // Copy a particle; not sure if I use this anywhere int patch::copyPart(const patch&q,int i){ for(unsigned v=0;v<parts.size();v+=1)parts[v]->push_back(q.parts[v],i); numberOfParts+=1; return Npart()-1; } patch::patch(const int Nx, const int Ny, const double bx, const double by, const double ex, const double ey, const int Ng, const double th): regionBegin(bx,by), regionEnd(ex,ey), dx((ex-bx)/double(Nx)), dy((ey-by)/double(Ny)), thick(th), Nghost(Ng), I(Nx+2*Ng+1), J(Ny+2*Ng+1){ // taking control of the managed arrays parts=commonPartsPtr;commonPartsPtr.clear();numberOfParts=0; nodes=commonNodesPtr;commonNodesPtr.clear(); resizeNodes(I*J); // lots of memory for nodes allocated here incCount=0; // laying out nodes in a grid for(int j=0;j<J;j+=1){ const double y=(j-Ng)*dy+regionBegin.y; for(int i=0;i<I;i+=1){ const double x=(i-Ng)*dx+regionBegin.x; const int n=j*I+i; gx[n]=Vector2(x,y); } } }
[ "bryangsmith@gmail.com" ]
bryangsmith@gmail.com
c481863bada211a5f81706761dc2a04bf36080d0
d2f30d9fb226185956c3da1e5372664aaa506312
/synthesis/MeasurementComponents/nPBWProjectFT.h
80dc3f15d009d2c039942e1d8b715bc275a8ce62
[]
no_license
radio-astro/casasynthesis
1e2fdacfcfc4313adde8f7524739a4dfd80d4c8f
1cb9cd6a346d3ade9a6f563696d225c24654041c
refs/heads/master
2021-01-17T05:22:01.380405
2019-01-08T10:43:34
2019-01-08T10:43:34
40,664,934
1
1
null
2022-12-16T13:17:36
2015-08-13T15:01:41
C++
UTF-8
C++
false
false
20,849
h
//# nPBWProjectFT.h: Definition for nPBWProjectFT //# Copyright (C) 1996,1997,1998,1999,2000,2002 //# Associated Universities, Inc. Washington DC, USA. //# //# 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; if not, write to the Free Software Foundation, //# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA. //# //# Correspondence concerning AIPS++ should be adressed as follows: //# Internet email: aips2-request@nrao.edu. //# Postal address: AIPS++ Project Office //# National Radio Astronomy Observatory //# 520 Edgemont Road //# Charlottesville, VA 22903-2475 USA //# //# //# $Id$ #ifndef SYNTHESIS_PBWPROJECTFT_H #define SYNTHESIS_PBWPROJECTFT_H #include <synthesis/TransformMachines/FTMachine.h> #include <casa/Arrays/Matrix.h> #include <scimath/Mathematics/FFTServer.h> #include <msvis/MSVis/VisBuffer.h> #include <images/Images/ImageInterface.h> #include <casa/Containers/Block.h> #include <casa/Arrays/Array.h> #include <casa/Arrays/Vector.h> #include <casa/Arrays/Matrix.h> #include <scimath/Mathematics/ConvolveGridder.h> #include <lattices/Lattices/LatticeCache.h> #include <lattices/Lattices/ArrayLattice.h> #include <ms/MeasurementSets/MSColumns.h> #include <measures/Measures/Measure.h> #include <measures/Measures/MDirection.h> #include <measures/Measures/MPosition.h> #include <coordinates/Coordinates/DirectionCoordinate.h> #include <synthesis/TransformMachines/VPSkyJones.h> #include <synthesis/TransformMachines/VLACalcIlluminationConvFunc.h> #include <synthesis/TransformMachines/VLAIlluminationConvFunc.h> #include <synthesis/TransformMachines/Utils.h> //#include <synthesis/MeasurementComponents/EPJones.h> #include <synthesis/MeasurementComponents/SolvableVisCal.h> #include <synthesis/MeasurementComponents/ConvFuncDiskCache.h> namespace casa { //# NAMESPACE CASA - BEGIN // <summary> An FTMachine for Gridded Fourier transforms including effects of primary beam and pointing offsets and the w-term</summary> // <use visibility=export> // <reviewed reviewer="" date="" tests="" demos=""> // <prerequisite> // <li> <linkto class=FTMachine>FTMachine</linkto> module // <li> <linkto class=SkyEquation>SkyEquation</linkto> module // <li> <linkto class=VisBuffer>VisBuffer</linkto> module // <li> <linto class=EPJones>EPJones</linkto> module // </prerequisite> // // <etymology> // FTMachine is a Machine for Fourier Transforms. Like // WProjectFT, nPBWProjectFT does Grid-based Fourier transforms but // also includes the effects of primary beam and antenna pointing // offsets. // </etymology> // // <synopsis> // // The <linkto class=SkyEquation>SkyEquation</linkto> needs to be // able to perform Fourier transforms on visibility // data. nPBWProjectFT allows efficient handling of direction // dependent effects due to the primary beam and antenna pointing // offsets using a <linkto class=VisBuffer>VisBuffer</linkto> which // encapsulates a chunk of visibility (typically all baselines for // one time) together with all the information needed for processing // (e.g. UVW coordinates). // // Using this FTMachine, errors due antenna pointing offsets can be // corrected during deconvolution. One form of antenna pointing // error which is known a-priori is the VLA polarization squint // (about 6% of the Primary beam width at any frequency). For // Stokes imaging, using this FTMachine, the VLA polarization squint // and beam polarization can also be corrected. Also since the // effects of antenna pointing errors is strongest in the range of // 1-2GHz band (where the sky is not quite empty while the beams are // not too large either), this FTMachine can also be setup to // correct for the w-term. // // Switches are provided in the get() method to compute the // derivatives with respect to the parameters of the primary beam // (only pointing offsets for now). This is used in the pointing // offset solver. // // See the documentation of other FTMachines for details about the // design of the FTMachines in general. // // </synopsis> // // <example> // See the example for <linkto class=SkyModel>SkyModel</linkto>. // </example> // // <motivation> // // Encapsulate the correction of direction dependent effects via // visibility plane convolutions with a potentially different // convolution function for each baseline. // // </motivation> // // <todo asof="2005/07/21"> // // <ul> Include the antenna based complex gain term as well since // that can interfere with the effects of pointing offsets. // // <ul> Factor out the actual convolution functions as a separate // class making FTMachines for various direction dependent effects // generic. // // </todo> // class EPJones; class SolvableVisJones; class nPBWProjectFT : public FTMachine { public: // Constructor: cachesize is the size of the cache in words // (e.g. a few million is a good number), tilesize is the // size of the tile used in gridding (cannot be less than // 12, 16 works in most cases). // <group> nPBWProjectFT(Int nFacets, Long cachesize, String& cfCacheDirName, Bool applyPointingOffset=True, Bool doPBCorr=True, Int tilesize=16, Float paSteps=5.0, Float pbLimit=5e-2, Bool usezero=False); // </group> // Construct from a Record containing the nPBWProjectFT state nPBWProjectFT(const RecordInterface& stateRec); // Copy constructor nPBWProjectFT(const nPBWProjectFT &other); // Assignment operator nPBWProjectFT &operator=(const nPBWProjectFT &other); ~nPBWProjectFT(); // void setEPJones(EPJones* ep_j) {epJ = ep_j;} void setEPJones(SolvableVisJones* ep_j) {epJ = ep_j;} void setDOPBCorrection(Bool doit=True) {doPBCorrection=doit;}; // Initialize transform to Visibility plane using the image // as a template. The image is loaded and Fourier transformed. virtual void initializeToVis(ImageInterface<Complex>& image, const VisBuffer& vb); // This version returns the gridded vis...should be used in conjunction // with the version of 'get' that needs the gridded visdata virtual void initializeToVis(ImageInterface<Complex>& image, const VisBuffer& vb, Array<Complex>& griddedVis, Vector<Double>& uvscale); // Finalize transform to Visibility plane: flushes the image // cache and shows statistics if it is being used. virtual void finalizeToVis(); // Initialize transform to Sky plane: initializes the image virtual void initializeToSky(ImageInterface<Complex>& image, Matrix<Float>& weight, const VisBuffer& vb); // Finalize transform to Sky plane: flushes the image // cache and shows statistics if it is being used. DOES NOT // DO THE FINAL TRANSFORM! virtual void finalizeToSky(); virtual void initVisBuffer(VisBuffer& vb, Type whichVBColumn); void initVisBuffer(VisBuffer& vb, Type whichVBColumn, Int row); // Get actual coherence from grid by degridding void get(VisBuffer& vb, Int row=-1); // Get the coherence from grid return it in the degrid // is used especially when scratch columns are not // present in ms. void get(VisBuffer& vb, Cube<Complex>& degrid, Array<Complex>& griddedVis, Vector<Double>& scale, Int row=-1); void get(VisBuffer& vb, Cube<Float>& pointingOffsets, Int row=-1, Type whichVBColumn=FTMachine::MODEL,Int Conj=0) { get(vb,vb,vb,pointingOffsets,row,whichVBColumn,whichVBColumn,Conj,0); } void get(VisBuffer& vb, VisBuffer& gradAzVB,VisBuffer& gradElVB, Cube<Float>& pointingOffsets,Int row=-1, Type whichVBColumn=FTMachine::MODEL, Type whichGradVBColumn=FTMachine::MODEL, Int Conj=0, Int doGrad=1) ; void nget(VisBuffer& vb, // These offsets should be appropriate for the VB Array<Float>& l_off, Array<Float>& m_off, Cube<Complex>& Mout, Cube<Complex>& dMout1, Cube<Complex>& dMout2, Int Conj=0, Int doGrad=1); // Get the coherence from grid return it in the degrid // is used especially when scratch columns are not // present in ms. void get(VisBuffer& vb, Cube<Complex>& degrid, Array<Complex>& griddedVis, Vector<Double>& scale, Cube<Float>& pointingOffsets,Int row=-1); // Put coherence to grid by gridding. void put(const VisBuffer&, TempImage<Complex>&, Vector<Double>&, int, UVWMachine*, Bool) { // throw(AipsError("nPBWProjectFT::put is not implemented")); } void put(const VisBuffer& vb, Int row=-1, Bool dopsf=False, FTMachine::Type type=FTMachine::OBSERVED); // Make the entire image void makeImage(FTMachine::Type type, VisSet& vs, ImageInterface<Complex>& image, Matrix<Float>& weight); // Get the final image: do the Fourier transform and // grid-correct, then optionally normalize by the summed weights virtual ImageInterface<Complex>& getImage(Matrix<Float>&, Bool normalize=True); virtual void normalizeImage(Lattice<Complex>& /*skyImage*/, const Matrix<Double>& /*sumOfWts*/, Lattice<Float>& /*sensitivityImage*/, Bool /*fftNorm*/) {throw(AipsError("nPBWProjectFT::normalizeImage() called"));} // Get the final weights image void getWeightImage(ImageInterface<Float>&, Matrix<Float>&); // Save and restore the nPBWProjectFT to and from a record Bool toRecord(String& error, RecordInterface& outRec, Bool withImage=False, const String diskimage=""); Bool fromRecord(String& error, const RecordInterface& inRec); // Can this FTMachine be represented by Fourier convolutions? Bool isFourier() {return True;} // Bool changed(const VisBuffer& vb) {return vpSJ->changed(vb,1);}; Bool changed(const VisBuffer& ) {return False;} virtual Int findPointingOffsets(const VisBuffer&, Array<Float>&, Array<Float>&, Bool Evaluate=True); virtual Int findPointingOffsets(const VisBuffer&, Cube<Float>&, Array<Float>&, Array<Float>&, Bool Evaluate=True); virtual Double getVBPA(const VisBuffer& vb) { // if (!rotateAperture_p) return currentCFPA; // else return getPA(vb); return getPA(vb); }; MDirection::Convert makeCoordinateMachine(const VisBuffer&, const MDirection::Types&, const MDirection::Types&, MEpoch& last); /* void makePB(const VisBuffer& vb, TempImage<Float>& PB, IPosition& shape,CoordinateSystem& coord); void makeAveragePB(const VisBuffer& vb, const ImageInterface<Complex>& image, Int& polInUse, TempImage<Float>& PB, TempImage<Float>& avgPB); */ // // Make a sensitivity image (sensitivityImage), given the gridded // weights (wtImage). These are related to each other by a // Fourier transform and normalization by the sum-of-weights // (sumWt) and normalization by the product of the 2D FFT size // along each axis. If doFFTNorm=False, normalization by the FFT // size is not done. If sumWt is not provided, normalization by // the sum of weights is also not done. // virtual void makeSensitivityImage(Lattice<Complex>& wtImage, ImageInterface<Float>& sensitivityImage, const Matrix<Float>& sumWt=Matrix<Float>(), const Bool& doFFTNorm=True); virtual Bool makeAveragePB0(const VisBuffer& vb, const ImageInterface<Complex>& image, Int& polInUse, TempImage<Float>& avgPB); /* void makeAveragePB(const VisBuffer& vb, const ImageInterface<Complex>& image, Int& polInUse, TempImage<Float>& avgPB); */ void makeConjPolMap(const VisBuffer& vb, const Vector<Int> cfPolMap, Vector<Int>& conjPolMap); // Vector<Int> makeConjPolMap(const VisBuffer& vb); void makeCFPolMap(const VisBuffer& vb, Vector<Int>& polM); // void reset() {vpSJ->reset();} void reset() {paChangeDetector.reset();} void setPAIncrement(const Quantity &paIncrement); Vector<Int>& getPolMap() {return polMap;}; virtual String name() const { return "PBWProjectFT";}; virtual Bool verifyAvgPB(ImageInterface<Float>& pb, ImageInterface<Float>& sky) {return verifyShapes(pb.shape(),sky.shape());} virtual Bool verifyAvgPB(ImageInterface<Float>& pb, ImageInterface<Complex>& sky) {return verifyShapes(pb.shape(),sky.shape());} virtual Bool verifyShapes(IPosition shape0, IPosition shape1); Bool findSupport(Array<Complex>& func, Float& threshold, Int& origin, Int& R); void makeAntiAliasingOp(Vector<Complex>& val, const Int len); void makeAntiAliasingCorrection(Vector<Complex>& correction, const Vector<Complex>& op, const Int nx); void applyAntiAliasingOp(ImageInterface<Complex>& cf, Vector<IPosition>& offset, Int op=0, Bool Square=False); void applyAntiAliasingOp(ImageInterface<Float>& cf, Vector<IPosition>& offset, Int op=0, Bool Square=False); void correctAntiAliasing(Lattice<Complex>& cf); virtual void setMiscInfo(const Int qualifier){(void)qualifier;}; virtual void ComputeResiduals(VisBuffer&/*vb*/, Bool /*useCorrected*/) {}; protected: // Padding in FFT Float padding_p; Int nint(Double val){return Int(floor(val+0.5));}; // Make the PB part of the convolution function Int makePBPolnCoords(//const ImageInterface<Complex>& image, CoordinateSystem& coord, const VisBuffer& vb); // Locate convolution functions on the disk Int locateConvFunction(Int Nw, Int polInUse, const VisBuffer& vb, Float &pa); void cacheConvFunction(Int which, Array<Complex>& cf, CoordinateSystem& coord); // Find the convolution function void findConvFunction(const ImageInterface<Complex>& image, const VisBuffer& vb); void makeConvFunction(const ImageInterface<Complex>& image, const VisBuffer& vb, Float pa); Int nWPlanes_p; // Get the appropriate data pointer Array<Complex>* getDataPointer(const IPosition&, Bool); void ok(); void init(); // Int getVisParams(); Int getVisParams(const VisBuffer& vb); // Is this record on Grid? check both ends. This assumes that the // ends bracket the middle Bool recordOnGrid(const VisBuffer& vb, Int rownr) const; // Image cache LatticeCache<Complex> * imageCache; // Sizes Long cachesize; Int tilesize; // Gridder ConvolveGridder<Double, Complex>* gridder; // Is this tiled? Bool isTiled; // Array lattice //Lattice<Complex> * arrayLattice; CountedPtr<Lattice<Complex> > arrayLattice; // Lattice. For non-tiled gridding, this will point to arrayLattice, // whereas for tiled gridding, this points to the image //Lattice<Complex>* lattice; CountedPtr<Lattice<Complex> > lattice; Float maxAbsData; // Useful IPositions IPosition centerLoc, offsetLoc; // Image Scaling and offset Vector<Double> uvScale, uvOffset; // Array for non-tiled gridding Array<Complex> griddedData; // Pointing columns MSPointingColumns* mspc; // Antenna columns MSAntennaColumns* msac; DirectionCoordinate directionCoord; MDirection::Convert* pointingToImage; Vector<Double> xyPos; MDirection worldPosMeas; Int priorCacheSize; // Grid/degrid zero spacing points? Bool usezero_p; Array<Complex> convFunc; Array<Complex> convWeights; CoordinateSystem convFuncCS_p; Int convSize; // // Vector to hold the support size info. for the convolution // functions pointed to by the elements of convFunctions_p. The // co-ordinates of this array are (W-term, Poln, PA). // Int convSampling; Cube<Int> convSupport, convWtSupport; // // Holder for the pointers to the convolution functions. Each // convolution function itself is a complex 3D array (U,V,W) per // PA. // PtrBlock < Array<Complex> *> convFuncCache, convWeightsCache; // Array<Complex>* convFunc_p; // // The index into the conv. func. cache for the current conv. func. // Int PAIndex; // // If true, all convolution functions are in the cache. // Bool convFuncCacheReady; Int wConvSize; Int lastIndex_p; Int getIndex(const ROMSPointingColumns& mspc, const Double& time, const Double& interval); Bool getXYPos(const VisBuffer& vb, Int row); // VPSkyJones *vpSJ; // // The PA averaged (and potentially antenna averaged) PB for // normalization // TempImage<Float> avgPB; // // No. of vis. polarization planes used in making the user defined // Stokes images // Int polInUse, bandID_p; Int maxConvSupport; // // Percentage of the peak of the PB after which the image is set // to zero. // Float pbLimit_p; // EPJones *epJ; SolvableVisJones *epJ; Double HPBW, Diameter_p, sigma; Int Nant_p; Int doPointing; Bool doPBCorrection; Bool makingPSF; Unit Second, Radian, Day; Array<Float> l_offsets,m_offsets; Int noOfPASteps; Vector<Float> pbPeaks; Bool pbNormalized,resetPBs,rotateAperture_p; Vector<Float> paList; ConvFuncDiskCache cfCache; Double currentCFPA; ParAngleChangeDetector paChangeDetector; Vector<Int> cfStokes; Vector<Complex> Area; Double cfRefFreq_p; Bool avgPBSaved; Bool avgPBReady; Vector<Complex> antiAliasingOp,antiAliasingCorrection; Float lastPAUsedForWtImg; // VLACalcIlluminationConvFunc vlaPB; // //---------------------------------------------------------------------- // virtual void normalizeAvgPB(); virtual void runFortranGet(Matrix<Double>& uvw,Vector<Double>& dphase, Cube<Complex>& visdata, IPosition& s, //Cube<Complex>& gradVisAzData, //Cube<Complex>& gradVisElData, //IPosition& gradS, Int& Conj, Cube<Int>& flags,Vector<Int>& rowFlags, Int& rownr,Vector<Double>& actualOffset, Array<Complex>* dataPtr, Int& aNx, Int& aNy, Int& npol, Int& nchan, VisBuffer& vb,Int& Nant_p, Int& scanNo, Double& sigma, Array<Float>& raoffsets, Array<Float>& decoffsets, Double area, Int& doGrad,Int paIndex); virtual void runFortranPut(Matrix<Double>& uvw,Vector<Double>& dphase, const Complex& visdata_p, IPosition& s, //Cube<Complex>& gradVisAzData, //Cube<Complex>& gradVisElData, //IPosition& gradS, Int& Conj, Cube<Int>& flags,Vector<Int>& rowFlags, const Matrix<Float>& weight, Int& rownr,Vector<Double>& actualOffset, Array<Complex>& dataPtr, Int& aNx, Int& aNy, Int& npol, Int& nchan, const VisBuffer& vb,Int& Nant_p, Int& scanNo, Double& sigma, Array<Float>& raoffsets, Array<Float>& decoffsets, Matrix<Double>& sumWeight, Double& area, Int& doGrad, Int& doPSF,Int paIndex); void runFortranGetGrad(Matrix<Double>& uvw,Vector<Double>& dphase, Cube<Complex>& visdata, IPosition& s, Cube<Complex>& gradVisAzData, Cube<Complex>& gradVisElData, // IPosition& gradS, Int& Conj, Cube<Int>& flags,Vector<Int>& rowFlags, Int& rownr,Vector<Double>& actualOffset, Array<Complex>* dataPtr, Int& aNx, Int& aNy, Int& npol, Int& nchan, VisBuffer& vb,Int& Nant_p, Int& scanNo, Double& sigma, Array<Float>& l_off, Array<Float>& m_off, Double area, Int& doGrad, Int paIndex); }; //void saveImmage(TempImage<Complex>& convFunc, Int wConvSize); } //# NAMESPACE CASA - END #endif
[ "gijs@pythonic.nl" ]
gijs@pythonic.nl
e0637b87f2308fb45f553254770c201f84f88078
2c8044db6c97ab2e98ba45269ed8d24e0984ae18
/AlgorithmsandDataStructures/6thLab/H(LcaH).cpp
deeb24a7229cbf1af5167d1d53d4c2df9a2b3b5d
[ "MIT" ]
permissive
Retnirps/ITMO
1b2f5363b99a69f518d03e03c8d1099e97b1d65f
29db54d96afef0558550471c58f695c962e1f747
refs/heads/master
2023-05-26T23:06:53.533352
2021-06-14T21:31:18
2021-06-14T21:31:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,671
cpp
#include <iostream> #include <vector> using namespace std; vector < vector <int> > dp, sons; vector <int> p, lvl, num, last, amount; vector <bool> came; int pow = 0; void log(int n) {while ((1 << pow) < n) ++pow;} int lca(int x, int y) { if (lvl[x] < lvl[y]) return lca(y, x); int dif = lvl[x] - lvl[y]; int lift = 0; while (dif > 0) { if (dif & 1) x = dp[x][lift]; dif >>= 1; ++lift; } for (int i = pow; i >= 0; --i) { if (dp[x][i] != dp[y][i]) { x = dp[x][i]; y = dp[y][i]; } } if (x != y) return p[x]; else return x; } void levels(int ind) { lvl[ind] = lvl[p[ind]] + 1; for (auto i : sons[ind]) levels(i); } void count(int ind) { came[ind] = 1; for (auto i : sons[ind]) { if (!came[i]) count(i); amount[ind] += amount[i]; } if (last[num[ind]] != -1) --amount[lca(ind, last[num[ind]])]; last[num[ind]] = ind; } int main() { int n; cin >> n; p.resize(n + 1); num = lvl = p; sons.resize(n + 1); log(n); dp.resize(n + 1, vector <int> (pow + 1)); dp[0][0] = p[0] = 0; lvl[0] = 1; for (int i = 1; i <= n; ++i) { int pr, c; cin >> pr >> c; dp[i][0] = p[i] = pr; if (i < pow + 1) dp[0][i] = 0; num[i] = c; sons[pr].push_back(i); } levels(0); for (int j = 1; j <= pow; ++j) for (int i = 1; i <= n; ++i) dp[i][j] = dp[dp[i][j - 1]][j - 1]; amount.resize(n + 1, 1); came.resize(n + 1, 0); last.resize(n + 1, -1); count(0); for (int i = 1; i <= n; ++i) cout << amount[i] << ' '; }
[ "mihpihnaty@yandex.com" ]
mihpihnaty@yandex.com
8eff900a0d9b00032569150c2a38117284c58e7e
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/arc035/A/2040456.cpp
0a08462ff3ae57034eeb1d8c55a530411c43fe7c
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
1,129
cpp
#include <iostream> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm> #include <functional> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <bitset> #include <cassert> #include <exception> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll,ll> P; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<string> vs; typedef vector<P> vp; #define rep(i,a,n) for(ll i = (a);i < (n);i++) #define per(i,a,n) for(ll i = (a);i > (n);i--) #define lep(i,a,n) for(ll i = (a);i <= (n);i++) #define pel(i,a,n) for(ll i = (a);i >= (n);i--) #define clr(a,b) memset((a),(b),sizeof(a)) #define pb push_back #define mp make_pair #define all(c) (c).begin(),(c).end() #define sz size() #define print(X) cout << (X) << endl const ll INF = 1e+9+7; ll n,m,l; string s,t; ll d[200010],dp[500][500]; int main(){ cin >> s; l = 0; rep(i,0,s.sz){ if(s[i] == '*' || s[s.sz-i-1] == '*')continue; if(s[i] != s[s.sz-i-1])l++; } if(l)puts("NO"); else puts("YES"); return 0; }
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
9c07bbf703babfe0559248edcbf055dc989e2664
de6e4feb306e8db4822b50988c270c28df81b316
/src/engine/director.cpp
d2b8e06aeca68d7c0a3c0c9709ca340e0eeef04e
[]
no_license
paarm/sfml_playground
d31baa43c04d7ac933991f4fe354c8da62f0fa16
4bbbc31a6fcb00e65fd881e0d5dfb2c52444107c
refs/heads/master
2020-05-20T12:25:32.794985
2017-03-11T19:40:15
2017-03-11T19:40:15
80,448,498
0
0
null
null
null
null
UTF-8
C++
false
false
4,813
cpp
#include "director.h" Director::Director() { std::cout << "Director created" << std::endl; mRootScene.scheduleUpdate(true); } Director::~Director() { if (mWindowHandle.mSFL_Window) { delete mWindowHandle.mSFL_Window; mWindowHandle.mSFL_Window=nullptr; } mRootScene.deleteChilds(); std::cout << "Director destroyed" << std::endl; } void Director::initialize(int rVirtualScreenResolutionX, int rVirtualScreenResolutionY) { //init SDL2 //if (!SDL_Init(SDL_INIT_VIDEO)) { // open window mWindowHandle.mSFL_Window = new sf::RenderWindow(sf::VideoMode(rVirtualScreenResolutionX, rVirtualScreenResolutionY), "Hello World!"); if (mWindowHandle.mSFL_Window) { mWindowHandle.mSFL_Window->setVerticalSyncEnabled(true); mIsInitialized=true; } else { std::cout << "Cannot create Window" << std::endl; } //} //mSDL_Window = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN); #if 0 if (mSDL_Window) { mSDL_Renderer = SDL_CreateRenderer(mSDL_Window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (mSDL_Renderer) { TextureManager::getInstance().setSDLRenderer(mSDL_Renderer); mIsInitialized=true; } else { std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; } } else { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; } } else { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; } #endif } void Director::switchScene(Node *n) { mStageScene=n; } #if 0 void Director::setMousePointer(SDL_Texture *rSDL_Texture, MousePointerAlignment rMousePointerAlignment) { mCustomMouseIcon.mSDL_Texture=rSDL_Texture; mCustomMouseIcon.mMousePointerAlignment=rMousePointerAlignment; if (mCustomMouseIcon.mSDL_Texture) { SDL_ShowCursor( SDL_DISABLE ); mCustomMouseIcon.mOffsetX=0; mCustomMouseIcon.mOffsetY=0; mCustomMouseIcon.mSDL_DestRect.x=0; mCustomMouseIcon.mSDL_DestRect.y=0; TextureManager::getInstance().queryTextureSize(mCustomMouseIcon.mSDL_Texture, &mCustomMouseIcon.mSDL_DestRect.w, &mCustomMouseIcon.mSDL_DestRect.h); /* Uint32 format; TextureManager::getInstance().queryTextureSizeAndFormat(mCustomMouseIcon.mSDL_Texture, &mCustomMouseIcon.mSDL_DestRect.w, &mCustomMouseIcon.mSDL_DestRect.h, &format); SDL_PixelFormat *pixelFormat=SDL_AllocFormat(format); SDL_SetColorKey(mCustomMouseIcon.mSDL_Texture,SDL_SRCCOLORKEY|SDL_RLEACCEL,SDL_MapRGB(pixelFormat,0x255,0x255,0x255)); SDL_FreeFormat(pixelFormat); */ if (mCustomMouseIcon.mMousePointerAlignment==MousePointerAlignment::Middle) { mCustomMouseIcon.mOffsetX=-mCustomMouseIcon.mSDL_DestRect.w/2; mCustomMouseIcon.mOffsetY=-mCustomMouseIcon.mSDL_DestRect.h/2; } } else { SDL_ShowCursor( SDL_ENABLE ); } } #endif void Director::runWithNode(Node *n) { if (mIsInitialized && !mIsRunning) { bool quit=false; mIsRunning=true; switchScene(n); while (!quit) { clock.tick(); sf::Event e; while (mWindowHandle.mSFL_Window->pollEvent(e)) { if (e.type == sf::Event::Closed) { mWindowHandle.mSFL_Window->close(); } } if (mStageScene) { mRootScene.deleteChilds(); mRootScene.addNode(mStageScene); mStageScene=nullptr; } mRootScene.executeUpdate(clock.getDelta()); mWindowHandle.mSFL_Window->clear(); mRootScene.executeDraw(*mWindowHandle.mSFL_Window, sf::Transform::Identity); mWindowHandle.mSFL_Window->display(); #if 0 SDL_PollEvent(&e); if (e.type == SDL_QUIT) { quit = true; std::cout << "SDL_QUIT" << endl; } if (e.type == SDL_KEYDOWN) { quit = true; std::cout << "SDL_KEYDOWN" << endl; } if (e.type == SDL_MOUSEBUTTONDOWN) { quit = true; std::cout << "SDL_MOUSEBUTTONDOWN" << endl; } /*if (e.type==SDL_MOUSEMOTION) { mouseRect.x = e.motion.x; mouseRect.y = e.motion.y; }*/ mRootScene.updateInternal(clock.getDelta()); //First clear the renderer SDL_RenderClear(mSDL_Renderer); //SDL_SetRenderDrawBlendMode(mSDL_Renderer, SDL_BLENDMODE_BLEND); // draw the hole node tree mRootScene.draw(mSDL_Renderer,0,0); if (mCustomMouseIcon.mSDL_Texture) { SDL_GetMouseState(&mCustomMouseIcon.mSDL_DestRect.x, &mCustomMouseIcon.mSDL_DestRect.y); mCustomMouseIcon.mSDL_DestRect.x+=mCustomMouseIcon.mOffsetX; mCustomMouseIcon.mSDL_DestRect.y+=mCustomMouseIcon.mOffsetY; SDL_RenderCopy(mSDL_Renderer, mCustomMouseIcon.mSDL_Texture, nullptr, &mCustomMouseIcon.mSDL_DestRect); } //Update the screen SDL_RenderPresent(mSDL_Renderer); if (mStageScene) { mRootScene.deleteChilds(); mRootScene.addNode(mStageScene); mStageScene=nullptr; } #endif if (quit==true) { break; } else { quit=(!mWindowHandle.mSFL_Window->isOpen()); } } mRootScene.deleteChilds(); mIsRunning=false; } }
[ "martin.paar@gmail.com" ]
martin.paar@gmail.com
74c85bf31f896f65d7ca2970293b58d747594689
367fcc22d70995296920e965a846b3d409c7c9fe
/src/designpattern/Prototype.hpp
a4d1b4a7e53cd9989215222e9d029fb28cf854ae
[ "MIT" ]
permissive
brucexia1/DesignPattern
1860a777a3eb9fd9bae47b70b1282c6e0329fa5b
09dab7aaa4e3d72b64467efe3906e4e504e220c4
refs/heads/master
2021-01-17T05:02:24.514110
2017-07-09T13:16:21
2017-07-09T13:16:21
68,620,087
0
0
null
null
null
null
UTF-8
C++
false
false
888
hpp
#pragma once class Prototype { public: virtual ~Prototype(void); virtual Prototype *Clone() const = 0; protected: Prototype(void); }; //派生自Prototype,实现其接口函数 class ConcretePrototype1:public Prototype { public: ConcretePrototype1(); ~ConcretePrototype1(); ConcretePrototype1(const ConcretePrototype1&);//拷贝构造函数 virtual Prototype* Clone() const;//实现基类定义的Clone接口,内部调用拷贝构造函数实现复制功能 }; //派生自Prototype,实现其接口函数 class ConcretePrototype2:public Prototype { public: ConcretePrototype2();//构造函数 ~ConcretePrototype2();//析构函数 ConcretePrototype2(const ConcretePrototype2&);//拷贝构造函数 virtual Prototype* Clone() const;//实现基类定义的Clone接口,内部调用拷贝构造函数实现复制功能 };
[ "bruce_xia@yeah.net" ]
bruce_xia@yeah.net
335cbf27f04fffe6f1ee49489bc3d9b8cc3fa1fd
792f2ee67210556f224daf88ef0b9785becadc9b
/atcoder/Other/panasonic2020-C.cpp
70dfa483dda3c53930b1ee0e0dd684e78f60b20f
[]
no_license
firiexp/contest_log
e5b345286e7d69ebf2a599d4a81bdb19243ca18d
6474a7127d3a2fed768ebb62031d5ff30eeeef86
refs/heads/master
2021-07-20T01:16:47.869936
2020-04-30T03:27:51
2020-04-30T03:27:51
150,196,219
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
#include <iostream> #include <algorithm> #include <iomanip> #include <map> #include <set> #include <queue> #include <stack> #include <numeric> #include <bitset> #include <cmath> static const int MOD = 1000000007; using ll = long long; using u32 = unsigned; using u64 = unsigned long long; using namespace std; template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208; int main() { ll a, b, c; cin >> a >> b >> c; if(a + b < c && c-a-b > 2 * sqrt((long double)a * b)) puts("Yes"); else puts("No"); return 0; }
[ "firiexp@PC.localdomain" ]
firiexp@PC.localdomain
3f0f4989a8e31cd2dc258de735e4d6e45b26a2bf
715e4935e21e02d8f36bebd9413f388d56d686a5
/no_cd_in.hpp
cd7af5d780d4e1f0a5ea02b250b63b70c1793ed9
[]
no_license
leonardoraele/oosdl
0c3566bf0039ad6088de22ac80032ac5aa208679
740ec22aaeaa1994ce252fd926719aee65a483b4
refs/heads/master
2021-01-20T07:20:31.328718
2017-05-02T04:41:50
2017-05-02T04:41:50
89,991,672
1
0
null
null
null
null
UTF-8
C++
false
false
151
hpp
#ifndef OOSDL_no_cd_in_HPP #define OOSDL_no_cd_in_HPP #include "exception.hpp" namespace OOSDL { class no_cd_in : public exception<> {}; }; #endif
[ "leonardoraele@gmail.com" ]
leonardoraele@gmail.com
3648789957f55fe7df0df71f453546ae73372a0d
6d3c407df83acdf75192c3145ce401f005625560
/codechef/CKISSHUG/CKISSHUG-1304720.cpp
f8fc98ef18fe5b17cada631bd1e93c11eb56a052
[]
no_license
premkamal13/my-code-repository
79928a6892a606a413decb93e6ac85bd10cfdd01
1d097b4b782f54953b8a43b2efcd38a95c637e71
refs/heads/master
2020-04-15T08:26:08.224633
2019-01-08T01:16:44
2019-01-08T01:16:44
164,520,710
0
0
null
2019-01-08T01:07:58
2019-01-08T00:33:36
null
UTF-8
C++
false
false
577
cpp
#include<cstdio> #include<iostream> using namespace std; unsigned long long int pw(unsigned long long int); unsigned long long int temp; int main() { unsigned long long int n,t; unsigned long long int y; scanf("%llu",&t); while(t--) { scanf("%llu",&n); if(n&1) {n=(n+3)/2;y=pw(n)-2;} else {n=n/2;y=3*pw(n)-2;} printf("%llu\n",y%1000000007); } return 0; } unsigned long long int pw(unsigned long long int a) { if(a==1) return 2; else if(a==2) return 4; else if(a&1){temp=pw((a-1)>>1); return (2*temp*temp)%1000000007;} else {temp=pw(a>>1); return (temp*temp)%1000000007;} }
[ "premkamal008@gmail.com" ]
premkamal008@gmail.com
8cddf4176d40f64ab7187c173089237c3e1ed099
097195d38ef281f0b9fbc8895dd1981af92ed7d4
/src/MentalLogic.cpp
cd1635e29857fb6a3bd58d888a3187b04b862b47
[]
no_license
envelopegen/Strums_Mental_VCV_Modules
ebf73d5e89d52f1fbec3b87495e05bd6e905450d
f21c96b963694599d7f87808eb49b21727c834b1
refs/heads/master
2021-08-15T21:46:29.819350
2017-11-18T11:14:06
2017-11-18T11:14:06
111,190,407
1
0
null
2017-11-18T08:49:50
2017-11-18T08:49:50
null
UTF-8
C++
false
false
7,274
cpp
/////////////////////////////////////////////////// // // Logic Gates VCV Module // // Strum 2017 // /////////////////////////////////////////////////// #include "mental.hpp" struct MentalLogic : Module { enum ParamIds { NUM_PARAMS }; enum InputIds { INPUT_A_1, INPUT_B_1, INPUT_A_2, INPUT_B_2, INPUT_INV_1, INPUT_INV_2, INPUT_A_3, INPUT_B_3, INPUT_C_3, INPUT_D_3, INPUT_E_3, NUM_INPUTS }; enum OutputIds { OUTPUT_AND_1, OUTPUT_OR_1, OUTPUT_AND_2, OUTPUT_OR_2, OUTPUT_INV_1, OUTPUT_INV_2, OUTPUT_OR_3, NUM_OUTPUTS }; enum LightIds { AND_LED_1, OR_LED_1, AND_LED_2, OR_LED_2, INV_LED_1, INV_LED_2, OR_LED_3, NUM_LIGHTS }; /*float and_led_1 = 0.0; float or_led_1 = 0.0; float and_led_2 = 0.0; float or_led_2 = 0.0; float inv_led_1 = 0.0; float inv_led_2 = 0.0; float or_led_3 = 0.0; */ MentalLogic() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {} void step() override; }; void MentalLogic::step() { float signal_in_A1 = inputs[INPUT_A_1].value; float signal_in_B1 = inputs[INPUT_B_1].value; float signal_in_A2 = inputs[INPUT_A_2].value; float signal_in_B2 = inputs[INPUT_B_2].value; float inv_1_input = inputs[INPUT_INV_1].value; float inv_2_input = inputs[INPUT_INV_2].value; float or_3_A_input = inputs[INPUT_A_3].value; float or_3_B_input = inputs[INPUT_B_3].value; float or_3_C_input = inputs[INPUT_C_3].value; float or_3_D_input = inputs[INPUT_D_3].value; float or_3_E_input = inputs[INPUT_E_3].value; if (inv_1_input > 0.0) { outputs[OUTPUT_INV_1].value = 0.0; //inv_led_1 = 0.0; lights[INV_LED_1].value = 0.0; } else { outputs[OUTPUT_INV_1].value = 10.0; //inv_led_1 = 1.0; lights[INV_LED_1].value = 1.0; } if (inv_2_input > 0.0) { outputs[OUTPUT_INV_2].value = 0.0; //inv_led_2 = 0.0; lights[INV_LED_2].value = 0.0; } else { outputs[OUTPUT_INV_2].value = 10.0; //inv_led_2 = 1.0; lights[INV_LED_2].value = 1.0; } ////////////////////////// if (signal_in_A1 > 0.0 && signal_in_B1 > 0.0 ) { outputs[OUTPUT_AND_1].value = 10.0; //and_led_1 = 1.0; lights[AND_LED_1].value = 1.0; } else { outputs[OUTPUT_AND_1].value = 0.0; //and_led_1 = 0.0; lights[AND_LED_1].value = 0.0; } if (signal_in_A1 > 0.0 || signal_in_B1 > 0.0 ) { outputs[OUTPUT_OR_1].value = 10.0; //or_led_1 = 1.0; lights[OR_LED_1].value = 1.0; } else { outputs[OUTPUT_OR_1].value = 0.0; //or_led_1 = 0.0; lights[OR_LED_1].value = 0.0; } ////////////////////////////////////// if (signal_in_A2 > 0.0 && signal_in_B2 > 0.0 ) { outputs[OUTPUT_AND_2].value = 10.0; //and_led_2 = 1.0; lights[AND_LED_2].value = 1.0; } else { outputs[OUTPUT_AND_2].value = 0.0; //and_led_2 = 0.0; lights[AND_LED_2].value = 0.0; } if (signal_in_A2 > 0.0 || signal_in_B2 > 0.0 ) { outputs[OUTPUT_OR_2].value = 10.0; //or_led_2 = 1.0; lights[OR_LED_2].value = 1.0; } else { outputs[OUTPUT_OR_2].value = 0.0; //or_led_2 = 0.0; lights[OR_LED_2].value = 0.0; } //////////////// Big or if ( or_3_A_input > 0.0 || or_3_B_input > 0.0 || or_3_C_input > 0.0 || or_3_D_input > 0.0 || or_3_E_input > 0.0 ) { outputs[OUTPUT_OR_3].value = 10.0; //or_led_3 = 1.0; lights[OR_LED_3].value = 1.0; } else { outputs[OUTPUT_OR_3].value = 0.0; //or_led_3 = 0.0; lights[OR_LED_3].value = 0.0; } } ///////////////////////// MentalLogicWidget::MentalLogicWidget() { MentalLogic *module = new MentalLogic(); setModule(module); box.size = Vec(15*5, 380); { SVGPanel *panel = new SVGPanel(); panel->box.size = box.size; //panel->setBackground(SVG::load("plugins/mental/res/MentalLogic.svg")); panel->setBackground(SVG::load(assetPlugin(plugin,"res/MentalLogic.svg"))); addChild(panel); } int input_column = 3; int output_column = 28; int led_column = 58; int first_row = 25; int row_spacing = 25; int vert_offset = 60; addInput(createInput<PJ301MPort>(Vec(input_column, first_row), module, MentalLogic::INPUT_A_1)); addInput(createInput<PJ301MPort>(Vec(input_column, first_row+row_spacing), module, MentalLogic::INPUT_B_1)); addOutput(createOutput<PJ301MPort>(Vec(output_column, first_row), module, MentalLogic::OUTPUT_AND_1)); addOutput(createOutput<PJ301MPort>(Vec(output_column, first_row+row_spacing), module, MentalLogic::OUTPUT_OR_1)); addChild(createLight<MediumLight<GreenLight>>(Vec(led_column, first_row + 8), module, MentalLogic::AND_LED_1)); addChild(createLight<MediumLight<GreenLight>>(Vec(led_column, first_row+row_spacing + 8), module, MentalLogic::OR_LED_1)); //////////////////////////// addInput(createInput<PJ301MPort>(Vec(input_column, vert_offset + first_row), module, MentalLogic::INPUT_A_2)); addInput(createInput<PJ301MPort>(Vec(input_column, vert_offset + first_row + row_spacing), module, MentalLogic::INPUT_B_2)); addOutput(createOutput<PJ301MPort>(Vec(output_column, vert_offset + first_row), module, MentalLogic::OUTPUT_AND_2)); addOutput(createOutput<PJ301MPort>(Vec(output_column, vert_offset + first_row + row_spacing), module, MentalLogic::OUTPUT_OR_2)); addChild(createLight<MediumLight<GreenLight>>(Vec(led_column, vert_offset + first_row + 8), module, MentalLogic::AND_LED_2)); addChild(createLight<MediumLight<GreenLight>>(Vec(led_column, vert_offset +first_row + row_spacing + 8), module, MentalLogic::OR_LED_2)); ///// Inverters addInput(createInput<PJ301MPort>(Vec(input_column, vert_offset * 2 + first_row), module, MentalLogic::INPUT_INV_1)); addInput(createInput<PJ301MPort>(Vec(input_column, vert_offset * 2 + first_row + row_spacing), module, MentalLogic::INPUT_INV_2)); addOutput(createOutput<PJ301MPort>(Vec(output_column, vert_offset * 2 + first_row), module, MentalLogic::OUTPUT_INV_1)); addOutput(createOutput<PJ301MPort>(Vec(output_column, vert_offset * 2 + first_row + row_spacing), module, MentalLogic::OUTPUT_INV_2)); addChild(createLight<MediumLight<GreenLight>>(Vec(led_column, vert_offset * 2 + first_row + 8), module, MentalLogic::INV_LED_1)); addChild(createLight<MediumLight<GreenLight>>(Vec(led_column, vert_offset * 2 + first_row + row_spacing + 8), module, MentalLogic::INV_LED_2)); ////// Big or addInput(createInput<PJ301MPort>(Vec(input_column, vert_offset + 150), module, MentalLogic::INPUT_A_3)); addInput(createInput<PJ301MPort>(Vec(input_column, vert_offset + 175), module, MentalLogic::INPUT_B_3)); addInput(createInput<PJ301MPort>(Vec(input_column, vert_offset + 200), module, MentalLogic::INPUT_C_3)); addInput(createInput<PJ301MPort>(Vec(input_column, vert_offset + 225), module, MentalLogic::INPUT_D_3)); addInput(createInput<PJ301MPort>(Vec(input_column, vert_offset + 250), module, MentalLogic::INPUT_E_3)); addOutput(createOutput<PJ301MPort>(Vec(output_column, vert_offset + 150), module, MentalLogic::OUTPUT_OR_3)); addChild(createLight<MediumLight<GreenLight>>(Vec(led_column, vert_offset + 158), module, MentalLogic::OR_LED_3)); }
[ "strum@softhome.net" ]
strum@softhome.net
008eff637bee93d61f49067769cfd95ebe55b256
19affc1bcce0b9818990e3e7b75dbf0b24d2abc2
/Sorting and Searching/Stick_Lengths.cpp
1f6e7aafcd0ff6d90007b6755033f7d4a2f89083
[]
no_license
nayakashutosh9/CSES-Problemset-Editorial
7e186d60d8efef7b9135036f6cb3b81396789e96
89f01f1e95a9a5d891f619b726a6292f4fb80a82
refs/heads/master
2023-02-08T11:51:45.725282
2020-12-24T15:03:31
2020-12-24T15:03:31
295,397,347
0
0
null
null
null
null
UTF-8
C++
false
false
1,325
cpp
/***************************************************** * created by: nayakashutosh9 * "Winners Never Quit and Quitters Never Win". *****************************************************/ #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> #pragma GCC optimize("Ofast") using namespace __gnu_pbds; using namespace std; #define int long long int #define endl '\n' #define mod 1000000007 #define inf 1e18 typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; const int N = 300005; /**********************************************************************************************/ void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; sort(a.begin(), a.end()); int x = a[n / 2], ans = 0; for (int i = 0; i < n; i++) ans += abs(a[i] - x); cout << ans << endl; } int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t = 1, z = 1; // cin >> t; cin.ignore(); while (t--) { // cout << "Case #" << (z++) << ": "; // clock_t start = clock(); solve(); // clock_t end = clock(); // cout << (end-start) << endl; //print execution time in ms } return 0; }
[ "nayakashutosh99@gmail.com" ]
nayakashutosh99@gmail.com
6e72e1a855372feb1240c74bee9eda03c9413111
7f85422924a88e835eddd0e5fb6f32ad1e55ba04
/headers/Mesh_Utils.h
18c393cadd93f401a426ca72c51153b285884981
[]
no_license
sangiole/Sticky-Branes
3eb9b2d05d4ca52d12b7d5a04ff1097bbdbdf6f2
5bba4b4ee846e979eb0208eaa2d7254eda66134f
refs/heads/master
2020-06-15T05:44:26.104768
2013-01-14T11:35:39
2013-01-14T11:35:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
795
h
// Utilities to calculate curvature and other quantities on a triangular mesh // Created by Stefano Angioletti-Uberti on 04/11/2012. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. #ifndef MESH__UTILS_H #define MESH_UTILS_H #include "headers/3D_Vectors.h" #include "headers/Simu_variables.h" #include "headers/Utils_distances.h" #include "headers/Bead.h" #include "headers/Plaquette.h" #include <vector> vector< double > Mean_Curvature_Area_At_Vertex( CBead *pbead, int vertex ); vector< double > Gaussian_Curvature_Area_At_Vertex( CBead *pbead, int vertex ); double Mean_Curvature_At_Vertex( CBead *pbead, int vertex ); double Gaussian_Curvature_At_Vertex( CBead *pbead, int vertex ); double Area_At_Vertex( CBead *pbead, int vertex ); double cotan( double x ); #endif
[ "stefano.steno@gmail.com" ]
stefano.steno@gmail.com
496ff1852ae8f017a6ad6f960dad63f8fe241ba2
41645a9ac81a1ac14496e623d33f2ec2cbfd573b
/Speed_Battle.ino
3bcc863ffcfa4b161fb2b71ed695791f0cfc934a
[]
no_license
aia39/Line-Follower
aa4197913f531c8cdfe68ba1443ff7c82fce03be
2b1fdcca1c3b895730b869be879ad4bd910fdf25
refs/heads/master
2021-06-21T01:37:00.320684
2021-02-15T06:23:03
2021-02-15T06:23:03
158,483,357
0
0
null
null
null
null
UTF-8
C++
false
false
5,473
ino
#define inA 2 #define inB 3 #define inC 4 #define inD 7 #define enA 5 #define enB 6 int leftBaseSpeed = 130; int rightBaseSpeed = 130; int maxSpeed = 255; // SENSOR PARAMETERS #define NUM_SENSORS 5 int thresholds[NUM_SENSORS] = {450, 450, 450, 450, 450}; int ledPins[5] = {8, 9, 10, 11, 12}; int sensorValues[NUM_SENSORS], sValues[NUM_SENSORS], lastSensor, psValues[NUM_SENSORS], mode,distR = 0, distF = 0;// durationF = 0, durationR = 0; unsigned long durationF=0,durationR=0; // PID PARAMETERS float kp = 48.0; float kd = 4.7; float ki = 0.75; int prevError = 0, error = 0; float p, i = 0, d; void setup() { // put your setup code here, to run once: //Initialize Motor Pins motorInit(); //Initialize Other Variables and Pins otherInit(); } void loop() { //if(distF<value&&disR<value) wallFollow(); lineFollow(); } void motorInit() { pinMode(inA, OUTPUT); pinMode(inB, OUTPUT); pinMode(inC, OUTPUT); pinMode(inD, OUTPUT); pinMode(enA, OUTPUT); pinMode(enB, OUTPUT); //Setting The Motor to zero speed digitalWrite(inA, HIGH); digitalWrite(inB, HIGH); digitalWrite(inC, HIGH); digitalWrite(inD, HIGH); } void otherInit() { //for (int i = 0; i < 5; i++) pinMode(ledPins[i], OUTPUT); lastSensor = 0; prevError = 0; Serial.begin(9600); } int readSensor() { for (int i = 0; i < NUM_SENSORS; i++) { //Read the raw sensor values sensorValues[i] = analogRead(i); //Serial.print(i+1); Serial.print(" : "); Serial.println(sensorValues[i]); delay(700); //Covert them into digital readings //And turning the corresponding LED on or off if (sensorValues[i] > thresholds[i]) { sValues[i] = 0; //digitalWrite(ledPins[i], LOW); } else { sValues[i] = 1; //digitalWrite(ledPins[i], HIGH); } //detectPos(); /*if (sensorValues[i] > thresholds[i]) { sValues[i] = psValues[i] + mode; } else { sValues[i] = psValues[i] - mode; }*/ } if (sValues[0] == 0 && sValues[1] == 0 && sValues[2] == 1 && sValues[3] == 0 && sValues[4] == 0) { error = 0; } else if (sValues[0] == 0 && sValues[1] == 0 && sValues[2] == 0 && sValues[3] == 1 && sValues[4] == 0) { error = 1; } else if (sValues[0] == 0 && sValues[1] == 1 && sValues[2] == 0 && sValues[3] == 0 && sValues[4] == 0) { error = -1; } else if (sValues[0] == 0 && sValues[1] == 0 && sValues[2] == 0 && sValues[3] == 0 && sValues[4] == 1) { error = 3; lastSensor = 2; } else if (sValues[0] == 1 && sValues[1] == 0 && sValues[2] == 0 && sValues[3] == 0 && sValues[4] == 0) { error = -3; lastSensor = 1; } else if (sValues[0] == 0 && sValues[1] == 0 && sValues[2] == 1 && sValues[3] == 1 && sValues[4] == 0) { error = 2; } else if (sValues[0] == 0 && sValues[1] == 1 && sValues[2] == 1 && sValues[3] == 0 && sValues[4] == 0) { error = -2; } else if (sValues[0] == 0 && sValues[1] == 0 && sValues[2] == 1 && sValues[3] == 1 && sValues[4] == 1) { error = 4; lastSensor = 2; } else if (sValues[0] == 1 && sValues[1] == 1 && sValues[2] == 1 && sValues[3] == 0 && sValues[4] == 0) { error = -4; lastSensor = 1; } else if (sValues[0] == 0 && sValues[1] == 1 && sValues[2] == 1 && sValues[3] == 1 && sValues[4] == 1) { error = 5; lastSensor = 2; } else if (sValues[0] == 1 && sValues[1] == 1 && sValues[2] == 1 && sValues[3] == 1 && sValues[4] == 0) { error = -5; lastSensor = 1; } else if (sValues[0] == 0 && sValues[1] == 0 && sValues[2] == 0 && sValues[3] == 0 && sValues[4] == 0) { if (lastSensor == 1) { error = -6; } else if (lastSensor == 2) { error = 6; } } return error; } void lineFollow() { int pid; //Read the sensor values and calculate error error = readSensor(); p = error * kp; i = (i + error) * ki; //i=i+ilast; d = (error - prevError) * kd; pid = int(p + i + d); //lasti=i; //motor_control(); wheel(leftBaseSpeed - pid, rightBaseSpeed + pid); prevError = error; if (error - prevError == 0) delay(10); } void wheel(int leftSpeed, int rightSpeed) { if ( leftSpeed == 0) { digitalWrite(inC, 1); digitalWrite(inD, HIGH); } if ( leftSpeed > 0) { digitalWrite(inC, 1); digitalWrite(inD, 0); //delay(5); } else if ( leftSpeed < 0) { digitalWrite(inC, 0); digitalWrite(inD, 1); //delay(5); } if (rightSpeed == 0) { digitalWrite(inA, HIGH); digitalWrite(inB, HIGH); } if ( rightSpeed > 0) { digitalWrite(inA, 1); digitalWrite(inB, 0); //delay(10); } else if ( rightSpeed < 0) { digitalWrite(inA, 0); digitalWrite(inB, 1); //delay(10); } if (abs(leftSpeed) > maxSpeed) leftSpeed = maxSpeed; if (abs(rightSpeed) > maxSpeed) rightSpeed = maxSpeed; analogWrite(enA, abs(rightSpeed)); analogWrite(enB, abs(leftSpeed)); } /*void detectPos(void) { int i, mem1, mem2 = 0; mem1 = psValues[0]; for (int i = 0; i < NUM_SENSORS; i++) { if (psValues[i] != mem1) { mem1 = psValues[i]; mem2++; } } if (mem2 >= 2) { mem2 = psValues[4] ; //Serial.println(mem2); //delay(250); mode = mem2; if (mode) { digitalWrite(13, 1); } else { digitalWrite(13, 0); } } } */
[ "noreply@github.com" ]
noreply@github.com
bcecfee1c29f98fbe5e080cb2e8a03ed58146c36
0fd7bfc4effe067c2887e2e29e08e9bfa4446398
/Source/Plugins/FilterNode/Dsp/ChebyshevII.h
0ee7d91840c51f4ef93caddec9f33451edcd51ad
[]
no_license
priyanjitdey94/plugin-GUI
baf4c17d9a50a8457fb047375f32672b7fa8d4bc
c1665986aac79888515b75a8a851211b1fb4c516
refs/heads/master
2021-01-17T17:54:01.994930
2016-04-07T18:28:27
2016-04-07T18:28:27
53,115,629
1
0
null
2016-03-04T07:17:38
2016-03-04T07:17:38
null
UTF-8
C++
false
false
10,662
h
/******************************************************************************* "A Collection of Useful C++ Classes for Digital Signal Processing" By Vincent Falco Official project location: http://code.google.com/p/dspfilterscpp/ See Documentation.cpp for contact information, notes, and bibliography. -------------------------------------------------------------------------------- License: MIT License (http://www.opensource.org/licenses/mit-license.php) Copyright (c) 2009 by Vincent Falco 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 DSPFILTERS_CHEBYSHEVII_H #define DSPFILTERS_CHEBYSHEVII_H #include "Common.h" #include "Cascade.h" #include "Design.h" #include "Filter.h" #include "PoleFilter.h" namespace Dsp { /* * Filters with Inverse Chebyshev response characteristics * */ namespace ChebyshevII { // Half-band analog prototypes (s-plane) class AnalogLowPass : public LayoutBase { public: AnalogLowPass(); void design(const int numPoles, double stopBandDb); private: int m_numPoles; double m_stopBandDb; }; //------------------------------------------------------------------------------ class AnalogLowShelf : public LayoutBase { public: AnalogLowShelf(); void design(int numPoles, double gainDb, double stopBandDb); private: int m_numPoles; double m_stopBandDb; double m_gainDb; }; //------------------------------------------------------------------------------ // Factored implementations to reduce template instantiations struct LowPassBase : PoleFilterBase <AnalogLowPass> { void setup(int order, double sampleRate, double cutoffFrequency, double stopBandDb); }; struct HighPassBase : PoleFilterBase <AnalogLowPass> { void setup(int order, double sampleRate, double cutoffFrequency, double stopBandDb); }; struct BandPassBase : PoleFilterBase <AnalogLowPass> { void setup(int order, double sampleRate, double centerFrequency, double widthFrequency, double stopBandDb); }; struct BandStopBase : PoleFilterBase <AnalogLowPass> { void setup(int order, double sampleRate, double centerFrequency, double widthFrequency, double stopBandDb); }; struct LowShelfBase : PoleFilterBase <AnalogLowShelf> { void setup(int order, double sampleRate, double cutoffFrequency, double gainDb, double stopBandDb); }; struct HighShelfBase : PoleFilterBase <AnalogLowShelf> { void setup(int order, double sampleRate, double cutoffFrequency, double gainDb, double stopBandDb); }; struct BandShelfBase : PoleFilterBase <AnalogLowShelf> { void setup(int order, double sampleRate, double centerFrequency, double widthFrequency, double gainDb, double stopBandDb); }; //------------------------------------------------------------------------------ // // Raw filters // template <int MaxOrder> struct LowPass : PoleFilter <LowPassBase, MaxOrder> { }; template <int MaxOrder> struct HighPass : PoleFilter <HighPassBase, MaxOrder> { }; template <int MaxOrder> struct BandPass : PoleFilter <BandPassBase, MaxOrder, MaxOrder*2> { }; template <int MaxOrder> struct BandStop : PoleFilter <BandStopBase, MaxOrder, MaxOrder*2> { }; template <int MaxOrder> struct LowShelf : PoleFilter <LowShelfBase, MaxOrder> { }; template <int MaxOrder> struct HighShelf : PoleFilter <HighShelfBase, MaxOrder> { }; template <int MaxOrder> struct BandShelf : PoleFilter <BandShelfBase, MaxOrder, MaxOrder*2> { }; //------------------------------------------------------------------------------ // // Gui-friendly Design layer // namespace Design { struct TypeIBase : DesignBase { enum { NumParams = 4 }; static int getNumParams() { return 4; } static const ParamInfo getParamInfo_2() { return ParamInfo::defaultCutoffFrequencyParam(); } static const ParamInfo getParamInfo_3() { return ParamInfo::defaultStopDbParam(); } }; template <class FilterClass> struct TypeI : TypeIBase, FilterClass { void setParams(const Params& params) { FilterClass::setup(int(params[1]), params[0], params[2], params[3]); } }; struct TypeIIBase : DesignBase { enum { NumParams = 5 }; static int getNumParams() { return 5; } static const ParamInfo getParamInfo_2() { return ParamInfo::defaultCenterFrequencyParam(); } static const ParamInfo getParamInfo_3() { return ParamInfo::defaultBandwidthHzParam(); } static const ParamInfo getParamInfo_4() { return ParamInfo::defaultStopDbParam(); } }; template <class FilterClass> struct TypeII : TypeIIBase, FilterClass { void setParams(const Params& params) { FilterClass::setup(int(params[1]), params[0], params[2], params[3], params[4]); } }; struct TypeIIIBase : DesignBase { enum { NumParams = 5 }; static int getNumParams() { return 5; } static const ParamInfo getParamInfo_2() { return ParamInfo::defaultCutoffFrequencyParam(); } static const ParamInfo getParamInfo_3() { return ParamInfo::defaultGainParam(); } static const ParamInfo getParamInfo_4() { return ParamInfo::defaultStopDbParam(); } }; template <class FilterClass> struct TypeIII : TypeIIIBase, FilterClass { void setParams(const Params& params) { FilterClass::setup(int(params[1]), params[0], params[2], params[3], params[4]); } }; struct TypeIVBase : DesignBase { enum { NumParams = 6 }; static int getNumParams() { return 6; } static const ParamInfo getParamInfo_2() { return ParamInfo::defaultCenterFrequencyParam(); } static const ParamInfo getParamInfo_3() { return ParamInfo::defaultBandwidthHzParam(); } static const ParamInfo getParamInfo_4() { return ParamInfo::defaultGainParam(); } static const ParamInfo getParamInfo_5() { return ParamInfo::defaultStopDbParam(); } }; template <class FilterClass> struct TypeIV : TypeIVBase, FilterClass { void setParams(const Params& params) { FilterClass::setup(int(params[1]), params[0], params[2], params[3], params[4], params[5]); } }; // Factored kind and name struct LowPassDescription { static Kind getKind() { return kindLowPass; } static const char* getName() { return "Chebyshev II Low Pass"; } }; struct HighPassDescription { static Kind getKind() { return kindHighPass; } static const char* getName() { return "Chebyshev II High Pass"; } }; struct BandPassDescription { static Kind getKind() { return kindHighPass; } static const char* getName() { return "Chebyshev II Band Pass"; } }; struct BandStopDescription { static Kind getKind() { return kindHighPass; } static const char* getName() { return "Chebyshev II Band Stop"; } }; struct LowShelfDescription { static Kind getKind() { return kindLowShelf; } static const char* getName() { return "Chebyshev II Low Shelf"; } }; struct HighShelfDescription { static Kind getKind() { return kindHighShelf; } static const char* getName() { return "Chebyshev II High Shelf"; } }; struct BandShelfDescription { static Kind getKind() { return kindBandShelf; } static const char* getName() { return "Chebyshev II Band Shelf"; } }; // This glues on the Order parameter template <int MaxOrder, template <class> class TypeClass, template <int> class FilterClass> struct OrderBase : TypeClass <FilterClass <MaxOrder> > { const ParamInfo getParamInfo_1() const { return ParamInfo(idOrder, "Order", "Order", 1, MaxOrder, 2, &ParamInfo::Int_toControlValue, &ParamInfo::Int_toNativeValue, &ParamInfo::Int_toString); } }; //------------------------------------------------------------------------------ // // Design Filters // template <int MaxOrder> struct LowPass : OrderBase <MaxOrder, TypeI, ChebyshevII::LowPass>, LowPassDescription { }; template <int MaxOrder> struct HighPass : OrderBase <MaxOrder, TypeI, ChebyshevII::HighPass>, HighPassDescription { }; template <int MaxOrder> struct BandPass : OrderBase <MaxOrder, TypeII, ChebyshevII::BandPass>, BandPassDescription { }; template <int MaxOrder> struct BandStop : OrderBase <MaxOrder, TypeII, ChebyshevII::BandStop>, BandStopDescription { }; template <int MaxOrder> struct LowShelf : OrderBase <MaxOrder, TypeIII, ChebyshevII::LowShelf>, LowShelfDescription { }; template <int MaxOrder> struct HighShelf : OrderBase <MaxOrder, TypeIII, ChebyshevII::HighShelf>, HighShelfDescription { }; template <int MaxOrder> struct BandShelf : OrderBase <MaxOrder, TypeIV, ChebyshevII::BandShelf>, BandShelfDescription { }; } } } #endif
[ "aacuelo@teleco.upv.es" ]
aacuelo@teleco.upv.es
fb7647bfca82a56e675726342be654e780f15064
4b15331951e5a6bdbc577ac08932b8841464ed73
/Projects/Cakewalk.cpp
d68873d7ff8011b48f83835d0d4a0172b915c58a
[]
no_license
abhaychandna/Practice
2d37db548272e836b44b47a77035889f2bd96b5a
2726564341eed6bdd912c9a7c67fc4f25cdd0c31
refs/heads/master
2022-12-26T11:11:21.641702
2022-12-17T13:35:44
2022-12-17T13:35:44
250,537,173
0
0
null
2020-03-27T14:15:32
2020-03-27T13:09:00
C++
UTF-8
C++
false
false
900
cpp
#include<iostream> #include<vector> #include<algorithm> #include<map> #include<stack> #include<queue> #include<string> #include<set> #include<cmath> #define ll long long #define mod 1000000007 #define INT_MAX 2147483647 #define INT_MIN -2147483648 #define vl vector<long long int> #define vvl vector<vector<long long int>> #define pl pair<long long int, long long int> #define pb push_back #define fo(i,n) for(int i=0;i<n;i++) #define forev(i,n) for(int i=n-1;i>=0;i--) using namespace std; bool cakewalk() { ll a[2], b[2], c[2]; cin >> a[0] >> a[1] >> b[0] >> b[1] >> c[0] >> c[1]; return (abs(a[0] - c[0]) + abs(a[1] - c[1])) < (abs(b[0] - c[0]) + abs(b[1] - c[1])); } ll Ynot() { ll ans = 0; return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t = 1; cin >> t; while (t--) { ll ans = 0; ans = Ynot(); cout << ans << '\n'; } }
[ "abhaychandna5@gmail.com" ]
abhaychandna5@gmail.com
019bbc55626a8fdc8722e3e1acf1d7f0fa847323
bdde281dae7b5bf7d23cb47339e4e2427388f3c8
/src/client.cpp
05921da285e633c4bc483bbaf68fb920e64f639a
[]
no_license
mfreiholz/qbroadcasttransfer
5a82ba3ab76eeb66720582066f71f37b799d1bbb
a3e19b5b1cda6efaeb0c16978a1a0710ecc12d7c
refs/heads/master
2016-09-05T17:37:55.584987
2014-09-14T20:04:50
2014-09-14T20:04:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,858
cpp
#include <QTcpSocket> #include <QUdpSocket> #include <QDataStream> #include <QTimerEvent> #include "client.h" #include "protocol.h" Client::Client(QObject *parent) : QObject(parent), _serverConnection(0) { qRegisterMetaType<QHostAddress>("QHostAddress"); _serverConnection = new ClientServerConnectionHandler(this, this); connect(_serverConnection->getSocket(), SIGNAL(connected()), SIGNAL(serverConnected())); connect(_serverConnection->getSocket(), SIGNAL(disconnected()), SIGNAL(serverDisconnected())); _dataSocket = new ClientUdpSocket(this, this); } Client::~Client() { delete _serverConnection; delete _dataSocket; } bool Client::listen() { if (_dataSocket->state() != QAbstractSocket::BoundState) { return _dataSocket->bind(UDPPORTCLIENT, QUdpSocket::ShareAddress); } return false; } void Client::close() { _dataSocket->close(); } const ClientServerConnectionHandler& Client::getServerConnection() const { return *_serverConnection; } void Client::connectToServer(const QHostAddress &address, quint16 port) { _serverConnection->connectToHost(address, port); } /////////////////////////////////////////////////////////////////////////////// // ClientUdpSocket /////////////////////////////////////////////////////////////////////////////// ClientUdpSocket::ClientUdpSocket(Client *client, QObject *parent) : QUdpSocket(parent), _client(client) { connect(this, SIGNAL(readyRead()), SLOT(onReadPendingDatagram())); } void ClientUdpSocket::onReadPendingDatagram() { while (hasPendingDatagrams()) { QByteArray datagram; QHostAddress sender; quint16 senderPort; datagram.resize(pendingDatagramSize()); readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); QDataStream in(datagram); quint8 magic = 0; in >> magic; if (magic != DGMAGICBIT) { qDebug() << QString("Datagram with invalid magic byte (size=%1)").arg(datagram.size()); continue; } quint8 type; in >> type; switch (type) { case DGHELLO: processHello(in, sender, senderPort); break; case DGDATA: processFileData(in, sender, senderPort); break; default: qDebug() << QString("Unknown datagram type"); break; } } } void ClientUdpSocket::processHello(QDataStream &in, const QHostAddress &sender, quint16 senderPort) { quint16 serverPort; in >> serverPort; if (_client->_serverConnection->getSocket()->state() == QAbstractSocket::UnconnectedState) { _client->connectToServer(sender, serverPort); emit _client->serverBroadcastReceived(sender, serverPort); } } void ClientUdpSocket::processFileData(QDataStream &in, const QHostAddress &sender, quint16 senderPort) { FileData fd; in >> fd; FileInfoPtr info = _client->_files2id.value(fd.id); if (!info) { qDebug() << QString("Received file data with unknown file-id (id=%1)").arg(fd.id); return; } qDebug() << QString("Received file data (id=%1; index=%2; size=%3)").arg(fd.id).arg(fd.index).arg(fd.data.size()); } /////////////////////////////////////////////////////////////////////////////// // ClientServerConnectionHandler /////////////////////////////////////////////////////////////////////////////// ClientServerConnectionHandler::ClientServerConnectionHandler(Client *client, QObject *parent) : QObject(parent), _client(client), _socket(new QTcpSocket(this)), _keepAliveTimerId(-1) { connect(_socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(onStateChanged(QAbstractSocket::SocketState))); connect(_socket, SIGNAL(readyRead()), SLOT(onReadyRead())); } ClientServerConnectionHandler::~ClientServerConnectionHandler() { delete _socket; if (_keepAliveTimerId >= 0) { killTimer(_keepAliveTimerId); } } void ClientServerConnectionHandler::connectToHost(const QHostAddress &address, quint16 port) { _socket->connectToHost(address, port); } void ClientServerConnectionHandler::sendKeepAlive() { qDebug() << QString("Send /keepalive."); QByteArray body; QDataStream out(&body, QIODevice::WriteOnly); out << QString("/keepalive"); TCP::Request req; req.setBody(body); _socket->write(_protocol.serialize(req)); } void ClientServerConnectionHandler::timerEvent(QTimerEvent *ev) { if (ev->timerId() == _keepAliveTimerId) { sendKeepAlive(); } } void ClientServerConnectionHandler::onStateChanged(QAbstractSocket::SocketState state) { switch (state) { case QAbstractSocket::ConnectedState: _keepAliveTimerId = startTimer(1500); break; case QAbstractSocket::UnconnectedState: killTimer(_keepAliveTimerId); _keepAliveTimerId = -1; emit disconnected(); break; } } void ClientServerConnectionHandler::onReadyRead() { qint64 available = 0; while ((available = _socket->bytesAvailable()) > 0) { QByteArray data = _socket->read(available); _protocol.append(data); } TCP::Request *request = 0; while ((request = _protocol.next()) != 0) { switch (request->header.type) { case TCP::Request::Header::REQ: processRequest(*request); break; case TCP::Request::Header::RESP: //processRequest(*request); break; } delete request; } } void ClientServerConnectionHandler::processRequest(TCP::Request &request) { QDataStream in(request.body); QString action; in >> action; if (action == "/keepalive") { processKeepAlive(request, in); } else if (action == "/file/register") { processFileRegister(request, in); } } void ClientServerConnectionHandler::processKeepAlive(TCP::Request &request, QDataStream &in) { TCP::Request response; response.initResponseByRequest(request); _socket->write(_protocol.serialize(response)); } void ClientServerConnectionHandler::processFileRegister(TCP::Request &request, QDataStream &in) { FileInfoPtr info(new FileInfo()); in >> *info.data(); _client->_files.append(info); _client->_files2id.insert(info->id, info); emit _client->filesChanged(); qDebug() << QString("Registered new file on client: %1 %2").arg(info->id).arg(info->path); TCP::Request response; response.initResponseByRequest(request); _socket->write(_protocol.serialize(response)); } void ClientServerConnectionHandler::processFileUnregister(TCP::Request &request, QDataStream &in) { FileInfo::fileid_t id; in >> id; for (int i = 0; i < _client->_files.size(); ++i) { FileInfoPtr fi = _client->_files.at(i); if (fi->id == id) { _client->_files.removeAt(i); _client->_files2id.remove(id); break; } } emit _client->filesChanged(); qDebug() << QString("Unregistered file on client: %1").arg(id); TCP::Request response; response.initResponseByRequest(request); _socket->write(_protocol.serialize(response)); } /////////////////////////////////////////////////////////////////////////////// // ClientFilesModel /////////////////////////////////////////////////////////////////////////////// ClientFilesModel::ClientFilesModel(Client *client, QObject *parent) : QAbstractTableModel(parent), _client(client) { _columnHeaders.insert(FileIdColumn, tr("Id")); _columnHeaders.insert(FileNameColumn, tr("Name")); _columnHeaders.insert(FileSizeColumn, tr("Size")); connect(_client, SIGNAL(filesChanged()), SLOT(onClientFilesChanged())); } int ClientFilesModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return _columnHeaders.size(); } QVariant ClientFilesModel::headerData(int section, Qt::Orientation orientation, int role) const { switch (orientation) { case Qt::Horizontal: switch (role) { case Qt::DisplayRole: return _columnHeaders.value(section); } break; } return QVariant(); } int ClientFilesModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent) return _client->_files.size(); } QVariant ClientFilesModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= _client->_files.size()) { return QVariant(); } switch (role) { case Qt::DisplayRole: switch (index.column()) { case FileIdColumn: return _client->_files.at(index.row())->id; case FileNameColumn: return _client->_files.at(index.row())->path; case FileSizeColumn: return _client->_files.at(index.row())->size; } break; } return QVariant(); } void ClientFilesModel::onClientFilesChanged() { beginResetModel(); endResetModel(); }
[ "manuel@insanefactory.com" ]
manuel@insanefactory.com
3e827d2e6aca7f8ff605dfbb65c955343d7ad55b
2f2b53cc5ccebdc44b50cc2bed10a0f77d6b974f
/praticasED/jogo/craps.cpp
ef588029e86c3fc51cd46b4a6eb2787c403f54d8
[]
no_license
joaovictor3g/estrutura-de-dados
ada00f6819a78113e883f851e7550c96f37d566f
bb8ea7ef99c356b6fcf473deea9d4567aa968b4c
refs/heads/master
2021-01-07T06:05:37.201580
2020-11-29T18:29:55
2020-11-29T18:29:55
241,600,837
4
1
null
null
null
null
UTF-8
C++
false
false
1,813
cpp
/*Um jogador rola dois dados. Cada dado tem seis faces. Essas faces contêm 1, 2, 3, 4, 5 e 6 pontos. Depois que os dados param de rolar, a soma dos pontos nas faces viradas para cima é calculada. Se a soma é 7 ou 11 na primeira rolagem dos dados, o jogador ganha. Se a soma é 2, 3 ou 12 na primeira rolagem dos dados (chamado ‘craps’), o jogador perde (isto é, a ‘casa’ ganha). Se a soma for 4, 5, 6, 8, 9 ou 10 na primeira rolagem dos dados, essa soma torna-se a ‘pontuação’ do jogador. Para ganhar, você deve continuar a lançar o dado até ‘fazer sua pontuação’. O jogador perde se obtiver um 7 antes de fazer sua pontuação.*/ #include <iostream> #include <cstdlib> int rollDice(); int rollDice() { int roll1 = 1 + std::rand() % 6; int roll2 = 1 + std::rand() % 6; std::cout << "Player rolled: " << roll1 << " + " << roll2 << " = " << roll1 + roll2 << std::endl; return roll1 + roll2; } int main() { std::srand(time(NULL)); enum Status { CONTINUE, WON, LOST }; int score = 0; Status gameStatus; int sumOfDice = rollDice(); switch ( sumOfDice ){ case 7: case 11: gameStatus = WON; break; case 2: case 3: case 12: gameStatus = LOST; break; default: score = sumOfDice; gameStatus = CONTINUE; break; } while (gameStatus == CONTINUE) { sumOfDice = rollDice(); if(sumOfDice == score) gameStatus = WON; else if(sumOfDice == 7) gameStatus = LOST; } if(gameStatus == WON) std::cout << "Player wins" << std::endl; else std::cout << "Player loses" << std::endl; return 0; }
[ "jvdias79797@gmail.com" ]
jvdias79797@gmail.com
9ea4323453c81f5b205758cd4256e17ff98dd4a3
1fbc9b916cff41d177710596e34f3599f22ac2e2
/philip.cpp
9c805f9a70c51baaa9ab5858ecd037b17bb21817
[]
no_license
PhilipOgweno/HMWORK6
b471c19f68776b4c4a130d6e4b98679552351579
0e3e872b074a681575bf73696d32cf300c13e696
refs/heads/master
2016-09-09T17:01:03.069341
2015-03-20T03:06:49
2015-03-20T03:06:49
32,431,249
0
0
null
null
null
null
UTF-8
C++
false
false
4,700
cpp
/* * Homework 6 Program, Station Channels * Goal: Understand how to declare and manipulate a collections of objects * using a arrays, enumerators, and structures * Author: Luke Philip Ogweno * 19 March 2015 * Github account: https://github.com/PhilipOgweno/HMWORK6.git */ // libraries #include <iostream> #include <string> #include <sstream> #include <cstdlib> #include <fstream> #include <iomanip> #include <ctype.h> #include <locale> using namespace std; // Definining variables // Using enum to declare months enum month {January = 1, February, March, April,May, June, July, August, September, October, November, December}; struct header { string EQID; string Date; string Day; string Year; string Time; string TimeZone; string EarthquakeName; string Lat; string Lon; string MagType; string Magnitude; string Event; }; struct signalInfo { string NetCode; string stnName; string BandName; string InstName; string OrientName; }; // Openning Input File and checking ii it is opened correctly void open_input(ifstream& inputFile, string inputFileName) { inputFile.open(inputFileName.c_str()); if (inputFile.fail()) { cout << "Error! Unable to open file for reading " << inputFileName << endl; exit(EXIT_FAILURE); } } // Printing the header information void WriteHeader (int EntryNumb, string EQID, string Day, string MonthName, string Year, string Time,string TimeZone, string EarthquakeName, string Lat, string Lon, string MagType, string Magnitude, string Events) { ofstream oFile; string oFileName = "philip.out" ; if (EntryNumb == 0) oFile.open(oFileName.c_str()); else oFile.open(oFileName.c_str(), ofstream::out | ofstream::app); oFile << "# " << day << " " << monthNmae << " " << year << " "<< time1 << " " << timeZone << " " << magType << " " << magnitude << " " << earthquakeName << " [" <<EQID << "] " << " (" << lat <<" , " <<lon << " " << Enumber << ")" << endl; } // Print to File void printToFile(string EQID, int EntryNumb, string NCode, string stationName, string instrumentName, string bandName, string orName) { ofstream oFile; string oFileName = "philip.out" ; if (EntryNumb > 0) oFile.open(oFileName.c_str(), ofstream::out | ofstream::app); else oFile.open(oFileName.c_str()); for (int unsigned i = 0 ; i < orName.length(); i++) { oFile << EQID << "." << NCode << "." << stationName << "." << uppercase(bandName) << uppercase(instrumentName) << orName[i] << endl; } } // Printing errors to Log file void WriteErrors(int EntryNumb, int validEntries, int invalidEntries, int totalSignal, bool ii, bool jj, bool kk, bool ll, bool pp, bool qq, bool mm, bool nn) { ofstream oErrFile; string oFileName = "philip.log" ; if (EntryNumb > 0) oErrFile.open(oFileName.c_str(), ofstream::out | ofstream::app); else oErrFile.open(oFileName.c_str()); if (ii == false) { oErrFile << "Entry # " << EntryNumb << " Invalid Network" << endl; cout << "Entry # " << EntryNumb << " Invalid Network" << endl; } else if (jj == false) { oErrFile << "Entry # " << EntryNumb << " Invalid Station" << endl; cout << "Entry # " << EntryNumb << " Invalid Station" << endl; } else if (kk == false) { oErrFile << "Entry # " << EntryNumb << " Invalid Band type" << endl; cout << "Entry # " << EntryNumb << " Invalid Band type" << endl; } else if (ll == false) { oErrFile << "Entry # " << EntryNumb << " Invalid Instrument" << endl; cout << "Entry # " << EntryNumb << " Invalid Instrument" << endl; } else if (pp == false) { oErrFile << "Entry # " << EntryNumb << " Invalid Orientation" << endl; cout << "Entry # " << EntryNumb << " Invalid Orientation" << endl; elseif (qq == false) { oErrFile << "Error # Date format wrong !" << endl; cout << "Error # Date format wrong !" << endl; } else if (mm == false){ oErrFile << "Error # Either Magnitude_type or Magnitude is wrong !" << endl; cout << "Error # Either Magnitude_type or Magnitude is wrong !" << endl; } else if (nn == false) { oErrFile << "Error # Either time format or time zone is wrong !" << endl; cout << "Error # Either time format or time zone is wrong !" << endl; } }
[ "ogwenop@gmail.com" ]
ogwenop@gmail.com
ed12ef21cabcfceaa979c580da0d5df503f02fc5
d69166c705602e264501b9dbf7b961e63f4cc27c
/11722.cpp
6fc76f4c1a94c7460f780783f8a863138a6c1153
[]
no_license
sieunK/Algorithm
3e98bdacb69abb49086ebe4ff9bbaf14e21d05bd
fc0c8b6c6bb764b0ebdaa4d962becb8d728c2f91
refs/heads/master
2020-05-16T05:03:39.681884
2019-06-02T05:11:08
2019-06-02T05:11:08
182,801,844
0
1
null
2019-05-15T16:39:22
2019-04-22T14:13:14
C++
UTF-8
C++
false
false
578
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int find_max(const vector<int>& vc, const vector<int>& res, int n) { int max_i = 0, max_v = 0; for(int i=0;i<n;++i) { if(vc[n] < vc[i] && res[i] > max_v) { max_i = i; max_v = res[i]; } } return max_v; } int main(void) { int N; cin >> N; vector<int> vc(N); for(int n=0;n<N;++n) cin >> vc[n]; vector<int> res(N,0); for(int n=0;n<N;++n) { res[n] = find_max(vc,res,n)+1; } int answer = *max_element(res.begin(), res.end()); cout << answer << endl; return 0; }
[ "april908@naver.com" ]
april908@naver.com
3d2e9ad435f02712f5048256db01da55824db779
91674ffe2596957dd0409029572c1db6792da299
/tensorflow/compiler/mlir/tfr/passes/passes.h
f7189c335ca6ec68e9f77ca48f65880318354396
[ "MIT", "Apache-2.0", "BSD-2-Clause" ]
permissive
shinybrar/tensorflow
7393778eaa2c195a63e92397bb9e620826b96682
49bd03e866739b069ab5d3c46f6574609190c517
refs/heads/master
2021-07-29T23:07:01.066510
2021-07-23T14:07:52
2021-07-23T14:07:52
184,306,157
0
0
Apache-2.0
2019-04-30T17:44:02
2019-04-30T17:44:01
null
UTF-8
C++
false
false
1,959
h
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_MLIR_TFR_IR_TFR_PASSES_H_ #define TENSORFLOW_COMPILER_MLIR_TFR_IR_TFR_PASSES_H_ #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "mlir/IR/BuiltinOps.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Support/LogicalResult.h" // from @llvm-project namespace mlir { namespace TFR { // Scans the func op and adds all the canonicalization patterns of the ops // except the tf ops, inside the function. void populateCanonicalizationPatterns(FuncOp func, OwningRewritePatternList &patterns); // Decompose ops. std::unique_ptr<OperationPass<FuncOp>> CreateDecomposeTFOpsPass( llvm::Optional<ModuleOp> tfr_module = llvm::None); // Rewrites quantized operands and results with their storage types. // This pass should be run at module level after decomposition, if there are // quantized operands or results. std::unique_ptr<OperationPass<FuncOp>> CreateRewriteQuantizedIOPass(); // Raise to TF ops. std::unique_ptr<OperationPass<FuncOp>> CreateRaiseToTFOpsPass( llvm::Optional<ModuleOp> tfr_module = llvm::None, bool materialize_derived_attrs = false); } // namespace TFR } // namespace mlir #endif // TENSORFLOW_COMPILER_MLIR_TFR_IR_TFR_PASSES_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
6d2062ab6d1f71be3fa62eee98b2a6eabf70c8a5
7b21a8a10cce25bf39daf61bd0a4f95bbc99c7c8
/droidCrypto/ot/TwoChooseOne/KosOtExtReceiver.h
e40c7bd79e3192325e7958e9b26b91cc41de5efe
[ "LicenseRef-scancode-public-domain", "MIT" ]
permissive
oliver-schick/mobile_psi_cpp
ffbed7f5e3a16148d525d24086a9690edb26221b
4c5f0f56142535ca0d3524c99781cfd0c07b9205
refs/heads/master
2023-05-31T00:06:51.998171
2021-06-18T14:50:42
2021-06-18T14:50:42
334,582,054
0
1
NOASSERTION
2021-03-19T14:51:04
2021-01-31T05:40:21
C
UTF-8
C++
false
false
993
h
#pragma once // This file and the associated implementation has been placed in the public domain, waiving all copyright. No restrictions are placed on its use. #include "OTExtInterface.h" #include <array> #include <droidCrypto/PRNG.h> namespace droidCrypto { class KosOtExtReceiver : public OtExtReceiver { public: KosOtExtReceiver() :mHasBase(false) {} bool hasBaseOts() const override { return mHasBase; } bool mHasBase; std::array<std::array<PRNG, 2>, gOtExtBaseOtCount> mGens; void setBaseOts( span<std::array<block, 2>> baseSendOts)override; std::unique_ptr<OtExtReceiver> split() override; void receive( const BitVector& choices, span<block> messages, PRNG& prng, ChannelWrapper& chl/*, std::atomic<u64>& doneIdx*/) override; }; }
[ "daniel.kales@tugraz.at" ]
daniel.kales@tugraz.at
528dc04146790e5ad6f436e6f7ffbf24c32dd0b8
cbd5049f4cb4113ac40aeba0c20dc47244b60ed3
/C++ OOP/Laboratoare rezolvate/L5/P22/P22/functii1.cpp
d445a591cbbfc03c1c5ab5565d7759b52d717c08
[]
no_license
ZavalichiR/Backup
b6989cec8b35534ba9b37bdc79c5e4f296b1dbca
9a34a136abb5a51c5ea2f18dbf2e33987c18b56a
refs/heads/master
2020-03-26T05:30:03.268047
2018-08-13T11:39:17
2018-08-13T11:39:17
144,560,065
1
1
null
null
null
null
UTF-8
C++
false
false
2,526
cpp
#include"Header1.h" Persoana::Persoana() { varsta = 0; gen = '\0'; //nume = new char[100]; //prenume = new char[100]; nume = nullptr; prenume = nullptr; } Persoana::Persoana(int v, char *n, char *p, char g) { varsta = v; this->gen = g; int len; len = strlen(n) + 1; this->nume = new char[len]; strcpy_s(nume, len, n); len = strlen(p) + 1; this->prenume = new char[len]; strcpy_s(prenume, len, p); cout << "constr cu argumente" << endl; } Persoana::Persoana(const Persoana &p) { varsta = p.varsta; gen = p.gen; int len; len = strlen(p.nume) + 1; nume = new char[len]; strcpy_s(nume, len, p.nume); len = strlen(p.prenume) + 1; prenume = new char[len]; strcpy_s(prenume, len, p.prenume); cout << "constructor de copiere" << endl; } void Persoana::citire() { char buffer[100]; int len; cout << "\nVarsta: "; cin >> varsta; cout << "Nume: "; cin.ignore(100, '\n'); cin.getline(buffer, 100); /*if (nume) { delete[] nume; nume = nullptr; }*/ len = strlen(buffer) + 1; nume = new char[len]; strcpy_s(nume, len, buffer); cout << "Prenume: "; cin.getline(buffer, 100); /*if (prenume) { delete[] prenume; prenume = nullptr; }*/ len = strlen(buffer) + 1; prenume = new char[len]; strcpy_s(prenume, len, buffer); cout << "Gen: "; cin >> gen; } void Persoana::afisare() { cout << endl; cout << "Nume: " << nume << endl; cout << "Prenume: " << prenume << endl; cout << "Varsta: " << varsta << endl; cout << "Gen: " << gen << endl; } Persoana::~Persoana() { varsta = 0; gen = '\0'; if (nume) { delete[] nume; nume = nullptr; } if (prenume) { delete[]prenume; prenume = nullptr; } } int Persoana::compara(Persoana &P) { if (strcmp(nume, P.nume) == 0 && strcmp(prenume, P.prenume) == 0) { return 1; } else { return 0; } } void Persoana::citire2() { char buffer[100]; cout << "Nume: "; cin.ignore(100, '\n'); cin.getline(buffer, 100); int len = strlen(buffer) + 1; nume = new char[len]; strcpy_s(nume, len, buffer); cout << "Prenume: "; cin.getline(buffer, 100); len = strlen(buffer) + 1; prenume = new char[len]; strcpy_s(prenume, len, buffer); } void Persoana::operator=(Persoana &p) { varsta = p.varsta; if (nume) { delete[] nume; nume = nullptr; } if (prenume) { delete[] prenume; prenume = nullptr; } nume = new char[strlen(p.nume) + 1]; prenume = new char[strlen(p.prenume) + 1]; strcpy_s(this->nume, strlen(p.nume) + 1, p.nume); strcpy_s(this->prenume, strlen(p.prenume) + 1, p.prenume); this->gen = p.gen; }
[ "z.zava96@gmail.com" ]
z.zava96@gmail.com
048aadb01e88c56a4621b60aa158e815cf4b0445
3e2b9e3d1c3c5aeb4a245046edabe943b0739a99
/Classes_Example/BMI.h
441ee859e10c62c37ed9d5a7d385986fd7dee5aa
[]
no_license
JasJohn3/BMI
31fcc4e173f25bed0f56c737c84a8aedbfe299ab
c16eb4d90655dec76dbe8ee125a0a6985776777f
refs/heads/master
2020-03-29T22:54:15.739161
2018-09-26T15:08:37
2018-09-26T15:08:37
150,446,597
0
0
null
null
null
null
UTF-8
C++
false
false
371
h
#pragma once #ifndef BMI_H #define BMI_H #include <iostream> #include <string> using namespace std; class BMI { public: //Constructor BMI(); //Deconstructor ~BMI(); //Overload Constructor BMI(string,int,double); private: //MEMBER VARIABLES string newName; int newHeight; double newWeight; protected: }; BMI::BMI() { } BMI::~BMI() { } #endif // !BMI_H
[ "JASJOHN3@uat.edu" ]
JASJOHN3@uat.edu
86d471c12653bd42a80aed800c0672ba8d19a3d1
ed8528fd21d383ebcd8282cf0816d01493673487
/Bison Graphics Engine Source/object3D.h
6cb1b0183bb4941a130b4233b7c2fc6ae69d683e
[ "MIT" ]
permissive
kpatel122/Bison-Graphics-Engine
27aa91b8c973a26950b06ff085d819ba1bcf4e4a
5fc9469f1440b2fe3655adfb7313d760aaaee924
refs/heads/master
2020-03-27T00:00:37.204599
2018-08-21T16:03:34
2018-08-21T16:03:34
145,586,092
0
0
null
null
null
null
UTF-8
C++
false
false
1,003
h
//#include "CVector.h" #define RELEASE(x) { if (x){delete[] x; x = NULL;} } struct OBJ_VERTEX { float x,y,z; }; struct OBJ_FACE { bool drawn[3]; int vertexIndex[3]; int texIndex[3]; short faceNeighbour[3]; }; struct AnimInfo { int startFrame; int endFrame; char frameName[256]; }; class CObject3d { public: int textureID; int *pSkins; int numberSkins; int numVerts; int numTexCoords; int numFaces; //int numFrames; CVector3 *pVerts; CVector2 *pTexCoords; CVector3 *pNormals; struct OBJ_FACE *pFace; struct PLANE *pPlanes; //CObject3d() {numberSkins = numTexCoords = numFaces = numVerts = 0;} //~CObject3d(){RELEASE(pVerts);RELEASE(pTexCoords);RELEASE(pNormals);RELEASE(pSkins)} }; class CModel3d { public: int numFrames; int numAnimations; int currentFrame; int currentAnimation; int render_type; int currFrame; int nextFrame; float interpol; float elapsedTime; float lastTime; vector<CObject3d> pObject; vector<AnimInfo> pAnimInfo; };
[ "kunal" ]
kunal
2a8b8b28f5850dd7b409d5f305f539a486afa161
3481f261778ec1c4a22c8cb9b62f7610e4f73464
/outputs/OscHandler.cpp
df739cce260711dbdfa12f38495ecd5d638e06fc
[]
no_license
ludoviclaffineur/MoOS
db4eba5b62d49c24a65b0d4003b4a5a75834f218
b917ce6550ed62bcc526ebdb38ad345b48dacef5
refs/heads/master
2021-06-07T12:07:38.739091
2016-10-31T08:32:14
2016-10-31T08:32:14
24,750,661
0
0
null
null
null
null
UTF-8
C++
false
false
6,684
cpp
// // Osc.cpp // libpcapTest // // Created by Ludovic Laffineur on 29/10/13. // Copyright (c) 2013 Ludovic Laffineur. All rights reserved. // #include "OscHandler.h" #include <string.h> #include <algorithm> #include "AppIncludes.h" OscHandler::OscHandler(): OutputsHandler("OscNew",0,1){ mDistant = lo_address_new("127.0.0.1", "57120"); mParamNumber = 0; mValueBeforeSending = 0; mIpAddress = new char [strlen("127.0.0.1") + 1]; strcpy(mIpAddress, "127.0.0.1"); mPort = new char [strlen("20000") + 1]; strcpy(mPort, "20000"); mOscAddress = new char [strlen("/UNDIFINED") + 1]; strcpy(mOscAddress, "/UNDIFINED"); mOscTag = new char [strlen("f") + 1]; strcpy(mOscTag , "f"); mIdController = -1; mOutputType = CONSTANCES::OSC; mParameters.push_back(new Parameter<int>("OutputType", &mOutputType)); mParameters.push_back(new Parameter<char*>("IPAddress", &mIpAddress)); mParameters.push_back(new Parameter<char*>("Port", &mPort)); mParameters.push_back(new Parameter<char*>("OscAddressPattern", &mOscAddress)); } OscHandler::OscHandler(const char* n, const char* ipAddress, const char* port, const char* oscAddress, const char* oscTag ):OutputsHandler(n,0,1){ mIpAddress = new char [strlen(ipAddress) + 1]; strcpy(mIpAddress, ipAddress); mPort = new char [strlen(port) + 1]; strcpy(mPort, port); mOscAddress = new char [strlen(oscAddress) + 1]; strcpy(mOscAddress, oscAddress); mOscTag = new char [strlen(oscTag) + 1]; strcpy(mOscTag , oscTag); mDistant = lo_address_new(mIpAddress, mPort); mParamNumber = 0; //mValueBeforeSending = 0; mOutputType = CONSTANCES::OSC; mParameters.push_back(new Parameter<char*>("IPAddress", &mIpAddress)); mParameters.push_back(new Parameter<int>("OutputType", &mOutputType)); mParameters.push_back(new Parameter<char*>("Port", &mPort)); mParameters.push_back(new Parameter<char*>("OscAddressPattern", &mOscAddress)); mValueBeforeSending = 0; mIdController = -1; //mParameters.push_back(new Parameter<char**>("OscTag", &mOscTag)); //mParameters.push_back(new Parameter<int*>("TagIValue", &mParamNumber)); //mParameters.push_back(new Parameter<int*>("Type", &mOutputType)); } OscHandler::OscHandler(const char* n, const char* ipAddress, const char* port, const char* oscAddress, const char* oscTag , int idController, float min, float max):OutputsHandler(n,min,max){ mIdController = idController; mIpAddress = new char [strlen(ipAddress) + 1]; strcpy(mIpAddress, ipAddress); mValueBeforeSending = 0; mPort = new char [strlen(port) + 1]; strcpy(mPort, port); mOscAddress = new char [strlen(oscAddress) + 1]; strcpy(mOscAddress, oscAddress); mOscTag = new char [strlen(oscTag) + 1]; strcpy(mOscTag , oscTag); mDistant = lo_address_new(mIpAddress, mPort); mParamNumber = 0; //mValueBeforeSending = 0; mOutputType = CONSTANCES::OSC; mParameters.push_back(new Parameter<char*>("IPAddress", &mIpAddress)); mParameters.push_back(new Parameter<int>("OutputType", &mOutputType)); mParameters.push_back(new Parameter<char*>("Port", &mPort)); mParameters.push_back(new Parameter<char*>("OscAddressPattern", &mOscAddress)); //mParameters.push_back(new Parameter<char**>("OscTag", &mOscTag)); //mParameters.push_back(new Parameter<int*>("TagIValue", &mParamNumber)); //mParameters.push_back(new Parameter<int*>("Type", &mOutputType)); } OscHandler::OscHandler(const char* ipAddress, const char* port){ mDistant = lo_address_new(ipAddress, port); mParamNumber = 0; mValueBeforeSending = 0; //mValueBeforeSending = 0; } bool OscHandler::sendData(){ //std::cout<< mName << " Sent value" << mValueBeforeSending<<std::endl; if (mIdController == -1){ //std::cout<<mValueBeforeSending<< std::endl; return lo_send(mDistant,mOscAddress, "f",mValueBeforeSending); } else{ //printf("%f \n", mValueBeforeSending); return lo_send(mDistant,mOscAddress, "if",mIdController,mValueBeforeSending); } } bool OscHandler::sendData(int paramNumber, float value){ return lo_send(mDistant,mOscAddress, "f",value); } bool OscHandler::setIpAdress(const char* newIp){ setTabChar(&mIpAddress, &newIp); lo_address osc = mDistant; //printf("New IpAddress %s \n", mIpAddress); mDistant = NULL; lo_address_free(osc); return mDistant = lo_address_new(mIpAddress, mPort); } const char* OscHandler::getIpAdress() const{ return mIpAddress; } bool OscHandler::setOscAddress(const char* newOscAddress){ return setTabChar(&mOscAddress, &newOscAddress); } const char* OscHandler::getOscAddress() const{ return mOscAddress; } bool OscHandler::setPort(const char* newPort){ setTabChar(&mPort, &newPort); lo_address osc = mDistant; mDistant = NULL; lo_address_free(osc); return mDistant = lo_address_new(mIpAddress, mPort); } const char* OscHandler::getPort() const{ return mPort; } bool OscHandler::setOscTag(const char* newOscTag){ return setTabChar(&mOscTag, &newOscTag); } const char* OscHandler::getOscTag() const{ return mOscTag; } void OscHandler::setParameters(std::vector<std::string> ParameterList){ for (int i=0; i<ParameterList.size(); i++) { if (ParameterList.at(i).compare("Name")==0) { OutputsHandler::setName(ParameterList.at(i+1).c_str()); } else if (ParameterList.at(i).compare("Identifier")==0) { setId(std::atoi(ParameterList.at(i+1).c_str())); } else if (ParameterList.at(i).compare("IPAddress")==0) { setIpAdress(ParameterList.at(i+1).c_str()); } else if (ParameterList.at(i).compare("Port")==0) { setPort(ParameterList.at(i+1).c_str()); } else if (ParameterList.at(i).compare("OscAddressPattern")==0) { std::replace( ParameterList.at(i+1).begin(), ParameterList.at(i+1).end(), ':', '/' ); setOscAddress(ParameterList.at(i+1).c_str()); } else if (ParameterList.at(i).compare("TagIValue")==0) { mParamNumber = std::atoi(ParameterList.at(i+1).c_str()); } } } bool OscHandler::setTabChar(char** target, const char** newValue){ if(*target){ delete[] *target; } //std::cout<< *newValue <<" length " << strlen(*newValue) <<std::endl; *target = new char [strlen(*newValue) + 1]; return(strcpy(*target, *newValue)); } OscHandler::~OscHandler(){ //lo_address_free(mDistant); delete mOscTag; delete mOscAddress; delete mIpAddress; delete mPort; }
[ "ludovic.laffineur@gmail.com" ]
ludovic.laffineur@gmail.com
3657a70fbc65e03495dd33a8d8c0571e4b75e972
0baae10272abfe079aee9bca38affc1c3382ec37
/src/raft/detail/snapshot.hpp
faa7343fd10768363da5d6e61e93605eebd0efe7
[]
no_license
tempbottle/raftcpp
5589af5552eb5409c9e0a045c856ff558a719796
20613714153ec745d846be4ac42e857bbcd7ca54
refs/heads/master
2021-06-09T20:43:05.003548
2016-12-20T09:27:31
2016-12-20T09:27:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,916
hpp
#pragma once namespace xraft { namespace detail { struct snapshot_head { uint32_t version_ = 1; uint32_t magic_num_ = 'X'+'R'+'A'+'F'+'T'; int64_t last_included_index_; int64_t last_included_term_; }; class snapshot_reader { public: snapshot_reader() { } bool open(const std::string &filepath) { filepath_ = filepath; if (file_.is_open()) file_.close(); int mode = std::ios::in | std::ios::binary | std::ios::app; file_.open(filepath_.c_str(), mode); return file_.good(); } bool read_sanpshot_head(snapshot_head &head) { std::string buffer; buffer.resize(sizeof(head)); file_.seekg(0, std::ios::beg); file_.read((char*)buffer.data(), buffer.size()); if (file_.gcount() != buffer.size()) return false; unsigned char *ptr = (unsigned char*)buffer.data(); if (endec::get_uint32(ptr) != head.version_ || endec::get_uint32(ptr) != head.magic_num_) return false; head.last_included_index_ = (int64_t)endec::get_uint64(ptr); head.last_included_term_ = (int64_t)endec::get_uint64(ptr); return true; } std::ifstream &get_snapshot_stream() { return file_; } private: std::string filepath_; std::ifstream file_; }; class snapshot_writer { public: snapshot_writer() { } operator bool() { return file_.is_open(); } bool open(const std::string &filepath) { filepath_ = filepath; assert(!file_.is_open()); int mode = std::ios::out | std::ios::binary | std::ios::trunc; file_.open(filepath_.c_str(), mode); return file_.good(); } void close() { if(file_.is_open()) file_.close(); } bool write_sanpshot_head(const snapshot_head &head) { std::string buffer; buffer.resize(sizeof(head)); unsigned char *ptr = (unsigned char*)buffer.data(); endec::put_uint32(ptr, head.version_); endec::put_uint32(ptr, head.magic_num_); endec::put_uint64(ptr, (uint64_t)head.last_included_index_); endec::put_uint64(ptr, (uint64_t)head.last_included_term_); assert(buffer.size() == ptr - (unsigned char*)buffer.data()); return write(buffer); } bool write(const std::string &buffer) { file_.write(buffer.data(), buffer.size()); file_.flush(); return file_.good(); } void discard() { close(); functors::fs::rm()(filepath_); } std::size_t get_bytes_writted() { return file_.tellp(); } std::string get_snapshot_filepath() { return filepath_; } private: std::string filepath_; std::ofstream file_; }; class snapshot_builder { public: using get_applied_index_handle = std::function<int64_t()>; using build_snapshot_callback = std::function<bool(const std::function<bool(const std::string &)>&, int64_t)>; using build_snapshot_done_callback = std::function<void(int64_t)>; using get_log_entry_term_handle = std::function<int64_t(int64_t)>; snapshot_builder() { } void set_snapshot_base_path(const std::string &path) { snapshot_base_path_ = path; if (!functors::fs::mkdir()(snapshot_base_path_)) throw std::runtime_error("mkdir "+ snapshot_base_path_+" failed"); } void regist_get_applied_index_handle(const get_applied_index_handle &handle) { get_applied_index_ = handle; } void regist_get_log_entry_term_handle(const get_log_entry_term_handle &handle) { get_log_entry_term_ = handle; } void regist_build_snapshot_callback(const build_snapshot_callback &callback) { build_snapshot_ = callback; } void regist_build_snapshot_done_callback(const build_snapshot_done_callback &callback) { build_snapshot_done_ = callback; } void make_snapshot() { do_make_snapshot(); } private: void do_make_snapshot() { snapshot_writer writer; snapshot_head head; auto index= get_applied_index_(); head.last_included_index_ = index; head.last_included_term_ = get_log_entry_term_(index); std::string filepath = snapshot_base_path_ + std::to_string(index) + ".ss"; if (!writer.open(filepath)) throw std::runtime_error("open "+filepath+ "error"); writer.write_sanpshot_head(head); auto result = build_snapshot_([&writer](const std::string &buffer) { writer.write(buffer); return true; }, index); if (result == false) { std::cout << "build_snapshot_ failed" << std::endl; writer.discard(); } writer.close(); build_snapshot_done_(index); //todo log snapshot done } std::string snapshot_base_path_; get_log_entry_term_handle get_log_entry_term_; get_applied_index_handle get_applied_index_; build_snapshot_callback build_snapshot_; build_snapshot_done_callback build_snapshot_done_; bool is_stop_ = false; int64_t distance_ = 10000; std::thread worker_; }; } }
[ "382018309@qq.com" ]
382018309@qq.com
07605d32f92555c643bb32a32631b34cc8b64aab
2b6640d30d261ee751093bde2f83c8473af3d5fc
/src/qt/sendcoinsentry.cpp
28564ac7cfbb5e61ebb0be886086cc4eb34d03c9
[ "MIT" ]
permissive
CryptoWolfX/AnimalsCoin
92fc2e4e915b4a969dd090b433b45c76db77deac
975be625f0326f79318eb6d5b2ab407570df96f0
refs/heads/master
2021-05-10T14:48:52.328267
2018-02-11T14:59:21
2018-02-11T14:59:21
118,532,750
0
1
null
null
null
null
UTF-8
C++
false
false
4,619
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a Animalscoin address (e.g. AeBg126xonwKJ9p7vpzgYJNNmY1pNtQsVw)")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } void SendCoinsEntry::setAddress(const QString &address) { ui->payTo->setText(address); ui->payAmount->setFocus(); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } }
[ "momocheyenn@gmail.com" ]
momocheyenn@gmail.com
e2b5255120a3884ad5533fca81c615173c8db15d
29b838b1680ac9ba0602950e3602e6bb8775b61f
/CONTEST/NEW_TOM_AND_JERRY.cpp
a62dec1ae39fbb9fda1515a0603f45bff76847ae
[]
no_license
sidsrivastavasks/CP-Programs
eeb74e7084679df5a923997a1e201eaf44818626
da12f5e74f937b94e78ce17642b7d5ebc7760306
refs/heads/main
2023-08-03T20:09:59.220248
2021-09-16T18:02:40
2021-09-16T18:02:40
359,374,844
0
1
null
null
null
null
UTF-8
C++
false
false
613
cpp
#include<iostream> using namespace std; long long int power(long long int x, long long int y) { if (y == 0) return 1; else if (y%2 == 0) return power(x, y/2)*power(x, y/2); else return x*power(x, y/2)*power(x, y/2); } int main() { long long int t,k,count,r,i,final; cin>>t; while(t--) { count = 0; k = 0; cin>>k; long long int z = k; if(k%2!=0) { final = (k-1)/2; } else { while(k%2==0) { count++; k = k/2; } r = count + 1; long long int res = power(2,r); final = z/res; } cout<<final<<endl; } return 0; }
[ "55981532+sidsrivastavasks@users.noreply.github.com" ]
55981532+sidsrivastavasks@users.noreply.github.com
b9cc5c8bf108bc8e6afd7389b0a5e05c4226c6b1
e743c9e9b9635ec356f1cb76c445a7c81e80a326
/Labs/Lab4/classDec.h
2336a5bdf76627a7d5148e4a77076640d0dfdcf4
[]
no_license
ryanrichter/CS2028
c0ff6c0434ce556ba4d1885df1228af555530589
7e801380112744c1f564899a1e9ff5834b6a00c9
refs/heads/master
2020-08-10T06:32:48.095763
2019-10-10T21:01:54
2019-10-10T21:01:54
214,283,614
0
0
null
null
null
null
UTF-8
C++
false
false
2,194
h
#include <iostream> #include <string> using namespace std; class baseGame{ protected: string player1; string playerInput1; string player2; string playerInput2; public: void getPlayer1(){ cout << "What is player 1's name? "; cin >> playerInput1; cout << endl; } void getPlayer2(){ cout << "What is player 2's name? "; cin >> playerInput2; cout << endl; } void setPlayer1(){ player1 = playerInput1; } void setPlayer2(){ player2 = playerInput2; } baseGame(){ player1 = "Bob"; player2 = "Jim"; } baseGame(string name1, string name2){ player1 = name1; player2 = name2; } virtual void Play(){ cout << "Let's Play" << endl; } void Winner(){ cout << "Not Yet" << endl; } }; class boardGame : public baseGame{ protected: string gameName; string nameInput; public: void getName(){ cout << "What is the name of the game? "; cin >> nameInput; cout << endl; } void setName(){ gameName = nameInput; } virtual void Play(){ cout << "Roll the dice." << endl; } void Winner(){ cout << "Dancing time." << endl; } }; class videoGame : public baseGame{ protected: string age; string ageInput; public: void getAge(){ cout << "What is your age? "; cin >> ageInput; cout << endl; } void setAge(){ age = ageInput; } virtual void Play(){ cout << "Mash the buttons." << endl; } void Winner(){ cout << "Winner music" << endl; } }; void callGame(baseGame &game){ // Function for calling play and winner functions game.Play(); game.Winner(); }
[ "noreply@github.com" ]
noreply@github.com
b2a01614b9c40efd9f4ead550cf8afa20b49dba2
e65a7a6dd0597e331d2fc5987b4163b11bf66e53
/OpenCode/CodeCore.hpp
ee66c31491db5e7b657b83166d51712d04b06593
[ "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
everysh95/OpenCodeLibrary
5f458a7410d4afa2bccae556eed7f9eb32719d3b
439ac7c8d12ba7bbeb395bbe5a2677b2bda0bec6
refs/heads/master
2020-12-25T14:58:37.711315
2016-10-05T14:09:08
2016-10-05T14:09:08
67,902,345
0
0
null
null
null
null
UTF-8
C++
false
false
513
hpp
#ifndef GF0B3039598B84CDDA20A579ECB483DA1 #define GF0B3039598B84CDDA20A579ECB483DA1 #include<iterator> namespace OpenCode { template<typename LT,typename F> auto operator|(LT& target,F&& effecter) -> decltype(effecter(target)) { return effecter(target); } template<typename CT> constexpr CT count_bit(CT target) { return (target > 0) ? target % 2 + count_bit(target >> 1) : 0; } template<typename LT> constexpr auto data(LT list) -> decltype(list.data()) { return list.data(); } } #endif
[ "satohiroaki88@gmail.com" ]
satohiroaki88@gmail.com
82f877f45141308e18b9d9246009b0581522b05c
01a547cdb1c116981f9a790709f982cf124204c0
/generators/AliGenMimicPbPb.cxx
56575dc11fc075d3a839290569954bf2c9e4d672
[]
no_license
Lucas-NL/GlobalMuonTracking
302252265245776626080f43ca22bc1dbd7315ce
dc3dab05a705fd37b060e7f4e481035a4e44c49c
refs/heads/master
2023-08-14T16:56:58.272451
2021-06-30T07:14:25
2021-07-11T10:28:46
337,792,548
0
0
null
2021-03-01T13:53:04
2021-02-10T17:01:55
null
UTF-8
C++
false
false
7,821
cxx
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //==================================================================================================================================================== // // // // // //==================================================================================================================================================== #include "AliConst.h" #include "AliRun.h" #include "AliGenEventHeader.h" #include "TDatabasePDG.h" #include "AliPDG.h" #include "TFile.h" #include "TF1.h" #include "TROOT.h" #include "AliGenMimicPbPb.h" #include "TVector3.h" #include "AliLog.h" #include "TGenPhaseSpace.h" #include <fstream> #include <iostream> #include <unistd.h> using namespace std ; ClassImp(AliGenMimicPbPb) //==================================================================================================================================================== AliGenMimicPbPb::AliGenMimicPbPb() : AliGenerator(), fHistNumFwdPrimePion(NULL), fHistNumFwdPrimeKaon(NULL), fHistNumFwdPrimeProton(NULL), fHistNumFwdPrimeMuon(NULL), fHistNumFwdPrimeElectron(NULL), fHistPrimePionRapPt(NULL), fHistPrimeKaonRapPt(NULL), fHistPrimeProtonRapPt(NULL), fHistPrimeMuonRapPt(NULL), fHistPrimeElectronRapPt(NULL), fNType(5), fDist(), fNum(), fPdgCode(), fNPart(), fMass() { // Default constructor } //==================================================================================================================================================== AliGenMimicPbPb::AliGenMimicPbPb(Int_t nPart/*, Char_t *inputFile*/): AliGenerator(nPart), fHistNumFwdPrimePion(NULL), fHistNumFwdPrimeKaon(NULL), fHistNumFwdPrimeProton(NULL), fHistNumFwdPrimeMuon(NULL), fHistNumFwdPrimeElectron(NULL), fHistPrimePionRapPt(NULL), fHistPrimeKaonRapPt(NULL), fHistPrimeProtonRapPt(NULL), fHistPrimeMuonRapPt(NULL), fHistPrimeElectronRapPt(NULL), fNType(5), fDist(), fNum(), fPdgCode(), fNPart(), fMass() { Init(); // Standard constructor } //==================================================================================================================================================== void AliGenMimicPbPb::Generate() { // Generate one trigger Double_t polar[3]= {0,0,0}; Int_t nt; Double_t origin[3]; Double_t time=0; for (Int_t j=0; j<3; j++) origin[j] = fOrigin[j]; time = fTimeOrigin; if (fVertexSmear==kPerEvent) { Vertex(); for (Int_t j=0; j<3; j++) origin[j] = fVertex[j]; time = fTime; } Int_t nPartGenerated = 0; TLorentzVector particle; for(Int_t iType=0; iType<fNType; ++iType){ fNPart[iType] = fNum[iType] -> GetRandom(); for(Int_t iPart=0; iPart<fNPart[iType]; ++iPart){ Double_t pt = 0; Double_t eta = 0; Double_t phi = gRandom->Uniform(0.,TMath::TwoPi()); fDist[iType]->GetRandom2(eta,pt); Int_t charge = 1; if (gRandom->Rndm() < 0.5){ charge = +1; } else{ charge = -1; } particle.SetPtEtaPhiM(pt,eta,phi,fMass[iType]); Double_t theta = particle.Theta(); if (TestBit(kThetaRange) && (theta<fThetaMin || theta>fThetaMax)){ continue; } PushTrack(1, -1, charge * fPdgCode[iType], particle.Px(),particle.Py(),particle.Pz(),particle.E(), origin[0],origin[1],origin[2],Double_t(time), polar[0],polar[1],polar[2], kPPrimary, nt, 1., 1); nPartGenerated++; } } AliGenEventHeader* header = new AliGenEventHeader("Mimic_HIJING"); header->SetPrimaryVertex(fVertex); header->SetNProduced(nPartGenerated); header->SetInteractionTime(fTime); // Passes header either to the container or to gAlice if (fContainer) { fContainer->AddHeader(header); } else { gAlice->SetGenEventHeader(header); } } //==================================================================================================================================================== void AliGenMimicPbPb::Init() { // Initialisation, check consistency of selected ranges /* if (TestBit(kPtRange) && TestBit(kMomentumRange)) Fatal("Init","You should not set the momentum range and the pt range at the same time!\n"); if ((!TestBit(kPtRange)) && (!TestBit(kMomentumRange))) Fatal("Init","You should set either the momentum or the pt range!\n"); if ((TestBit(kYRange) && TestBit(kThetaRange)) || (TestBit(kYRange) && TestBit(kEtaRange)) || (TestBit(kEtaRange) && TestBit(kThetaRange))) Fatal("Init","You should only set the range of one of these variables: y, eta or theta\n"); if ((!TestBit(kYRange)) && (!TestBit(kEtaRange)) && (!TestBit(kThetaRange))) Fatal("Init","You should set the range of one of these variables: y, eta or theta\n"); */ AliPDG::AddParticlesToPdgDataBase(); TFile* inFile = TFile::Open("./include/inputHijingParam.root"); fNum[0] = (TH1F*)inFile->Get("fHistNumFwdPrimePion") -> Clone(); fNum[1] = (TH1F*)inFile->Get("fHistNumFwdPrimeKaon") -> Clone(); fNum[2] = (TH1F*)inFile->Get("fHistNumFwdPrimeProton") -> Clone(); fNum[3] = (TH1F*)inFile->Get("fHistNumFwdPrimeMuon") -> Clone(); fNum[4] = (TH1F*)inFile->Get("fHistNumFwdPrimeElectron") -> Clone(); fDist[0] = (TH2F*)inFile->Get("fHistPrimePionRapPt") -> Clone(); fDist[1] = (TH2F*)inFile->Get("fHistPrimeKaonRapPt") -> Clone(); fDist[2] = (TH2F*)inFile->Get("fHistPrimeProtonRapPt") -> Clone(); fDist[3] = (TH2F*)inFile->Get("fHistPrimeMuonRapPt") -> Clone(); fDist[4] = (TH2F*)inFile->Get("fHistPrimeElectronRapPt") -> Clone(); fMass[0] = TDatabasePDG::Instance()->GetParticle(211) -> Mass(); fMass[1] = TDatabasePDG::Instance()->GetParticle(321) -> Mass(); fMass[2] = TDatabasePDG::Instance()->GetParticle(2212) -> Mass(); fMass[3] = TDatabasePDG::Instance()->GetParticle(13) -> Mass(); fMass[4] = TDatabasePDG::Instance()->GetParticle(11) -> Mass(); fPdgCode[0] = 211; fPdgCode[1] = 321; fPdgCode[2] = 2212; fPdgCode[3] = 13; fPdgCode[4] = 11; }
[ "rafael.pezzi@ufrgs.br" ]
rafael.pezzi@ufrgs.br
7a48877cd3604ec92a65e4c4865b42332d0c05b6
6895d9a7bbfafad93cea9353d12bf61adfd7533a
/quiz/bitcount.cpp
9c5c88b7887e0355f092ebc6fea5b08220de6541
[]
no_license
pisces312/AlgorithmInC
d6691d5bbb55012ae6cbe0cb99c2ea4f8abcd348
e2adce9fdefd7ec8b3dbb094dbbe9f4d5864fc2d
refs/heads/master
2021-01-17T22:24:16.574995
2017-04-21T12:15:36
2017-04-21T12:15:36
84,197,159
0
0
null
2017-04-21T12:15:37
2017-03-07T12:34:59
C++
GB18030
C++
false
false
7,718
cpp
#include"bitcount.h" #include"../common.h" #include <nmmintrin.h> int bitCountByRemainder(unsigned int n) { unsigned int c = 0 ; while(n > 0) { if((n %2) == 1) ++c ; n/=2; } return c ; } int bitCountByBitOp(unsigned int n) { unsigned int c = 0 ; // 计数器 while(n > 0) { if((n & 0x1) == 1) // 当前位是1 ++c ; // 计数器加1 n >>= 1 ; // 移位 } return c ; } int bitCountByBitOp2(unsigned int n) { unsigned int c = 0 ; for(c = 0; n>0 ; n >>= 1) c += n & 1 ; return c ; } int bitCountByBitOp3(unsigned int n) { unsigned int c = 0 ; while(n>0) { n-=n&(-n); ++c; } return c ; } int bitCountFast(unsigned int n) { unsigned int c = 0 ; for(c = 0; n; ++c) n &= (n - 1) ; // 清除最低位的1 return c ; } int bitCountByDynamicTable(unsigned int n) { unsigned char BitsSetTable256[256] = {0} ; // 初始化表 //1.如果它是偶数,那么n的二进制中1的个数与n/2中1的个数是相同的 //因为n是由n/2左移一位而来,而移位并不会增加1的个数。 //2.如果n是奇数,那么n的二进制中1的个数是n/2中1的个数+1 //因为当n是奇数时,n相当于n/2左移一位再加1。 for(int i = 0; i < 256; i++) BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; unsigned int c = 0 ; // 查表 // 分割为4部分,每部分8bit,对于这四个部分分别求出1的个数,再累加起来即可。 // 而8bit对应2^8 = 256种01组合方式 //! use 8bit char pointer to access to each part of 32bit int unsigned char * p = (unsigned char *) &n ; c = BitsSetTable256[p[0]] + BitsSetTable256[p[1]] + BitsSetTable256[p[2]] + BitsSetTable256[p[3]]; return c ; } int bitCountStatic4bitTable(unsigned int n) { unsigned int table[16] = { //0(0),1(1),2(10),3(11) 0, 1, 1, 2, //4(100),5(101),6(110),7(111) 1, 2, 2, 3, //8(1000),9(1001),10(1010),11(1011) 1, 2, 2, 3, //12(1100),13(1101),14(1110),15(1111) 2, 3, 3, 4 } ; unsigned int c = 0 ; while(n) { c += table[n & 0xf] ; n >>= 4 ; } return c ; } int bitCountStatic8bitTable(unsigned int n) { unsigned int table[256] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, }; return table[n & 0xff] + table[(n >> 8) & 0xff] + table[(n >> 16) & 0xff] + table[(n >> 24) & 0xff] ; } int bitCountParalell(unsigned int n) { n = (n & 0x55555555) + ((n >> 1) & 0x55555555) ; n = (n & 0x33333333) + ((n >> 2) & 0x33333333) ; n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f) ; n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff) ; n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff) ; return n ; } //About mod calculate int bitCountParalell2(unsigned int n) { //32bits at most has 32 // //every 2bits group, 01,10 n = (n & 0x55555555) + ((n >> 1) & 0x55555555) ; //every 4bits group, 0001,0010,0011,0100 n = (n & 0x33333333) + ((n >> 2) & 0x33333333) ; //every 8bits group n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f) ; return n%255; } //Oct, not Hex int bitCountBy3bitGroup(unsigned int n) { //1. For every 3bit group: (4a + 2b + c) – (2a + b) – a = a + b + c // Count 1's number within each 3bit group //2. Calculate 2a+b for 3bit group // 1) n>>1 // When right shift, higher 3bit group's lowest bit become // highest bit of lower 3bit group // To make sure every 3bit group divide 2 will not larger than // original value // E.g. // 111|001 -> divide 2 -> 011|101, expect value is 011|001 // 2) So have to &033333333333 // 033333333333=011|011|011|011... // 011111111111=001|001|001|001... //3. Calculate a, similar as #2 //4. Sum nearby 3bit group: tmp + (tmp >> 3) // Some groups will be summed twice // E.g. (a)001 (b)010 (c)011 (d)100 // + (a)001 (b)010 (c)011 (d)100 // = 001 011 101 111 // & 000 111 000 111 // = 000 011 | 000 111 // 1's number in 6bit group // Should only keep odd groups, so & 030707070707 // 011|000|111|000|111|000|111|... //5. Every 6bit group now // x0+x1*64+x2*64*64 = x0+x1+x2 (mod 63) unsigned int tmp = n - ((n >> 1) & 033333333333) - ((n >> 2) & 011111111111); return ((tmp + (tmp >> 3)) & 030707070707) % 63; } struct _byte { unsigned a:1; unsigned b:1; unsigned c:1; unsigned d:1; unsigned e:1; unsigned f:1; unsigned g:1; unsigned h:1; }; unsigned bitCountOfChar(unsigned char b) { struct _byte *by = (struct _byte*)&b; return (by->a+by->b+by->c+by->d+by->e+by->f+by->g+by->h); } int bitCountByByteStruct(unsigned int n) { unsigned char * p = (unsigned char *) &n; return bitCountOfChar(p[0]) + bitCountOfChar(p[1]) + bitCountOfChar(p[2]) + bitCountOfChar(p[3]); } //-msse4.2 //target specific option mismatch inline int bitCountByCPU(unsigned int n) { return _mm_popcnt_u32(n) ; } /////////////////////////////// typedef int(*BitCountFunc)(unsigned int); /** Print, time, assert F: function N: number **/ #define assertBitCount(F,N) {\ int start = clock();\ int c=(F)((N));\ int clicks = clock() - start;\ printf("%s(%d)=%d\tclicks=%d\ttime=%gns\n",\ (#F),(N),c, clicks,\ 1e9*clicks/((float) CLOCKS_PER_SEC)); \ assert(c==bitCountByRemainder(N));} //Add different algorithms void testBitCountCore(unsigned int n) { // printf("Input: %x\n",n); assertBitCount(bitCountByRemainder,n); assertBitCount(bitCountByBitOp,n); assertBitCount(bitCountByBitOp2,n); assertBitCount(bitCountByBitOp3,n); assertBitCount(bitCountFast,n); assertBitCount(bitCountByDynamicTable,n); assertBitCount(bitCountStatic4bitTable,n); assertBitCount(bitCountStatic8bitTable,n); assertBitCount(bitCountBy3bitGroup,n); assertBitCount(bitCountParalell,n); assertBitCount(bitCountParalell2,n); assertBitCount(bitCountByByteStruct,n); assertBitCount(bitCountByCPU,n); printf("\n\n"); } //Add different inputs void testBitCount() { testBitCountCore(65535); testBitCountCore(42235); testBitCountCore(19283); unsigned int n=1; printf("Dec:%d, Hex:%x, Hex(-n):%x, n&(-n):%x\n",n,n,-n,n&(-n)); n=3;//11->1 printf("Dec:%d, Hex:%x, Hex(-n):%x, n&(-n):%x\n",n,n,-n,n&(-n)); n=15;//1111->1 printf("Dec:%d, Hex:%x, Hex(-n):%x, n&(-n):%x\n",n,n,-n,n&(-n)); n=12;//1100->100 printf("Dec:%d, Hex:%x, Hex(-n):%x, n&(-n):%x\n",n,n,-n,n&(-n)); // printf("%d\n",((1+64+64*64+64*64*64)%63)); }
[ "lee.ni@emc.com" ]
lee.ni@emc.com
85b301321219e318229fd329a2035ed3d1ccfe6e
a15950e54e6775e6f7f7004bb90a5585405eade7
/chromeos/components/proximity_auth/proximity_auth_local_state_pref_manager.cc
004b6f55678c84694204c2b1f2d6a1cd7686603f
[ "BSD-3-Clause" ]
permissive
whycoding126/chromium
19f6b44d0ec3e4f1b5ef61cc083cae587de3df73
9191e417b00328d59a7060fa6bbef061a3fe4ce4
refs/heads/master
2023-02-26T22:57:28.582142
2018-04-09T11:12:57
2018-04-09T11:12:57
128,760,157
1
0
null
2018-04-09T11:17:03
2018-04-09T11:17:03
null
UTF-8
C++
false
false
4,750
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/components/proximity_auth/proximity_auth_local_state_pref_manager.h" #include <memory> #include <vector> #include "base/logging.h" #include "base/macros.h" #include "base/values.h" #include "chromeos/components/proximity_auth/logging/logging.h" #include "chromeos/components/proximity_auth/proximity_auth_pref_names.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" namespace proximity_auth { ProximityAuthLocalStatePrefManager::ProximityAuthLocalStatePrefManager( PrefService* local_state) : local_state_(local_state) {} ProximityAuthLocalStatePrefManager::~ProximityAuthLocalStatePrefManager() {} // static. void ProximityAuthLocalStatePrefManager::RegisterPrefs( PrefRegistrySimple* registry) { // Prefs for all users are stored in a dictionary under this pref name. registry->RegisterDictionaryPref(prefs::kEasyUnlockLocalStateUserPrefs); } void ProximityAuthLocalStatePrefManager::SetIsEasyUnlockEnabled( bool is_easy_unlock_enabled) const { NOTREACHED(); } void ProximityAuthLocalStatePrefManager::SetActiveUser( const AccountId& active_user) { active_user_ = active_user; } void ProximityAuthLocalStatePrefManager::SetLastPasswordEntryTimestampMs( int64_t timestamp_ms) { NOTREACHED(); } int64_t ProximityAuthLocalStatePrefManager::GetLastPasswordEntryTimestampMs() const { NOTREACHED(); return 0; } void ProximityAuthLocalStatePrefManager::SetLastPromotionCheckTimestampMs( int64_t timestamp_ms) { NOTREACHED(); } int64_t ProximityAuthLocalStatePrefManager::GetLastPromotionCheckTimestampMs() const { NOTREACHED(); return 0; } void ProximityAuthLocalStatePrefManager::SetPromotionShownCount(int count) { NOTREACHED(); } int ProximityAuthLocalStatePrefManager::GetPromotionShownCount() const { NOTREACHED(); return 0; } void ProximityAuthLocalStatePrefManager::SetProximityThreshold( ProximityThreshold value) { NOTREACHED(); } bool ProximityAuthLocalStatePrefManager::IsEasyUnlockAllowed() const { bool pref_value; const base::DictionaryValue* user_prefs = GetActiveUserPrefsDictionary(); if (!user_prefs || !user_prefs->GetBooleanWithoutPathExpansion( prefs::kEasyUnlockAllowed, &pref_value)) { PA_LOG(ERROR) << "Failed to get easyunlock_allowed."; return true; } return pref_value; } bool ProximityAuthLocalStatePrefManager::IsEasyUnlockEnabled() const { bool pref_value; const base::DictionaryValue* user_prefs = GetActiveUserPrefsDictionary(); if (!user_prefs || !user_prefs->GetBooleanWithoutPathExpansion( prefs::kEasyUnlockEnabled, &pref_value)) { PA_LOG(ERROR) << "Failed to get easyunlock_enabled."; return false; } return pref_value; } ProximityAuthLocalStatePrefManager::ProximityThreshold ProximityAuthLocalStatePrefManager::GetProximityThreshold() const { int pref_value; const base::DictionaryValue* user_prefs = GetActiveUserPrefsDictionary(); if (!user_prefs || !user_prefs->GetIntegerWithoutPathExpansion( prefs::kEasyUnlockProximityThreshold, &pref_value)) { PA_LOG(ERROR) << "Failed to get proximity_threshold."; return ProximityThreshold::kClose; } return static_cast<ProximityThreshold>(pref_value); } void ProximityAuthLocalStatePrefManager::SetIsChromeOSLoginEnabled( bool is_enabled) { NOTREACHED(); } bool ProximityAuthLocalStatePrefManager::IsChromeOSLoginEnabled() { bool pref_value; const base::DictionaryValue* user_prefs = GetActiveUserPrefsDictionary(); if (!user_prefs || !user_prefs->GetBooleanWithoutPathExpansion( prefs::kProximityAuthIsChromeOSLoginEnabled, &pref_value)) { PA_LOG(ERROR) << "Failed to get is_chrome_login_enabled."; return false; } return pref_value; } const base::DictionaryValue* ProximityAuthLocalStatePrefManager::GetActiveUserPrefsDictionary() const { if (!active_user_.is_valid()) { PA_LOG(ERROR) << "No active account."; return nullptr; } const base::DictionaryValue* all_user_prefs_dict = local_state_->GetDictionary(prefs::kEasyUnlockLocalStateUserPrefs); DCHECK(all_user_prefs_dict); const base::DictionaryValue* current_user_prefs; if (!all_user_prefs_dict->GetDictionaryWithoutPathExpansion( active_user_.GetUserEmail(), &current_user_prefs)) { PA_LOG(ERROR) << "Failed to find prefs for current user."; return nullptr; } return current_user_prefs; } } // namespace proximity_auth
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
55d65c829846d87d1b13a36adf5f1f6b5d525d1d
d36f11ac4059d5806348d322cf065a0e30fa6ffe
/ZF/ZFUIWidget/src/ZFUIWidget/ZFUIDialogBasic.h
dd44c422e33718c660beb806746b5bc3fe2235b5
[]
no_license
hasmorebug/ZFFramework
ea9fa14d375658dd843b1f62ec34fcd2b5b1446f
fa14d0f04ad68cc59457908a3fcba148738ef8c3
refs/heads/master
2021-01-15T08:28:09.034834
2016-08-04T17:35:36
2016-08-04T17:35:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,045
h
/* ====================================================================== * * Copyright (c) 2010-2016 ZFFramework * home page: http://ZFFramework.com * blog: http://zsaber.com * contact: master@zsaber.com (Chinese and English only) * Distributed under MIT license: * https://github.com/ZFFramework/ZFFramework/blob/master/license/license.txt * ====================================================================== */ /** * @file ZFUIDialogBasic.h * @brief basic dialog */ #ifndef _ZFI_ZFUIDialogBasic_h_ #define _ZFI_ZFUIDialogBasic_h_ #include "ZFUIDialog.h" ZF_NAMESPACE_GLOBAL_BEGIN // ============================================================ // ZFUIDialogButtonType /** * @brief see #ZFPROPERTY_TYPE_DECLARE * * serializable data: * @code * <ZFUIDialogButtonTypeEnum value="value"> * </ZFUIDialogButtonTypeEnum> * @endcode */ #define ZFPropertyTypeId_ZFUIDialogButtonTypeEnum zfText("ZFUIDialogButtonTypeEnum") /** * @brief button state */ ZFENUM_BEGIN(ZFUIDialogButtonType) ZFENUM_VALUE(Normal) /**< @brief normal button */ ZFENUM_VALUE(Yes) /**< @brief yes button */ ZFENUM_VALUE(No) /**< @brief no button */ ZFENUM_VALUE(Cancel) /**< @brief cancel button */ ZFENUM_VALUE(Destructive) /**< @brief for destructive operations */ ZFENUM_SEPARATOR(ZFUIDialogButtonType) ZFENUM_VALUE_REGISTER(Normal) ZFENUM_VALUE_REGISTER(Yes) ZFENUM_VALUE_REGISTER(No) ZFENUM_VALUE_REGISTER(Cancel) ZFENUM_VALUE_REGISTER(Destructive) ZFENUM_END(ZFUIDialogButtonType) // ============================================================ /** * @brief abstract dialog content for #ZFUIDialogBasic */ zfinterface ZF_ENV_EXPORT ZFUIDialogContent : zfextends ZFInterface { ZFINTERFACE_DECLARE(ZFUIDialogContent, ZFInterface) public: // ============================================================ // events /** * @brief see #ZFObject::observerNotify * * called when dialog button added, * param0 is the dialog button */ ZFOBSERVER_EVENT(DialogButtonOnAdd) /** * @brief see #ZFObject::observerNotify * * called when dialog button removed, * param0 is the dialog button */ ZFOBSERVER_EVENT(DialogButtonOnRemove) public: // ============================================================ // title /** * @brief container to hold custom title views */ virtual ZFUIView *dialogTitleContainer(void) = 0; /** * @brief title text view */ virtual ZFUITextView *dialogTitleView(void) = 0; /** * @brief set the dialog's title text */ virtual void dialogTitleTextSet(ZF_IN const zfchar *text) { this->dialogTitleView()->textContentStringSet(text); } /** * @brief get the dialog's title text */ virtual const zfchar *dialogTitleText(void) { return this->dialogTitleView()->textContentString(); } // ============================================================ // content /** * @brief container to hold custom content views */ virtual ZFUIView *dialogContentContainer(void) = 0; /** * @brief content text view */ virtual ZFUITextView *dialogContentView(void) = 0; /** * @brief set the dialog's content text */ virtual void dialogContentTextSet(ZF_IN const zfchar *text) { this->dialogContentView()->textContentStringSet(text); } /** * @brief get the dialog's content text */ virtual const zfchar *dialogContentText(void) { return this->dialogContentView()->textContentString(); } // ============================================================ // button /** * @brief container to hold custom button views */ virtual ZFUIView *dialogButtonContainer(void) = 0; /** * @brief access dialog button with specifed type * * if autoCreateIfNotExist is not true, * button won't be created automatically, * and may return null if not exist, * see #dialogButtonRemove\n * access #ZFUIDialogButtonType::e_Normal would always return null */ virtual ZFUIButton *dialogButton(ZF_IN ZFUIDialogButtonTypeEnum dialogButtonType, ZF_IN_OPT zfbool autoCreateIfNotExist = zftrue) = 0; /** * @brief text of the button */ virtual const zfchar *dialogButtonText(ZF_IN ZFUIDialogButtonTypeEnum dialogButtonType) = 0; /** * @brief see #dialogButtonText */ virtual void dialogButtonTextSet(ZF_IN ZFUIDialogButtonTypeEnum dialogButtonType, ZF_IN const zfchar *text) = 0; /** * @brief remove specified button type, see #dialogButton */ virtual void dialogButtonRemove(ZF_IN ZFUIDialogButtonTypeEnum dialogButtonType) = 0; /** @brief util method to access #dialogButton */ virtual inline ZFUIButton *dialogButton_Yes(ZF_IN_OPT zfbool autoCreateIfNotExist = zftrue) { return this->dialogButton(ZFUIDialogButtonType::e_Yes, autoCreateIfNotExist); } /** @brief util method to access #dialogButton */ virtual inline ZFUIButton *dialogButton_No(ZF_IN_OPT zfbool autoCreateIfNotExist = zftrue) { return this->dialogButton(ZFUIDialogButtonType::e_No, autoCreateIfNotExist); } /** @brief util method to access #dialogButton */ virtual inline ZFUIButton *dialogButton_Cancel(ZF_IN_OPT zfbool autoCreateIfNotExist = zftrue) { return this->dialogButton(ZFUIDialogButtonType::e_Cancel, autoCreateIfNotExist); } /** @brief util method to access #dialogButton */ virtual inline ZFUIButton *dialogButton_Destructive(ZF_IN_OPT zfbool autoCreateIfNotExist = zftrue) { return this->dialogButton(ZFUIDialogButtonType::e_Destructive, autoCreateIfNotExist); } /** @brief util method to access #dialogButtonText */ virtual inline const zfchar *dialogButtonText_Yes(void) { return this->dialogButtonText(ZFUIDialogButtonType::e_Yes); } /** @brief util method to access #dialogButtonTextSet */ virtual inline void dialogButtonTextSet_Yes(ZF_IN const zfchar *text) { this->dialogButtonTextSet(ZFUIDialogButtonType::e_Yes, text); } /** @brief util method to access #dialogButtonText */ virtual inline const zfchar *dialogButtonText_No(void) { return this->dialogButtonText(ZFUIDialogButtonType::e_No); } /** @brief util method to access #dialogButtonTextSet */ virtual inline void dialogButtonTextSet_No(ZF_IN const zfchar *text) { this->dialogButtonTextSet(ZFUIDialogButtonType::e_No, text); } /** @brief util method to access #dialogButtonText */ virtual inline const zfchar *dialogButtonText_Cancel(void) { return this->dialogButtonText(ZFUIDialogButtonType::e_Cancel); } /** @brief util method to access #dialogButtonTextSet */ virtual inline void dialogButtonTextSet_Cancel(ZF_IN const zfchar *text) { this->dialogButtonTextSet(ZFUIDialogButtonType::e_Cancel, text); } /** @brief util method to access #dialogButtonText */ virtual inline const zfchar *dialogButtonText_Destructive(void) { return this->dialogButtonText(ZFUIDialogButtonType::e_Destructive); } /** @brief util method to access #dialogButtonTextSet */ virtual inline void dialogButtonTextSet_Destructive(ZF_IN const zfchar *text) { this->dialogButtonTextSet(ZFUIDialogButtonType::e_Destructive, text); } // ============================================================ // button /** * @brief button count with #ZFUIDialogButtonType::e_Normal type */ virtual zfindex dialogButtonCount(void) = 0; /** * @brief access button at index, for #ZFUIDialogButtonType::e_Normal type only */ virtual ZFUIButton *dialogButtonAtIndex(ZF_IN zfindex index) = 0; /** * @brief find button's index, for #ZFUIDialogButtonType::e_Normal type only */ virtual zfindex dialogButtonFind(ZF_IN ZFUIButton *dialogButton) = 0; /** * @brief manually add a button with #ZFUIDialogButtonType::e_Normal type */ virtual void dialogButtonAdd(ZF_IN ZFUIButton *button, ZF_IN_OPT zfindex atIndex = zfindexMax) = 0; /** * @brief manually remove a specified button, which can be #dialogButton */ virtual void dialogButtonRemove(ZF_IN ZFUIButton *button) = 0; /** * @brief manually remove a specified button at index */ virtual void dialogButtonRemoveAtIndex(ZF_IN zfindex index) = 0; /** * @brief manually remove all button */ virtual void dialogButtonRemoveAll(void) = 0; protected: /** @brief see #EventDialogButtonOnAdd */ virtual inline void dialogButtonOnAdd(ZF_IN ZFUIButton *button) { this->toObject()->observerNotify(ZFUIDialogContent::EventDialogButtonOnAdd(), button); } /** @brief see #EventDialogButtonOnRemove */ virtual inline void dialogButtonOnRemove(ZF_IN ZFUIButton *button) { this->toObject()->observerNotify(ZFUIDialogContent::EventDialogButtonOnRemove(), button); } }; // ============================================================ /** * @brief set the default class of content view for #ZFUIDialogBasic * * #ZFUIDialogContentBasic by default, * set null to reset to default */ extern ZF_ENV_EXPORT void ZFUIDialogContentClassSet(ZF_IN const ZFClass *cls); /** * @brief see #ZFUIDialogContentClassSet */ extern ZF_ENV_EXPORT const ZFClass *ZFUIDialogContentClass(void); // ============================================================ // ZFUIDialogBasic /** * @brief basic dialog with title, content and buttons * * actual dialog content is implemented by #ZFUIDialogContent, * you may change the default impl by #ZFUIDialogContentClassSet, * or directly change #ZFUIDialogBasic::dialogContent */ zfclass ZF_ENV_EXPORT ZFUIDialogBasic : zfextends ZFUIDialog, zfimplements ZFUIDialogContent { ZFOBJECT_DECLARE(ZFUIDialogBasic, ZFUIDialog) ZFIMPLEMENTS_DECLARE(ZFUIDialogContent) ZFSTYLE_DEFAULT_DECLARE(ZFUIDialogBasic) public: /** * @brief dialog content, create instance from #ZFUIDialogContentClass by default */ ZFPROPERTY_RETAIN_WITH_INIT(ZFUIDialogContent *, dialogContent, ZFPropertyInitValue(ZFUIDialogContentClass()->newInstance().to<ZFUIDialogContent *>())) ZFPROPERTY_CUSTOM_SETTER_DECLARE(ZFUIDialogContent *, dialogContent); public: // ============================================================ // title zfoverride virtual inline ZFUIView *dialogTitleContainer(void) {return this->dialogContent()->dialogTitleContainer();} zfoverride virtual inline ZFUITextView *dialogTitleView(void) {return this->dialogContent()->dialogTitleView();} // ============================================================ // content zfoverride virtual inline ZFUIView *dialogContentContainer(void) {return this->dialogContent()->dialogContentContainer();} zfoverride virtual inline ZFUITextView *dialogContentView(void) {return this->dialogContent()->dialogContentView();} // ============================================================ // button zfoverride virtual inline ZFUIView *dialogButtonContainer(void) {return this->dialogContent()->dialogButtonContainer();} zfoverride virtual inline ZFUIButton *dialogButton(ZF_IN ZFUIDialogButtonTypeEnum dialogButtonType, ZF_IN_OPT zfbool autoCreateIfNotExist = zftrue) {return this->dialogContent()->dialogButton(dialogButtonType, autoCreateIfNotExist);} zfoverride virtual inline const zfchar *dialogButtonText(ZF_IN ZFUIDialogButtonTypeEnum dialogButtonType) {return this->dialogContent()->dialogButtonText(dialogButtonType);} zfoverride virtual inline void dialogButtonTextSet(ZF_IN ZFUIDialogButtonTypeEnum dialogButtonType, ZF_IN const zfchar *text) {this->dialogContent()->dialogButtonTextSet(dialogButtonType, text);} zfoverride virtual inline void dialogButtonRemove(ZF_IN ZFUIDialogButtonTypeEnum dialogButtonType) {this->dialogContent()->dialogButtonRemove(dialogButtonType);} // ============================================================ // button zfoverride virtual inline zfindex dialogButtonCount(void) {return this->dialogContent()->dialogButtonCount();} zfoverride virtual inline ZFUIButton *dialogButtonAtIndex(ZF_IN zfindex index) {return this->dialogContent()->dialogButtonAtIndex(index);} zfoverride virtual inline zfindex dialogButtonFind(ZF_IN ZFUIButton *dialogButton) {return this->dialogContent()->dialogButtonFind(dialogButton);} zfoverride virtual inline void dialogButtonAdd(ZF_IN ZFUIButton *button, ZF_IN_OPT zfindex atIndex = zfindexMax) {this->dialogContent()->dialogButtonAdd(button, atIndex);} zfoverride virtual inline void dialogButtonRemove(ZF_IN ZFUIButton *button) {this->dialogContent()->dialogButtonRemove(button);} zfoverride virtual inline void dialogButtonRemoveAtIndex(ZF_IN zfindex index) {this->dialogContent()->dialogButtonRemoveAtIndex(index);} zfoverride virtual inline void dialogButtonRemoveAll(void) {this->dialogContent()->dialogButtonRemoveAll();} public: zfoverride virtual ZFObject *objectOnInit(void); zfoverride virtual void objectOnDeallocPrepare(void); zfoverride virtual void objectOnDealloc(void); zffinal void _ZFP_ZFUIDialogBasic_dialogButtonOnAdd(ZF_IN ZFUIButton *button) { this->dialogButtonOnAdd(button); } zffinal void _ZFP_ZFUIDialogBasic_dialogButtonOnRemove(ZF_IN ZFUIButton *button) { this->dialogButtonOnRemove(button); } }; ZF_NAMESPACE_GLOBAL_END #endif // #ifndef _ZFI_ZFUIDialogBasic_h_ #include "ZFUIDialogContentBasic.h"
[ "z@zsaber.com" ]
z@zsaber.com
9d25d51c640445c306fcacae79855ae716048f0d
efa09bded0b7ae305223c98a611dd44995aea37f
/level.h
4c61370d22c74e8d8e4298fafcf8c1ab89fd84cc
[]
no_license
cioltanandrei/XmasProject
2fd95b1735c653c6960c4c52b1a19aab44d87305
d7207e79cb7028868760f72a58f9275263c183ea
refs/heads/master
2021-08-19T08:40:48.959493
2017-11-25T15:11:29
2017-11-25T15:11:29
109,484,320
0
0
null
null
null
null
UTF-8
C++
false
false
392
h
#ifndef LEVEL_H #define LEVEL_H #include "player.h" #include "map.h" class Level { private: Player player; Map map; SDL_Rect position; public: void Load(char *_player_name,int w,int h); void Clear(); void Print(Texture *_screen); void Handle_Events(); void Start(char *_player_name,Texture *_screen); bool Player_make_move(int dirX,int dirY,int distance); }; #endif // LEVEL_H
[ "pixelretrogames@github.com" ]
pixelretrogames@github.com
633dcb69719470a9c425acc8c5822bdbf997e226
8ee0be0b14ec99858712a5c37df4116a52cb9801
/Client/Interface/SlotContainer/ClanSkillSlot.cpp
01e5274eb40a646ae3a5371a79a90e621b0a6a7d
[]
no_license
eRose-DatabaseCleaning/Sources-non-evo
47968c0a4fd773d6ff8c9eb509ad19caf3f48d59
2b152f5dba3bce3c135d98504ebb7be5a6c0660e
refs/heads/master
2021-01-13T14:31:36.871082
2019-05-24T14:46:41
2019-05-24T14:46:41
72,851,710
6
3
null
2016-11-14T23:30:24
2016-11-04T13:47:51
C++
UHC
C++
false
false
8,700
cpp
#include "stdafx.h" #include ".\clanskillslot.h" #include "../../Common/IO_Skill.h" #include "../../GameCommon/Skill.h" //---------------------------------------------------------------------------------------------------- /// @param /// @brief constructor //---------------------------------------------------------------------------------------------------- CClanSkillSlot::CClanSkillSlot(void) { memset( m_SkillSlot, 0, sizeof( m_SkillSlot ) ); } //---------------------------------------------------------------------------------------------------- /// @param /// @brief constructor //---------------------------------------------------------------------------------------------------- CClanSkillSlot::~CClanSkillSlot(void) { } //---------------------------------------------------------------------------------------------------- /// @param /// @brief delete all skill slot //---------------------------------------------------------------------------------------------------- void CClanSkillSlot::ClearSlot() { for( int i = 0; i < MAX_CLAN_SKILL_SLOT ; i++ ) { if( m_SkillSlot[ i ] != NULL ) { m_Event.SetID( CTEventClanSkill::EID_DEL_SKILL ); m_Event.SetIndex( i ); SetChanged(); NotifyObservers( &m_Event ); delete m_SkillSlot[ i ]; m_SkillSlot[ i ] = NULL; } } } //---------------------------------------------------------------------------------------------------- /// @param /// @brief 스킬 슬롯 초기화 //---------------------------------------------------------------------------------------------------- void CClanSkillSlot::InitSlot() { ClearSlot(); } //---------------------------------------------------------------------------------------------------- /// 주목적은 타이머의 진행을 위해서임 //---------------------------------------------------------------------------------------------------- void CClanSkillSlot::UpdateSkillSlot() { CSkill* pSkill = NULL; for( int i = 0; i < MAX_CLAN_SKILL_SLOT ; i++ ) { pSkill = GetSkill( i ); if( pSkill != NULL ) { pSkill->Process(); } } } //---------------------------------------------------------------------------------------------------- /// @param nSlotIndex 스킬 슬롯 인덱스 /// @param nSlotIndex 스킬 인덱스 /// @param nSlotIndex 스킬 레벨 /// @param nSlotIndex 스킬 슬롯 인덱스 /// @brief 새로운 스킬을 스킬 슬롯에 등록 //---------------------------------------------------------------------------------------------------- void CClanSkillSlot::SetSkillSlot(short nSlotIndex, short nSkillIndex, short nSkillLevel, DWORD expire_time_abssec ) { if( m_SkillSlot[ nSlotIndex ] != NULL ) RemoveBySlotIndex( nSlotIndex ); CSkill* pSkill = g_SkillManager.CreateNewSkill( SKILL_SLOT_CLAN, nSkillIndex ); if( pSkill == NULL ) { //assert( 0 && "SetSkillSlot[ pSkill == NULL ]" ); return; } if( pSkill->HasExpiredTime() ) pSkill->SetExpiredTime( expire_time_abssec ); pSkill->SetSkillSlot( nSlotIndex ); m_SkillSlot[ nSlotIndex ] = pSkill; m_Event.SetID( CTEventClanSkill::EID_ADD_SKILL ); m_Event.SetIndex( nSlotIndex ); SetChanged(); NotifyObservers( &m_Event ); } //---------------------------------------------------------------------------------------------------- /// @param nSlotIndex 스킬 슬롯 인덱스 /// @param nSlotIndex 스킬 인덱스 /// @brief 스킬레벨업을 하면서 타입이 변경되는 스킬일경우 기존것을 지우고 새로 만들어주어야 한다. //---------------------------------------------------------------------------------------------------- void CClanSkillSlot::SkillLevelUp( int iSkillSlotNo, int iSkillIndex ) { assert( m_SkillSlot[ iSkillSlotNo ] ); if( m_SkillSlot[ iSkillSlotNo ] == NULL ) return; int iOldSkillType = SKILL_TYPE( iSkillIndex - 1 ); int iNewSkillType = SKILL_TYPE( iSkillIndex ); if( iOldSkillType != iNewSkillType ) { CSkill* pSkill = g_SkillManager.CreateNewSkill( SKILL_SLOT_CLAN, iSkillIndex ); if( pSkill == NULL ) return; pSkill->SetSkillSlot( iSkillSlotNo ); delete m_SkillSlot[ iSkillSlotNo ]; m_SkillSlot[ iSkillSlotNo ] = pSkill; } m_Event.SetID( CTEventClanSkill::EID_LEVELUP ); m_Event.SetIndex( iSkillSlotNo ); SetChanged(); NotifyObservers( &m_Event ); } //---------------------------------------------------------------------------------------------------- /// @param /// @brief 스킬번호로 스킬슬롯을 얻고 실제 스킬객체를 얻어온다. /// 서버로 부터는 스킬번호만 받기 때문에 역으로 번호로 슬롯을 얻어올 필요가 있다.( 타이머 세팅 ) //---------------------------------------------------------------------------------------------------- CSkill* CClanSkillSlot::GetSkillBySkillIDX( int iSkillIDX ) { CSkill* pSkill = NULL; for( int i = 0; i < MAX_CLAN_SKILL_SLOT ; i++ ) { pSkill = GetSkill( i ); if( pSkill != NULL ) { if( pSkill->GetSkillIndex() == iSkillIDX ) return pSkill; } } return pSkill; } //---------------------------------------------------------------------------------------------------- /// @param /// @brief 스킬번호로 스킬슬롯을 얻고 실제 스킬객체를 얻어온다. /// 서버로 부터는 스킬번호만 받기 때문에 역으로 번호로 슬롯을 얻어올 필요가 있다.( 타이머 세팅 ) //---------------------------------------------------------------------------------------------------- CSkill* CClanSkillSlot::GetSkillByBaseSkillIDX( int iBaseSkillIDX ) { CSkill* pSkill = NULL; for( int i = 0; i < MAX_CLAN_SKILL_SLOT ; i++ ) { if( pSkill = GetSkill( i ) ) { if( SKILL_1LEV_INDEX( pSkill->GetSkillIndex() ) == iBaseSkillIDX ) return pSkill; } } return NULL; } //---------------------------------------------------------------------------------------------------- /// @param /// @brief 해당 슬롯의 스킬 번호를 얻어온다. //---------------------------------------------------------------------------------------------------- short CClanSkillSlot::GetSkillIndex(short nSlotIndex) { if( nSlotIndex >= MAX_CLAN_SKILL_SLOT || nSlotIndex < 0 || m_SkillSlot[ nSlotIndex ] == NULL ) return 0; return m_SkillSlot[ nSlotIndex ]->GetSkillIndex(); } //---------------------------------------------------------------------------------------------------- /// @param /// @brief 해당 슬롯의 레벨을 얻어온다. //---------------------------------------------------------------------------------------------------- short CClanSkillSlot::GetSkillLevel(short nSlotIndex) { if( nSlotIndex >= MAX_CLAN_SKILL_SLOT || nSlotIndex < 0 || m_SkillSlot[ nSlotIndex ] == NULL ) return 0; return m_SkillSlot[ nSlotIndex ]->GetSkillLevel(); } //---------------------------------------------------------------------------------------------------- /// @param /// @brief 해당 슬롯의 Delay time를 얻어온다. //---------------------------------------------------------------------------------------------------- short CClanSkillSlot::GetSkillDelayTime(short nSlotIndex) { if( nSlotIndex >= MAX_CLAN_SKILL_SLOT || nSlotIndex < 0 || m_SkillSlot[ nSlotIndex ] == NULL ) return 0; return m_SkillSlot[ nSlotIndex ]->GetSkillDelayTime(); } //---------------------------------------------------------------------------------------------------- /// @param /// @brief 아이콘 번호를 얻어온다. //---------------------------------------------------------------------------------------------------- short CClanSkillSlot::GetSkillIconIndex(short nSlotIndex) { short nSkillIndex = GetSkillIndex( nSlotIndex ); if( nSkillIndex == 0 ) return 0; short nIconIndex = SKILL_ICON_NO( nSkillIndex ); return nIconIndex; } //---------------------------------------------------------------------------------------------------- /// @param /// @brief //---------------------------------------------------------------------------------------------------- void CClanSkillSlot::RemoveBySlotIndex( short nSlotIndex ) { assert( nSlotIndex >= 0 && nSlotIndex < MAX_CLAN_SKILL_SLOT ); if( nSlotIndex >= 0 && nSlotIndex < MAX_CLAN_SKILL_SLOT ) { if( m_SkillSlot[ nSlotIndex ] != NULL ) { m_Event.SetID( CTEventClanSkill::EID_DEL_SKILL ); m_Event.SetIndex( nSlotIndex ); SetChanged(); NotifyObservers( &m_Event ); delete m_SkillSlot[ nSlotIndex ]; m_SkillSlot[ nSlotIndex ] = NULL; } } }
[ "hugo.delannoy@hotmail.com" ]
hugo.delannoy@hotmail.com
85d732f749b9f13fd69830c6a6b9192a35fe800f
425a40722860acaea7f92d0edcbfbbe4f3881a16
/volume0/0067.cpp
935a73e729a3483745c9b57d4c02664868244c71
[]
no_license
eternity514/AOJ-solved
eb23556826676a204d403625d6890ef3d3002525
186d83c4884e0d388837ab58b3083bf195f230e2
refs/heads/master
2021-01-19T02:38:52.487975
2020-07-30T08:26:44
2020-07-30T08:26:44
73,489,404
0
0
null
null
null
null
UTF-8
C++
false
false
650
cpp
#include <iostream> #include <string> using namespace std; int a[12][12] = { 0 }; void remove(int y, int x) { if (y > 11 || x > 11 || y < 0 || x < 0 || a[y][x] == 0) return; a[y][x] = 0; remove(y + 1, x); remove(y - 1, x); remove(y, x + 1); remove(y, x - 1); } int main() { string s; do { for (int i = 0; i < 12; i++) { getline(cin, s); for (int j = 0; j < 12; j++) { a[i][j] = s[j] - '0'; } } int count = 0; for (int i = 0; i < 12; i++) { for (int j = 0; j < 12; j++) { if (a[i][j] == 1) { remove(i, j); count++; } } } cout << count << endl; getline(cin, s); } while (cin); return 0; }
[ "0514eternity@gmail.com" ]
0514eternity@gmail.com
ed8a29e70a3441c420ab9776c55ccc2f87bf7eff
bb782ac840a8fde4c8477b5ef7b2825a6ca1e093
/Simulator/srSimulator/Systems/Humanoid/Humanoid_Dyn_environment.cpp
1ee4e6d006eaaeb29c414d880d0eb1386dcf95ba
[]
no_license
hchlhwang/DynaCoRE
f689629d0e0a002e56988e43a2b655b5f6b74fd4
3876ab25e2220fde0575fc1cfbc3e877229d246f
refs/heads/master
2022-11-27T03:48:14.865992
2020-08-03T19:28:30
2020-08-03T19:28:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,063
cpp
#include "Humanoid_Dyn_environment.h" #include <iostream> #include "srDyn/srSpace.h" #include <stdio.h> #include "common/utils.h" #include <DynaController/Humanoid_Controller/Humanoid_interface.hpp> #include <DynaController/Humanoid_Controller/Humanoid_DynaCtrl_Definition.h> #include <RobotSystems/Humanoid/Humanoid_Definition.h> #include <srTerrain/Ground.h> #include <srConfiguration.h> Humanoid_Dyn_environment::Humanoid_Dyn_environment(): ang_vel_(3) { /********** Space Setup **********/ m_Space = new srSpace(); m_ground = new Ground(); m_Space->AddSystem(m_ground->BuildGround()); /********** Robot Set **********/ robot_ = new Humanoid(); robot_->BuildRobot(Vec3 (0., 0., 0.), srSystem::FIXED, srJoint::TORQUE, ModelPath"Humanoid/humanoid.urdf"); //srSystem::FIXED, srJoint::TORQUE, ModelPath"Humanoid/humanoid_tello.urdf"); m_Space->AddSystem((srSystem*)robot_); /******** Interface set ********/ interface_ = new Humanoid_interface(); data_ = new Humanoid_SensorData(); cmd_ = new Humanoid_Command(); m_Space->DYN_MODE_PRESTEP(); m_Space->SET_USER_CONTROL_FUNCTION_2(ControlFunction); m_Space->SetTimestep(0.001); m_Space->SetGravity(0.0,0.0,-9.81); m_Space->SetNumberofSubstepForRendering(5); std::cout<<robot_->link_[robot_->link_idx_map_.find("R_Foot")->second] ->GetPosition()<<std::endl;; std::cout<<robot_->link_[robot_->link_idx_map_.find("L_Foot")->second] ->GetPosition()<<std::endl;; printf("[Humanoid Dynamic Environment] Build Dynamic Environment\n"); } void Humanoid_Dyn_environment::ControlFunction( void* _data ) { static int count(0); ++count; Humanoid_Dyn_environment* pDyn_env = (Humanoid_Dyn_environment*)_data; Humanoid* robot = (Humanoid*)(pDyn_env->robot_); Humanoid_SensorData* p_data = pDyn_env->data_; std::vector<double> torque_command(robot->num_act_joint_); for(int i(0); i<robot->num_act_joint_; ++i){ p_data->jpos[i] = robot->r_joint_[i]->m_State.m_rValue[0]; p_data->jvel[i] = robot->r_joint_[i]->m_State.m_rValue[1]; p_data->jtorque[i] = robot->r_joint_[i]->m_State.m_rValue[3]; } pDyn_env->_CheckFootContact( p_data->rfoot_contact, p_data->lfoot_contact); std::vector<double> imu_acc(3); std::vector<double> imu_ang_vel(3); pDyn_env->getIMU_Data(imu_acc, imu_ang_vel); for (int i(0); i<3; ++i){ p_data->imu_ang_vel[i] = imu_ang_vel[i]; p_data->imu_acc[i] = -imu_acc[i]; } pDyn_env->interface_->GetCommand(p_data, pDyn_env->cmd_); for(int i(0); i<3; ++i){ robot->vp_joint_[i]->m_State.m_rCommand = 0.0; robot->vr_joint_[i]->m_State.m_rCommand = 0.0; } //if( count < 100 ){ //robot->vp_joint_[0]->m_State.m_rCommand = //-1000. * robot->vp_joint_[0]->m_State.m_rValue[0] //- 10. * robot->vp_joint_[0]->m_State.m_rValue[1]; //robot->vp_joint_[1]->m_State.m_rCommand = //-1000. * robot->vp_joint_[1]->m_State.m_rValue[0] //- 10. * robot->vp_joint_[1]->m_State.m_rValue[1]; //} double Kp(100.); double Kd(5.0); double ramp(1.); if( count < 10 ){ ramp = ((double)count)/10.; } for(int i(0); i<robot->num_act_joint_; ++i){ robot->r_joint_[i]->m_State.m_rCommand = pDyn_env->cmd_->jtorque_cmd[i] + Kp * (pDyn_env->cmd_->jpos_cmd[i] - p_data->jpos[i]) + Kd * (pDyn_env->cmd_->jvel_cmd[i] - p_data->jvel[i]); robot->r_joint_[i]->m_State.m_rCommand *= ramp; // TEST //robot->r_joint_[i]->m_State.m_rCommand = 0.0; } } void Humanoid_Dyn_environment::Rendering_Fnc(){ } void Humanoid_Dyn_environment::_Get_Orientation(dynacore::Quaternion & rot){ SO3 so3_body = robot_-> link_[robot_->link_idx_map_.find("torso")->second]->GetOrientation(); Eigen::Matrix3d ori_mtx; for (int i(0); i<3; ++i){ ori_mtx(i, 0) = so3_body[0+i]; ori_mtx(i, 1) = so3_body[3+i]; ori_mtx(i, 2) = so3_body[6+i]; } dynacore::Quaternion ori_quat(ori_mtx); rot = ori_quat; } Humanoid_Dyn_environment::~Humanoid_Dyn_environment() { SR_SAFE_DELETE(interface_); SR_SAFE_DELETE(robot_); SR_SAFE_DELETE(m_Space); SR_SAFE_DELETE(m_ground); } void Humanoid_Dyn_environment::_CheckFootContact(bool & r_contact, bool & l_contact){ Vec3 lfoot_pos = robot_-> link_[robot_->link_idx_map_.find("L_Foot")->second]->GetPosition(); Vec3 rfoot_pos = robot_-> link_[robot_->link_idx_map_.find("R_Foot")->second]->GetPosition(); //std::cout<<"right: "<<rfoot_pos<<std::endl; //std::cout<<"left: "<<lfoot_pos<<std::endl; if( fabs(lfoot_pos[2]) < 0.03){ l_contact = true; //printf("left contact\n"); }else { l_contact = false; } if (fabs(rfoot_pos[2])<0.03 ){ r_contact = true; //printf("right contact\n"); } else { r_contact = false; } //printf("\n"); } void Humanoid_Dyn_environment::getIMU_Data( std::vector<double> & imu_acc, std::vector<double> & imu_ang_vel){ // IMU data se3 imu_se3_vel = robot_->link_[robot_->link_idx_map_.find("torso")->second]->GetVel(); se3 imu_se3_acc = robot_->link_[robot_->link_idx_map_.find("torso")->second]->GetAcc(); SE3 imu_frame = robot_->link_[robot_->link_idx_map_.find("torso")->second]->GetFrame(); SO3 imu_ori = robot_->link_[robot_->link_idx_map_.find("torso")->second]->GetOrientation(); Eigen::Matrix3d Rot; Rot<< imu_frame(0,0), imu_frame(0,1), imu_frame(0,2), imu_frame(1,0), imu_frame(1,1), imu_frame(1,2), imu_frame(2,0), imu_frame(2,1), imu_frame(2,2); dynacore::Vect3 grav; grav.setZero(); grav[2] = 9.81; dynacore::Vect3 local_grav = Rot.transpose() * grav; for(int i(0); i<3; ++i){ imu_ang_vel[i] = imu_se3_vel[i]; imu_acc[i] = local_grav[i]; } }
[ "alex.d.kim0821@gmail.com" ]
alex.d.kim0821@gmail.com
e8250e64a44da3cbc53897f1d243c8e8b693e4f7
6861ff3f56821b5e263de6ceec117e08d4ac19e8
/Game/Debugging/DebugCategory.cpp
13280e87ad9b2a8aed0a83c9007756a0918e7aac
[ "MIT" ]
permissive
Dev-Awesome/Artemis
8c306be781f31069ef2d63eca50f3233216e9c6c
1038e66537b491fdb55b2cbe4760bcc6ac08c55b
refs/heads/master
2023-06-27T18:31:59.297850
2021-03-02T19:41:23
2021-03-02T19:41:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
33
cpp
#include "DebugCategory.h"
[ "danieleverland@gmail.com" ]
danieleverland@gmail.com
d6f242e0a2c935d0774c106e7cb4ab066cf298a0
96eaebd467794284f338a56b123bdfa5b98dd4d1
/core/test/lib/boost/boost/asio/detail/impl/epoll_reactor.ipp
ff9a9982c3bb99d360d4d349482b55849cacc721
[ "MIT" ]
permissive
KhalilBellakrid/lib-ledger-core
d80dc1fe0c4e3843eabe373f53df210307895364
639f89a64958ee642a2fdb0baf22d2f9da091cc3
refs/heads/develop
2021-05-14T07:19:17.424487
2019-05-20T20:33:05
2019-05-20T20:33:05
116,260,592
0
3
MIT
2019-06-26T08:07:16
2018-01-04T13:01:57
C++
UTF-8
C++
false
false
23,161
ipp
// // detail/impl/epoll_reactor.ipp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_IMPL_EPOLL_REACTOR_IPP #define BOOST_ASIO_DETAIL_IMPL_EPOLL_REACTOR_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_EPOLL) #include <cstddef> #include <sys/epoll.h> #include <boost/asio/detail/epoll_reactor.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/error.hpp> #if defined(BOOST_ASIO_HAS_TIMERFD) # include <sys/timerfd.h> #endif // defined(BOOST_ASIO_HAS_TIMERFD) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { epoll_reactor::epoll_reactor(boost::asio::execution_context& ctx) : execution_context_service_base<epoll_reactor>(ctx), scheduler_(use_service<scheduler>(ctx)), mutex_(BOOST_ASIO_CONCURRENCY_HINT_IS_LOCKING( REACTOR_REGISTRATION, scheduler_.concurrency_hint())), interrupter_(), epoll_fd_(do_epoll_create()), timer_fd_(do_timerfd_create()), shutdown_(false), registered_descriptors_mutex_(mutex_.enabled()) { // Add the interrupter's descriptor to epoll. epoll_event ev = { 0, { 0 } }; ev.events = EPOLLIN | EPOLLERR | EPOLLET; ev.data.ptr = &interrupter_; epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, interrupter_.read_descriptor(), &ev); interrupter_.interrupt(); // Add the timer descriptor to epoll. if (timer_fd_ != -1) { ev.events = EPOLLIN | EPOLLERR; ev.data.ptr = &timer_fd_; epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, timer_fd_, &ev); } } epoll_reactor::~epoll_reactor() { if (epoll_fd_ != -1) close(epoll_fd_); if (timer_fd_ != -1) close(timer_fd_); } void epoll_reactor::shutdown() { mutex::scoped_lock lock(mutex_); shutdown_ = true; lock.unlock(); op_queue<operation> ops; while (descriptor_state* state = registered_descriptors_.first()) { for (int i = 0; i < max_ops; ++i) ops.push(state->op_queue_[i]); state->shutdown_ = true; registered_descriptors_.free(state); } timer_queues_.get_all_timers(ops); scheduler_.abandon_operations(ops); } void epoll_reactor::notify_fork( boost::asio::execution_context::fork_event fork_ev) { if (fork_ev == boost::asio::execution_context::fork_child) { if (epoll_fd_ != -1) ::close(epoll_fd_); epoll_fd_ = -1; epoll_fd_ = do_epoll_create(); if (timer_fd_ != -1) ::close(timer_fd_); timer_fd_ = -1; timer_fd_ = do_timerfd_create(); interrupter_.recreate(); // Add the interrupter's descriptor to epoll. epoll_event ev = { 0, { 0 } }; ev.events = EPOLLIN | EPOLLERR | EPOLLET; ev.data.ptr = &interrupter_; epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, interrupter_.read_descriptor(), &ev); interrupter_.interrupt(); // Add the timer descriptor to epoll. if (timer_fd_ != -1) { ev.events = EPOLLIN | EPOLLERR; ev.data.ptr = &timer_fd_; epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, timer_fd_, &ev); } update_timeout(); // Re-register all descriptors with epoll. mutex::scoped_lock descriptors_lock(registered_descriptors_mutex_); for (descriptor_state* state = registered_descriptors_.first(); state != 0; state = state->next_) { ev.events = state->registered_events_; ev.data.ptr = state; int result = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, state->descriptor_, &ev); if (result != 0) { boost::system::error_code ec(errno, boost::asio::error::get_system_category()); boost::asio::detail::throw_error(ec, "epoll re-registration"); } } } } void epoll_reactor::init_task() { scheduler_.init_task(); } int epoll_reactor::register_descriptor(socket_type descriptor, epoll_reactor::per_descriptor_data& descriptor_data) { descriptor_data = allocate_descriptor_state(); BOOST_ASIO_HANDLER_REACTOR_REGISTRATION(( context(), static_cast<uintmax_t>(descriptor), reinterpret_cast<uintmax_t>(descriptor_data))); { mutex::scoped_lock descriptor_lock(descriptor_data->mutex_); descriptor_data->reactor_ = this; descriptor_data->descriptor_ = descriptor; descriptor_data->shutdown_ = false; for (int i = 0; i < max_ops; ++i) descriptor_data->try_speculative_[i] = true; } epoll_event ev = { 0, { 0 } }; ev.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLPRI | EPOLLET; descriptor_data->registered_events_ = ev.events; ev.data.ptr = descriptor_data; int result = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, descriptor, &ev); if (result != 0) { if (errno == EPERM) { // This file descriptor type is not supported by epoll. However, if it is // a regular file then operations on it will not block. We will allow // this descriptor to be used and fail later if an operation on it would // otherwise require a trip through the reactor. descriptor_data->registered_events_ = 0; return 0; } return errno; } return 0; } int epoll_reactor::register_internal_descriptor( int op_type, socket_type descriptor, epoll_reactor::per_descriptor_data& descriptor_data, reactor_op* op) { descriptor_data = allocate_descriptor_state(); BOOST_ASIO_HANDLER_REACTOR_REGISTRATION(( context(), static_cast<uintmax_t>(descriptor), reinterpret_cast<uintmax_t>(descriptor_data))); { mutex::scoped_lock descriptor_lock(descriptor_data->mutex_); descriptor_data->reactor_ = this; descriptor_data->descriptor_ = descriptor; descriptor_data->shutdown_ = false; descriptor_data->op_queue_[op_type].push(op); for (int i = 0; i < max_ops; ++i) descriptor_data->try_speculative_[i] = true; } epoll_event ev = { 0, { 0 } }; ev.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLPRI | EPOLLET; descriptor_data->registered_events_ = ev.events; ev.data.ptr = descriptor_data; int result = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, descriptor, &ev); if (result != 0) return errno; return 0; } void epoll_reactor::move_descriptor(socket_type, epoll_reactor::per_descriptor_data& target_descriptor_data, epoll_reactor::per_descriptor_data& source_descriptor_data) { target_descriptor_data = source_descriptor_data; source_descriptor_data = 0; } void epoll_reactor::start_op(int op_type, socket_type descriptor, epoll_reactor::per_descriptor_data& descriptor_data, reactor_op* op, bool is_continuation, bool allow_speculative) { if (!descriptor_data) { op->ec_ = boost::asio::error::bad_descriptor; post_immediate_completion(op, is_continuation); return; } mutex::scoped_lock descriptor_lock(descriptor_data->mutex_); if (descriptor_data->shutdown_) { post_immediate_completion(op, is_continuation); return; } if (descriptor_data->op_queue_[op_type].empty()) { if (allow_speculative && (op_type != read_op || descriptor_data->op_queue_[except_op].empty())) { if (descriptor_data->try_speculative_[op_type]) { if (reactor_op::status status = op->perform()) { if (status == reactor_op::done_and_exhausted) if (descriptor_data->registered_events_ != 0) descriptor_data->try_speculative_[op_type] = false; descriptor_lock.unlock(); scheduler_.post_immediate_completion(op, is_continuation); return; } } if (descriptor_data->registered_events_ == 0) { op->ec_ = boost::asio::error::operation_not_supported; scheduler_.post_immediate_completion(op, is_continuation); return; } if (op_type == write_op) { if ((descriptor_data->registered_events_ & EPOLLOUT) == 0) { epoll_event ev = { 0, { 0 } }; ev.events = descriptor_data->registered_events_ | EPOLLOUT; ev.data.ptr = descriptor_data; if (epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, descriptor, &ev) == 0) { descriptor_data->registered_events_ |= ev.events; } else { op->ec_ = boost::system::error_code(errno, boost::asio::error::get_system_category()); scheduler_.post_immediate_completion(op, is_continuation); return; } } } } else if (descriptor_data->registered_events_ == 0) { op->ec_ = boost::asio::error::operation_not_supported; scheduler_.post_immediate_completion(op, is_continuation); return; } else { if (op_type == write_op) { descriptor_data->registered_events_ |= EPOLLOUT; } epoll_event ev = { 0, { 0 } }; ev.events = descriptor_data->registered_events_; ev.data.ptr = descriptor_data; epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, descriptor, &ev); } } descriptor_data->op_queue_[op_type].push(op); scheduler_.work_started(); } void epoll_reactor::cancel_ops(socket_type, epoll_reactor::per_descriptor_data& descriptor_data) { if (!descriptor_data) return; mutex::scoped_lock descriptor_lock(descriptor_data->mutex_); op_queue<operation> ops; for (int i = 0; i < max_ops; ++i) { while (reactor_op* op = descriptor_data->op_queue_[i].front()) { op->ec_ = boost::asio::error::operation_aborted; descriptor_data->op_queue_[i].pop(); ops.push(op); } } descriptor_lock.unlock(); scheduler_.post_deferred_completions(ops); } void epoll_reactor::deregister_descriptor(socket_type descriptor, epoll_reactor::per_descriptor_data& descriptor_data, bool closing) { if (!descriptor_data) return; mutex::scoped_lock descriptor_lock(descriptor_data->mutex_); if (!descriptor_data->shutdown_) { if (closing) { // The descriptor will be automatically removed from the epoll set when // it is closed. } else if (descriptor_data->registered_events_ != 0) { epoll_event ev = { 0, { 0 } }; epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, descriptor, &ev); } op_queue<operation> ops; for (int i = 0; i < max_ops; ++i) { while (reactor_op* op = descriptor_data->op_queue_[i].front()) { op->ec_ = boost::asio::error::operation_aborted; descriptor_data->op_queue_[i].pop(); ops.push(op); } } descriptor_data->descriptor_ = -1; descriptor_data->shutdown_ = true; descriptor_lock.unlock(); BOOST_ASIO_HANDLER_REACTOR_DEREGISTRATION(( context(), static_cast<uintmax_t>(descriptor), reinterpret_cast<uintmax_t>(descriptor_data))); scheduler_.post_deferred_completions(ops); // Leave descriptor_data set so that it will be freed by the subsequent // call to cleanup_descriptor_data. } else { // We are shutting down, so prevent cleanup_descriptor_data from freeing // the descriptor_data object and let the destructor free it instead. descriptor_data = 0; } } void epoll_reactor::deregister_internal_descriptor(socket_type descriptor, epoll_reactor::per_descriptor_data& descriptor_data) { if (!descriptor_data) return; mutex::scoped_lock descriptor_lock(descriptor_data->mutex_); if (!descriptor_data->shutdown_) { epoll_event ev = { 0, { 0 } }; epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, descriptor, &ev); op_queue<operation> ops; for (int i = 0; i < max_ops; ++i) ops.push(descriptor_data->op_queue_[i]); descriptor_data->descriptor_ = -1; descriptor_data->shutdown_ = true; descriptor_lock.unlock(); BOOST_ASIO_HANDLER_REACTOR_DEREGISTRATION(( context(), static_cast<uintmax_t>(descriptor), reinterpret_cast<uintmax_t>(descriptor_data))); // Leave descriptor_data set so that it will be freed by the subsequent // call to cleanup_descriptor_data. } else { // We are shutting down, so prevent cleanup_descriptor_data from freeing // the descriptor_data object and let the destructor free it instead. descriptor_data = 0; } } void epoll_reactor::cleanup_descriptor_data( per_descriptor_data& descriptor_data) { if (descriptor_data) { free_descriptor_state(descriptor_data); descriptor_data = 0; } } void epoll_reactor::run(long usec, op_queue<operation>& ops) { // This code relies on the fact that the scheduler queues the reactor task // behind all descriptor operations generated by this function. This means, // that by the time we reach this point, any previously returned descriptor // operations have already been dequeued. Therefore it is now safe for us to // reuse and return them for the scheduler to queue again. // Calculate timeout. Check the timer queues only if timerfd is not in use. int timeout; if (usec == 0) timeout = 0; else { timeout = (usec < 0) ? -1 : ((usec - 1) / 1000 + 1); if (timer_fd_ == -1) { mutex::scoped_lock lock(mutex_); timeout = get_timeout(timeout); } } // Block on the epoll descriptor. epoll_event events[128]; int num_events = epoll_wait(epoll_fd_, events, 128, timeout); #if defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING) // Trace the waiting events. for (int i = 0; i < num_events; ++i) { void* ptr = events[i].data.ptr; if (ptr == &interrupter_) { // Ignore. } # if defined(BOOST_ASIO_HAS_TIMERFD) else if (ptr == &timer_fd_) { // Ignore. } # endif // defined(BOOST_ASIO_HAS_TIMERFD) else { unsigned event_mask = 0; if ((events[i].events & EPOLLIN) != 0) event_mask |= BOOST_ASIO_HANDLER_REACTOR_READ_EVENT; if ((events[i].events & EPOLLOUT)) event_mask |= BOOST_ASIO_HANDLER_REACTOR_WRITE_EVENT; if ((events[i].events & (EPOLLERR | EPOLLHUP)) != 0) event_mask |= BOOST_ASIO_HANDLER_REACTOR_ERROR_EVENT; BOOST_ASIO_HANDLER_REACTOR_EVENTS((context(), reinterpret_cast<uintmax_t>(ptr), event_mask)); } } #endif // defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING) #if defined(BOOST_ASIO_HAS_TIMERFD) bool check_timers = (timer_fd_ == -1); #else // defined(BOOST_ASIO_HAS_TIMERFD) bool check_timers = true; #endif // defined(BOOST_ASIO_HAS_TIMERFD) // Dispatch the waiting events. for (int i = 0; i < num_events; ++i) { void* ptr = events[i].data.ptr; if (ptr == &interrupter_) { // No need to reset the interrupter since we're leaving the descriptor // in a ready-to-read state and relying on edge-triggered notifications // to make it so that we only get woken up when the descriptor's epoll // registration is updated. #if defined(BOOST_ASIO_HAS_TIMERFD) if (timer_fd_ == -1) check_timers = true; #else // defined(BOOST_ASIO_HAS_TIMERFD) check_timers = true; #endif // defined(BOOST_ASIO_HAS_TIMERFD) } #if defined(BOOST_ASIO_HAS_TIMERFD) else if (ptr == &timer_fd_) { check_timers = true; } #endif // defined(BOOST_ASIO_HAS_TIMERFD) else { // The descriptor operation doesn't count as work in and of itself, so we // don't call work_started() here. This still allows the scheduler to // stop if the only remaining operations are descriptor operations. descriptor_state* descriptor_data = static_cast<descriptor_state*>(ptr); if (!ops.is_enqueued(descriptor_data)) { descriptor_data->set_ready_events(events[i].events); ops.push(descriptor_data); } else { descriptor_data->add_ready_events(events[i].events); } } } if (check_timers) { mutex::scoped_lock common_lock(mutex_); timer_queues_.get_ready_timers(ops); #if defined(BOOST_ASIO_HAS_TIMERFD) if (timer_fd_ != -1) { itimerspec new_timeout; itimerspec old_timeout; int flags = get_timeout(new_timeout); timerfd_settime(timer_fd_, flags, &new_timeout, &old_timeout); } #endif // defined(BOOST_ASIO_HAS_TIMERFD) } } void epoll_reactor::interrupt() { epoll_event ev = { 0, { 0 } }; ev.events = EPOLLIN | EPOLLERR | EPOLLET; ev.data.ptr = &interrupter_; epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, interrupter_.read_descriptor(), &ev); } int epoll_reactor::do_epoll_create() { #if defined(EPOLL_CLOEXEC) int fd = epoll_create1(EPOLL_CLOEXEC); #else // defined(EPOLL_CLOEXEC) int fd = -1; errno = EINVAL; #endif // defined(EPOLL_CLOEXEC) if (fd == -1 && (errno == EINVAL || errno == ENOSYS)) { fd = epoll_create(epoll_size); if (fd != -1) ::fcntl(fd, F_SETFD, FD_CLOEXEC); } if (fd == -1) { boost::system::error_code ec(errno, boost::asio::error::get_system_category()); boost::asio::detail::throw_error(ec, "epoll"); } return fd; } int epoll_reactor::do_timerfd_create() { #if defined(BOOST_ASIO_HAS_TIMERFD) # if defined(TFD_CLOEXEC) int fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC); # else // defined(TFD_CLOEXEC) int fd = -1; errno = EINVAL; # endif // defined(TFD_CLOEXEC) if (fd == -1 && errno == EINVAL) { fd = timerfd_create(CLOCK_MONOTONIC, 0); if (fd != -1) ::fcntl(fd, F_SETFD, FD_CLOEXEC); } return fd; #else // defined(BOOST_ASIO_HAS_TIMERFD) return -1; #endif // defined(BOOST_ASIO_HAS_TIMERFD) } epoll_reactor::descriptor_state* epoll_reactor::allocate_descriptor_state() { mutex::scoped_lock descriptors_lock(registered_descriptors_mutex_); return registered_descriptors_.alloc(BOOST_ASIO_CONCURRENCY_HINT_IS_LOCKING( REACTOR_IO, scheduler_.concurrency_hint())); } void epoll_reactor::free_descriptor_state(epoll_reactor::descriptor_state* s) { mutex::scoped_lock descriptors_lock(registered_descriptors_mutex_); registered_descriptors_.free(s); } void epoll_reactor::do_add_timer_queue(timer_queue_base& queue) { mutex::scoped_lock lock(mutex_); timer_queues_.insert(&queue); } void epoll_reactor::do_remove_timer_queue(timer_queue_base& queue) { mutex::scoped_lock lock(mutex_); timer_queues_.erase(&queue); } void epoll_reactor::update_timeout() { #if defined(BOOST_ASIO_HAS_TIMERFD) if (timer_fd_ != -1) { itimerspec new_timeout; itimerspec old_timeout; int flags = get_timeout(new_timeout); timerfd_settime(timer_fd_, flags, &new_timeout, &old_timeout); return; } #endif // defined(BOOST_ASIO_HAS_TIMERFD) interrupt(); } int epoll_reactor::get_timeout(int msec) { // By default we will wait no longer than 5 minutes. This will ensure that // any changes to the system clock are detected after no longer than this. const int max_msec = 5 * 60 * 1000; return timer_queues_.wait_duration_msec( (msec < 0 || max_msec < msec) ? max_msec : msec); } #if defined(BOOST_ASIO_HAS_TIMERFD) int epoll_reactor::get_timeout(itimerspec& ts) { ts.it_interval.tv_sec = 0; ts.it_interval.tv_nsec = 0; long usec = timer_queues_.wait_duration_usec(5 * 60 * 1000 * 1000); ts.it_value.tv_sec = usec / 1000000; ts.it_value.tv_nsec = usec ? (usec % 1000000) * 1000 : 1; return usec ? 0 : TFD_TIMER_ABSTIME; } #endif // defined(BOOST_ASIO_HAS_TIMERFD) struct epoll_reactor::perform_io_cleanup_on_block_exit { explicit perform_io_cleanup_on_block_exit(epoll_reactor* r) : reactor_(r), first_op_(0) { } ~perform_io_cleanup_on_block_exit() { if (first_op_) { // Post the remaining completed operations for invocation. if (!ops_.empty()) reactor_->scheduler_.post_deferred_completions(ops_); // A user-initiated operation has completed, but there's no need to // explicitly call work_finished() here. Instead, we'll take advantage of // the fact that the scheduler will call work_finished() once we return. } else { // No user-initiated operations have completed, so we need to compensate // for the work_finished() call that the scheduler will make once this // operation returns. reactor_->scheduler_.compensating_work_started(); } } epoll_reactor* reactor_; op_queue<operation> ops_; operation* first_op_; }; epoll_reactor::descriptor_state::descriptor_state(bool locking) : operation(&epoll_reactor::descriptor_state::do_complete), mutex_(locking) { } operation* epoll_reactor::descriptor_state::perform_io(uint32_t events) { mutex_.lock(); perform_io_cleanup_on_block_exit io_cleanup(reactor_); mutex::scoped_lock descriptor_lock(mutex_, mutex::scoped_lock::adopt_lock); // Exception operations must be processed first to ensure that any // out-of-band data is read before normal data. static const int flag[max_ops] = { EPOLLIN, EPOLLOUT, EPOLLPRI }; for (int j = max_ops - 1; j >= 0; --j) { if (events & (flag[j] | EPOLLERR | EPOLLHUP)) { try_speculative_[j] = true; while (reactor_op* op = op_queue_[j].front()) { if (reactor_op::status status = op->perform()) { op_queue_[j].pop(); io_cleanup.ops_.push(op); if (status == reactor_op::done_and_exhausted) { try_speculative_[j] = false; break; } } else break; } } } // The first operation will be returned for completion now. The others will // be posted for later by the io_cleanup object's destructor. io_cleanup.first_op_ = io_cleanup.ops_.front(); io_cleanup.ops_.pop(); return io_cleanup.first_op_; } void epoll_reactor::descriptor_state::do_complete( void* owner, operation* base, const boost::system::error_code& ec, std::size_t bytes_transferred) { if (owner) { descriptor_state* descriptor_data = static_cast<descriptor_state*>(base); uint32_t events = static_cast<uint32_t>(bytes_transferred); if (operation* op = descriptor_data->perform_io(events)) { op->complete(owner, ec, 0); } } } } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_EPOLL) #endif // BOOST_ASIO_DETAIL_IMPL_EPOLL_REACTOR_IPP
[ "andrii.korol@ledger.fr" ]
andrii.korol@ledger.fr
7d239ca212b3fea02fb82775506133d884414380
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/boost/property/rank1_object_property.hpp
04d1de21229f688023ab2f11de1b2325cab3bd08
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
1,038
hpp
// (C) Copyright 2004: Reece H. Dunn. Distributed under the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_PROPERTY_RANK1_OBJECT_PROPERTY_HPP #define BOOST_PROPERTY_RANK1_OBJECT_PROPERTY_HPP #include <boost/property/property_type.hpp> namespace boost { /** Implement a rank 1 property using member functions of an object. */ template < typename T, typename I, class Object, T ( Object::*getter )( I ) const, void ( Object::*setter )( I, const T & ) > class rank1_object_property: public property_type< T, Object *, T &, I > { Object * object; public: T get( I i ) const /**< get the value of the property. */ { return ( object ->* getter )( i ); } void set( I i, const T & v ) /**< set the value of the property. */ { ( object ->* setter )( i, v ); } public: inline rank1_object_property( Object * o ): object( o ) { } }; } #endif
[ "msclrhd@hotmail.com" ]
msclrhd@hotmail.com
678c0cce1a6456791c7f852bd1def5ee2848bd23
4e7f736969804451a12bf2a1124b964f15cc15e8
/AtCoder/ABC/ABC032/C.cpp
7e830b69aba7ddd24edd7794569d8daaeea80a1f
[]
no_license
hayaten0415/Competitive-programming
bb753303f9d8d1864991eb06fa823a9f74e42a4c
ea8bf51c1570566e631699aa7739cda973133f82
refs/heads/master
2022-11-26T07:11:46.953867
2022-11-01T16:18:04
2022-11-01T16:18:04
171,068,479
0
0
null
null
null
null
UTF-8
C++
false
false
616
cpp
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); i++) using namespace std; using P = pair<int, int>; typedef long long ll; int main() { int n, k; cin >> n >> k; vector<ll> a(n); rep(i, n){ cin >> a[i]; } rep(i, n){ if(a[i] == 0){ cout << n << endl; return 0; } } int ans = 0; ll sum = 1; int right = 0; for (int left = 0; left < n; left++){ while(right < n && sum * a[right] <= k){ sum *= a[right]; right++; } ans = max(ans,right - left); if(right == left)right++; else sum /= a[left]; } cout << ans << endl; }
[ "hayaten415@gmail.com" ]
hayaten415@gmail.com
50a53393f1a4a63d63648bec3360262529b2570e
02a5e3091a348d73fed9907f550ee65691b6f057
/COMP710-2019-S2/teams/JN/Wheelspin/Wheelspin/SplashScreen.cpp
5ab6bdc7de9a8997099da2ac9e92923f6545fc05
[]
no_license
Arniox/Game-Programming-Work
86ef44405246fd3d88bd5eb9979ce42ca5176ce8
33473a0be84ea547f8a1316a236cbe272301a65c
refs/heads/master
2020-06-30T21:57:27.969713
2020-02-18T07:19:55
2020-02-18T07:19:55
200,958,619
0
0
null
null
null
null
UTF-8
C++
false
false
1,614
cpp
#include "SplashScreen.h" #include "backbuffer.h" #include "IniParser.h" #include "InputManager.h" #include "sprite.h" #include "SceneManager.h" #include "game.h" #include "logmanager.h" #include <string> SplashScreen::SplashScreen(const char* logo, SCENES nextScene) : m_pMaxSplashTime(0.0f) , m_pScreenTime(0.0f) , m_nextScene(SCENE_QUIT) { LogManager::Title("Splash Screen"); Game* game = Game::GetInstance(); IniParser* iniFile = game->GetIniFile(); BackBuffer* backBuffer = game->GetBackBuffer(); m_pInput = game->GetInputManager(); m_pMaxSplashTime = iniFile->GetValueAsFloat("SplashScreen", "time"); m_nextScene = nextScene; m_pLogo = backBuffer->CreateSprite(iniFile->GetValueAsString("SplashScreen", logo).c_str()); m_pLogo->SetX((game->GetScreenWidth() / 2) - (m_pLogo->GetWidth() / 2)); m_pLogo->SetY((game->GetScreenHeight() / 2 ) - (m_pLogo->GetHeight() / 2)); backBuffer->SetClearColour(0x00, 0x00, 0x00); } SplashScreen::~SplashScreen() { delete m_pLogo; m_pLogo = nullptr; } void SplashScreen::Proccess(float deltaTime) { m_pScreenTime += deltaTime; if (m_pScreenTime >= m_pMaxSplashTime) { // Splash Screen State is over Game::GetSceneManager()->SetNextState(m_nextScene); } } void SplashScreen::Draw(BackBuffer& backBuffer) { m_pLogo->Draw(backBuffer); } void SplashScreen::ProcessControls() { // Skip current screen if (m_pInput->KeyDown(KEY_SPACE) || m_pInput->JoyButtonDown(JOY_A)) Game::GetSceneManager()->SetNextState(m_nextScene); // ESC, quit game if (m_pInput->KeyDown(KEY_ESCAPE) || m_pInput->JoyButtonDown(JOY_START)) Game::GetInstance()->Quit(); }
[ "nikkdiehl@gmail.com" ]
nikkdiehl@gmail.com
429ebe048da8bac26c7bb1a593da0d38c25556c0
2dc745549bb886a55f211b0eaa61a47169fc7dd6
/ESP32_IOT_demo_2/iot_deshboard/iot_deshboard.ino
4e662d34b6bd6af24a684b7afe01b8eae1194dc3
[]
no_license
bench2012/IOT-Training
108c730b905642c1a67159c86108dd3e9fe5c517
f6e3a2a9051cd5b38206e591e8701a1692255a17
refs/heads/main
2023-05-29T15:02:16.736552
2021-06-11T14:51:15
2021-06-11T14:51:15
360,429,366
0
0
null
null
null
null
UTF-8
C++
false
false
7,296
ino
#include <dataControlsJS.h> #include <dataGraphJS.h> #include <dataIndexHTML.h> #include <dataNormalizeCSS.h> #include <dataSliderJS.h> #include <dataStyleCSS.h> #include <dataTabbedcontentJS.h> #include <dataZeptoJS.h> /********* Complete rewritten (GUi) using ESPUI *********/ #include <ESPUI.h> #ifdef ESP32 #include <WiFi.h> #include <AsyncTCP.h> #else #include <ESP8266WiFi.h> #include <ESPAsyncTCP.h> #endif #include <ESPmDNS.h> #include <WiFiUdp.h> #include <ArduinoOTA.h> #include <ESPAsyncWebServer.h> #include "DHT.h" #define green_led 19 #define red_led 12 //#define led 2 #define button_1 18 #define DHTPIN 4 #define ldr 36 #define DHTTYPE DHT11 bool buttonState = false; int light_level = 0; int statusLabelId; int graphId; int testSwitchId; int HumidityLabelId; int TemperatureLabelId; DHT dht(DHTPIN, DHTTYPE); // REPLACE WITH YOUR NETWORK CREDENTIALS const char* ssid = "macross2010"; const char* password = "qswdefrgthyjukil"; const char* ap_ssid = "iot_ap"; const char* ap_password = "iot12345"; boolean WiFiUp = false; //Wifi LED const int led = 2; //Wifi LED //Wifi connect wait timer const int Wifi_Retry = 3; void numberCall(Control *sender, int type) { Serial.println(sender->value); } void switch_green(Control *sender, int value) { switch (value) { case S_ACTIVE: digitalWrite(green_led,HIGH); Serial.print("Switch On:"); break; case S_INACTIVE: digitalWrite(green_led,LOW); Serial.print("Switch Off"); break; } } void switch_red(Control *sender, int value) { switch (value) { case S_ACTIVE: digitalWrite(red_led,HIGH); Serial.print("Switch On:"); break; case S_INACTIVE: digitalWrite(red_led,LOW); Serial.print("Switch Off"); break; } Serial.print(" "); Serial.println(sender->id); } void setup() { ESPUI.setVerbosity(Verbosity::Verbose); Serial.begin(115200); Serial.println("Booting"); pinMode(led, OUTPUT); pinMode(green_led, OUTPUT); pinMode(red_led, OUTPUT); pinMode(button_1, INPUT); dht.begin(); //All the Wifi connection bit WiFi.setAutoConnect(false); Serial.printf("Scanning for %s\r\n", ssid); // if WiFi/LAN is available WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); WiFi.disconnect(); delay(100); int n = WiFi.scanNetworks(); //Setup Status LED Off is sleeping pinMode(led, OUTPUT); //Wait for Wifi. If nothing after 20 loop, change to AP mode for (int i = 0; i < n; ++i) { if (WiFi.SSID(i) == ssid) { WiFiUp = true; WiFi.mode(WIFI_AP_STA); // LAN and AP and UDP clients //WiFi.config(ip, gateway, subnet); // LAN fixed IP WiFi.begin(ssid, password); // connect to LAN with credentials Serial.printf("Found %s, trying to connect ", ssid); break; } delay(10); } connectWiFi(); // OTA Stuff // Port defaults to 3232 // ArduinoOTA.setPort(3232); // Hostname defaults to esp3232-[MAC] // ArduinoOTA.setHostname("myesp32"); // No authentication by default // ArduinoOTA.setPassword("admin"); // Password can be set with it's md5 value as well // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3 // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3"); ArduinoOTA .onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) type = "sketch"; else // U_SPIFFS type = "filesystem"; // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial.println("Start updating " + type); }) .onEnd([]() { Serial.println("\nEnd"); }) .onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }) .onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); Serial.println(); Serial.print("ESP IP Address: http://"); Serial.println(WiFi.localIP()); //Start ESPUI HumidityLabelId = ESPUI.label("Humidity:", ControlColor::Emerald, "0"); TemperatureLabelId = ESPUI.label("Temperature:", ControlColor::Emerald, "0"); testSwitchId = ESPUI.switcher("Button one", &switch_red, ControlColor::Alizarin, false); ESPUI.switcher("Green LED ", &switch_green, ControlColor::Wetasphalt, false); graphId = ESPUI.graph("Light Level", ControlColor::Wetasphalt); ESPUI.begin("IOT Dashboard"); } void connectWiFi() { if (WiFiUp) { byte w8 = 0; while (WiFi.status() != WL_CONNECTED && w8++ < Wifi_Retry) { delay(333); // try for 5 seconds Serial.print(">"); Wifi_connecting_blink(); } Serial.printf("\r\n"); } if (WiFi.status() == WL_CONNECTED) { Serial.printf("\tConnected to %s IP address %s strength %d%%\r\n", ssid, WiFi.localIP().toString().c_str(), 2 * (WiFi.RSSI() + 100)); WiFi.setAutoReconnect(false); digitalWrite(led, HIGH); } else { WiFi.mode(WIFI_AP); // drop station mode if LAN/WiFi is down // WiFi.softAP(ap_ssid, ap_password); WiFi.softAP(ap_ssid); Serial.printf("\tLAN Connection failed\r\n\tTry %s AP with IP address %s\r\n", ap_ssid, WiFi.softAPIP().toString().c_str()); Wifi_connecting_blink(); } } void Wifi_connecting_blink() { delay(500); Serial.print("."); digitalWrite(led,HIGH); delay(800); digitalWrite(led,LOW); delay(500); } void loop() { buttonState = digitalRead(button_1); Serial.print("Current Light level "); light_level=analogRead(ldr); Serial.println(light_level); if (buttonState == LOW) { // turn LED on: digitalWrite(red_led, HIGH); Serial.println("button is Pressed!"); buttonState=!buttonState; } else { // turn LED off: digitalWrite(red_led, LOW); buttonState=!buttonState; } delay(2000); // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); // Read temperature as Celsius (the default) float t = dht.readTemperature(); float f = dht.readTemperature(true); float hif = dht.computeHeatIndex(f, h); // Compute heat index in Celsius (isFahreheit = false) float hic = dht.computeHeatIndex(t, h, false); if (isnan(h) || isnan(t) || isnan(f)) { Serial.println(F("Failed to read from DHT sensor!")); return; } // Compute heat index in Fahrenheit (the default) Serial.print(F("Humidity: ")); Serial.print(h); Serial.print(F("% Temperature: ")); Serial.print(t); Serial.print(F("°C ")); Serial.print(f); Serial.print(F("°F Heat index: ")); Serial.print(hic); Serial.print(F("°C ")); Serial.print(hif); Serial.println(F("°F")); ESPUI.print(HumidityLabelId, String(h)); ESPUI.print(TemperatureLabelId, String(t)); ESPUI.updateSwitcher(testSwitchId, buttonState); ESPUI.addGraphPoint(graphId, light_level); ArduinoOTA.handle(); }
[ "bench2004@gmail.com" ]
bench2004@gmail.com
0221acb74389e02c525abfe84bfdb01a20c84c12
77b9933f6ed769b8cfcc9a16031ed7e494d0e023
/common/TreeFile.hh
c60540132e4055e662d6b916e2714b33cac7c824
[ "MIT" ]
permissive
m-dupont/TreeOuput
0066a7966ba171abe1c483fc9fe4b20ec4ab94bc
4167ec31d898e20676448999cf4b65b3a2b71695
refs/heads/master
2023-03-16T12:26:38.289706
2020-03-17T16:01:44
2020-03-17T16:01:44
187,620,705
0
0
null
null
null
null
UTF-8
C++
false
false
3,186
hh
// // Created by mdupont on 12/03/18. // #pragma once #include <string> #include <typeindex> #include <typeinfo> #include <unordered_map> #include <iostream> #include <memory> #include <fstream> #include "File.hh" class Data { public: Data(const void * pointer_to_data, const std::string _name, const std::type_index type_index ) : m_pointer_to_data(pointer_to_data), m_name(_name), m_type_index(type_index) { } const std::string &name() const { return m_name; } const void *m_pointer_to_data; const std::string m_name; std::type_index m_type_index; }; class Tree { public: static std::string default_tree_name(); Tree(); template <class T> static std::unique_ptr<T> _create_method() { return std::unique_ptr<T>(new T()); } protected: virtual void register_variable(const std::string &name, const void *p, std::type_index t_index) = 0; virtual void register_variable(const std::string &name, const std::string *p, size_t nb_char) = 0; virtual void register_variable(const std::string &name, const char *p, size_t nb_char) = 0; private: template<typename T> void add_size() { m_tmapOfSize[typeid(T)] = sizeof(T); } template<typename T> void add_name(const std::string &name) { // m_tmapOfName[typeid(T)] = name; m_tmapOfName.emplace(typeid(T), name); } protected: const std::string type_to_name(std::type_index t_index); std::unordered_map<std::type_index, std::size_t> m_tmapOfSize; std::unordered_map<std::type_index, std::string> m_tmapOfName; }; class OutputTreeFile : public File { public: OutputTreeFile(); virtual void open(const std::string& s) = 0; virtual void write_header() = 0; virtual void fill() = 0; virtual void write_variable(const std::string &name, const void *p, std::type_index t_index) = 0; virtual void write_variable(const std::string &name, const std::string *p, size_t nb_char) = 0; virtual void write_variable(const std::string &name, const char *p, size_t nb_char) = 0; virtual void set_tree_name(const std::string &name) ; virtual ~OutputTreeFile(); protected: std::string m_nameOfTree; }; class InputTreeFile : public File { public: InputTreeFile(); virtual ~InputTreeFile() = default; virtual void open(const std::string& s) = 0; virtual void read_header() = 0; virtual void read_next_entrie() = 0; virtual void read_entrie(const uint64_t& i) = 0; virtual bool data_to_read() = 0; virtual void set_tree_name(const std::string &name) ; virtual void read_variable(const std::string &name, void *p, std::type_index t_index) = 0; virtual void read_variable(const std::string &name, char* p); virtual void read_variable(const std::string &name, char* p, size_t nb_char); virtual void read_variable(const std::string &name, std::string *p); virtual bool has_variable(const std::string &name) = 0; virtual std::type_index get_type_of_variable(const std::string &name) = 0; virtual uint64_t nb_elements() = 0; template<typename T> void read_variable(const std::string &name, T *p) { read_variable(name, p, typeid(T)); } protected: std::string m_nameOfTree; };
[ "mdupont@cppm.in2p3.fr" ]
mdupont@cppm.in2p3.fr
f1f7900be8b92683103e8bc1375d25c421dde34f
18cd709cad01d13f06051e22a53111b4318a1ce2
/src/rpcmasternode-vote.cpp
1637a44f68c683763b25880642d16a9602a09ffb
[ "MIT" ]
permissive
NodeHost/NODECore
8e0ba2794e6bd23af4e5c2126335c25a9c6e27ac
527a1eee6f1a9992f0d3f1cb9ffecf67e0211b43
refs/heads/master
2020-04-02T09:04:44.575856
2019-02-07T05:02:29
2019-02-07T05:02:29
154,274,665
0
0
null
null
null
null
UTF-8
C++
false
false
23,518
cpp
// Copyright (c) 2018-2019 The NodeHost developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "db.h" #include "init.h" #include "main.h" #include "masternode-vote.h" #include "masternode-payments.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "masternode-helpers.h" #include "rpcserver.h" #include "utilmoneystr.h" #include <univalue.h> #include <fstream> using namespace std; void communityToJSON(CCommunityProposal* pcommunityProposal, UniValue& bObj) { bObj.push_back(Pair("Name", pcommunityProposal->GetName())); bObj.push_back(Pair("Description", pcommunityProposal->GetDescription())); bObj.push_back(Pair("Hash", pcommunityProposal->GetHash().ToString())); bObj.push_back(Pair("FeeHash", pcommunityProposal->nFeeTXHash.ToString())); bObj.push_back(Pair("BlockEnd", (int64_t)pcommunityProposal->GetBlockEnd())); bObj.push_back(Pair("Ratio", pcommunityProposal->GetRatio())); bObj.push_back(Pair("Yeas", (int64_t)pcommunityProposal->GetYeas())); bObj.push_back(Pair("Nays", (int64_t)pcommunityProposal->GetNays())); bObj.push_back(Pair("Abstains", (int64_t)pcommunityProposal->GetAbstains())); bObj.push_back(Pair("IsEstablished", pcommunityProposal->IsEstablished())); std::string strError = ""; bObj.push_back(Pair("IsValid", pcommunityProposal->IsValid(strError))); bObj.push_back(Pair("IsValidReason", strError.c_str())); bObj.push_back(Pair("fValid", pcommunityProposal->fValid)); } UniValue preparecommunityproposal(const UniValue& params, bool fHelp) { CBlockIndex* pindexPrev = chainActive.Tip(); if (fHelp || params.size() != 3) throw runtime_error( "preparecommunityproposal \"proposal-name\" \"proposal-description\" block-end\n" "\nPrepare a community vote proposal for network by signing and creating tx\n" "\nArguments:\n" "1. \"proposal-name\": (string, required) Desired proposal name (20 character limit)\n" "2. \"proposal-description\": (string, required) Description of proposal (160 character limit)\n" "3. block-end: (numeric, required) Last block available for votes\n" "\nResult:\n" "\"xxxx\" (string) community vote proposal fee hash (if successful) or error message (if failed)\n" "\nExamples:\n" + HelpExampleCli("preparecommunityproposal", "\"test-proposal\" \"proposal-description\" 820800") + HelpExampleRpc("preparecommunityproposal", "\"test-proposal\" \"proposal-description\" 820800")); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); std::string strProposalName = SanitizeString(params[0].get_str()); if (strProposalName.size() > 20) throw runtime_error("Invalid proposal name, limit of 20 characters."); std::string strProposalDescription = SanitizeString(params[1].get_str()); if (strProposalDescription.size() > 160) throw runtime_error("Invalid proposal description, limit of 160 characters."); int nBlockEnd = params[2].get_int(); if (nBlockEnd < pindexPrev->nHeight) throw runtime_error("Invalid block end - must be a higher than current block height."); //************************************************************************* // create transaction 15 minutes into the future, to allow for confirmation time CCommunityProposalBroadcast communityProposalBroadcast(strProposalName, strProposalDescription, nBlockEnd, 0); std::string strError = ""; if (!communityProposalBroadcast.IsValid(strError, false)) throw runtime_error("Community Proposal is not valid - " + communityProposalBroadcast.GetHash().ToString() + " - " + strError); bool useIX = false; //true; CWalletTx wtx; if (!pwalletMain->GetCommunityVoteSystemCollateralTX(wtx, communityProposalBroadcast.GetHash(), useIX)) throw runtime_error("Error making collateral transaction for community proposal. Please check your wallet balance."); // make our change address CReserveKey reservekey(pwalletMain); //send the tx to the network pwalletMain->CommitTransaction(wtx, reservekey, useIX ? "ix" : "tx"); return wtx.GetHash().ToString(); } UniValue submitcommunityproposal(const UniValue& params, bool fHelp) { int nBlockMin = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if (fHelp || params.size() != 4) throw runtime_error( "submitcommunityproposal \"proposal-name\" \"proposal-description\" block-end \"fee-tx\"\n" "\nSubmit community proposal to the network\n" "\nArguments:\n" "1. \"proposal-name\": (string, required) Desired proposal name (20 character limit)\n" "2. \"proposal-description\": (string, required) Description of proposal (160 character limit)\n" "3. block-end: (numeric, required) Last block available for votes\n" "4. \"fee-tx\": (string, required) Transaction hash from preparecommunityproposal command\n" "\nResult:\n" "\"xxxx\" (string) proposal hash (if successful) or error message (if failed)\n" "\nExamples:\n" + HelpExampleCli("submitcommunityproposal", "\"test-proposal\" \"proposal-description\" 820800") + HelpExampleRpc("submitcommunityproposal", "\"test-proposal\" \"proposal-description\" 820800")); // Check these inputs the same way we check the vote commands: // ********************************************************** std::string strProposalName = SanitizeString(params[0].get_str()); if (strProposalName.size() > 20) throw runtime_error("Invalid proposal name, limit of 20 characters."); std::string strProposalDescription = SanitizeString(params[1].get_str()); if (strProposalDescription.size() > 160) throw runtime_error("Invalid proposal description, limit of 160 characters."); int nBlockEnd = params[2].get_int(); if (nBlockEnd < pindexPrev->nHeight) throw runtime_error("Invalid block end - must be a higher than current block height."); uint256 hash = ParseHashV(params[3], "parameter 1"); //create the proposal incase we're the first to make it CCommunityProposalBroadcast communityProposalBroadcast(strProposalName, strProposalDescription, nBlockEnd, hash); std::string strError = ""; int nConf = 0; if (!IsCommunityCollateralValid(hash, communityProposalBroadcast.GetHash(), strError, communityProposalBroadcast.nTime, nConf)) throw runtime_error("Proposal FeeTX is not valid - " + hash.ToString() + " - " + strError); if (!masternodeSync.IsBlockchainSynced()) throw runtime_error("Must wait for client to sync with masternode network. Try again in a minute or so."); communityVote.mapSeenMasternodeCommunityProposals.insert(make_pair(communityProposalBroadcast.GetHash(), communityProposalBroadcast)); communityProposalBroadcast.Relay(); if(communityVote.AddProposal(communityProposalBroadcast)) { return communityProposalBroadcast.GetHash().ToString(); } throw runtime_error("Invalid proposal, see debug.log for details."); } UniValue getcommunityinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getcommunityinfo ( \"proposal\" )\n" "\nShow current masternode community proposals\n" "\nArguments:\n" "1. \"proposal\" (string, optional) Proposal name\n" "\nResult:\n" "[\n" " {\n" " \"Name\": \"xxxx\", (string) Proposal Name\n" " \"Description\": \"xxxx\", (string) Proposal Description\n" " \"Hash\": \"xxxx\", (string) Proposal vote hash\n" " \"FeeHash\": \"xxxx\", (string) Proposal fee hash\n" " \"BlockEnd\": n, (numeric) Proposal ending block\n" " \"Ratio\": x.xxx, (numeric) Ratio of yeas vs nays\n" " \"Yeas\": n, (numeric) Number of yea votes\n" " \"Nays\": n, (numeric) Number of nay votes\n" " \"Abstains\": n, (numeric) Number of abstains\n" " \"IsEstablished\": true|false, (boolean) Established (true) or (false)\n" " \"IsValid\": true|false, (boolean) Valid (true) or Invalid (false)\n" " \"IsValidReason\": \"xxxx\", (string) Error message, if any\n" " \"fValid\": true|false, (boolean) Valid (true) or Invalid (false)\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getcommunityinfo", "") + HelpExampleRpc("getcommunityinfo", "")); UniValue ret(UniValue::VARR); std::string strShow = "valid"; if (params.size() == 1) { std::string strProposalName = SanitizeString(params[0].get_str()); CCommunityProposal* pcommunityProposal = communityVote.FindProposal(strProposalName); if (pcommunityProposal == nullptr) throw runtime_error("Unknown proposal name"); UniValue bObj(UniValue::VOBJ); communityToJSON(pcommunityProposal, bObj); ret.push_back(bObj); return ret; } std::vector<CCommunityProposal*> winningProps = communityVote.GetAllProposals(); for (CCommunityProposal* pcommunityProposal : winningProps) { if (strShow == "valid" && !pcommunityProposal->fValid) continue; UniValue bObj(UniValue::VOBJ); communityToJSON(pcommunityProposal, bObj); ret.push_back(bObj); } return ret; } UniValue checkcommunityproposals(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "checkcommunityproposals\n" "\nInitiates a community proposal check cycle manually\n" "\nExamples:\n" + HelpExampleCli("checkcommunityproposals", "") + HelpExampleRpc("checkcommunityproposals", "")); communityVote.CheckAndRemove(); return NullUniValue; } UniValue getcommunityproposalvotes(const UniValue& params, bool fHelp) { if (params.size() != 1) throw runtime_error( "getcommunityproposalvotes \"proposal-name\"\n" "\nPrint vote information for a community proposal\n" "\nArguments:\n" "1. \"proposal-name\": (string, required) Name of the proposal\n" "\nResult:\n" "[\n" " {\n" " \"mnId\": \"xxxx\", (string) Hash of the masternode's collateral transaction\n" " \"nHash\": \"xxxx\", (string) Hash of the vote\n" " \"Vote\": \"YES|NO\", (string) Vote cast ('YES' or 'NO')\n" " \"nTime\": xxxx, (numeric) Time in seconds since epoch the vote was cast\n" " \"fValid\": true|false, (boolean) 'true' if the vote is valid, 'false' otherwise\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getcommunityproposalvotes", "\"test-proposal\"") + HelpExampleRpc("getcommunityproposalvotes", "\"test-proposal\"")); std::string strProposalName = SanitizeString(params[0].get_str()); UniValue ret(UniValue::VARR); CCommunityProposal* pcommunityProposal = communityVote.FindProposal(strProposalName); if (pcommunityProposal == nullptr) throw runtime_error("Unknown proposal name"); std::map<uint256, CCommunityVote>::iterator it = pcommunityProposal->mapVotes.begin(); while (it != pcommunityProposal->mapVotes.end()) { UniValue bObj(UniValue::VOBJ); bObj.push_back(Pair("mnId", (*it).second.vin.prevout.hash.ToString())); bObj.push_back(Pair("nHash", (*it).first.ToString().c_str())); bObj.push_back(Pair("Vote", (*it).second.GetVoteString())); bObj.push_back(Pair("nTime", (int64_t)(*it).second.nTime)); bObj.push_back(Pair("fValid", (*it).second.fValid)); ret.push_back(bObj); it++; } return ret; } UniValue mncommunityvote(const UniValue& params, bool fHelp) { std::string strCommand; if (params.size() >= 1) { strCommand = params[0].get_str(); } if (fHelp || (params.size() == 3 && (strCommand != "local" && strCommand != "many")) || (params.size() == 4 && strCommand != "alias") || params.size() > 4 || params.size() < 3) throw runtime_error( "mncommunityvote \"local|many|alias\" \"votehash\" \"yes|no\" ( \"alias\" )\n" "\nVote on a community proposal\n" "\nArguments:\n" "1. \"mode\" (string, required) The voting mode. 'local' for voting directly from a masternode, 'many' for voting with a MN controller and casting the same vote for each MN, 'alias' for voting with a MN controller and casting a vote for a single MN\n" "2. \"votehash\" (string, required) The vote hash for the proposal\n" "3. \"votecast\" (string, required) Your vote. 'yes' to vote for the proposal, 'no' to vote against\n" "4. \"alias\" (string, required for 'alias' mode) The MN alias to cast a vote for.\n" "\nResult:\n" "{\n" " \"overall\": \"xxxx\", (string) The overall status message for the vote cast\n" " \"detail\": [\n" " {\n" " \"node\": \"xxxx\", (string) 'local' or the MN alias\n" " \"result\": \"xxxx\", (string) Either 'Success' or 'Failed'\n" " \"error\": \"xxxx\", (string) Error message, if vote failed\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("mncommunityvote", "\"local\" \"ed2f83cedee59a91406f5f47ec4d60bf5a7f9ee6293913c82976bd2d3a658041\" \"yes\"") + HelpExampleRpc("mncommunityvote", "\"local\" \"ed2f83cedee59a91406f5f47ec4d60bf5a7f9ee6293913c82976bd2d3a658041\" \"yes\"")); uint256 hash = ParseHashV(params[1], "parameter 1"); std::string strVote = params[2].get_str(); if (strVote != "yes" && strVote != "no") return "You can only vote 'yes' or 'no'"; int nVote = VOTE_ABSTAIN; if (strVote == "yes") nVote = VOTE_YES; if (strVote == "no") nVote = VOTE_NO; int success = 0; int failed = 0; UniValue resultsObj(UniValue::VARR); if (strCommand == "local") { CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; UniValue statusObj(UniValue::VOBJ); while (true) { if (!masternodeSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(statusObj); break; } CMasternode* pmn = mnodeman.Find(activeMasternode.vin); if (pmn == nullptr) { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to find masternode in list : " + activeMasternode.vin.ToString())); resultsObj.push_back(statusObj); break; } CCommunityVote vote(activeMasternode.vin, hash, nVote); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to sign.")); resultsObj.push_back(statusObj); break; } std::string strError = ""; if (communityVote.UpdateProposal(vote, nullptr, strError)) { success++; communityVote.mapSeenMasternodeCommunityVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "success")); statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Error voting : " + strError)); } resultsObj.push_back(statusObj); break; } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "many") { BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; UniValue statusObj(UniValue::VOBJ); if (!masternodeSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(statusObj); continue; } CMasternode* pmn = mnodeman.Find(pubKeyMasternode); if (pmn == nullptr) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Can't find masternode by pubkey")); resultsObj.push_back(statusObj); continue; } CCommunityVote vote(pmn->vin, hash, nVote); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to sign.")); resultsObj.push_back(statusObj); continue; } std::string strError = ""; if (communityVote.UpdateProposal(vote, nullptr, strError)) { communityVote.mapSeenMasternodeCommunityVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "success")); statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", strError.c_str())); } resultsObj.push_back(statusObj); } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "alias") { std::string strAlias = params[3].get_str(); std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries; mnEntries = masternodeConfig.getEntries(); for (CMasternodeConfig::CMasternodeEntry mne : masternodeConfig.getEntries()) { if (strAlias != mne.getAlias()) continue; std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; UniValue statusObj(UniValue::VOBJ); if(!masternodeSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)){ failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(statusObj); continue; } CMasternode* pmn = mnodeman.Find(pubKeyMasternode); if(pmn == nullptr) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Can't find masternode by pubkey")); resultsObj.push_back(statusObj); continue; } CCommunityVote vote(pmn->vin, hash, nVote); if(!vote.Sign(keyMasternode, pubKeyMasternode)){ failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to sign.")); resultsObj.push_back(statusObj); continue; } std::string strError = ""; if(communityVote.UpdateProposal(vote, nullptr, strError)) { communityVote.mapSeenMasternodeCommunityVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "success")); statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", strError.c_str())); } resultsObj.push_back(statusObj); } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } return NullUniValue; }
[ "konez2k@gmail.com" ]
konez2k@gmail.com
a5c80f00103ad19def76b9f5793e08e40d24fb2f
afeedc93b8108c18eb58065d3843f69d6fcf6437
/EUD-Ops/src/EudOpsTrigGen.cpp
b74e160d801ed537ec28647faa8e5f06f84e8420
[ "MIT" ]
permissive
TheNitesWhoSay/EUD-Ops
649a5d1f32e275ae5b38f0b1bd5e4874414668f1
99846f59bb96b3d90c071b0216fef9d407d82f1c
refs/heads/master
2022-03-30T11:36:16.470233
2018-01-01T13:52:55
2018-01-01T13:52:55
113,746,442
0
0
null
null
null
null
UTF-8
C++
false
false
18,370
cpp
#include "EudOpsTrigGen.h" #include <stdarg.h> #include <cstdarg> #include <cmath> bool EudOpsTrigGen::GenerateNoArg(std::string &output, GenerationData genData, EudOpDef def, EudAddress eudAddress) { output = "Generate case for " + def.eudOpName + " not found!"; return false; } bool EudOpsTrigGen::GenerateWithConstant(std::string &output, GenerationData genData, EudOpDef def, EudAddress eudAddress, u32 constant) { EudOpsTrigGen eudOpsGen = EudOpsTrigGen(genData, eudAddress); bool caseNotFound = false; bool success = false; switch (def.eudOp) { case EudOp::SetToConstant: success = eudOpsGen.setToConstant(constant); break; case EudOp::CheckEqual: success = eudOpsGen.checkEqual(constant); break; case EudOp::CheckAtLeast: success = eudOpsGen.checkAtLeast(constant); break; case EudOp::CheckAtMost: success = eudOpsGen.checkAtMost(constant); break; case EudOp::CheckGreaterThan: success = eudOpsGen.checkGreaterThan(constant); break; case EudOp::CheckLessThan: success = eudOpsGen.checkLessThan(constant); break; default: caseNotFound = true; break; } if (caseNotFound) { output = "Generate case for " + def.eudOpName + " not found!"; return false; } else if ( success ) { eudOpsGen.end(); eudOpsGen.gen = TextTrigGenerator(); std::string trigString(""); return eudOpsGen.gen.GenerateTextTrigs(eudOpsGen.dummyMap, output); } return success; } bool EudOpsTrigGen::GenerateWithDeathCounter(std::string &output, GenerationData genData, EudOpDef def, EudAddress eudAddress, DeathCounter deathCounter) { EudOpsTrigGen eudOpsGen = EudOpsTrigGen(genData, eudAddress); bool caseNotFound = false; bool success = false; switch (def.eudOp) { case EudOp::SetToDeaths: success = eudOpsGen.setToDeaths(deathCounter); break; case EudOp::CopyToDeaths: success = eudOpsGen.copyToDeaths(deathCounter); break; default: caseNotFound = true; break; } if (caseNotFound) { output = "Generate case for " + def.eudOpName + " not found!"; return false; } else if ( success ) { eudOpsGen.end(); eudOpsGen.gen = TextTrigGenerator(); std::string trigString(""); return eudOpsGen.gen.GenerateTextTrigs(eudOpsGen.dummyMap, output); } return success; } bool EudOpsTrigGen::setToConstant(u32 constant) { u32 address = targetAddress.address; u32 bitLength = targetAddress.bitLength; u32 bitsBeforeAddress = 8 * (address % 4 == 0 ? 0 : 3-address % 4); u32 bitsAfterAddress = 32 - bitsBeforeAddress - bitLength; DeathCounter slackSpace = genData.getSlackSpace(); u32 bit = 0; for (; bit < bitsBeforeAddress; bit++) stripBit(slackSpace, bit, true); if (bitsAfterAddress > 0) { u32 bitsBeforeRemainder = bit + bitLength; for (; bit < bitsBeforeRemainder; bit++) stripBit(slackSpace, bit, false); u32 valueToAdd = constant << bitsAfterAddress; if (valueToAdd != 0) { trigger(owners); always(); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Add, valueToAdd); } } else // bitsAfterAddress == 0 { trigger(owners); always(); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::SetTo, constant); } while (!restoreActions.empty()) { RestoreAction action = restoreActions.top(); restoreActions.pop(); trigger(owners); deaths(slackSpace.playerId, slackSpace.unitId, NumericComparison::AtLeast, action.modification); setDeaths(slackSpace.playerId, slackSpace.unitId, NumericModifier::Subtract, action.modification); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Add, action.modification); } return true; } bool EudOpsTrigGen::setToDeaths(DeathCounter srcValue) { u32 address = targetAddress.address; u32 bitLength = targetAddress.bitLength; u32 bitsBeforeAddress = 8 * (address % 4 == 0 ? 0 : 3-address % 4); u32 bitsAfterAddress = 32 - bitsBeforeAddress - bitLength; DeathCounter slackSpace = genData.getSlackSpace(); u32 bit = 0; for (; bit < bitsBeforeAddress; bit++) stripBit(slackSpace, bit, true); u32 bitsBeforeRemainder = bit + bitLength; for (; bit < bitLength; bit++) stripBit(slackSpace, bit, false); for (bit = 0; bit < bitLength; bit++) { trigger(owners); u32 unshiftedValue = pow(2, bitLength-bit-1); u32 shiftedValue = unshiftedValue << bitsAfterAddress; deaths(srcValue.playerId, srcValue.unitId, NumericComparison::AtLeast, unshiftedValue); setDeaths(srcValue.playerId, srcValue.unitId, NumericModifier::Subtract, unshiftedValue); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Add, shiftedValue); } while (!restoreActions.empty()) { RestoreAction action = restoreActions.top(); restoreActions.pop(); trigger(owners); deaths(slackSpace.playerId, slackSpace.unitId, NumericComparison::AtLeast, action.modification); setDeaths(slackSpace.playerId, slackSpace.unitId, NumericModifier::Subtract, action.modification); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Add, action.modification); } return true; } bool EudOpsTrigGen::copyToDeaths(DeathCounter destValue) { u32 address = targetAddress.address; u32 bitLength = targetAddress.bitLength; u32 bitsBeforeAddress = 8 * (address % 4 == 0 ? 0 : 3-address % 4); u32 bitsAfterAddress = 32 - bitsBeforeAddress - bitLength; DeathCounter slackSpace = genData.getSlackSpace(); u32 bit = 0; for (; bit < bitsBeforeAddress; bit++) stripBit(slackSpace, bit, true); u32 bitsBeforeRemainder = bit + bitLength; for (; bit < bitLength; bit++) stripBit(slackSpace, bit, false); for (bit = 0; bit < bitLength; bit++) { trigger(owners); u32 unshiftedValue = pow(2, bitLength-bit-1); u32 shiftedValue = unshiftedValue << bitsAfterAddress; deaths(targetAddress.playerId, targetAddress.unitId, NumericComparison::AtLeast, shiftedValue); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Subtract, shiftedValue); setDeaths(destValue.playerId, destValue.unitId, NumericModifier::Add, shiftedValue); } while (!restoreActions.empty()) { RestoreAction action = restoreActions.top(); restoreActions.pop(); trigger(owners); deaths(slackSpace.playerId, slackSpace.unitId, NumericComparison::AtLeast, action.modification); setDeaths(slackSpace.playerId, slackSpace.unitId, NumericModifier::Subtract, action.modification); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Add, action.modification); } return true; } bool EudOpsTrigGen::checkEqual(u32 constant) { u32 address = targetAddress.address; u32 bitLength = targetAddress.bitLength; u32 bitsBeforeAddress = 8 * (address % 4 == 0 ? 0 : 3-address % 4); u32 bitsAfterAddress = 32 - bitsBeforeAddress - bitLength; DeathCounter slackSpace = genData.getSlackSpace(); u32 bit = 0; for (; bit < bitsBeforeAddress; bit++) stripBit(slackSpace, bit, true); u32 valueMin = constant << bitsAfterAddress; u32 valueMax = ((constant+1) << bitsAfterAddress)-1; trigger(owners); if ( valueMin == valueMax ) deaths(targetAddress.playerId, targetAddress.unitId, NumericComparison::Exactly, valueMin); else { deaths(targetAddress.playerId, targetAddress.unitId, NumericComparison::AtLeast, valueMin); deaths(targetAddress.playerId, targetAddress.unitId, NumericComparison::AtMost, valueMax); } setSwitch(0, SwitchModifier::Set); while (!restoreActions.empty()) { RestoreAction action = restoreActions.top(); restoreActions.pop(); trigger(owners); deaths(slackSpace.playerId, slackSpace.unitId, NumericComparison::AtLeast, action.modification); setDeaths(slackSpace.playerId, slackSpace.unitId, NumericModifier::Subtract, action.modification); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Add, action.modification); } return true; } bool EudOpsTrigGen::checkAtLeast(u32 constant) { u32 address = targetAddress.address; u32 bitLength = targetAddress.bitLength; u32 bitsBeforeAddress = 8 * (address % 4 == 0 ? 0 : 3-address % 4); u32 bitsAfterAddress = 32 - bitsBeforeAddress - bitLength; DeathCounter slackSpace = genData.getSlackSpace(); u32 bit = 0; for (; bit < bitsBeforeAddress; bit++) stripBit(slackSpace, bit, true); u32 valueMin = constant << bitsAfterAddress; trigger(owners); deaths(targetAddress.playerId, targetAddress.unitId, NumericComparison::AtLeast, valueMin); setSwitch(0, SwitchModifier::Set); while (!restoreActions.empty()) { RestoreAction action = restoreActions.top(); restoreActions.pop(); trigger(owners); deaths(slackSpace.playerId, slackSpace.unitId, NumericComparison::AtLeast, action.modification); setDeaths(slackSpace.playerId, slackSpace.unitId, NumericModifier::Subtract, action.modification); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Add, action.modification); } return true; } bool EudOpsTrigGen::checkAtMost(u32 constant) { u32 address = targetAddress.address; u32 bitLength = targetAddress.bitLength; u32 bitsBeforeAddress = 8 * (address % 4 == 0 ? 0 : 3-address % 4); u32 bitsAfterAddress = 32 - bitsBeforeAddress - bitLength; DeathCounter slackSpace = genData.getSlackSpace(); u32 bit = 0; for (; bit < bitsBeforeAddress; bit++) stripBit(slackSpace, bit, true); u32 valueMax = ((constant+1) << bitsAfterAddress)-1; trigger(owners); deaths(targetAddress.playerId, targetAddress.unitId, NumericComparison::AtMost, valueMax); setSwitch(0, SwitchModifier::Set); while (!restoreActions.empty()) { RestoreAction action = restoreActions.top(); restoreActions.pop(); trigger(owners); deaths(slackSpace.playerId, slackSpace.unitId, NumericComparison::AtLeast, action.modification); setDeaths(slackSpace.playerId, slackSpace.unitId, NumericModifier::Subtract, action.modification); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Add, action.modification); } return true; } bool EudOpsTrigGen::checkGreaterThan(u32 constant) { u32 address = targetAddress.address; u32 bitLength = targetAddress.bitLength; u32 bitsBeforeAddress = 8 * (address % 4 == 0 ? 0 : 3-address % 4); u32 bitsAfterAddress = 32 - bitsBeforeAddress - bitLength; DeathCounter slackSpace = genData.getSlackSpace(); u32 bit = 0; for (; bit < bitsBeforeAddress; bit++) stripBit(slackSpace, bit, true); u32 valueMin = (constant+1) << bitsAfterAddress; trigger(owners); deaths(targetAddress.playerId, targetAddress.unitId, NumericComparison::AtLeast, valueMin); setSwitch(0, SwitchModifier::Set); while (!restoreActions.empty()) { RestoreAction action = restoreActions.top(); restoreActions.pop(); trigger(owners); deaths(slackSpace.playerId, slackSpace.unitId, NumericComparison::AtLeast, action.modification); setDeaths(slackSpace.playerId, slackSpace.unitId, NumericModifier::Subtract, action.modification); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Add, action.modification); } return true; } bool EudOpsTrigGen::checkLessThan(u32 constant) { u32 address = targetAddress.address; u32 bitLength = targetAddress.bitLength; u32 bitsBeforeAddress = 8 * (address % 4 == 0 ? 0 : 3-address % 4); u32 bitsAfterAddress = 32 - bitsBeforeAddress - bitLength; DeathCounter slackSpace = genData.getSlackSpace(); u32 bit = 0; for (; bit < bitsBeforeAddress; bit++) stripBit(slackSpace, bit, true); u32 valueMax = (constant << bitsAfterAddress)-1; trigger(owners); deaths(targetAddress.playerId, targetAddress.unitId, NumericComparison::AtMost, valueMax); setSwitch(0, SwitchModifier::Set); while (!restoreActions.empty()) { RestoreAction action = restoreActions.top(); restoreActions.pop(); trigger(owners); deaths(slackSpace.playerId, slackSpace.unitId, NumericComparison::AtLeast, action.modification); setDeaths(slackSpace.playerId, slackSpace.unitId, NumericModifier::Subtract, action.modification); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Add, action.modification); } return true; } void EudOpsTrigGen::stripBit(DeathCounter slackSpace, u32 bit, bool restore) { s64 change = pow(2, (31 - bit)); trigger(owners); deaths(targetAddress.playerId, targetAddress.unitId, NumericComparison::AtLeast, change); setDeaths(targetAddress.playerId, targetAddress.unitId, NumericModifier::Subtract, change); if (restore) { setDeaths(slackSpace.playerId, slackSpace.unitId, NumericModifier::Add, change); restoreActions.push(RestoreAction(slackSpace, change)); } } void EudOpsTrigGen::trigger(u8* players) { if ( triggerCount > 0 ) dummyMap->addTrigger(currTrig); triggerCount++; didComment = false; currTrig = Trigger(); memcpy(currTrig.players, players, 28); /*out << "Trigger(" << players << "){" << endl << "Conditions:" << endl;*/ } void EudOpsTrigGen::end() { if ( triggerCount > 0 ) dummyMap->addTrigger(currTrig); } // Accumulate // Always bool EudOpsTrigGen::always() { Condition condition = Condition(ConditionId::Always); return currTrig.addCondition(condition); //out << " Always();" << endl; } // Bring // Command // Command the Least // Command the Least At // Command the Most // Commands the Most At // Countdown Timer // Deaths bool EudOpsTrigGen::deaths(u32 playerId, u32 unitId, NumericComparison numericComparison, u32 amount) { Condition condition(ConditionId::Deaths); condition.players = playerId; condition.unitID = unitId; condition.comparison = (u8)numericComparison; condition.amount = amount; return currTrig.addCondition(condition); //out << " Deaths(\"" << player << "\", \"" << unit << "\", " << mod << ", " << amount << ");" << endl; } // Elapsed Time // Highest Score // Kill // Least Kills // Least Resources // Lowest Score // Memory bool EudOpsTrigGen::memory(u32 address, NumericComparison numericComparison, u32 value) { Condition condition(ConditionId::Deaths); condition.players = address; condition.unitID = 0; condition.comparison = (u8)numericComparison; condition.amount = value; return currTrig.addCondition(condition); //out << " Memory(" << address << ", " << mod << ", " << value << ");" << endl; } // Most Kills // Most Resources // Never // Opponents // Score // Switch bool EudOpsTrigGen::switchState(u32 switchNum, SwitchState state) { Condition condition(ConditionId::Switch); condition.typeIndex = switchNum; condition.comparison = (u8)state; return currTrig.addCondition(condition); //out << " Switch(\"" << switchTitle << "\", " << state << ");" << endl; } // Center View // Comment bool EudOpsTrigGen::comment(const std::string &text) { bool success = false; if (!noComments) { ChkdString str(emptyComments ? "" : text); Action action(ActionId::Comment); u32 stringNum = 0; if ( dummyMap->addString<u32>(ChkdString(text), stringNum, false) ) { action.stringNum = stringNum; success = currTrig.addAction(action); } //out << " Comment(\"\");" << endl; //out << " Comment(\"" << text << "\");" << endl; } didComment = true; return success; } // Create Unit // Create Unit with Properties // Defeat // Display Text Message // Draw // Give Units to Player // Kill Unit // Kill Unit At Location // Leaderboard (Control At Location) // Leaderboard (Control) // Leaderboard (Greed) // Leaderboard (Kills) // Leaderboard (Points) // Leaderboard (Resources) // Leaderboard Computer Players(State) // Leaderboard Goal (Control At Location) // Leaderboard Goal (Control) // Leaderboard Goal (Kills) // Leaderboard Goal (Points) // Leaderboard Goal (Resources) // Minimap Ping // Modify Unit Energy // Modify Unit Hanger Count // Modify Unit Hit Points // Modify Unit Resource Amount // Modify Unit Shield Points // Move Location // Move Unit // Mute Unit Speech // Order // Pause Game // Pause Timer // Play WAV // Preserve Trigger bool EudOpsTrigGen::preserveTrigger() { Action action = Action(ActionId::PreserveTrigger); return currTrig.addAction(action); //out << " Preserve Trigger();" << endl; } // Remove Unit // Remove Unit At Location // Run AI Script // Run AI Script At Location // Set Alliance Status // Set Countdown Timer // Set Deaths bool EudOpsTrigGen::setDeaths(u32 playerId, u32 unitId, NumericModifier numericModifier, u32 value) { Action action = Action(ActionId::SetDeaths); action.group = playerId; action.type = unitId; action.type2 = (u8)numericModifier; action.number = value; return currTrig.addAction(action); } // Set Doodad State // Set Invincibility // Set Mission Objectives // Set Next Scenario // Set Resources // Set Score // Set Switch bool EudOpsTrigGen::setSwitch(u32 switchNum, SwitchModifier switchModifier) { Action action = Action(ActionId::SetSwitch); action.number = switchNum; action.type2 = (u8)switchModifier; return currTrig.addAction(action); //out << " Set Switch(\"" << Switch << "\", " << state << ");" << endl; } // Talking Portrait // Transmission // Unmute Unit Speech // Unpause Game // Unpause Timer // Victory // Wait
[ "forwardtojj@gmail.com" ]
forwardtojj@gmail.com
117203c03f4b5bcffb18b60104ae86af7cd5d395
d04f89b08c66a493859e81338938b1fdc8155a7d
/Laskari3/Laskari3/Ex2.cpp
2206e8e50d971b4ed053c9c5d384d6f1858faeca
[]
no_license
AlexeySofiev/MonteCarlo
ee2ce747a26da3eac4380e1173fbdf41226eb82f
33d876f002f6b7db0583bea60076c45c6340d44f
refs/heads/master
2021-01-13T05:24:59.846073
2017-03-06T07:26:18
2017-03-06T07:26:18
81,415,892
0
0
null
null
null
null
UTF-8
C++
false
false
2,176
cpp
#include <iostream> #include <math.h> using namespace std; void init_genrand64(unsigned long long seed); double genrand64_real3(void); int Ex2() { cout << "Exercise 2" << endl; init_genrand64(431); genrand64_real3(); long double R=0.0; double dMinRatio=double(pow(10,7)), dMaxRatio=0.0, dMeanRatio=0.0; double dTemp=0.0; int iBins=40; double dBinLength=1.0/double(iBins); //symmetricy double aPosition[15]={-1}; double aTempPosition[15]={-1}; int iHit, iMiss; int iMaxRepeat=pow(10,1); for (int N=1;N<16; N++){ // cout << "N: "<< N << endl; // for each N iHit=0; iMiss=0; aPosition[15]={-1}; dMinRatio=double(pow(10,7)), dMaxRatio=0.0, dMeanRatio=0.0; for(int iRepeat=0; iRepeat<iMaxRepeat;iRepeat++){ for(int i=0; i<pow(iBins, N)+1;i++){ R=0; for(int iArrayPass=0; iArrayPass<N+1; iArrayPass++){ aTempPosition[iArrayPass]=aPosition[iArrayPass]+genrand64_real3()*dBinLength; R=R+pow(aTempPosition[iArrayPass],2); } if(R<1){ iHit++; }else{ iMiss++; } aPosition[0]+=dBinLength; for(int iArrayPass=0; iArrayPass<N; iArrayPass++){ if(aPosition[iArrayPass]>0){ //symmetricy aPosition[iArrayPass]=-1; aPosition[iArrayPass+1]+=dBinLength; } } //aMatrix[i]=genrand64_real3(); } // cout << "N: " << N <<", Volume: " << double(iHit)/double(iMiss + iHit) *double(pow(2,N))<< endl; dTemp=double(iHit)/(double(iHit)+double(iMiss))*double(pow(2,N)); if(dTemp>dMaxRatio){dMaxRatio=dTemp;} if(dTemp<dMinRatio){dMinRatio=dTemp;} dMeanRatio+=dTemp; } cout <<"N: "<<N << ", Volyymi: "<< dMeanRatio/double(iMaxRepeat) << "+-" << max(dMeanRatio/double(iMaxRepeat) - dMinRatio, dMaxRatio - dMeanRatio/double(iMaxRepeat)) << endl; } return 0; }
[ "sofiev@localhost.localdomain" ]
sofiev@localhost.localdomain
d721da4733186be3260697e52b36ff18cd79b6c4
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/Rfast2/src/col_row_utilities.cpp
ea8afad50caa9f2875011ac53db50b08fa99b496
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
C++
false
false
6,832
cpp
#include <RcppArmadillo.h> #include "templates.h" using namespace Rcpp; /*template<class T> void group_col_vars_h(SEXP& x,SEXP& gr,const int length_unique,Environment& result){ const int ncl=Rf_ncols(x),nrw=Rf_nrows(x); SEXP f=PROTECT(Rf_allocMatrix(TYPEOF(x),length_unique,ncl)); SEXP f2=PROTECT(Rf_allocMatrix(TYPEOF(x),length_unique,ncl)); int *ggr=INTEGER(gr); T *ff=(T*)DATAPTR(f),*ff2=(T*)DATAPTR(f2),*xx=(T*)DATAPTR(x); for(int j=0;j<length_unique*ncl;++j){ ff[j]=0; ff2[j]=0; } for(int j=0;j<ncl;++j){ const int col_index_f=j*length_unique,col_index_x=j*nrw; for(int i=0;i<nrw;++i){ int ind_gr=ggr[i]-1; double v=xx[i+col_index_x]; //tmp*=tmp; ff[ind_gr+col_index_f]+=ff[ind_gr+col_index_f]*v; ff2[ind_gr+col_index_f]+=(ff2[ind_gr+col_index_f]+v)*(ff2[ind_gr+col_index_f]+v); } } result["x"]=f; result["x2"]=f2; UNPROTECT(2); }*/ //[[Rcpp::export]] SEXP group_col(SEXP x,SEXP y,const int length_unique,const string method="sum"){ if(method == "sum"){ if(Rf_isInteger(x)) return group_col_h<int,madd<int,int>>(x,y,length_unique); else if(Rf_isReal(x)) return group_col_h<double,madd<double,double>>(x,y,length_unique); else stop("Error: Unsupported type of matrix."); }else if(method == "max"){ if(Rf_isInteger(x)) return group_col_h<int,mmax<int,int>,INT_MIN>(x,y,length_unique); else if(Rf_isReal(x)) return group_col_h<double,mmax<double,double>,INT_MIN>(x,y,length_unique); else stop("Error: Unsupported type of matrix."); }else if(method == "min"){ if(Rf_isInteger(x)) return group_col_h<int,mmin<int,int>,INT_MAX>(x,y,length_unique); else if(Rf_isReal(x)) return group_col_h<double,mmin<double,double>,INT_MAX>(x,y,length_unique); else stop("Error: Unsupported type of matrix."); }/*else if(method == "var"){ if(Rf_isInteger(x)) group_col_vars_h<int>(x,y,length_unique,result); else if(Rf_isReal(x)) group_col_vars_h<double>(x,y,length_unique,result); else stop("Error: Unsupported type of matrix."); return R_NilValue; }*/else if(method == "median"){ if(Rf_isInteger(x)) return group_col_med_h<int>(x,y,length_unique); else if(Rf_isReal(x)) return group_col_med_h<double>(x,y,length_unique); else stop("Error: Unsupported type of matrix."); } stop("Error: Unsupported method.\n"); return R_NilValue; } RcppExport SEXP Rfast2_col_group(SEXP x,SEXP y,SEXP length_uniqueSEXP,SEXP methodSEXP){ BEGIN_RCPP RObject __result; RNGScope __rngScope; traits::input_parameter< const int >::type length_unique(length_uniqueSEXP); traits::input_parameter< const string >::type method(methodSEXP); __result = group_col(x,y,length_unique,method); return __result; END_RCPP } /***********************************************************************************/ mat col_Quantile(NumericMatrix X,NumericVector Probs,const bool parallel){ mat x(X.begin(),X.nrow(),X.ncol(),false); colvec probs(Probs.begin(),Probs.size(),false); mat f(probs.n_elem,x.n_cols); if(parallel){ #pragma omp parallel for for(unsigned int i=0;i<f.n_cols;++i) f.col(i)=Quantile<colvec,colvec>(x.col(i),probs); }else{ for(unsigned int i=0;i<f.n_cols;++i) f.col(i)=Quantile<colvec,colvec>(x.col(i),probs); } return f; } RcppExport SEXP Rfast2_col_Quantile(SEXP xSEXP,SEXP ProbsSEXP,SEXP parallelSEXP){ BEGIN_RCPP RObject __result; RNGScope __rngScope; traits::input_parameter< NumericMatrix >::type x(xSEXP); traits::input_parameter< NumericVector >::type Probs(ProbsSEXP); traits::input_parameter< const bool >::type parallel(parallelSEXP); __result = col_Quantile(x,Probs,parallel); return __result; END_RCPP } /***********************************************************************************/ mat row_Quantile(NumericMatrix X,NumericVector Probs,const bool parallel){ mat x(X.begin(),X.nrow(),X.ncol(),false); colvec probs(Probs.begin(),Probs.size(),false); mat f(x.n_rows,probs.n_elem); if(parallel){ #pragma omp parallel for for(unsigned int i=0;i<f.n_rows;++i) f.row(i)=Quantile<rowvec,rowvec>(x.row(i),probs); }else{ for(unsigned int i=0;i<f.n_rows;++i) f.row(i)=Quantile<rowvec,rowvec>(x.row(i),probs); } return f; } RcppExport SEXP Rfast2_row_Quantile(SEXP xSEXP,SEXP ProbsSEXP,SEXP parallelSEXP){ BEGIN_RCPP RObject __result; RNGScope __rngScope; traits::input_parameter< NumericMatrix >::type x(xSEXP); traits::input_parameter< NumericVector >::type Probs(ProbsSEXP); traits::input_parameter< const bool >::type parallel(parallelSEXP); __result = row_Quantile(x,Probs,parallel); return __result; END_RCPP } /************************************************************************************/ NumericVector colTrimMean(NumericMatrix X,const double a=0.05,const bool parallel=false){ mat x(X.begin(),X.nrow(),X.ncol(),false); NumericVector f(x.n_cols); colvec ff(f.begin(),f.size(),false); if(parallel){ #pragma omp parallel for for(unsigned int i=0;i<x.n_cols;++i) ff(i)=trimmean_h<colvec>(x.col(i),a); }else{ for(unsigned int i=0;i<x.n_cols;++i) ff(i)=trimmean_h<colvec>(x.col(i),a); } return f; } RcppExport SEXP Rfast2_colTrimMean(SEXP xSEXP,SEXP aSEXP,SEXP parallelSEXP){ BEGIN_RCPP RObject __result; RNGScope __rngScope; traits::input_parameter< NumericMatrix >::type X(xSEXP); traits::input_parameter< const double >::type a(aSEXP); traits::input_parameter< const bool >::type parallel(parallelSEXP); __result = colTrimMean(X,a,parallel); return __result; END_RCPP } NumericVector rowTrimMean(NumericMatrix X,const double a=0.05,const bool parallel=false){ mat x(X.begin(),X.nrow(),X.ncol(),false); NumericVector f(x.n_rows); colvec ff(f.begin(),f.size(),false); if(parallel){ #pragma omp parallel for for(unsigned int i=0;i<x.n_rows;++i) ff(i)=trimmean_h<rowvec>(x.row(i),a); }else{ for(unsigned int i=0;i<x.n_rows;++i) ff(i)=trimmean_h<rowvec>(x.row(i),a); } return f; } RcppExport SEXP Rfast2_rowTrimMean(SEXP xSEXP,SEXP aSEXP,SEXP parallelSEXP){ BEGIN_RCPP RObject __result; RNGScope __rngScope; traits::input_parameter< NumericMatrix >::type X(xSEXP); traits::input_parameter< const double >::type a(aSEXP); traits::input_parameter< const bool >::type parallel(parallelSEXP); __result = rowTrimMean(X,a,parallel); return __result; END_RCPP }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
a5861fb1f81a183d87f937a5878a255617df89cb
e04f52ed50f42ad255c66d7b6f87ba642f41e125
/appseed/aura/graphics/visual/detect_8bit_borders.cpp
d65a88dccdd9c8990594411f46abde55d686b3fc
[]
no_license
ca2/app2018
6b5f3cfecaa56b0e8c8ec92ed26e8ce44f9b44c0
89e713c36cdfb31329e753ba9d7b9ff5b80fe867
refs/heads/main
2023-03-19T08:41:48.729250
2018-11-15T16:27:31
2018-11-15T16:27:31
98,031,531
3
0
null
null
null
null
UTF-8
C++
false
false
3,722
cpp
#include "framework.h" #define pixel(x, y) (ba[(pointer->m_rect.height() - (y) - 1) * iScan + (x)]) bool detect_8bit_borders(::draw2d::dib * pdibCompose, ::visual::dib_sp::array * pdiba, ::visual::dib_sp::pointer * pointer, int uFrameIndex, byte * ba, int iScan, array < COLORREF > & cra, int transparentIndex) { COLORREF cr; COLORREF crBack = 0; ::count cTransparent = 0; bool bTransparent; ::count c = 0; int64_t iR = 0; int64_t iG = 0; int64_t iB = 0; //int iLight = 0; //int iDark = 0; // Roughly detect colors on transparency borders... // ... first, at horizontal orientation... for (index y = 0; y < pointer->m_dib->m_size.cy; y++) { bTransparent = true; for (index x = 0; x < pointer->m_dib->m_size.cx; x++) { index iIndex = pixel(x, y); index iNextIndex = -1; if (x < pointer->m_dib->m_size.cx - 1) { iNextIndex = pixel(x + 1, y); } if (iIndex >= cra.get_count()) { continue; } if (bTransparent) { if (iIndex == transparentIndex) { cTransparent++; continue; } else { cr = cra[iIndex]; bTransparent = false; } } else { if (iNextIndex == transparentIndex) { cr = cra[iIndex]; bTransparent = true; } else { continue; } } iR += argb_get_r_value(cr); iG += argb_get_g_value(cr); iB += argb_get_b_value(cr); c++; } } // ... then, at vertical orientation... for (index x = 0; x < pointer->m_dib->m_size.cx; x++) { bTransparent = true; for (index y = 0; y < pointer->m_dib->m_size.cy; y++) { index iIndex = pixel(x, y); index iNextIndex = -1; if (y < pointer->m_dib->m_size.cy - 1) { iNextIndex = pixel(x, y + 1); } if (iIndex >= cra.get_count()) { continue; } if (bTransparent) { if (iIndex == transparentIndex) { continue; } else { cr = cra[iIndex]; bTransparent = false; } } else { if (iNextIndex == transparentIndex) { cr = cra[iIndex]; bTransparent = true; } else { continue; } } iR += argb_get_r_value(cr); iG += argb_get_g_value(cr); iB += argb_get_b_value(cr); c++; } } // and if detected transparency, roughly calculate if average border color is dark or light. if (cTransparent <= 0) { crBack = ARGB(255, 127, 127, 127); pdiba->m_bTransparent = false; } else { byte bAverage = (byte)((iR + iG + iB) / (3 * c)); double bLite = 127 + 63; double bDark = 127 - 63; if (bAverage > bLite) // Light { crBack = ARGB(255, 255, 255, 255); pdiba->m_bTransparent = true; } else if (bAverage < bDark) { crBack = ARGB(255, 0, 0, 0); pdiba->m_bTransparent = true; } else { crBack = ARGB(255, 127, 127, 127); pdiba->m_bTransparent = false; } } pdiba->m_crTransparent = crBack; return true; }
[ "camilo@ca2.email" ]
camilo@ca2.email
bec2d8f2ec62867adf65d15a1a744adae2f3b923
fc76556b01d2efa1b4f83da4172472cb6efe91ca
/kernel/text_screen.h
8f76fb88174d4cacb94835168c5c940de0f72bb5
[ "MIT" ]
permissive
mras0/attos
fda0f798b433f116330f5e7464017d130608fe92
43344666108a427799684019f58a4b1cbb08cb91
refs/heads/master
2020-05-21T15:00:18.809593
2016-09-24T13:31:31
2016-09-24T13:31:31
62,079,760
2
0
null
null
null
null
UTF-8
C++
false
false
611
h
#ifndef ATTOS_VGA_TEXT_SCREEN_H #define ATTOS_VGA_TEXT_SCREEN_H #include <attos/out_stream.h> namespace attos { namespace vga { class text_screen : public out_stream { public: explicit text_screen(); text_screen(const text_screen&) = delete; text_screen& operator=(const text_screen&) = delete; void clear(); virtual void write(const void* data, size_t n) override; private: int x_ = 0; int y_ = 0; uint8_t attr_ = 0x07; void put(int c); void newline(); void clear_line(int y); void set_cursor(); }; } } // namespace attos::vga #endif
[ "michaelrasmussen1337@gmail.com" ]
michaelrasmussen1337@gmail.com
3e5beea90679f7b1f43d3cfe9093bcc5a3c493a4
fdfc2b3438a8fc210eaec23672ccbe561ce36b07
/poc/openepos/.svn/pristine/3e/3e5beea90679f7b1f43d3cfe9093bcc5a3c493a4.svn-base
36512d86e002f1dd0fafb7f3573a24371a2a6875
[]
no_license
soldi/mestrado
e26dac3dbc5f1ff88f36765a6ef239c9520460bf
e9e3d33ec7f361de4637aeb8f9f8e7996dcf4d56
refs/heads/master
2021-01-15T11:28:49.113106
2015-10-30T15:31:56
2015-10-30T15:31:56
16,246,005
0
1
null
null
null
null
UTF-8
C++
false
false
385
// EPOS-- ATMega128 Mediator Implementation #include <mach/atmega128/ic.h> __BEGIN_SYS ATMega128_IC::Interrupt_Handler ATMega128_IC::_int_vector[INTS]; __END_SYS __USING_SYS extern "C" void __epos_call_handler(char offset); extern "C" void __epos_call_handler(char offset) { IC::Interrupt_Handler handler = IC::int_vector(offset); if (handler != 0) handler(0); }
[ "soldi" ]
soldi
ae5039c4dd05ee02c12ab14ce6e15261d0e0eae4
ab8a81faf0288d9b5ec651bd3f5b758087018390
/Transform.h
4dcdc60f3a830e5bf0f27176c55a4fd0d752f67b
[]
no_license
nybblr/cs4496-project-4
c661b1264fbf79b4a95803a595a738dbcff61591
882ea70e274a6bca2841645493c86ead49629c46
refs/heads/master
2020-04-09T20:18:44.610863
2013-05-01T15:33:12
2013-05-01T15:33:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
941
h
#ifndef __TRANSFORM_H__ #define __TRANSFORM_H__ #include "vl/VLd.h" class Dof; class Transform { public: virtual void Apply() = 0; virtual ~Transform() {} virtual Mat4d GetTransform(){Mat4d m=vl_zero;return m;} // return a 4x4 affine transformation evaluated at the current dof virtual bool IsDof() { return false; } // if this transformation involves dof, returns true; otherwise false virtual int GetDofCount() { return 0; } // returns the number of dofs involved in this transformation virtual int GetIndex() { return mIndex; } // retursn the type of this transformation (i.e, scale, rotateEuler, or translate) virtual Dof* GetDof( int dof ) { return 0; } // returns a pointer to the specified dof int mIndex; // virtual bool ContainsDof( Dof* dof ) { return false; } virtual Mat4d GetDeriv(int dof){ Mat4d m=vl_zero; return m;} // TODO: implement this function for each subclass }; #endif
[ "me@nybblr.com" ]
me@nybblr.com
42269a1c82412c9426a94fcb7ce0031bb30419e7
df61634940f7017cf82fca3a56b6d2cd2f794a54
/Sample/Sample/HelloLevel2D.h
456bbb42d88e756eb37000cc061711a10ef5a947
[]
no_license
Ukun115/CarBOOM
af323a099ca0797b5c82a0622ec4d67450732666
70e3ea83897712579f728817b449415706fb6f48
refs/heads/master
2023-07-17T21:51:44.939018
2021-08-26T02:55:23
2021-08-26T02:55:23
373,708,624
2
0
null
null
null
null
SHIFT_JIS
C++
false
false
414
h
#pragma once #include "level2D/Level2D.h" /// <summary> /// レベル2D処理のサンプルクラス。 /// </summary> class HelloLevel2D : public IGameObject { bool Start() override; void Update() override; void Render(RenderContext& rc) override; private: Level2D m_level2D; //レベル2D。 Sprite m_sprite; //スプライト。 Vector3 m_position; //座標。 Vector3 m_scale; //大きさ。 };
[ "kbc18b09@stu.kawahara.ac.jp" ]
kbc18b09@stu.kawahara.ac.jp
0ab68c8524b43947a04bd58daf1d1ebcfe405ec8
51247d7a36526e81d720727d0328ceab2fc4e077
/RedFogMagic/RedFogMagic/Type.hpp
146c6d6daa6410018dff9b9599bf4200458e50f1
[]
no_license
RedFog/RedFogMagic
c6b9ca0380c3a5de0389c7c8c74035a1e07ee568
7ce40bb4c8ffda7a1345eb52e8b6897ae4628fdf
refs/heads/master
2021-03-12T20:38:29.546056
2014-10-22T13:09:40
2014-10-22T13:09:40
25,562,253
0
1
null
null
null
null
GB18030
C++
false
false
37,053
hpp
#pragma once #include "PMP.hpp" #include <functional> #define $lf(item) Types::FunctorType<decltype(item)>::Result namespace Types{ template<typename...>struct TypeArray; template<size_t...>struct NumArray; template<char...>struct TMPString; template<typename Type, Type...>struct ScalarArray; //result: <bool> 类型表层上是否有const标记 //Result: <type> 表层上去除const标记的类型 template<typename _1>struct ConstType{ static const bool result = false; typedef _1 Result; }; template<typename _1>struct ConstType<_1 const>{ static const bool result = true; typedef _1 Result; }; //result: <bool> 类型表层上是否有volatile标记 //Result: <type> 表层上去除volatile标记的类型 template<typename _1>struct VolatileType{ static const bool result = false; typedef _1 Result; }; template<typename _1>struct VolatileType<_1 volatile>{ static const bool result = true; typedef _1 Result; }; //Result: <type> 去除类型表层上的const和volatile template<typename _1>struct RemoveCV{ typedef typename VolatileType <typename ConstType<_1>::Result>::Result Result; }; //result: <bool> 类型是否相等 //Select: <template<_,_>> 相等则选前者,否则选后者 template<typename _1, typename _2>struct SameType{ static const bool result = false; template<typename _3, typename _4>struct Select{ typedef _4 Result; }; }; template<typename _1>struct SameType<_1,_1>{ static const bool result = true; template<typename _3, typename _4>struct Select{ typedef _3 Result; }; }; //result: <bool> 其余类型中是否有一个与_1相等 template<typename _1, typename _2, typename... _n>struct AnySameType{ static const bool result = SameType<_1, _2>::result || AnySameType<_1, _n...>::result; }; template<typename _1, typename _2>struct AnySameType<_1,_2>{ static const bool result = SameType<_1, _2>::result; }; //result: <bool> 其余类型中是否都与_1相等 template<typename _1, typename _2, typename... _n>struct AllSameType{ static const bool result = SameType<_1, _2>::result && AllSameType<_1, _n...>::result; }; template<typename _1, typename _2>struct AllSameType<_1, _2>{ static const bool result = SameType<_1, _2>::result; }; //result: <bool> 是否为有符号整数 template<typename _1>struct SignedIntegralType{ typedef typename RemoveCV<_1>::Result once; static const bool result = AnySameType <once, signed char, short, int, long, long long>::result; }; //result: <bool> 是否为无符号整数 template<typename _1>struct UnsignedIntegralType{ typedef typename RemoveCV<_1>::Result once; static const bool result = AnySameType <once, unsigned char, unsigned short, unsigned, unsigned long, unsigned long long>::result; }; //result: <bool> 是否为bool,char,wchar_t template<typename _1>struct OtherIntegralType{ typedef typename RemoveCV<_1>::Result once; static const bool result = AnySameType<once, bool, char, wchar_t>::result; }; //result: <bool> 是否为整数 template<typename _1>struct IntegralType{ static const bool result = SignedIntegralType<_1>::result || UnsignedIntegralType<_1>::result || OtherIntegralType<_1>::result; }; //result: <bool> 是否为浮点数 template<typename _1>struct FloatType{ typedef typename RemoveCV<_1>::Result once; static const bool result = AnySameType <once, float, double, long double>::result; }; //result: <bool> 是否为void template<typename _1>struct VoidType{ typedef typename RemoveCV<_1>::Result once; static const bool result = SameType<once, void>::result; }; //result: <size_t> 数组大小,0表示非数组 //Result: <type> 数组元素类型 template<typename _1>struct ArrayType{ static const size_t result = 0; typedef _1 Result; }; template<typename _1, size_t size>struct ArrayType<_1[size]>{ static const size_t result = size; typedef _1 Result; }; //result: <bool> 是否为指针 //Result: <type> 被指向类型 template<typename _1>struct PointerType{ template<typename _2>struct Helper{ static const bool result = false; typedef _2 Result; }; template<typename _2>struct Helper<_2*>{ static const bool result = true; typedef _2 Result; }; typedef typename RemoveCV<_1>::Result once; static const bool result = Helper<once>::result; typedef typename Helper<once>::Result Result; }; //result: <size_t> 主线指针层数 template<typename _1>struct PointerDepth{ template<size_t depth, typename _2>struct Helper{ static const size_t result = depth; typedef _2 Result; }; template<size_t depth, typename _2>struct Helper<depth, _2*>{ typedef typename RemoveCV<_2>::Result once; static const size_t result = Helper<depth + 1, once>::result; typedef typename Helper<depth + 1, once>::Result Result; }; typedef typename RemoveCV<_1>::Result once; static const size_t result = Helper<0, once>::result; typedef typename Helper<0, once>::Result Result; }; //result: <size_t> 1为左值引用,2为右值引用,0为非引用类型 //Result: <type> 被引用类型 template<typename _1>struct ReferenceType{ static const size_t result = 0; typedef _1 Result; }; template<typename _1>struct ReferenceType<_1&>{ static const size_t result = 1; typedef _1 Result; }; template<typename _1>struct ReferenceType<_1&&>{ static const size_t result = 2; typedef _1 Result; }; //result: <bool> 是否为成员类型 //Result: <type> 成员形态 template<typename _1>struct MemberType{ static const bool result = false; typedef void Result; typedef void Class; }; template<typename _1, typename C>struct MemberType<_1 C::*>{ static const bool result = true; typedef _1 Result; typedef C Class; }; template<typename Ret, typename C, typename... Args> struct MemberType<Ret(C::*)(Args...)>{ static const bool result = true; typedef Ret Result(Args...); typedef C Class; }; template<typename Ret, typename C, typename... Args> struct MemberType<Ret(C::*)(Args...)const>{ static const bool result = true; typedef Ret Result(Args...); typedef C Class; }; template<typename Ret, typename C, typename... Args> struct MemberType<Ret(C::*)(Args...,...)>{ static const bool result = true; typedef Ret Result(Args...,...); typedef C Class; }; template<typename Ret, typename C, typename... Args> struct MemberType<Ret(C::*)(Args...,...)const>{ static const bool result = true; typedef Ret Result(Args...,...); typedef C Class; }; //result: <bool> 是否为数值 template<typename _1>struct NumberType{ static const bool result = IntegralType<_1>::result || FloatType<_1>::result; }; //result: <bool> 是否为内建类型 template<typename _1>struct IntrinsicType{ static const bool result = NumberType<_1>::result || VoidType<_1>::result; }; //result: <bool> 非内建类型 template<typename _1>struct NonIntrinsicType{ static const bool result = !IntrinsicType<_1>::result; }; //result: <size_t> 主线数组深度 //Result: <type> 数组根元素类型 //Select: <template<N>> 第N层数组大小【由里到外】 //SizeArray: <NumArray> 数组大小的整数序列 template<typename _1>struct ArrayDepth{ template<typename _A, size_t w>struct Array{ static const size_t result = w; typedef _A Result; }; template<size_t depth, typename _arr, typename _A>struct Helper{ typedef _arr RawType; typedef _A SizeArray; static const size_t result = depth; }; template<size_t depth, typename _arr, size_t _size, typename _A> struct Helper<depth, _arr[_size], _A> :Helper<depth + 1, _arr, Array<_A, _size> >{}; typedef Helper<0, _1, int > Next; typedef typename Next::RawType Result; typedef typename Next::SizeArray _SizeArray; static const size_t result = Next::result; template<size_t index>struct Select{ template<size_t index, typename _A> struct Helper:Helper<index - 1, typename _A::Result >{}; template<typename _A>struct Helper<0, _A>{ static const size_t result = _A::result; }; static const size_t result = Helper<index, SizeArray>::result; }; template<typename NA1, typename NA2>struct MakeArray; template<size_t... nums, typename NA2> struct MakeArray<NumArray<nums...>, NA2> :MakeArray<NumArray<nums..., NA2::result>, typename NA2::Result>{}; template<size_t... nums>struct MakeArray<NumArray<nums...>, int>{ typedef NumArray<nums...> Result; }; typedef typename MakeArray<NumArray<>, _SizeArray>::Result SizeArray; }; //result: <size_t> 字节对齐所需要的个数 template<typename _1>struct AlignmentType{ static const size_t result = std::alignment_of<_1>::value; }; //result: <bool> 是否为Enum类型 template<typename _1>struct EnumType{ static const bool result = std::is_enum<_1>::value; }; //result: <bool> 是否为Union类型 template<typename _1>struct UnionType{ static const bool result = std::is_union<_1>::value; }; //result: <bool> 是否为class类型,而不是union类型 template<typename _1>struct ClassType{ template<typename _2>static char TypeTester(void (_2::*)()){}; template<typename _2>static long TypeTester(...){}; static const bool result = sizeof(TypeTester<_1>(nullptr)) == sizeof(char) && !UnionType<_1>::result; }; //result: <bool> 是否是对象类型(数值或类) template<typename _1>struct ObjectType{ static const bool result = !PointerType<_1>::result && !ReferenceType<_1>::result && !VoidType<_1>::result; }; //result: <bool> 是否为标量类型 template<typename _1>struct ScalarType{ static const bool result = NumberType<_1>::result || VoidType<_1>::result || EnumType<_1>::result || MemberType<_1>::result; }; //Result: <type> 是则为前者,否则为后者 template<bool check, typename _1, typename _2>struct SelectType{ typedef _2 Result; }; template<typename _1, typename _2>struct SelectType<true, _1, _2>{ typedef _1 Result; }; //result: <bool> 是否为函数或仿函数类型 //Result: <type> 函数形态 template<typename _1>struct FunctorType{ template<typename _2>struct Helper{ static const bool result = false; typedef void Result; }; template<typename Ret, typename... Args>struct Helper<Ret(Args...)>{ static const bool result = true; typedef Ret Result(Args...); }; template<typename Ret, typename... Args>struct Helper<Ret(Args...,...)>{ static const bool result = true; typedef Ret Result(Args...,...); }; template<typename Ret, typename... Args>struct Helper<Ret(*)(Args...)>{ static const bool result = true; typedef Ret Result(Args...); }; template<typename Ret, typename... Args>struct Helper<Ret(&)(Args...)>{ static const bool result = true; typedef Ret Result(Args...); }; template<typename Ret, typename... Args>struct Helper<Ret(*)(Args...,...)>{ static const bool result = true; typedef Ret Result(Args...,...); }; template<typename Ret, typename... Args>struct Helper<Ret(&)(Args...,...)>{ static const bool result = true; typedef Ret Result(Args...,...); }; template<typename Class, typename Ret, typename... Args> struct Helper<Ret(Class::*)(Args...)>{ static const bool result = true; typedef Ret Result(Args...); }; template<typename Class, typename Ret, typename... Args> struct Helper<Ret(Class::*)(Args...)const>{ static const bool result = true; typedef Ret Result(Args...); }; template<typename Class, typename Ret, typename... Args> struct Helper<Ret(Class::*)(Args...,...)>{ static const bool result = true; typedef Ret Result(Args...,...); }; template<typename Class, typename Ret, typename... Args> struct Helper<Ret(Class::*)(Args...,...)const>{ static const bool result = true; typedef Ret Result(Args...,...); }; template<typename Class, typename Ret, typename... Args> struct Helper<Ret(Class::*)(Args...)volatile>{ static const bool result = true; typedef Ret Result(Args...); }; template<typename Class, typename Ret, typename... Args> struct Helper<Ret(Class::*)(Args...)const volatile>{ static const bool result = true; typedef Ret Result(Args...); }; template<typename Class, typename Ret, typename... Args> struct Helper<Ret(Class::*)(Args..., ...)volatile>{ static const bool result = true; typedef Ret Result(Args..., ...); }; template<typename Class, typename Ret, typename... Args> struct Helper<Ret(Class::*)(Args..., ...)const volatile>{ static const bool result = true; typedef Ret Result(Args..., ...); }; typedef typename RemoveCV<_1>::Result once; template<bool check, typename _2>struct FunctorHelper{ static const bool result = false; typedef void Result; }; template<typename _2>struct FunctorHelper<true, _2>{ typedef Helper<decltype(&_2::operator())> Next; static const bool result = Next::result; typedef typename Next::Result Result; }; template<typename _2>static char operatorhelper(decltype(&_2::operator()) w){}; template<typename _2>static long operatorhelper(...){}; typedef Helper<once> Xonce; typedef FunctorHelper <sizeof(operatorhelper<once>(nullptr)) == sizeof(char), _1> Xtwice; static const bool result = Xonce::result || Xtwice::result; typedef typename SelectType<Xonce::result, typename Xonce::Result, typename Xtwice::Result>::Result Result; }; //获取函数的信息 template<typename _1>struct GetFuncInfo{ typedef typename FunctorType<_1>::Result Method; template<typename>struct Helper; template<typename Ret, typename... Args>struct Helper<Ret(Args...)>{ typedef Ret Return; typedef TypeArray<Args...> Arg; }; template<typename Ret, typename... Args>struct Helper<Ret(Args..., ...)>{ typedef Ret Return; typedef TypeArray<Args...> Arg; }; typedef typename Helper<Method>::Return Ret; typedef typename Helper<Method>::Arg Args; }; //result: <bool> 是否为空类 template<typename _1>struct EmptyClassType{ template<typename _2, bool check>struct Helper{ static const bool result = false; }; template<typename _2>struct Helper<_2, true>{ class Derive : _2{ int a; }; static const bool result = sizeof(Derive) == sizeof(int); }; static const bool result = Helper<_1, ClassType<_1>::result>::result; }; //result: <bool> 是否含虚函数 template<typename _1>struct VirtualClassType{ template<typename _2, bool check>struct Helper{ static const bool result = false; }; template<typename _2>struct Helper<_2, true>{ class Base : _2{ int a; }; class Derive : Base{ virtual ~Derive(){}; }; static const bool result = sizeof(Derive) == sizeof(Base); }; static const bool result = Helper<_1, ClassType<_1>::result>::result; }; //result: <bool> 是否是抽象类 template<typename _1>struct AbstractType{ template<typename _2>static char helper(_2(*)[1]){}; template<typename _2>static long helper(...){}; static const bool result = VirtualClassType<_1>::result && sizeof(helper<_1>(nullptr)) == sizeof(long); }; //result: <bool> 是否是POD类型 template<typename _1>struct PODType{ static const bool result = std::is_pod<_1>::value; }; //result: <bool> 两个类型能否进行隐式转换 template<typename _1, typename _2>struct ImplicitConvertible{ static char helper(_1){}; static long helper(...){}; static const bool result = sizeof(helper(_2())) == sizeof(char); }; //result: <bool> 两个类型能否进行显式转换 template<typename _1, typename _2>struct ExplicitConvertible{ template<typename _3> static auto helper(_3* w)->decltype(_2(*w), true){}; template<typename _3>static long helper(...){}; static const bool result = sizeof(helper<_1>(nullptr)) == sizeof(bool); }; //result: <bool> 是否是继承关系 template<typename _1, typename _2>struct InheritType{ template<bool X, typename _3>struct Helper{ static const bool result = false; }; template<typename _3>struct Helper<true, _3>{ static char helper(_3*){}; static long helper(...){}; static const bool result = sizeof(helper((_2*)0)) == sizeof(char); }; static const bool result = Helper<ClassType<_1>::result && ClassType<_2>::result, _1>::result; }; //call : <template<_,_>> 反向调用元函数 template<template<typename, typename>class Func>struct ReverseFunc{ template<typename _1, typename _2>struct call:Func<_2, _1>{}; }; //call : <template<_>> 将类型在二元元函数上调用 template<template<typename, typename>class Func>struct SelfTwiceFunc{ template<typename _1>struct call :Func<_1, _1>{}; }; //call : <template<_>> 将函数递归的调用两次 template<template<typename>class Func>struct RecursionFunc{ template<typename _1>struct call :Func<typename Func<_1>::Result>{}; }; //Result: <type> 去除主线上的引用,指针,数组,CV标记后的类型 template<typename _1>struct OriginalType{ typedef typename ReferenceType<_1>::Result _2; //typedef typename RemoveCV<_2>::Result _3; template<bool a, bool b, typename _3, typename _4>struct Helper; template<bool b, typename _3, typename _4>struct Helper<false, b, _3, _4>{ typedef typename Helper< (bool)PointerDepth<_4>::result, (bool)ArrayDepth<_4>::result, typename PointerDepth<_4>::Result, typename ArrayDepth<_4>::Result>::Result Result; }; template<bool a, typename _3, typename _4>struct Helper<a, false, _3, _4>{ typedef typename Helper< (bool)PointerDepth<_3>::result, (bool)ArrayDepth<_3>::result, typename PointerDepth<_3>::Result, typename ArrayDepth<_3>::Result>::Result Result; }; template<typename _3, typename _4>struct Helper<false, false, _3, _4>{ typedef _3 Result; }; typedef typename Helper<(bool)PointerDepth<_2>::result, (bool)ArrayDepth<_2>::result, typename PointerDepth<_2>::Result, typename ArrayDepth<_2>::Result> ::Result _5; typedef typename RemoveCV<_5>::Result Result; }; //Result: <type> 添加const标记 template<typename _1>struct AddConst{ typedef _1 const Result; }; //Result: <type> 添加volatile标记 template<typename _1>struct AddVolatile{ typedef _1 volatile Result; }; //Result: <type> 添加CV标记 template<typename _1>struct AddCV{ typedef _1 const volatile Result; }; //Result: <type> 添加左值引用标记 template<typename _1>struct AddReference{ typedef typename ReferenceType<_1>::Result _2; typedef _2& Result; }; //Result: <type> 添加常量左值引用标记 template<typename _1>struct AddConstReference{ typedef typename ReferenceType<_1>::Result _2; typedef _2 const& Result; }; //Result: <type> 添加右值引用标记 template<typename _1>struct AddRValueReference{ typedef typename ReferenceType<_1>::Result _2; typedef _2&& Result; }; //Result: <type> 添加指针标记 template<typename _1>struct AddPointer{ typedef typename ReferenceType<_1>::Result _2; typedef _2* Result; }; //Result: <type> 添加size重指针标记 template<typename _1, size_t size>struct AddMultiPointer{ typedef typename ReferenceType<_1>::Result _2; typedef typename AddMultiPointer<_2*, size - 1>::Result Result; }; template<typename _1>struct AddMultiPointer<_1, 0>{ typedef _1 Result; }; //Result: <type> 添加常量指针标记 template<typename _1>struct AddConstPointer{ typedef typename ReferenceType<_1>::Result _2; typedef _2* const Result; }; //Result: <type> 添加数组标记 template<typename _1, size_t size>struct AddArray{ typedef _1 Result[size]; }; //result: <size_t> 对应数字 //Next : <type> 下一个数字类型 //Prev : <type> 上一个数字类型 template<size_t index>struct TypeForNumber{ static const size_t result = index; typedef TypeForNumber<index + 1> Next; typedef TypeForNumber<index - 1> Prev; }; //Result: <type> 对应的类型 template<size_t index, typename Head, typename... Types> struct SelectTypeInGroup : SelectTypeInGroup<index - 1, Types...>{}; template<typename Head, typename... Types> struct SelectTypeInGroup<0, Head, Types...>{ typedef Head Result; }; //Result: <TypeArray || void> 类型模板参数 template<typename _1>struct TemplateClassType{ template<template <typename...> class A, typename... B> static TypeArray<B...>* helper(A<B...>*){}; template<template<template<typename>class, typename...> class A, template<typename>class C, typename... B> static TypeArray<B...>* helper(A<C, B...>*){}; template<template<template<typename, typename>class, typename...> class A, template<typename, typename>class C, typename... B> static TypeArray<B...>* helper(A<C, B...>*){}; template<template<template<typename...>class, typename...> class A, template<typename...>class C, typename... B> static TypeArray<B...>* helper(A<C, B...>*){}; //static void* helper(...){}; typedef decltype(helper((_1*)nullptr)) once; typedef typename PointerType<once>::Result Result; static const bool result = VoidType<once>::result; }; //result: <bool> 可复制的类型 template<typename _1>struct Replicable{ static const bool result = ExplicitConvertible<_1, _1>::result; }; //result: <bool> 有默认构造函数的类型 template<typename _1>struct DefaultInitializable{ template<typename _2>static auto helper(void*)->decltype(_2(), true){}; template<typename _2>static long helper(...){}; static const bool result = sizeof(helper<_1>(nullptr)) == sizeof(bool); }; //result: <bool> 有移动构造函数的类型 template<typename _1>struct MoveReplicable{ static const bool result = ExplicitConvertible<AddRValueReference<_1>::Result, _1>::result; }; //result: <bool> 可赋值的类型 template<typename _1>struct CopyAssignable{ template<typename _2> static auto helper(void*)->decltype((*(_2*)0)=(*(_2*)0), true){}; template<typename _2>static long helper(...){}; static const bool result = sizeof(helper<_1>(nullptr)) == sizeof(bool); }; //result: <bool> 可赋值的两个类型 template<typename _1, typename _2>struct Assignable{ template<typename _3> static auto helper(void*)->decltype((*(_3*)0)=(*(_2*)0), true){}; template<typename _3>static long helper(...){}; static const bool result = sizeof(helper<_1>(nullptr)) == sizeof(bool); }; template<typename TS>struct TMPStringToCString; template<char... chs>struct TMPStringToCString<TMPString<chs...>>{ template<bool check, size_t num>struct Helper{ static const char result = '\0'; }; template<size_t num>struct Helper<true, num>{ template<size_t x, char w, char... chs>struct SubHelper :SubHelper<x - 1, chs...>{}; template<char w, char... chs>struct SubHelper<0, w, chs...>{ static const char result = w; }; static const char result = SubHelper<num, chs...>::result; }; template<size_t num>struct SuperHelper{ static const size_t once = sizeof...(chs); static const char result = Helper<(num < once), num>::result; }; static const char result[258]; }; template<char... chs> const char TMPStringToCString<TMPString<chs...>>::result[258] = { #define M(n,data) TMPStringToCString<TMPString<chs...>>::SuperHelper<n>::result, TMPStringToCString<TMPString<chs...>>::SuperHelper<0>::result, NOB_REPEAT(256, M, ~) '\0' #undef M }; template<size_t num>struct NumToStringHelper{ template<size_t num_2, typename CA>struct Helper; template<size_t num_2, char... chs>struct Helper<num_2, TMPString<chs...>> :Helper<num_2 / 10, TMPString<num_2 % 10 + '0', chs...>>{}; template<char... chs>struct Helper<0, TMPString<chs...>> :TMPStringToCString<TMPString<chs...>>{ typedef TMPString<chs...> Result; }; typedef Helper<num, TMPString<>> Result; }; //value : <const char[]> 编译期数值转字符串 template<size_t num>struct NumToString :NumToStringHelper<num>::Result{}; template<size_t num>struct ArraySizeHelperHelper{ template<typename>struct Helper; template<char... chs>struct Helper<TMPString<chs...>>{ typedef TMPString<'[', chs..., ']'> Result; }; typedef TMPStringToCString<typename Helper <typename NumToStringHelper<num>::Result::Result>::Result> Result; }; template<size_t num>struct ArraySizeHelper :ArraySizeHelperHelper<num>::Result{}; //Result: <type>最适合作为参数的类型 template<typename _1>struct ParamType{ typedef typename SelectType<IntrinsicType<_1>::result || PointerType<_1>::result, _1, _1 const&>::Result Result; }; template<typename _1>struct ParamType<_1&>{ typedef _1& Result; }; template<typename _1>struct ParamType<_1&&>{ typedef _1&& Result; }; }; namespace Types{ //size : <size_t> 类型数组的大小 //Result: <type> 首项【空数组无定义】 //Next : <TypeArray> 除首项以外的项【空数组无定义】 //get : <template<_>> 选出第N个项 //add : <template<_>> 在数组末端加上一项 template<typename... Args>struct TypeArray; template<typename Head, typename... Others>struct TypeArray<Head, Others...>{ typedef TypeArray<Others...> Next; typedef Head Result; template<int index>struct get{ typedef typename SelectTypeInGroup<index,Head,Others...>::Result Result; }; template<typename... _1>struct add{ typedef TypeArray<Head, Others..., _1...> Result; }; template<typename _1>struct shift{ typedef TypeArray<_1, Head, Others...> Result; }; static const size_t size = sizeof...(Others)+1; }; template<>struct TypeArray<>{ template<int index>struct get; template<typename... _1>struct add{ typedef TypeArray<_1...> Result; }; template<typename _1>struct shift{ typedef TypeArray<_1> Result; }; static const size_t size = 0; }; //Result: <TypeArray> 连接两个类型数组 template<typename Array1, typename Array2>struct ArrayConcat; template<typename... Array1, typename... Array2> struct ArrayConcat<TypeArray<Array1...>, TypeArray<Array2...> >{ typedef TypeArray<Array1..., Array2...> Result; }; //Array1: <TypeArray> 将第二个类型数组的首项加在第一个类型数组末端 //Array2: <TypeArray> 第二个类型数组除去首项 template<typename Array1, typename Array2>struct ArrayTransfer; template<typename Array, typename... Types> struct ArrayTransfer<TypeArray<Types...>,Array>{ typedef TypeArray<Types..., typename Array::Result> Array1; typedef typename Array::Next Array2; }; //Result: <TypeArray> 在类型数组前端弹出times个项 template<size_t times,typename Array>struct ArrayShift{ typedef typename ArrayShift<times - 1, typename Array::Next>::Result Result; }; template<typename Array>struct ArrayShift<0,Array>{ typedef typename Array Result; }; //Result: <TypeArray> 从类型数组末端弹出times个项 template<size_t times, typename Array>struct ArrayPop{ template<size_t index, typename Array_1, typename Array_2>struct ArrayTransport{ typedef typename ArrayTransfer<Array_1, Array_2>::Array1 Array1; typedef typename ArrayTransport<index - 1, Array1, typename Array_2::Next>::Result Result; }; template<typename Array_1, typename Array_2> struct ArrayTransport<0, Array_1, Array_2>{ typedef Array_1 Result; }; typedef typename ArrayTransport<Array::size - times, TypeArray<>, Array>::Result Result; }; template<typename Array>struct ArrayPop<0,Array>{ typedef Array Result; }; //Result: <TypeArray> 选出类型数组里面[index1,index2]的项 template<size_t index1, size_t index2, typename Array>struct ArraySelect{ typedef typename ArrayShift<index1, typename ArrayPop<Array::size - index2 - 1, Array>::Result>::Result Result; }; //Result: <TypeArray> 删除类型数组里面[index1,index2]的项 template<size_t index1, size_t index2, typename Array>struct ArrayDelete{ typedef typename ArrayConcat<typename ArrayPop <Array::size - index1, Array>::Result, typename ArrayShift <index2 + 1, Array>::Result>::Result Result; }; //result: <bool> 类型数组存在一个项经过函数得到true template<typename Array, template<typename> class Func>struct ArrayAny{ static const bool result = Func<typename Array::Result>::result || ArrayAny<typename Array::Next,Func>::result; }; template<template<typename> class Func> struct ArrayAny<TypeArray<>,Func>{ static const bool result = false; }; //result: <bool> 类型数组每一个项经过函数得到true template<typename Array, template<typename> class Func> struct ArrayAll{ static const bool result = Func<typename Array::Result>::result && ArrayAny<typename Array::Next, Func>::result; }; template<template<typename> class Func> struct ArrayAll<TypeArray<>, Func>{ static const bool result = true; }; //Result: <TypeArray> 将每个类型进行迭代转化为新类型 template<typename Array,template<typename> class Func>struct ArrayMap; template<typename... Types, template<typename> class Func> struct ArrayMap<TypeArray<Types...>, Func>{ typedef TypeArray<typename Func<Types>::Result...> Result; }; //Result: <TypeArray> 将每个类型进行迭代转化为新类型 template<typename Array, template<typename> class Func> using ArrayCollect = ArrayMap<Array,Func>; //Result: <TypeArray> 选出符合要求的类型 template<typename Array, template<typename> class Func> struct ArraySelectIf{ template<typename Array1, typename Array2>struct Transport{ typedef typename Transport<typename SelectType< Func<typename Array2::Result>::result, typename ArrayTransfer<Array1, Array2>::Array1, Array1>::Result, typename Array2::Next>::Result Result; }; template<typename Array1>struct Transport<Array1, TypeArray<> >{ typedef Array1 Result; }; typedef typename Transport<TypeArray<>, Array>::Result Result; }; //Result: <TypeArray> 清除符合要求的类型 template<typename Array, template<typename> class Func> struct ArrayDeleteIf{ template<typename Array1, typename Array2>struct Transport{ typedef typename Transport<typename SelectType <!Func<typename Array2::Result>::result, typename ArrayTransfer<Array1, Array2>::Array1, Array1>::Result, typename Array2::Next>::Result Result; }; template<typename Array1>struct Transport<Array1, TypeArray<> >{ typedef Array1 Result; }; typedef typename Transport<TypeArray<>, Array>::Result Result; }; //Result: <TypeArray> 在指定索引前插入类型 template<typename Array, size_t index, typename Type> struct ArrayInsert{ typedef typename ArrayConcat<typename ArrayConcat<typename ArrayPop <Array::size - index, Array>::Result, TypeArray<Type> >::Result, typename ArrayShift<index, Array>::Result>::Result Result; }; //Result: <TypeArray> 将类型数组中第index个替换为Type template<typename Array, size_t index, typename Type> struct ArrayReplace{ typedef typename ArrayInsert<typename ArrayDelete <index, index, Array>::Result, index,Type>::Result Result; }; //result: <bool> 判断类型数组中是否含有该类型 template<typename Array,typename Type>struct ArrayInclude; template<typename... Types, typename Type> struct ArrayInclude<TypeArray<Types...>, Type>{ static const bool result = AnySameType<Type, Types...>::result; }; template<typename Type>struct ArrayInclude<TypeArray<>, Type>{ static const bool result = false; }; //Result: <TypeArray> 对类型进行排序 template<typename Array,template<typename,typename> class Func>struct ArraySort{ typedef typename Array::Result First; template<typename Type>struct Compare_1{ static const bool result = Func<Type, First>::result; }; template<typename Type>struct Compare_2{ static const bool result = !Func<Type, First>::result; }; typedef typename ArraySelectIf<typename Array::Next, Compare_1>::Result Left; typedef typename ArraySelectIf<typename Array::Next, Compare_2>::Result Right; typedef typename ArrayConcat<typename ArraySort<Left, Func>::Result, typename ArrayConcat<TypeArray<First>, typename ArraySort<Right, Func>::Result>::Result>::Result Result; }; template<typename Type1, typename Type2, template<typename, typename> class Func> struct ArraySort<TypeArray<Type1, Type2>, Func>{ typedef typename SelectType<Func<Type1, Type2>::result, TypeArray<Type1, Type2>, TypeArray<Type2, Type1> >::Result Result; }; template<typename Type, template<typename, typename> class Func> struct ArraySort<TypeArray<Type>, Func>{ typedef TypeArray<Type> Result; }; template<template<typename, typename> class Func> struct ArraySort<TypeArray<>, Func>{ typedef TypeArray<> Result; }; //Result: <TypeArray> 去除重复的类型 template<typename Array>struct ArrayUnique{ template<typename Array1,typename Array2>struct Transport{ typedef typename Transport<typename SelectType< ArrayInclude<Array1,typename Array2::Result>::result, Array1, typename ArrayTransfer<Array1, Array2>::Array1 >::Result,typename Array2::Next>::Result Result; }; template<typename Array1>struct Transport<Array1, TypeArray<> >{ typedef Array1 Result; }; typedef typename Transport<TypeArray<>, Array>::Result Result; }; //Result: <TypeArray> 按定制的函数去除重复的类型 template<typename Array,template<typename,typename> class Func = SameType> struct ArrayUniqueIf{ template<typename Array, typename Type>struct Helper{ template<typename Type_1>struct SameUnary{ static const bool result = Func<Type, Type_1>::result; }; static const bool result = ArrayAny<Array, SameUnary>::result; }; template<typename Array1, typename Array2>struct Transport{ typedef typename Transport<typename SelectType< Helper<Array1, typename Array2::Result>::result, Array1, typename ArrayTransfer<Array1, Array2>::Array1 >::Result, typename Array2::Next>::Result Result; }; template<typename Array1>struct Transport<Array1, TypeArray<> >{ typedef Array1 Result; }; typedef typename Transport<TypeArray<>, Array>::Result Result; }; template<typename Array>struct ArrayUniqueIf<Array,SameType>{ template<typename Array1, typename Array2>struct Transport{ typedef typename Transport<typename SelectType< ArrayInclude<Array1, typename Array2::Result>::result, Array1, typename ArrayTransfer<Array1, Array2>::Array1 >::Result, typename Array2::Next>::Result Result; }; template<typename Array1>struct Transport<Array1, TypeArray<> >{ typedef Array1 Result; }; typedef typename Transport<TypeArray<>, Array>::Result Result; }; //Result: <TypeArray> 将索引与类型同时迭代获得新类型 template<typename, template<size_t, typename>class>struct ArrayMapWithIndex; template<typename... Types, template<size_t, typename>class Func> struct ArrayMapWithIndex<TypeArray<Types...>, Func>{ template<size_t n, typename Array>struct Iter{ typedef typename TypeArray<Types...>::template get<TypeArray<Types...>::size - n>::Result _1; typedef typename Array::template add<typename Func <TypeArray<Types...>::size - n, _1>::Result>::Result NewArray; typedef typename Iter<n - 1, NewArray>::Result Result; }; template<typename Array>struct Iter<0, Array>{ typedef Array Result; }; typedef typename Iter<TypeArray<Types...>::size, TypeArray<>>::Result Result; }; //Result: <TypeArray> 将嵌套TypeArray展开 template<typename Array>struct ArrayFlatten{ template<typename T, typename NotCheck, typename Checked>struct Helper :Helper<typename NotCheck::Result, typename NotCheck::Next, typename Checked::template add<T>::Result>{}; template<typename T, typename Checked> struct Helper<T, TypeArray<>, Checked>{ typedef typename Checked::template add<T>::Result Result; }; template<typename... Types, typename NotCheck, typename Checked> struct Helper<TypeArray<Types...>, NotCheck, Checked> :Helper<typename NotCheck::Result, typename NotCheck::Next, typename Checked::template add<Types...>::Result>{}; template<typename... Types, typename Checked> struct Helper<TypeArray<Types...>, TypeArray<>, Checked>{ typedef typename Checked::template add<Types...>::Result Result; }; typedef typename Helper<typename Array::Result, typename Array::Next, TypeArray<>>::Result Result; }; template<>struct ArrayFlatten<TypeArray<>>{ typedef TypeArray<> Result; }; }; template<typename Func> std::function<typename Types::FunctorType<Func>::Result> make_func(Func const& fun){ return std::function<typename Types::FunctorType<Func>::Result>(fun); };
[ "lunaticecho@gmail.com" ]
lunaticecho@gmail.com
8c7117e2fe17c761842cac284c3114326114800f
fb9eeef1ce1f67b7d3f5544949d59c5b35dd1428
/11.container-with-most-water.cpp
9b184f709e88203630c220f962f28991fdaccf60
[]
no_license
ZanneZankyo/LeetCodeSandBox
af5b226ad8008f2a091a2ebb7028a2eb55c64fc1
ed91e4311e5dc654278bfa8e507f7c2f6a26b61c
refs/heads/master
2022-06-09T01:51:34.314253
2022-03-14T01:11:07
2022-03-14T01:11:07
175,725,861
0
0
null
null
null
null
UTF-8
C++
false
false
1,744
cpp
/* * @lc app=leetcode id=11 lang=cpp * * [11] Container With Most Water * * https://leetcode.com/problems/container-with-most-water/description/ * * algorithms * Medium (42.94%) * Total Accepted: 328K * Total Submissions: 763.8K * Testcase Example: '[1,8,6,2,5,4,8,3,7]' * * Given n non-negative integers a1, a2, ..., an , where each represents a * point at coordinate (i, ai). n vertical lines are drawn such that the two * endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together * with x-axis forms a container, such that the container contains the most * water. * * Note: You may not slant the container and n is at least 2. * * * * * * The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In * this case, the max area of water (blue section) the container can contain is * 49. * * * * Example: * * * Input: [1,8,6,2,5,4,8,3,7] * Output: 49 * */ class Solution { public: int maxArea(vector<int>& height) { int maxArea = 0; for(int i = 0; i < height.size(); i++) { for(int j = height.size() - 1; j > i; j--) { if(height[j] < height[i]) continue; int area = (j - i) * height[i]; if(area > maxArea) maxArea = area; break; } for(int j = 0; j < i; j++) { if(height[j] < height[i]) continue; int area = (i - j) * height[i]; if(area > maxArea) maxArea = area; break; } } return maxArea; } };
[ "zannezankyo@gmail.com" ]
zannezankyo@gmail.com
d359afea6910b29b78ae51ac2def2479aa93ac10
f1650097b029bb2446e4d23fc76b53ec971e2a53
/stm32loader/src/ap/boot/device/stm32_pid_450.cpp
b549ff22d1c37330e04c4e03319722be49969555
[ "Apache-2.0" ]
permissive
chcbaram/stm32loader
be762407a4d86160cb380eebbddb0a1fc3dfd439
e8c55a4be92c4b6060153b6717b9cb6b5b505de3
refs/heads/master
2023-04-06T06:51:28.192323
2023-03-17T19:20:18
2023-03-17T19:20:18
185,759,217
2
1
null
null
null
null
UTF-8
C++
false
false
538
cpp
/* * stm32_pid_449.cpp * * Created on: 2019. 5. 10. * Author: HanCheol Cho */ #include "boot/boot.h" static device_info_t stm32_pid_450[16+2]; device_info_t *stm32_pid_450_info(void) { int i; for (i=0; i<16; i++) { stm32_pid_450[i].sector_index = i; stm32_pid_450[i].sector_addr = 0x08000000 + (128 * 1024 * i); stm32_pid_450[i].sector_length = 128 * 1024; } stm32_pid_450[i].sector_index = -1; stm32_pid_450[i].sector_addr = 0; stm32_pid_450[i].sector_length = 0; return stm32_pid_450; }
[ "chc@robotis.com" ]
chc@robotis.com
9715dbb0a478eacc7221e6dd27dd166a5ac2b87c
85e3837c748ecb287e1a0ba8407954741962ffd1
/Randomly/10035_218.cpp
ebe44debf8554070e1248da9ac64bae43b0f9324
[]
no_license
infyloop/uva-solns
cc146c1ea1853a834ce324cfd73d470a5a8e252d
df6c94ece4c9f7e552210f6ab901327f14e4ed81
refs/heads/master
2021-05-26T22:26:26.198382
2013-02-04T05:58:55
2013-02-04T05:58:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
741
cpp
#include<iostream> using namespace std; int main() { unsigned long n1,n2,c,c0,op = 0; while(cin>>n1>>n2 &&( n1 != 0 || n2 != 0)) { c0 = 0;op = 0; while(n1 > 0 || n2 > 0) { c = 0; c = n1%10 + n2%10 + c0; if(c > 9) { op++; c0 = 1; } n1 /= 10; n2 /= 10; } if(op == 0) cout<<"No carry operation."<<endl; else if(op == 1) cout<<"1 carry operation."<<endl; else cout<<op<<" carry operations."<<endl; } return 0; }
[ "contact@fruiapps.com" ]
contact@fruiapps.com
db1a2fbf8b705c9c25d53b56910fc85a0d99bd3d
9fd0b6465570129c86f4892e54da27d0e9842f9b
/src/runtime/libc++/test/containers/associative/multiset/lower_bound.pass.cpp
585c341cd23821208533501e1fedb6e5737ab015
[ "BSL-1.0" ]
permissive
metta-systems/metta
cdbdcda872c5b13ae4047a7ceec6c34fc6184cbf
170dd91b5653626fb3b9bfab01547612efe531c5
refs/heads/develop
2022-04-06T07:25:16.069905
2020-02-17T08:22:10
2020-02-17T08:22:10
6,562,050
39
11
BSL-1.0
2019-02-22T08:53:20
2012-11-06T12:54:03
C++
UTF-8
C++
false
false
2,130
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <set> // class multiset // iterator lower_bound(const key_type& k); // const_iterator lower_bound(const key_type& k) const; #include <set> #include <cassert> int main() { typedef int V; typedef std::multiset<int> M; { typedef M::iterator R; V ar[] = { 5, 5, 5, 7, 7, 7, 9, 9, 9 }; M m(ar, ar+sizeof(ar)/sizeof(ar[0])); R r = m.lower_bound(4); assert(r == next(m.begin(), 0)); r = m.lower_bound(5); assert(r == next(m.begin(), 0)); r = m.lower_bound(6); assert(r == next(m.begin(), 3)); r = m.lower_bound(7); assert(r == next(m.begin(), 3)); r = m.lower_bound(8); assert(r == next(m.begin(), 6)); r = m.lower_bound(9); assert(r == next(m.begin(), 6)); r = m.lower_bound(11); assert(r == next(m.begin(), 9)); } { typedef M::const_iterator R; V ar[] = { 5, 5, 5, 7, 7, 7, 9, 9, 9 }; const M m(ar, ar+sizeof(ar)/sizeof(ar[0])); R r = m.lower_bound(4); assert(r == next(m.begin(), 0)); r = m.lower_bound(5); assert(r == next(m.begin(), 0)); r = m.lower_bound(6); assert(r == next(m.begin(), 3)); r = m.lower_bound(7); assert(r == next(m.begin(), 3)); r = m.lower_bound(8); assert(r == next(m.begin(), 6)); r = m.lower_bound(9); assert(r == next(m.begin(), 6)); r = m.lower_bound(11); assert(r == next(m.begin(), 9)); } }
[ "berkus@exquance.com" ]
berkus@exquance.com
8a3f8e1f62ee27f95e1880d1e8c1168fe7cb043e
83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1
/third_party/WebKit/Source/platform/graphics/gpu/WebGLImageConversion.h
282615fa63f37171cb90e14978c01070fe081730
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "Apache-2.0" ]
permissive
cool2528/miniblink49
d909e39012f2c5d8ab658dc2a8b314ad0050d8ea
7f646289d8074f098cf1244adc87b95e34ab87a8
refs/heads/master
2020-06-05T03:18:43.211372
2019-06-01T08:57:37
2019-06-01T08:59:56
192,294,645
2
0
Apache-2.0
2019-06-17T07:16:28
2019-06-17T07:16:27
null
UTF-8
C++
false
false
8,174
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 WebGLImageConversion_h #define WebGLImageConversion_h #include "platform/PlatformExport.h" #include "platform/graphics/Image.h" #include "third_party/khronos/GLES2/gl2.h" #include "third_party/khronos/GLES2/gl2ext.h" //#include "third_party/khronos/GLES3/gl3.h" #include "third_party/skia/include/core/SkBitmap.h" #include "wtf/RefPtr.h" namespace blink { class Image; class IntSize; // Helper functions for texture uploading and pixel readback. class PLATFORM_EXPORT WebGLImageConversion { public: // Attempt to enumerate all possible native image formats to // reduce the amount of temporary allocations during texture // uploading. This enum must be public because it is accessed // by non-member functions. // "_S" postfix indicates signed type. enum DataFormat { DataFormatRGBA8 = 0, DataFormatRGBA8_S, DataFormatRGBA16, DataFormatRGBA16_S, DataFormatRGBA32, DataFormatRGBA32_S, DataFormatRGBA16F, DataFormatRGBA32F, DataFormatRGBA2_10_10_10, DataFormatRGB8, DataFormatRGB8_S, DataFormatRGB16, DataFormatRGB16_S, DataFormatRGB32, DataFormatRGB32_S, DataFormatRGB16F, DataFormatRGB32F, DataFormatBGR8, DataFormatBGRA8, DataFormatARGB8, DataFormatABGR8, DataFormatRGBA5551, DataFormatRGBA4444, DataFormatRGB565, DataFormatRGB10F11F11F, DataFormatRGB5999, DataFormatRG8, DataFormatRG8_S, DataFormatRG16, DataFormatRG16_S, DataFormatRG32, DataFormatRG32_S, DataFormatRG16F, DataFormatRG32F, DataFormatR8, DataFormatR8_S, DataFormatR16, DataFormatR16_S, DataFormatR32, DataFormatR32_S, DataFormatR16F, DataFormatR32F, DataFormatRA8, DataFormatRA16F, DataFormatRA32F, DataFormatAR8, DataFormatA8, DataFormatA16F, DataFormatA32F, DataFormatD16, DataFormatD32, DataFormatD32F, DataFormatDS24_8, DataFormatNumFormats }; enum ChannelBits { ChannelRed = 1, ChannelGreen = 2, ChannelBlue = 4, ChannelAlpha = 8, ChannelDepth = 16, ChannelStencil = 32, ChannelRG = ChannelRed | ChannelGreen, ChannelRGB = ChannelRed | ChannelGreen | ChannelBlue, ChannelRGBA = ChannelRGB | ChannelAlpha, ChannelDepthStencil = ChannelDepth | ChannelStencil, }; // Possible alpha operations that may need to occur during // pixel packing. FIXME: kAlphaDoUnmultiply is lossy and must // be removed. enum AlphaOp { AlphaDoNothing = 0, AlphaDoPremultiply = 1, AlphaDoUnmultiply = 2 }; enum ImageHtmlDomSource { HtmlDomImage = 0, HtmlDomCanvas = 1, HtmlDomVideo = 2, HtmlDomNone = 3 }; class PLATFORM_EXPORT ImageExtractor { public: ImageExtractor(Image*, ImageHtmlDomSource, bool premultiplyAlpha, bool ignoreGammaAndColorProfile); ~ImageExtractor(); bool extractSucceeded() { return m_extractSucceeded; } const void* imagePixelData() { return m_imagePixelData; } unsigned imageWidth() { return m_imageWidth; } unsigned imageHeight() { return m_imageHeight; } DataFormat imageSourceFormat() { return m_imageSourceFormat; } AlphaOp imageAlphaOp() { return m_alphaOp; } unsigned imageSourceUnpackAlignment() { return m_imageSourceUnpackAlignment; } ImageHtmlDomSource imageHtmlDomSource() { return m_imageHtmlDomSource; } private: // Extract the image and keeps track of its status, such as width, height, Source Alignment, format and AlphaOp etc. // This needs to lock the resources or relevant data if needed and return true upon success bool extractImage(bool premultiplyAlpha, bool ignoreGammaAndColorProfile); SkBitmap m_bitmap; SkBitmap m_skiaBitmap; Image* m_image; ImageHtmlDomSource m_imageHtmlDomSource; bool m_extractSucceeded; const void* m_imagePixelData; unsigned m_imageWidth; unsigned m_imageHeight; DataFormat m_imageSourceFormat; AlphaOp m_alphaOp; unsigned m_imageSourceUnpackAlignment; }; // Computes the components per pixel and bytes per component // for the given format and type combination. Returns false if // either was an invalid enum. static bool computeFormatAndTypeParameters(GLenum format, GLenum type, unsigned* componentsPerPixel, unsigned* bytesPerComponent); // Computes the image size in bytes. If paddingInBytes is not null, padding // is also calculated in return. Returns NO_ERROR if succeed, otherwise // return the suggested GL error indicating the cause of the failure: // INVALID_VALUE if width/height is negative or overflow happens. // INVALID_ENUM if format/type is illegal. static GLenum computeImageSizeInBytes(GLenum format, GLenum type, GLsizei width, GLsizei height, GLint alignment, unsigned* imageSizeInBytes, unsigned* paddingInBytes); // Check if the format is one of the formats from the ImageData or DOM elements. // The formats from ImageData is always RGBA8. // The formats from DOM elements vary with Graphics ports. It can only be RGBA8 or BGRA8. static ALWAYS_INLINE bool srcFormatComeFromDOMElementOrImageData(DataFormat SrcFormat) { return SrcFormat == DataFormatBGRA8 || SrcFormat == DataFormatRGBA8; } // The input can be either format or internalformat. static unsigned getChannelBitsByFormat(GLenum); // The Following functions are implemented in GraphicsContext3DImagePacking.cpp // Packs the contents of the given Image which is passed in |pixels| into the passed Vector // according to the given format and type, and obeying the flipY and AlphaOp flags. // Returns true upon success. static bool packImageData(Image*, const void* pixels, GLenum format, GLenum type, bool flipY, AlphaOp, DataFormat sourceFormat, unsigned width, unsigned height, unsigned sourceUnpackAlignment, Vector<uint8_t>& data); // Extracts the contents of the given ImageData into the passed Vector, // packing the pixel data according to the given format and type, // and obeying the flipY and premultiplyAlpha flags. Returns true // upon success. static bool extractImageData(const uint8_t*, const IntSize&, GLenum format, GLenum type, bool flipY, bool premultiplyAlpha, Vector<uint8_t>& data); // Helper function which extracts the user-supplied texture // data, applying the flipY and premultiplyAlpha parameters. // If the data is not tightly packed according to the passed // unpackAlignment, the output data will be tightly packed. // Returns true if successful, false if any error occurred. static bool extractTextureData(unsigned width, unsigned height, GLenum format, GLenum type, unsigned unpackAlignment, bool flipY, bool premultiplyAlpha, const void* pixels, Vector<uint8_t>& data); // End GraphicsContext3DImagePacking.cpp functions private: // Helper for packImageData/extractImageData/extractTextureData which implement packing of pixel // data into the specified OpenGL destination format and type. // A sourceUnpackAlignment of zero indicates that the source // data is tightly packed. Non-zero values may take a slow path. // Destination data will have no gaps between rows. // Implemented in GraphicsContext3DImagePacking.cpp static bool packPixels(const uint8_t* sourceData, DataFormat sourceDataFormat, unsigned width, unsigned height, unsigned sourceUnpackAlignment, unsigned destinationFormat, unsigned destinationType, AlphaOp, void* destinationData, bool flipY); }; } // namespace blink #endif // WebGLImageConversion_h
[ "22249030@qq.com" ]
22249030@qq.com
571d71d0c4753ee13154db418eccd465407769f9
72a382bb6c092837662e80c11ed00f7034be11e8
/Design a Simple Automaton (Finite State Machine)/Source.cpp
f3fcf503af17d365db612aeec9605d8e6fe40997
[]
no_license
Uni-M/CodewarsC
4dc0887d31d92425ab6f21be72d74a6ca1cbd276
29ef82ccfc6ae68e3565d6d4c477f7d5d8335608
refs/heads/master
2023-06-26T06:44:07.412333
2021-07-26T08:57:02
2021-07-26T08:57:02
389,310,685
2
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
#include "stdafx.h" #include "AutomatonClass.h" using namespace std; int main() { setlocale(LC_ALL, "ru"); Automaton a; vector<char> v = { '1', '0', '0', '1', '0' }; cout << a.read_commands(v); // ==> false system("pause"); }
[ "noreply@github.com" ]
noreply@github.com
f6e4dd0d48416e04516a68ec9a9ae84781bc21ba
092e8797ce9a28a5ae4ad9f473dd6612aa80d210
/compiler/Engines/optimized-engine/specific/include/Initializable.hpp
1a029bd8fa1976fdb414343cc49ee60ad83d02a1
[ "LicenseRef-scancode-cecill-b-en" ]
permissive
toandv/IFinder
faf4730e5065ff6bc2c457b432b9bb100b027bba
7d7c48c87034fb1f66ceb5473f516dd833f49450
refs/heads/master
2021-04-19T23:44:27.674959
2020-03-24T07:36:33
2020-03-24T07:36:33
249,641,738
0
0
null
null
null
null
UTF-8
C++
false
false
3,224
hpp
/** * Copyright Verimag laboratory. * * contributors: * Jacques Combaz (jacques.combaz@univ-grenoble-alpes.fr) * * This software is a computer program whose purpose is to generate * executable code from BIP models. * * This software is governed by the CeCILL-B license under French law and * abiding by the rules of distribution of free software. You can use, * modify and/ or redistribute the software under the terms of the CeCILL-B * license as circulated by CEA, CNRS and INRIA at the following URL * "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-B license and that you accept its terms. */ #ifndef _BIP_Engine_Initializable_HPP_ #define _BIP_Engine_Initializable_HPP_ #include <bip-engineiface-config.hpp> using namespace bipbasetypes; using namespace biptypes; /** \brief */ class InitializableItf { public: // constructor and destructor InitializableItf(bool initialized = false) : mIsInitialized(initialized) { } virtual ~InitializableItf() { } // setters and getters void dependsOn(InitializableItf &initializable) { mDependencies.push_back(&initializable); } // operations void initialize(); protected: // operations virtual void compute() = 0; bool isInitialized() const { return mIsInitialized; } void initialized() { mIsInitialized = true; } // protected attributes vector<InitializableItf *> mDependencies; mutable bool mIsInitialized; }; template<class T, class C> class Initializable : public InitializableItf { public: // constructor and destructor Initializable(C *instance, void (C::*method)(T& t)) : mInstance(*instance), mMethod(method) { } Initializable(bool initialized, C *instance, void (C::*method)(T& t)) : InitializableItf(initialized), mInstance(*instance), mMethod(method) { } virtual ~Initializable() { } // setters and getters const T &value() const { assert(isInitialized()); return mObject; } protected: // operations virtual void compute() { (mInstance.*mMethod)(mObject); } // protected attributes C &mInstance; void (C::*mMethod)(T& t); T mObject; }; #endif // _BIP_Engine_Initializable_HPP_
[ "you@example.com" ]
you@example.com
dc6606cf17681f00a5f60f66d28962299b9e8109
caff618dd73c0c8cc1c2f8b9e71893385f2d3b8d
/lib/HMC5883L/HMC5883L.cpp
dc6e5d19d650378bed8c580c57b792d745835a95
[]
no_license
DominicChm/AntennaTracker
03fc10054ce9142524d7805cf66ddcbd2299e577
4f000b98cba8e90676254f2187988cb67a61898b
refs/heads/master
2022-11-27T18:31:31.155797
2020-08-11T19:30:37
2020-08-11T19:30:37
286,830,361
0
0
null
null
null
null
UTF-8
C++
false
false
17,332
cpp
// // Created by Dominic on 8/3/2020. // #include "HMC5883L.h" using namespace HMC5883L_CFG; bool HMC5883L::begin(int sda, int scl) { aWire.begin(sda, scl); if ((readSync8(REGISTERS::IDENT_A) != EXPECTED_IDENT::A) || (readSync8(REGISTERS::IDENT_B) != EXPECTED_IDENT::B) || (readSync8(REGISTERS::IDENT_C) != EXPECTED_IDENT::C)) { return false; } isInitialized = true; /*Init*/ return setConfiguration(configuration); } bool HMC5883L::setConfiguration(HMC5833LConfiguration configuration) { this->configuration = configuration; if (isInitialized) { //Generate configuration bytes (Masks ensure cfg. errors don't affect other things.) uint8_t A = 0x00; A |= configuration.samples << 5 & SAMPLES_MASK; A |= configuration.rate << 2 & DATA_RATE_MASK; A |= configuration.flow & MEASUREMENT_FLOW_MASK; uint8_t B = 0x00; B |= configuration.gain << 5 & GAIN_MASK; uint8_t M = 0x00; M |= configuration.mode; //Write configuration bytes writeSync8(A, REGISTERS::CONFIG_A); writeSync8(B, REGISTERS::CONFIG_B); writeSync8(M, REGISTERS::MEASUREMENT_MODE); //Check config applied correctly. return (readSync8(REGISTERS::CONFIG_A) == A) && (readSync8(REGISTERS::CONFIG_B) == B) && (readSync8(REGISTERS::MEASUREMENT_MODE) == M); } return false; } void HMC5883L::loop() { if (!isInitialized) { return; } switch (state) { case STATE::INIT : { state = STATE::WAITING_TO_WRITE_MODE; break; } case STATE::WAITING_TO_WRITE_MODE: { uint32_t t = micros(); if (t - lastReadTime > configuration.sampleInterval) { while (t - lastReadTime > configuration.sampleInterval) { lastReadTime += configuration.sampleInterval; } uint8_t req[2] = {REGISTERS::MEASUREMENT_MODE, MODE::SINGLE}; didReadBegin_TRK = true; writeAsync(req, 2, STATE::WAITING_TO_REQUEST); } break; } case STATE::WAITING_TO_REQUEST: { uint32_t t = micros(); if (t - lastReadTime > 6000) { //Wait 10ms state = STATE::REQUESTING_DATA; } break; } case STATE::REQUESTING_DATA: { //Serial.println("REQ"); readAsync(6, STATE::DATA_RECEIVED); break; } case STATE::DATA_RECEIVED: { //Serial.println("REC"); rawData.x = ((uint16_t) buffer[0]) << 8 | buffer[1]; rawData.z = ((uint16_t) buffer[2]) << 8 | buffer[3]; rawData.y = ((uint16_t) buffer[4]) << 8 | buffer[5]; isDataAvailable_TRK = true; state = STATE::WAITING_TO_WRITE_MODE; break; } case STATE::WAITING: { break; } default: break; } aWire.loop(); } void HMC5883L::readAsync(uint8_t len, STATE nextState) { //If state is already waiting, exit - we shouldn't be called twice in the same state. if (state == STATE::WAITING) { return; } //Modify our held argument request with the new callback state. fsmAsyncArg.cbState = nextState; uint8_t reg = REGISTERS::OUT_X_M; //Send [rootreg] to set the register pointer and request [len] bytes. aWire.request(ADDRESS, &reg, 1, len, [](uint8_t status, void *arg, uint8_t *data, uint8_t datalen) { //Cast void * arg to the FMSRequestArg struct we passed earlier. FSMAsyncArg *a = static_cast<FSMAsyncArg *>(arg); //Copy data from i2c buffer to the buffer passed in the arg struct memcpy(a->buffer, data, datalen); //Dereference and set the passed status variable. *(a->status) = status; //Dereference and set the passed state variable to the passed new state. *(a->state) = a->cbState; }, static_cast<void *>(&fsmAsyncArg)); state = STATE::WAITING; } void HMC5883L::readAsync(REGISTERS rootReg, uint8_t len, STATE nextState) { //If state is already waiting, exit - we shouldn't be called twice in the same state. if (state == STATE::WAITING) { return; } //Modify our held argument request with the new callback state. fsmAsyncArg.cbState = nextState; //Send [rootreg] to set the register pointer and request [len] bytes. aWire.request(ADDRESS, (uint8_t *) &rootReg, 1, len, [](uint8_t status, void *arg, uint8_t *data, uint8_t datalen) { //Cast void * arg to the FMSRequestArg struct we passed earlier. FSMAsyncArg *a = static_cast<FSMAsyncArg *>(arg); //Copy data from i2c buffer to the buffer passed in the arg struct memcpy(a->buffer, data, datalen); //Dereference and set the passed status variable. *(a->status) = status; //Dereference and set the passed state variable to the passed new state. *(a->state) = a->cbState; }, static_cast<void *>(&fsmAsyncArg)); state = STATE::WAITING; } void HMC5883L::writeAsync(uint8_t *data, uint8_t len, STATE nextState) { //If state is already waiting, exit - we shouldn't be called twice in the same state. if (state == STATE::WAITING) { return; } //Modify our held argument request with the new callback state. fsmAsyncArg.cbState = nextState; aWire.send(ADDRESS, data, len, [](uint8_t status, void *arg) { //Cast void * arg to the FMSRequestArg struct we passed earlier. FSMAsyncArg *a = static_cast<FSMAsyncArg *>(arg); //Dereference and set the passed status variable. *(a->status) = status; //Dereference and set the passed state variable to the passed new state. *(a->state) = a->cbState; }, static_cast<void *>(&fsmAsyncArg)); state = STATE::WAITING; } void HMC5883L::writePointerAsync(REGISTERS reg, STATE nextState) { writeAsync((uint8_t *) &reg, 1, nextState); } void HMC5883L::rawReadInto(int16_t *x, int16_t *y, int16_t *z) { *x = rawData.x; *y = rawData.y; *z = rawData.z; isDataAvailable_TRK = false; } void HMC5883L::calibratedReadInto(double *x, double *y, double *z) { *x = rawData.x * gainToFactor(configuration.gain) * calibration.xGainFactor + calibration.xOffset; *y = rawData.y * gainToFactor(configuration.gain) * calibration.yGainFactor + calibration.yOffset; *z = rawData.z * gainToFactor(configuration.gain) * calibration.zGainFactor + calibration.zOffset; isDataAvailable_TRK = false; } Vector3<int16_t> HMC5883L::rawRead() { isDataAvailable_TRK = false; return rawData; } Vector3<double> HMC5883L::calibratedRead() { Vector3<double> data; calibratedReadInto(&data.x, &data.y, &data.z); isDataAvailable_TRK = false; return data; } void HMC5883L::printCalibration(Stream &stream, HMC5833LCalibration calibration) { stream.printf("xGainFactor:\t%f\n", calibration.xGainFactor); stream.printf("yGainFactor:\t%f\n", calibration.yGainFactor); stream.printf("zGainFactor:\t%f\n", calibration.zGainFactor); stream.printf("xOffset:\t%f\n", calibration.xOffset); stream.printf("yOffset:\t%f\n", calibration.yOffset); stream.printf("zOffset:\t%f\n", calibration.zOffset); } Vector3<double> HMC5883L::preformGainCalibration(Stream &stream, FLOW flow, Vector3<double> targetExcitation) { uint8_t buf[16]; uint16_t ctr = 0; Vector3<int16_t> data = {}; //Enable the passed field self-test with 8 averaged samples. HMC5833LConfiguration cfg; cfg.flow = flow; cfg.gain = GAIN::G_4_7GA; cfg.rate = RATE::D_30HZ; cfg.samples = SAMPLES::S8; cfg.mode = MODE::CONTINUOUS; setConfiguration(cfg); stream.printf("HMC5883L configured for gain calibration, taking 100 samples...\n"); //Take 100 readings while (ctr < 100) { readSync(buf, 6, REGISTERS::OUT_X_M); data = bufToRawVec(buf); ctr++; delay(33); } stream.printf("Took %u readings to generate gain factors:\n", ctr); //Get scaled readings using a default calibration. Vector3<double> scaledData = rawVecToCalibratedVec(data, HMC5833LCalibration()); Vector3<double> correctionFactors = {}; correctionFactors.x = fabs(targetExcitation.x / scaledData.x); correctionFactors.y = fabs(targetExcitation.y / scaledData.y); correctionFactors.z = fabs(targetExcitation.z / scaledData.z); switch (flow) { case FLOW::POSITIVE: stream.printf("(+) Scaled X: %f;\tCorrection factor: %f\n", scaledData.x, correctionFactors.x); stream.printf("(+) Scaled Y: %f;\tCorrection factor: %f\n", scaledData.y, correctionFactors.y); stream.printf("(+) Scaled Z: %f;\tCorrection factor: %f\n", scaledData.z, correctionFactors.z); break; case FLOW::NEGATIVE: stream.printf("(-) Scaled X: %f;\tCorrection factor: %f\n", scaledData.x, correctionFactors.x); stream.printf("(-) Scaled Y: %f;\tCorrection factor: %f\n", scaledData.y, correctionFactors.y); stream.printf("(-) Scaled Z: %f;\tCorrection factor: %f\n", scaledData.z, correctionFactors.z); break; default: break; } return correctionFactors; } Vector3<double> HMC5883L::preformOffsetCalibration(Stream &stream, HMC5833LCalibration gainCalibration) { #define waitForUser() while(stream.available() <= 0) {;} #define flushStream() while(stream.available()) {stream.read();} uint8_t buf[16]; Vector3<double> data = {}; HMC5833LConfiguration cfg; cfg.flow = FLOW::NONE; cfg.gain = GAIN::G_1_3GA; cfg.rate = RATE::D_30HZ; cfg.samples = SAMPLES::S2; cfg.mode = MODE::CONTINUOUS; setConfiguration(cfg); stream.printf("HMC5883L configured for offset calibration.\n"); stream.printf("Rotate the HMC5883L in all directions until the max. values shown stop changing.\n"); stream.printf("Then, send any character to finish.\n"); stream.printf("Send any character to start.\n"); waitForUser(); flushStream(); Vector3<double> mins = {}; mins.x = infinity(); mins.y = infinity(); mins.z = infinity(); Vector3<double> maxes = {}; maxes.x = -infinity(); maxes.y = -infinity(); maxes.z = -infinity(); stream.printf("Starting.......\n"); for (int i = 0; i < 50; i++) { readSync(buf, 6, REGISTERS::OUT_X_M); delay(33); } //Dump first 100 vals. while (stream.available() <= 0) { readSync(buf, 6, REGISTERS::OUT_X_M); data = rawVecToCalibratedVec(bufToRawVec(buf), gainCalibration); mins.x = min<double>(mins.x, data.x); mins.y = min<double>(mins.y, data.y); mins.z = min<double>(mins.z, data.z); maxes.x = max<double>(maxes.x, data.x); maxes.y = max<double>(maxes.y, data.y); maxes.z = max<double>(maxes.z, data.z); Serial.printf("xMin: %f,\tyMin: %f,\tzMin: %f,\txMax: %f,\tyMax: %f,\tzMax: %f\n", mins.x, mins.y, mins.z, maxes.x, maxes.y, maxes.z); delay(33); } flushStream(); Serial.printf("\nFinished! Final Max/Mins:\n"); Serial.printf("xMin: %f,\tyMin: %f,\tzMin: %f,\txMax: %f,\tyMax: %f,\tzMax: %f\n", mins.x, mins.y, mins.z, maxes.x, maxes.y, maxes.z); Vector3<double> offsets = {}; offsets.x = (maxes.x - mins.x) / 2 - maxes.x; offsets.y = (maxes.y - mins.y) / 2 - maxes.y; offsets.z = (maxes.z - mins.z) / 2 - maxes.z; return offsets; } HMC5833LCalibration HMC5883L::preformInteractiveCalibration(Stream &stream) { if (!isInitialized) { stream.printf("Error in HMC5833L calibration:\n"); stream.printf("HMC5883L object hasn't started! Did you call <name_of_HMC5833L_object>.begin(Wire); ?\n"); return HMC5833LCalibration(); } HMC5833LCalibration newCal = {}; Vector3<double> targetExcitation = {}; targetExcitation.x = XY_EXCITATION; targetExcitation.y = XY_EXCITATION; targetExcitation.z = Z_EXCITATION; stream.printf("\n--------------Calibrating Positive Gain--------------\n"); Vector3<double> correctionFactor_p = preformGainCalibration(stream, FLOW::POSITIVE, targetExcitation); stream.printf("\n--------------Calibrating Negative Gain--------------\n"); Vector3<double> correctionFactor_n = preformGainCalibration(stream, FLOW::NEGATIVE, targetExcitation); newCal.xGainFactor = (correctionFactor_p.x + correctionFactor_n.x) / 2; newCal.yGainFactor = (correctionFactor_p.y + correctionFactor_n.y) / 2; newCal.zGainFactor = (correctionFactor_p.z + correctionFactor_n.z) / 2; stream.printf("AVG. gain factors:\n"); stream.printf("X: %f\n", newCal.xGainFactor); stream.printf("Y: %f\n", newCal.yGainFactor); stream.printf("Z: %f\n", newCal.zGainFactor); if (newCal.xGainFactor < 0.8 || newCal.xGainFactor > 1.2 || newCal.yGainFactor < 0.8 || newCal.yGainFactor > 1.2 || newCal.zGainFactor < 0.8 || newCal.zGainFactor > 1.2) { stream.printf( "Calibration values are out of acceptable range. Please restart the HMC5883L and program by fully cutting and then restoring power.\n"); HMC5833LCalibration c = {}; return c; } stream.printf("\n--------------Calibrating Offsets--------------\n"); Vector3<double> offsets = preformOffsetCalibration(stream, newCal); newCal.xOffset = offsets.x; newCal.yOffset = offsets.y; newCal.zOffset = offsets.z; stream.printf("\n--------------HMC5833L Calibration Results--------------\n"); stream.printf("(Hint: Use these to create a HMC5833LCalibration struct and pass it to " "your HMC5883L object to enable accurate readings)\n"); printCalibration(stream, newCal); return newCal; } Vector3<int16_t> HMC5883L::bufToRawVec(uint8_t *buffer) { Vector3<int16_t> vec = {}; vec.x = ((int16_t) buffer[0]) << 8 | buffer[1]; vec.z = ((int16_t) buffer[2]) << 8 | buffer[3]; vec.y = ((int16_t) buffer[4]) << 8 | buffer[5]; return vec; } Vector3<double> HMC5883L::rawVecToCalibratedVec(Vector3<int16_t> rawData, HMC5833LCalibration calibration) { Vector3<double> vec = {}; vec.x = ((double) rawData.x) * gainToFactor(configuration.gain) * calibration.xGainFactor + calibration.xOffset; vec.y = ((double) rawData.y) * gainToFactor(configuration.gain) * calibration.yGainFactor + calibration.yOffset; vec.z = ((double) rawData.z) * gainToFactor(configuration.gain) * calibration.zGainFactor + calibration.zOffset; return vec; } uint8_t HMC5883L::readSync(uint8_t *buf, uint8_t len) { RequestArg cb(buf, len); aWire.request(ADDRESS, NULL, 0, len, [](uint8_t status, void *arg, uint8_t *data, uint8_t datalen) { RequestArg *ra = static_cast<RequestArg *>(arg); memcpy(ra->buffer, data, ra->dataLen); ra->lock = false; ra->status = status; }, static_cast<void *>(&cb)); while (cb.lock) { ESP.wdtFeed(); aWire.loop(); } return cb.status; } uint8_t HMC5883L::readSync(uint8_t *buf, uint8_t len, uint8_t reg) { RequestArg cb(buf, len); aWire.request(ADDRESS, &reg, 1, len, [](uint8_t status, void *arg, uint8_t *data, uint8_t datalen) { RequestArg *ra = static_cast<RequestArg *>(arg); memcpy(ra->buffer, data, ra->dataLen); ra->lock = false; ra->status = status; }, static_cast<void *>(&cb)); while (cb.lock) { ESP.wdtFeed(); aWire.loop(); } return cb.status; } uint8_t HMC5883L::readSync8() { uint8_t result = 0x00; readSync(&result, 1); return result; } uint8_t HMC5883L::readSync8(uint8_t reg) { uint8_t result = 0x00; readSync(&result, 1, reg); return result; } void HMC5883L::writeSync(uint8_t *data, uint8_t len, uint8_t reg) { uint8_t req[len + 1]; memcpy(&req[1], data, len); req[0] = reg; writeSync(req, static_cast<uint8_t>(len + 1)); } void HMC5883L::writeSync(uint8_t *data, uint8_t len) { SendArg sa; aWire.send(ADDRESS, data, len, [](uint8_t status, void *arg) { SendArg *sap = static_cast<SendArg *>(arg); sap->lock = false; sap->status = status; }, static_cast<void *>(&sa)); while (sa.lock) { ESP.wdtFeed(); aWire.loop(); } } void HMC5883L::setRegisterPointer(uint8_t reg) { writeSync8(reg, 1); } void HMC5883L::writeSync8(uint8_t data, uint8_t reg) { writeSync(&data, 1, reg); } void HMC5883L::writeSync8(uint8_t data) { writeSync(&data, 1); }
[ "dominicchm.g@gmail.com" ]
dominicchm.g@gmail.com
e1a44abc06282ebdf8d09729a62b15f3700d4cc2
fc71d399c24b9994e19e10d8e9c57eb2a4936cb3
/io/point_cloud_io.h
045a63dad3c6c18076c356f755a287b168af95e5
[ "Apache-2.0" ]
permissive
mctyro/draco
515e62ee6098c8d044d4e0b90abca2b880932d2d
259b198fcf55f7b44c60508e92e767f45a56e9e9
refs/heads/master
2021-01-11T19:02:51.216001
2017-01-18T03:39:02
2017-01-18T03:39:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,991
h
// Copyright 2016 The Draco Authors. // // 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 DRACO_IO_POINT_CLOUD_IO_H_ #define DRACO_IO_POINT_CLOUD_IO_H_ #include "compression/config/compression_shared.h" #include "compression/decode.h" #include "compression/encode.h" namespace draco { template <typename OutStreamT> OutStreamT WritePointCloudIntoStream(const PointCloud *pc, OutStreamT &&os, PointCloudEncodingMethod method, const EncoderOptions &options) { EncoderBuffer buffer; EncoderOptions local_options = options; local_options.SetGlobalInt("encoding_method", method); if (!EncodePointCloudToBuffer(*pc, local_options, &buffer)) { os.setstate(std::ios_base::badbit); return os; } os.write(static_cast<const char *>(buffer.data()), buffer.size()); return os; } template <typename OutStreamT> OutStreamT WritePointCloudIntoStream(const PointCloud *pc, OutStreamT &&os, PointCloudEncodingMethod method) { const EncoderOptions options = CreateDefaultEncoderOptions(); return WritePointCloudIntoStream(pc, os, method, options); } template <typename OutStreamT> OutStreamT &WritePointCloudIntoStream(const PointCloud *pc, OutStreamT &&os) { return WritePointCloudIntoStream(pc, os, POINT_CLOUD_SEQUENTIAL_ENCODING); } template <typename InStreamT> InStreamT &ReadPointCloudFromStream(std::unique_ptr<PointCloud> *point_cloud, InStreamT &&is) { // Determine size of stream and write into a vector auto is_size = is.tellg(); is.seekg(0, std::ios::end); is_size = is.tellg() - is_size; is.seekg(0, std::ios::beg); std::vector<char> data(is_size); is.read(&data[0], is_size); // Create a point cloud from that data. DecoderBuffer buffer; buffer.Init(&data[0], data.size()); *point_cloud = DecodePointCloudFromBuffer(&buffer); if (*point_cloud == nullptr) { is.setstate(std::ios_base::badbit); } return is; } // Reads a point cloud from a file. The function automatically chooses the // correct decoder based on the extension of the files. Currently, .obj and .ply // files are supported. Other file extensions are processed by the default // draco::PointCloudDecoder. // Returns nullptr if the decoding failed. std::unique_ptr<PointCloud> ReadPointCloudFromFile( const std::string &file_name); } // namespace draco #endif // DRACO_IO_POINT_CLOUD_IO_H_
[ "fgalligan@google.com" ]
fgalligan@google.com
586da1b421aaceb00bb4abf5d40358c2c3c39c8b
c993b955f1d0e77952c53a2abfe8f582a32a802c
/ref-impl/include/OM/OMWeakReferenceVectorIter.h
cca9392a893fcff429bc924863943dbca6d3fa8d
[]
no_license
christianscheuer/aaf
6d67e767f439d6f43c3b7fba64336876bcbc0b8d
0b76dd5bf4f70b0e7b3c33fd6d923ce6f67c71aa
refs/heads/master
2020-05-01T03:08:19.586353
2019-05-01T09:34:40
2019-05-01T09:34:40
177,238,098
0
0
null
2019-03-23T03:12:02
2019-03-23T03:12:02
null
UTF-8
C++
false
false
9,293
h
//=---------------------------------------------------------------------= // // $Id$ $Name$ // // The contents of this file are subject to the AAF SDK Public Source // License Agreement Version 2.0 (the "License"); You may not use this // file except in compliance with the License. The License is available // in AAFSDKPSL.TXT, or you may obtain a copy of the License from the // Advanced Media Workflow Association, Inc., or its successor. // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and limitations // under the License. Refer to Section 3.3 of the License for proper use // of this Exhibit. // // WARNING: Please contact the Advanced Media Workflow Association, // Inc., for more information about any additional licenses to // intellectual property covering the AAF Standard that may be required // to create and distribute AAF compliant products. // (http://www.amwa.tv/policies). // // Copyright Notices: // The Original Code of this file is Copyright 1998-2009, licensor of the // Advanced Media Workflow Association. All rights reserved. // // The Initial Developer of the Original Code of this file and the // licensor of the Advanced Media Workflow Association is // Avid Technology. // All rights reserved. // //=---------------------------------------------------------------------= // @doc OMEXTERNAL #ifndef OMWEAKREFERENCEVECTORITER_H #define OMWEAKREFERENCEVECTORITER_H #include "OMVectorIterator.h" #include "OMReferenceContainerIter.h" #include "OMContainerElement.h" template <typename Key, typename ReferencedObject> class OMWeakReferenceVectorProperty; // @class Iterators over <c OMWeakReferenceVectorProperty>s. // @tcarg class | ReferencedObject | The type of the contained objects. // @tcarg class | Key | The type of the identifier of the contained object. // @base public | <c OMReferenceContainerIterator> // @cauthor Tim Bingham | tjb | Avid Technology, Inc. template <typename Key, typename ReferencedObject> class OMWeakReferenceVectorIterator : public OMReferenceContainerIterator { public: // @access Public members. // @cmember Create an <c OMWeakReferenceVectorIterator> over the given // <c OMWeakReferenceVectorProperty> <p vector> and // initialize it to the given <p initialPosition>. // If <p initialPosition> is specified as // <e OMIteratorPosition.OMBefore> then this // <c OMWeakReferenceVectorIterator> is made ready to traverse // the associated <c OMWeakReferenceVectorProperty> in the // forward direction (increasing indexes). // If <p initialPosition> is specified as // <e OMIteratorPosition.OMAfter> then this // <c OMWeakReferenceVectorIterator> is made ready to traverse // the associated <c OMWeakReferenceVectorProperty> in the // reverse direction (decreasing indexes). OMWeakReferenceVectorIterator( const OMWeakReferenceVectorProperty<Key, ReferencedObject>& vector, OMIteratorPosition initialPosition = OMBefore); // @cmember Create a copy of this <c OMWeakReferenceVectorIterator>. virtual OMReferenceContainerIterator* copy(void) const; // @cmember Destroy this <c OMWeakReferenceVectorIterator>. virtual ~OMWeakReferenceVectorIterator(void); // @cmember Reset this <c OMWeakReferenceVectorIterator> to the given // <p initialPosition>. // If <p initialPosition> is specified as // <e OMIteratorPosition.OMBefore> then this // <c OMWeakReferenceVectorIterator> is made ready to traverse // the associated <c OMWeakReferenceVectorProperty> in the // forward direction (increasing indexes). // If <p initialPosition> is specified as // <e OMIteratorPosition.OMAfter> then this // <c OMWeakReferenceVectorIterator> is made ready to traverse // the associated <c OMWeakReferenceVectorProperty> in the // reverse direction (decreasing indexes). virtual void reset(OMIteratorPosition initialPosition = OMBefore); // @cmember Is this <c OMWeakReferenceVectorIterator> positioned before // the first <p ReferencedObject> ? virtual bool before(void) const; // @cmember Is this <c OMWeakReferenceVectorIterator> positioned after // the last <p ReferencedObject> ? virtual bool after(void) const; // @cmember Is this <c OMWeakReferenceVectorIterator> validly // positioned on a <p ReferencedObject> ? virtual bool valid(void) const; // @cmember The number of <p ReferencedObject>s in the associated // <c OMWeakReferenceVectorProperty>. virtual size_t count(void) const; // @cmember Advance this <c OMWeakReferenceVectorIterator> to the // next <p ReferencedObject>, if any. // If the end of the associated // <c OMWeakReferenceVectorProperty> is not reached then the // result is <e bool.true>, // <mf OMWeakReferenceVectorIterator::valid> becomes // <e bool.true> and <mf OMWeakReferenceVectorIterator::after> // becomes <e bool.false>. // If the end of the associated // <c OMWeakReferenceVectorProperty> is reached then the result // is <e bool.false>, <mf OMWeakReferenceVectorIterator::valid> // becomes <e bool.false> and // <mf OMWeakReferenceVectorIterator::after> becomes // <e bool.true>. virtual bool operator++(); // @cmember Retreat this <c OMWeakReferenceVectorIterator> to the // previous <p ReferencedObject>, if any. // If the beginning of the associated // <c OMWeakReferenceVectorProperty> is not reached then the // result is <e bool.true>, // <mf OMWeakReferenceVectorIterator::valid> becomes // <e bool.true> and <mf OMWeakReferenceVectorIterator::before> // becomes <e bool.false>. // If the beginning of the associated // <c OMWeakReferenceVectorProperty> is reached then the result // is <e bool.false>, <mf OMWeakReferenceVectorIterator::valid> // becomes <e bool.false> and // <mf OMWeakReferenceVectorIterator::before> becomes // <e bool.true>. virtual bool operator--(); // @cmember Return the <p ReferencedObject> in the associated // <c OMWeakReferenceVectorProperty> at the position currently // designated by this <c OMWeakReferenceVectorIterator>. virtual ReferencedObject* value(void) const; // @cmember Set the <p ReferencedObject> in the associated // <c OMWeakReferenceVectorProperty> at the position currently // designated by this <c OMWeakReferenceVectorIterator> to // <p newObject>. The previous <p ReferencedObject>, if any, // is returned. virtual ReferencedObject* setValue(const ReferencedObject* newObject); // @cmember Set the <p ReferencedObject> in the associated // <c OMWeakReferenceVectorProperty> at the position currently // designated by this <c OMWeakReferenceVectorIterator> to 0. // The previous <p ReferencedObject>, if any, is returned. virtual ReferencedObject* clearValue(void); // @cmember Return the index of the <p ReferencedObject> in the // associated <c OMWeakReferenceVectorProperty> at the position // currently designated by this // <c OMWeakReferenceVectorIterator>. virtual size_t index(void) const; // @cmember Return the <p Key> of the <p ReferencedObject> in the // associated <c OMWeakReferenceVectorProperty> at the position // currently designated by this <c OMWeakReferenceVectorIterator>. Key identification(void) const; // @cmember Return the <p OMObject> in the associated // reference container property at the position currently // designated by this <c OMWeakReferenceVectorIterator>. virtual OMObject* currentObject(void) const; // @cmember Clear (set to 0) the <p OMObject> in the associated // reference container at the position currently // designated by this <c OMWeakReferenceVectorIterator>. // The existing object, if any, is returned. The associated // reference container is not modified in that no entry is // removed, the existing entry remains but no longer refers // to a valid object. virtual OMObject* clearObject(void); protected: typedef OMWeakReferenceVectorElement VectorElement; typedef OMVectorIterator<VectorElement> VectorIterator; // @cmember Create an <c OMWeakReferenceVectorIterator> given // an underlying <c OMVectorIterator>. OMWeakReferenceVectorIterator(const VectorIterator& iter); private: VectorIterator _iterator; }; #include "OMWeakReferenceVectorIterT.h" #endif
[ "" ]
a273a5982be776085c16f9ae5858cb1cf52a7b8d
a01c6409954dece57baf5193e6b8d1cc6a347efd
/Classes/HelloWorldScene.cpp
325802b11b88ede463200d6747a8a4657ab3752a
[]
no_license
AidanBrasseur/Asteroid-Dodge
9e31b917c926184a1eac9adbbc5f5548f3667554
b909a5c2d292cce87d87fc33cb938405cf5a2b2b
refs/heads/master
2020-04-18T20:18:40.108317
2019-01-26T20:20:45
2019-01-26T20:20:45
167,734,542
0
0
null
null
null
null
UTF-8
C++
false
false
14,754
cpp
/**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. 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 "HelloWorldScene.h" #include "SimpleAudioEngine.h" #include <iostream> #include <string> USING_NS_CC; using namespace std; Scene* GetScene1(); Scene* GetSceneGameOver(int); Scene* HelloWorld::createScene() { return HelloWorld::create(); } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if (!Scene::init()) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); //background Sprite* background = Sprite::create("background.png"); float scale = MAX(visibleSize.width / background->getContentSize().width, visibleSize.height / background->getContentSize().height); background->setScale(scale); background->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)); this->addChild(background, 0); //Title cocos2d::Label *titleLabel; titleLabel = Label::createWithTTF("ASTEROID DODGE", "fonts/Marker Felt.ttf", 60); titleLabel->setColor(Color3B::WHITE); titleLabel->setPosition(Point(visibleSize.width/2, visibleSize.height - 300)); this->addChild(titleLabel , 1); //music audio auto audio = CocosDenshion::SimpleAudioEngine::getInstance(); audio->preloadBackgroundMusic("backgroundmusic.wav"); audio->playBackgroundMusic("backgroundmusic.wav", true); Vector<MenuItem*>menuItems; auto menuItemLabel1 = Label::createWithTTF("Play Game", "fonts/Marker Felt.ttf", 30); auto menuItem1 = MenuItemLabel::create(menuItemLabel1, [&](Ref* sender) { Director::getInstance()->pushScene(GetScene1()); } ); menuItem1->setPosition(Vec2(menuItem1->getPosition().x, menuItem1->getPosition().y + 30)); menuItems.pushBack(menuItem1); auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setAnchorPoint(Vec2(1, 1)); closeItem->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); menuItems.pushBack(closeItem); auto menu = Menu::createWithArray(menuItems); this->addChild(menu, 1); return true; } Scene* GetScene1() { auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto scene = Scene::createWithPhysics(); //effect audio auto audio = CocosDenshion::SimpleAudioEngine::getInstance(); audio->preloadEffect("explosion.wav"); //create player sprite Sprite* playerbot = Sprite::create("botfront1.png"); playerbot->setScale(2); playerbot->setTag(10); playerbot->setPosition(Vec2(visibleSize.width / 2 + origin.x, 350)); Vector<SpriteFrame*> playerbot_animFrames; playerbot_animFrames.reserve(3); playerbot_animFrames.pushBack(SpriteFrame::create("botfront1.png", Rect(0, 0, 32, 59))); playerbot_animFrames.pushBack(SpriteFrame::create("botfront2.png", Rect(0, 0, 32, 60))); playerbot_animFrames.pushBack(SpriteFrame::create("botfront3.png", Rect(0, 0, 32, 63))); auto playerbot_animation = Animation::createWithSpriteFrames(playerbot_animFrames, 0.1f); auto playerbot_animate = Animate::create(playerbot_animation); playerbot->runAction(RepeatForever::create(playerbot_animate)); scene->addChild(playerbot, 1); //create background Sprite* background = Sprite::create("background.png"); float scale = MAX(visibleSize.width / background->getContentSize().width, visibleSize.height / background->getContentSize().height); background->setScale(scale); background->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)); scene->addChild(background, 0); //close menu auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png", [&](Ref* sender) { Director::getInstance()->replaceScene(HelloWorld::create()); } ); closeItem->setAnchorPoint(Vec2(1, 1)); closeItem->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); auto menu = Menu::create(closeItem, NULL); scene->addChild(menu); //touch drag controls auto _eventDispatcher = Director::getInstance()->getEventDispatcher(); auto listener1 = EventListenerTouchOneByOne::create(); listener1->setSwallowTouches(true); listener1->onTouchBegan = [&](Touch* touch, Event* event) { return true; }; listener1->onTouchMoved = [=](Touch* touch, Event* event) { if (touch->getLocation().x < visibleSize.width && touch->getLocation().x > 0) { playerbot->setPositionX(touch->getLocation().x); } if (touch->getLocation().y < visibleSize.height && touch->getLocation().y > 0) { playerbot->setPositionY(touch->getLocation().y); } }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, scene); //scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); //Draw hitboxes for testing //create boundary line Sprite* boundary = Sprite::create("boundary line.png"); boundary->setTag(20); boundary->setScale(2); boundary->setPosition(visibleSize.width / 2, -10); auto boundaryphysicsBody = PhysicsBody::createBox(boundary->getContentSize(), PhysicsMaterial(0.1f, 1.0, 0.0f)); boundaryphysicsBody->setDynamic(false); boundaryphysicsBody->setContactTestBitmask(0x01); boundary->setPhysicsBody(boundaryphysicsBody); scene->addChild(boundary, 1); //physics for player auto spritephysicsBody = PhysicsBody::createBox(playerbot->getContentSize()/2, PhysicsMaterial(0.1f, 1.0, 0.0f)); //make hitbox half the size of the player for less frustration spritephysicsBody->setContactTestBitmask(0x01); spritephysicsBody->setDynamic(false); playerbot->setPhysicsBody(spritephysicsBody); //spawn first slow platforms auto scheduler = Director::getInstance()->getScheduler(); scheduler->schedule([=](float dt) { Sprite* asteroid = Sprite::create("Asteroid Brown.png"); asteroid->setScale(0.7); asteroid->setSkewY(30.0f); asteroid->setTag(5); asteroid->setPosition(cocos2d::RandomHelper::random_int(5, 530), 1000); auto asteroidPhysicsBody = PhysicsBody::createBox(asteroid->getContentSize(), PhysicsMaterial(0.1f, 1.0, 0.0f)); asteroidPhysicsBody->setVelocity(Vec2(0, -500)); asteroidPhysicsBody->setContactTestBitmask(0x01); asteroid->setPhysicsBody(asteroidPhysicsBody); scene->addChild(asteroid,1); }, scene, 0.5f, 10, 0.0f, false, "myCallbackKey"); //spawn faster platforms auto scheduler2 = Director::getInstance()->getScheduler(); scheduler2->schedule([=](float dt) { Sprite* asteroid = Sprite::create("Asteroid Brown.png"); asteroid->setScale(0.7); asteroid->setSkewY(30.0f); asteroid->setTag(5); asteroid->setPosition(cocos2d::RandomHelper::random_int(5, 530), 1000); auto asteroidPhysicsBody = PhysicsBody::createBox(asteroid->getContentSize(), PhysicsMaterial(0.1f, 1.0, 0.0f)); asteroidPhysicsBody->setVelocity(Vec2(0, -1000)); asteroidPhysicsBody->setContactTestBitmask(0x01); asteroid->setPhysicsBody(asteroidPhysicsBody); scene->addChild(asteroid, 1); }, scene, 0.5f, 10, 7.0f, false, "myCallbackKey2"); //spawn fastest platforms auto scheduler3 = Director::getInstance()->getScheduler(); scheduler2->schedule([=](float dt) { Sprite* asteroid = Sprite::create("Asteroid Brown.png"); asteroid->setScale(0.7); asteroid->setSkewY(30.0f); asteroid->setTag(5); asteroid->setPosition(cocos2d::RandomHelper::random_int(5, 530), 1000); auto asteroidPhysicsBody = PhysicsBody::createBox(asteroid->getContentSize(), PhysicsMaterial(0.1f, 1.0, 0.0f)); asteroidPhysicsBody->setVelocity(Vec2(0, -1200)); asteroidPhysicsBody->setContactTestBitmask(0x01); asteroid->setPhysicsBody(asteroidPhysicsBody); scene->addChild(asteroid, 1); }, scene, 0.4f, kRepeatForever, 12.0f, false, "myCallbackKey3"); //sometimes spawn 2 platforms when in fastest mode auto scheduler4 = Director::getInstance()->getScheduler(); scheduler4->schedule([=](float dt) { Sprite* asteroid = Sprite::create("Asteroid Brown.png"); asteroid->setScale(0.7); asteroid->setSkewY(30.0f); asteroid->setTag(5); asteroid->setPosition(cocos2d::RandomHelper::random_int(5, 530), 1000); auto asteroidPhysicsBody = PhysicsBody::createBox(asteroid->getContentSize(), PhysicsMaterial(0.1f, 1.0, 0.0f)); asteroidPhysicsBody->setVelocity(Vec2(0, -1200)); asteroidPhysicsBody->setContactTestBitmask(0x01); asteroid->setPhysicsBody(asteroidPhysicsBody); scene->addChild(asteroid, 1); }, scene, 1.0f, kRepeatForever, 20.0f, false, "myCallbackKey4"); //score Sprite* sprScore = Sprite::create("botfront1.png"); sprScore->setTag(10000); scene->addChild(sprScore, -2); cocos2d::Label *scoreLabel; scoreLabel = Label::createWithTTF(to_string(0), "fonts/Marker Felt.ttf", 35); scoreLabel->setColor(Color3B::WHITE); scoreLabel->setPosition(Point(120, visibleSize.height-30)); scene->addChild(scoreLabel, 1); cocos2d::Label *scoreLabelName; scoreLabelName = Label::createWithTTF("Score: ", "fonts/Marker Felt.ttf", 35); scoreLabelName->setColor(Color3B::WHITE); scoreLabelName->setPosition(Point(50, visibleSize.height - 30)); scene->addChild(scoreLabelName, 1); //contact auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = [=](PhysicsContact& contact) { auto nodeA = contact.getShapeA()->getBody()->getNode(); auto nodeB = contact.getShapeB()->getBody()->getNode(); scoreLabel->setString(to_string((sprScore->getTag() - 10000))); if (nodeA&&nodeB) { if (nodeA->getTag() == 10 && nodeB->getTag() == 5|| nodeA->getTag() == 5 && nodeB->getTag() == 10) { audio->playEffect("explosion.wav"); Director::getInstance()->pushScene(TransitionFade::create(0.5,GetSceneGameOver(sprScore->getTag()))); //return false; //invicibility for testing } else if (nodeA->getTag() == 5 && nodeB->getTag() == 20) { sprScore->setTag(sprScore->getTag() + 1);//score up nodeA->removeFromParentAndCleanup(true); } else if (nodeB->getTag() == 5 && nodeA->getTag() == 20) { sprScore->setTag(sprScore->getTag() + 1);//score up nodeB->removeFromParentAndCleanup(true); } else if (nodeB->getTag() == 5 && nodeA->getTag() == 5) { return false; } } return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, scene); return scene; } Scene* GetSceneGameOver(int score) { auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto scene = Scene::create(); //background Sprite* background = Sprite::create("gameoverbackground.jpg"); float scale = MAX(visibleSize.width / background->getContentSize().width, visibleSize.height / background->getContentSize().height); background->setScale(scale); background->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)); scene->addChild(background, 0); //gameover label auto label = Label::createWithTTF("Game Over", "fonts/Marker Felt.ttf", 70); auto vecLabel = Vec2(visibleSize.width / 2, visibleSize.height/1.25); label->setPosition(vecLabel); scene->addChild(label, 1); //score cocos2d::Label *scoreLabel; scoreLabel = Label::createWithTTF(to_string(score-10000), "fonts/Marker Felt.ttf", 35); scoreLabel->setColor(Color3B::WHITE); scoreLabel->setPosition(Point(visibleSize.width/2+40, visibleSize.height/1.5)); scene->addChild(scoreLabel, 1); cocos2d::Label *scoreLabelName; scoreLabelName = Label::createWithTTF("Score: ", "fonts/Marker Felt.ttf", 35); scoreLabelName->setColor(Color3B::WHITE); scoreLabelName->setPosition(Point(visibleSize.width/2-40, visibleSize.height/1.5)); scene->addChild(scoreLabelName, 1); Vector<MenuItem*>menuItems; //Try again menu auto menuItemLabel1 = Label::createWithTTF("Try Again? ", "fonts/Marker Felt.ttf", 35); auto menuItem1 = MenuItemLabel::create(menuItemLabel1, [&](Ref* sender) { Director::getInstance()->replaceScene(GetScene1()); } ); menuItem1->setPosition(Vec2(menuItem1->getPosition().x, menuItem1->getPosition().y + 30)); menuItems.pushBack(menuItem1); //close menu auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png", [&](Ref* sender) { Director::getInstance()->replaceScene(HelloWorld::create()); } ); closeItem->setAnchorPoint(Vec2(1, 1)); closeItem->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); menuItems.pushBack(closeItem); auto menu = Menu::createWithArray(menuItems); scene->addChild(menu, 1); return scene; } void HelloWorld::menuCloseCallback(Ref* pSender) { //Close the cocos2d-x game scene and quit the application Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif /*To navigate back to native iOS screen(if present) without quitting the application ,do not use Director::getInstance()->end() and exit(0) as given above,instead trigger a custom event created in RootViewController.mm as below*/ //EventCustom customEndEvent("game_scene_close_event"); //_eventDispatcher->dispatchEvent(&customEndEvent); }
[ "noreply@github.com" ]
noreply@github.com
dbdd15fc046105550323e3f2659e8ecb366fad5b
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/curl/gumtree/curl_repos_function_163_curl-7.51.0.cpp
9e2d92d0705ff8b0e532f6b7c4435c8d58654625
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
766
cpp
static void mcode_or_die(const char *where, CURLMcode code) { if(CURLM_OK != code) { const char *s; switch (code) { case CURLM_BAD_HANDLE: s="CURLM_BAD_HANDLE"; break; case CURLM_BAD_EASY_HANDLE: s="CURLM_BAD_EASY_HANDLE"; break; case CURLM_OUT_OF_MEMORY: s="CURLM_OUT_OF_MEMORY"; break; case CURLM_INTERNAL_ERROR: s="CURLM_INTERNAL_ERROR"; break; case CURLM_BAD_SOCKET: s="CURLM_BAD_SOCKET"; break; case CURLM_UNKNOWN_OPTION: s="CURLM_UNKNOWN_OPTION"; break; case CURLM_LAST: s="CURLM_LAST"; break; default: s="CURLM_unknown"; } MSG_OUT("ERROR: %s returns %s\n", where, s); exit(code); } }
[ "993273596@qq.com" ]
993273596@qq.com
919a3b4a6e084f0496555594cc417674a1a762a6
e0387cf8f45d3e2b7ea3788b299f195a621708a8
/Source/Sable/Graphics/LensFlare/RenderPass.h
e36c569155f4205afe3b28438d99e434433c3edb
[]
no_license
ClementVidal/sable.sable
eea0e822d90739269e35bed20805a2789b5fbc81
0ec2cd03867a4673472c1bc7b071a3f16b55fb1b
refs/heads/master
2021-01-13T01:28:54.070144
2013-10-15T15:21:49
2013-10-15T15:21:49
39,085,785
0
0
null
null
null
null
UTF-8
C++
false
false
1,775
h
#ifndef _SABLE_GRAPHICS_LENSFLARE_RENDERPASS_ #define _SABLE_GRAPHICS_LENSFLARE_RENDERPASS_ #include <Sable\Core\Common\DataTypes.h> #include <Sable\Graphics\Geometry\Header.h> #include <Sable\Graphics\Shader\Header.h> #include <Sable\Graphics\RenderPass\RenderPass.h> #include <Sable\Graphics\States\HEader.h> #define WorldLensFlareRenderer CLensFlareRenderPass::GetInstance() #define WORLDLENSFLARERENDERER_MAX_FLARE 32 namespace Sable { class CSceneWorld; class CLensFlare; class CRenderer; class CSceneWorld; /** \ingroup SceneWorld WorldLensFlareRenderer */ class CLensFlareRenderPass : public CRenderPass { DEFINE_MANAGED_CLASS( CLensFlareRenderPass ); public: /** @name DataTypes*/ //@{ struct SVertex { CVector2f Pos; CVector2f TexCoord0; }; //@} /** @name Constructor/Destructor*/ //@{ CLensFlareRenderPass(); CLensFlareRenderPass(CRenderer& renderer); ~CLensFlareRenderPass(); //@} /** @name Accessors*/ //@{ Void AddLensFlare( CLensFlare& flare ); //@} /** @name Manipulator*/ //@{ Void Initialize(CRenderer &renderer); Bool ProcessTraversedNode( CNode& node, CRenderer& renderer ); Void Render( CRenderer& renderer ); //@} private: // Method //Attribute CLensFlare* m_FlareTable[WORLDLENSFLARERENDERER_MAX_FLARE]; UInt32 m_FlareCount; CGeometryVertexBuffer m_VertexBuffer; CGeometryVertexLayout m_VertexLayout; CRef<CShader> m_Shader; CStatesBlend m_BlendStates; CStatesDepthStencil m_DepthStates; }; } #endif
[ "clement.vidal@lam.fr" ]
clement.vidal@lam.fr
e63b011891167f27bfeb4f6cf3f018f328fa9b0d
1f27129f4400f633428231f459e15d6f9d48db89
/TransferList.cpp
71067296a6e942c0b2e55e4e7e62082e49bf1b49
[]
no_license
Disky/sdat2img
7b4947ea47baae5c0201a6b1d297f69e54a38ecf
9a9b47ccf43f025e7e3b864686f91ec71cbc6e8a
refs/heads/master
2021-01-12T16:28:46.103874
2016-08-31T06:14:41
2016-08-31T06:14:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,530
cpp
/* -*- coding: utf-8 -*- * Filename : TransferList.cpp * Date : 2016-08-16 */ #include <cstdio> #include <cstdlib> #include <cstring> #include <vector> #include <string> #include <algorithm> #include <TransferList.hpp> TransferList::TransferList(FILE *__fp) { Initializer(__fp); } void TransferList::Initializer(FILE *__transfer_fp) { char buf[255] = {0}; this->version = atoi(fgets(buf,sizeof(buf),__transfer_fp)); this->count = atoi(fgets(buf,sizeof(buf),__transfer_fp)); while(fgets(buf,sizeof(buf),__transfer_fp)) { if(!strncmp(buf,erase_prefix,strlen(erase_prefix))) this->erase_cmd = split(strstr(buf," ") + 1,','); else if(!strncmp(buf,new_prefix,strlen(new_prefix))) this->new_cmd = split(strstr(buf," ") + 1,','); else if(!strncmp(buf,zero_prefix,strlen(zero_prefix))) this->zero_cmd = split(strstr(buf," ") + 1,','); } } std::vector<int> TransferList::split(char *__src,const char __deim) { std::vector<int> temp; std::string str(__src); unsigned begin = 0,end = 0; for(;(end = str.find_first_of(__deim,begin)) != std::string::npos;) { temp.push_back(atoi(str.substr(begin,end - begin).c_str())); begin = end + 1; } temp.push_back(atoi(str.substr(begin).c_str())); return temp; } int TransferList::GetMax() { int v1 = *std::max_element(this->erase_cmd.begin(),this->erase_cmd.end()); int v2 = *std::max_element(this->new_cmd.begin(),this->new_cmd.end()); int v3 = *std::max_element(this->zero_cmd.begin(),this->zero_cmd.end()); int max = std::max({v1,v2,v3}); return max; }
[ "zerozakiGeek@gmail.com" ]
zerozakiGeek@gmail.com
29f3361ae7502e56fdf02a156fc6119abd4248d6
e95adb59feacfe95904c3a8e90a4159860b6c26a
/build/Android/Preview/outsideTheBox/app/src/main/include/Uno.ColorHelper.h
140e424b8bef71153c651ab9d0f8e6bfb8dfb6a1
[]
no_license
deliloka/bethebox
837dff20c1ff55db631db1e0f6cb51d935497e91
f9bc71b8593dd54b8aaf86bc0a654d233432c362
refs/heads/master
2021-01-21T08:20:42.970891
2016-02-19T10:00:37
2016-02-19T10:00:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
630
h
// This file was generated based on '/usr/local/share/uno/Packages/UnoCore/0.23.4/Source/Uno/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.h> namespace g{namespace Uno{struct ColorHelper;}} namespace g{ namespace Uno{ // internal static class ColorHelper :1517 // { uClassType* ColorHelper_typeof(); void ColorHelper__BaseValue_fn(uChar* c, int* __retval); void ColorHelper__ParseBase_fn(uString* str, int* radix, int* __retval); struct ColorHelper : uObject { static int BaseValue(uChar c); static int ParseBase(uString* str, int radix); }; // } }} // ::g::Uno
[ "Havard.Halse@nrk.no" ]
Havard.Halse@nrk.no
f2a4eea9a284b9591b5cb41eddd9e12903daf21a
4a19d087cf29ea07ac6b19e6f86c416793f89966
/geom/segment3.hpp
e2f2d9e486704a60c9aea76b4fa8597c5ec2266d
[]
no_license
venkat78/agrid
17a9e570bd15ae3b76a821e1a726e7a83658798a
511894fc385c416aad2a113fe5fb5081676ef6a0
refs/heads/master
2021-01-01T05:49:49.362889
2013-03-30T14:44:29
2013-03-30T14:44:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,363
hpp
#ifndef _GEOM_SEGMENT3_H_ #define _GEOM_SEGMENT3_H_ namespace geom { class cBOX3; class cSEGMENT3 { public: cSEGMENT3() {} cSEGMENT3(const cSEGMENT3 &segment) : m_endPoints(segment.m_endPoints) {} cSEGMENT3(const cPOINT3 &point1, const cPOINT3 &point2) : m_endPoints(point1, point2) {} cBOX3 ComputeBbox() const ;//{ // return cBOX3(m_endPoints[0], m_endPoints[1]); // } VOID Invert() { cPOINT3 p = m_endPoints[0]; m_endPoints[0] = m_endPoints[1]; m_endPoints[1] = p; } BOOL HasOn(const cPOINT3 &point) const ; /* * Returns index of the endpoint if point is an end. * Returns -1 if point is not an endpoint. */ INT IsEndPoint(const cPOINT3 &point) const { if(point == Source()) return 0; if(point == Target()) return 1; return -1; } cPOINT3 MidPoint() const { return (m_endPoints[0] + m_endPoints[1])*0.5; } cPOINT3 Vertex(INT i) const { return m_endPoints[i]; } VOID Print(FILE *stream = stdout) const { fprintf(stream, "Segment ep1 %.12lf %.12lf %.12lf \n", m_endPoints[0][0], m_endPoints[0][1], m_endPoints[0][2]); fprintf(stream, "Segment ep2 %.12lf %.12lf %.12lf \n", m_endPoints[1][0], m_endPoints[1][1], m_endPoints[1][2]); } REAL Length() { return Vector().Length(); } VOID Print1(FILE *stream = stdout) const { fprintf(stream, "%lf %lf %lf; ", m_endPoints[0][0], m_endPoints[0][1], m_endPoints[0][2]); fprintf(stream, "%lf %lf %lf;\n", m_endPoints[1][0], m_endPoints[1][1], m_endPoints[1][2]); } const cPOINT3& Source() const { return m_endPoints[0]; } const cPOINT3& Target() const { return m_endPoints[1]; } cVECTOR3 Vector() const { return m_endPoints[1] - m_endPoints[0];} cLINE3 SupportingLine() const { return cLINE3(m_endPoints[0], m_endPoints[1]); } cPOINT3 Evaluate(REAL param) const { return (Source()*(1.0-param)) + (Target()*param); } REAL PointProjectionParam(const cPOINT3 &point); cPOINT3 PointProjectionPoint(const cPOINT3 &point); BOOL SegmentDistanceParams(const cSEGMENT3 &seg, REAL & param1, REAL & param2) const; /* * Assumes point is on the segment. */ REAL Param(const cPOINT3 &point) const { return cLINE3(Vertex(0), Vertex(1)).Param(point); } protected: tPAIR<cPOINT3> m_endPoints; }; } #endif //_GEOM_SEGMENT3_H_
[ "Bujji@localhost" ]
Bujji@localhost
abd567cd578dd38248b645c21e5fb78e03890c60
f712e1363a52e67c50631b3dcc712c361f53a1a2
/Gold/src/Gold/Renderer/SubTexture2D.cpp
c69dd83cd8aefba7a6eacadbb60fe7d82354a5ec
[ "Apache-2.0" ]
permissive
namolab/Gold
98de8eacd859ad59ce371d775d886b1feeb6ccc5
a6f848248efd596887e7b411e84edde3451f8a01
refs/heads/main
2023-09-05T09:32:16.963944
2021-11-21T07:11:52
2021-11-21T07:11:52
400,080,126
0
0
null
null
null
null
UTF-8
C++
false
false
833
cpp
#include "hzpch.h" #include "SubTexture2D.h" namespace Gold { SubTexture2D::SubTexture2D(const Ref<Texture2D>& texture, const glm::vec2& min, const glm::vec2& max) :m_Texture(texture) { m_TexCoords[0] = { min.x,min.y }; m_TexCoords[1] = { max.x,min.y }; m_TexCoords[2] = { max.x,max.y }; m_TexCoords[3] = { min.x,max.y }; } Ref<SubTexture2D> SubTexture2D::CreateFromCoords(const Ref<Texture2D>& texture, const glm::vec2& coords, const glm::vec2& cellSize, const glm::vec2& spriteSize) { glm::vec2 min = { (coords.x * cellSize.x / texture->GetWidth()), (coords.y * cellSize.y / texture->GetHeight()) }; glm::vec2 max = { ((coords.x + spriteSize.x) * cellSize.x) / texture->GetWidth(), ((coords.y + spriteSize.y) * cellSize.y) / texture->GetHeight() }; return CreateRef<SubTexture2D>(texture, min, max); } }
[ "namolab108@gmail.com" ]
namolab108@gmail.com
3894c39e41130c219639491b130d25e864143a87
31e23df00ac3c137622fc26ca9b3d158b82197db
/sodium/sodium.cpp
7189a811f54a40eb6bc3d51848cabdf923505f52
[]
no_license
indigos33k3r/sodium-cxx
6fb5c580676b69df959e5a247272d54dd48ea5eb
e25e2884e2543f608de34fb92d719f0724d5a5c7
refs/heads/master
2020-04-15T13:41:31.792765
2017-08-03T00:26:59
2017-08-03T00:26:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,396
cpp
/** * Copyright (c) 2012-2014, Stephen Blackheath and Anthony Jones * Released under a BSD3 licence. * * C++ implementation courtesy of International Telematics Ltd. */ #include <sodium/sodium.h> using namespace std; using namespace boost; namespace sodium { namespace impl { stream_::stream_() { } /*! * listen to streams. */ std::function<void()>* stream_::listen_raw( transaction_impl* trans, const SODIUM_SHARED_PTR<impl::node>& target, std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>* handler, bool suppressEarlierFirings) const { SODIUM_SHARED_PTR<holder> h(new holder(handler)); return listen_impl(trans, target, h, suppressEarlierFirings); } cell_ stream_::hold_(transaction_impl* trans, const light_ptr& initA) const { return cell_( SODIUM_SHARED_PTR<impl::cell_impl>(impl::hold(trans, initA, *this)) ); } cell_ stream_::hold_lazy_(transaction_impl* trans, const std::function<light_ptr()>& initA) const { return cell_( SODIUM_SHARED_PTR<impl::cell_impl>(impl::hold_lazy(trans, initA, *this)) ); } #define KILL_ONCE(ppKill) \ do { \ function<void()>* pKill = *ppKill; \ if (pKill != NULL) { \ *ppKill = NULL; \ (*pKill)(); \ delete pKill; \ } \ } while (0) stream_ stream_::once_(transaction_impl* trans1) const { SODIUM_SHARED_PTR<function<void()>*> ppKill(new function<void()>*(NULL)); SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = impl::unsafe_new_stream(); *ppKill = listen_raw(trans1, SODIUM_TUPLE_GET<1>(p), new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [ppKill] (const std::shared_ptr<impl::node>& target, impl::transaction_impl* trans2, const light_ptr& ptr) { if (*ppKill) { send(target, trans2, ptr); KILL_ONCE(ppKill); } }), false); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup( new std::function<void()>([ppKill] () { KILL_ONCE(ppKill); }) ); } stream_ stream_::merge_(transaction_impl* trans1, const stream_& other) const { SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = impl::unsafe_new_stream(); SODIUM_SHARED_PTR<impl::node> left(new impl::node); const SODIUM_SHARED_PTR<impl::node>& right = SODIUM_TUPLE_GET<1>(p); char* h = new char; if (left->link(h, right)) trans1->to_regen = true; // defer right side to make sure merge is left-biased auto kill1 = this->listen_raw(trans1, left, new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [right] (const std::shared_ptr<impl::node>&, impl::transaction_impl* trans2, const light_ptr& a) { send(right, trans2, a); }), false); auto kill2 = other.listen_raw(trans1, right, NULL, false); auto kill3 = new std::function<void()>([left, h] () { left->unlink(h); delete h; }); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup(kill1, kill2, kill3); } struct coalesce_state { coalesce_state() {} ~coalesce_state() {} boost::optional<light_ptr> oValue; }; stream_ stream_::coalesce_(transaction_impl* trans1, const std::function<light_ptr(const light_ptr&, const light_ptr&)>& combine ) const { SODIUM_SHARED_PTR<coalesce_state> pState(new coalesce_state); SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = impl::unsafe_new_stream(); auto kill = listen_raw(trans1, SODIUM_TUPLE_GET<1>(p), new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [pState, combine] (const std::shared_ptr<impl::node>& target, impl::transaction_impl* trans2, const light_ptr& ptr) { if (!pState->oValue) { pState->oValue = boost::optional<light_ptr>(ptr); trans2->prioritized(target, [target, pState] (transaction_impl* trans3) { if (pState->oValue) { send(target, trans3, pState->oValue.get()); pState->oValue = boost::optional<light_ptr>(); } }); } else pState->oValue = make_optional(combine(pState->oValue.get(), ptr)); }), false); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup(kill); } stream_ stream_::last_firing_only_(transaction_impl* trans) const { return coalesce_(trans, [] (const light_ptr& fst, const light_ptr& snd) { return snd; }); } /*! * Sample the cell's value as at the transaction before the * current one, i.e. no changes from the current transaction are * taken. */ stream_ stream_::snapshot_(transaction_impl* trans1, const cell_& beh, const std::function<light_ptr(const light_ptr&, const light_ptr&)>& combine ) const { SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = impl::unsafe_new_stream(); auto kill = listen_raw(trans1, SODIUM_TUPLE_GET<1>(p), new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [beh, combine] (const std::shared_ptr<impl::node>& target, impl::transaction_impl* trans2, const light_ptr& a) { send(target, trans2, combine(a, beh.impl->sample())); }), false); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup(kill); } /*! * Filter this stream based on the specified predicate, passing through values * where the predicate returns true. */ stream_ stream_::filter_(transaction_impl* trans1, const std::function<bool(const light_ptr&)>& pred ) const { SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = impl::unsafe_new_stream(); auto kill = listen_raw(trans1, std::get<1>(p), new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [pred] (const std::shared_ptr<impl::node>& target, impl::transaction_impl* trans2, const light_ptr& ptr) { if (pred(ptr)) send(target, trans2, ptr); }), false); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup(kill); } cell_impl::cell_impl() : updates(stream_()), kill(NULL) { } cell_impl::cell_impl( const stream_& updates_, const SODIUM_SHARED_PTR<cell_impl>& parent_) : updates(updates_), kill(NULL), parent(parent_) { } cell_impl::~cell_impl() { if (kill) { (*kill)(); delete kill; } } /*! * Function to push a value into an stream */ void send(const SODIUM_SHARED_PTR<node>& n, transaction_impl* trans1, const light_ptr& a) { if (n->firings.begin() == n->firings.end()) trans1->last([n] () { n->firings.clear(); }); n->firings.push_front(a); SODIUM_FORWARD_LIST<node::target>::iterator it = n->targets.begin(); while (it != n->targets.end()) { node::target* f = &*it; trans1->prioritized(f->n, [f, a] (transaction_impl* trans2) { trans2->inCallback++; try { ((holder*)f->h)->handle(f->n, trans2, a); trans2->inCallback--; } catch (...) { trans2->inCallback--; throw; } }); it++; } } /*! * Creates an stream, that values can be pushed into using impl::send(). */ SODIUM_TUPLE<stream_, SODIUM_SHARED_PTR<node> > unsafe_new_stream() { SODIUM_SHARED_PTR<node> n1(new node); SODIUM_WEAK_PTR<node> n_weak(n1); boost::intrusive_ptr<listen_impl_func<H_STRONG> > impl( new listen_impl_func<H_STRONG>(new listen_impl_func<H_STRONG>::closure([n_weak] (transaction_impl* trans1, const SODIUM_SHARED_PTR<node>& target, const SODIUM_SHARED_PTR<holder>& h, bool suppressEarlierFirings) -> std::function<void()>* { // Register listener SODIUM_SHARED_PTR<node> n2 = n_weak.lock(); if (n2) { #if !defined(SODIUM_SINGLE_THREADED) transaction_impl::part->mx.lock(); #endif if (n2->link(h.get(), target)) trans1->to_regen = true; #if !defined(SODIUM_SINGLE_THREADED) transaction_impl::part->mx.unlock(); #endif if (!suppressEarlierFirings && n2->firings.begin() != n2->firings.end()) { SODIUM_FORWARD_LIST<light_ptr> firings = n2->firings; trans1->prioritized(target, [target, h, firings] (transaction_impl* trans2) { for (SODIUM_FORWARD_LIST<light_ptr>::const_iterator it = firings.begin(); it != firings.end(); it++) h->handle(target, trans2, *it); }); } SODIUM_SHARED_PTR<holder>* h_keepalive = new SODIUM_SHARED_PTR<holder>(h); return new std::function<void()>([n_weak, h_keepalive] () { // Unregister listener impl::transaction_ trans2; trans2.impl()->last([n_weak, h_keepalive] () { std::shared_ptr<node> n3 = n_weak.lock(); if (n3) n3->unlink((*h_keepalive).get()); delete h_keepalive; }); }); } else return NULL; })) ); n1->listen_impl = boost::intrusive_ptr<listen_impl_func<H_NODE> >( reinterpret_cast<listen_impl_func<H_NODE>*>(impl.get())); boost::intrusive_ptr<listen_impl_func<H_STREAM> > li_stream( reinterpret_cast<listen_impl_func<H_STREAM>*>(impl.get())); return SODIUM_MAKE_TUPLE(stream_(li_stream), n1); } stream_sink_impl::stream_sink_impl() { } stream_ stream_sink_impl::construct() { SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = impl::unsafe_new_stream(); this->target = SODIUM_TUPLE_GET<1>(p); return SODIUM_TUPLE_GET<0>(p); } void stream_sink_impl::send(transaction_impl* trans, const light_ptr& value) const { sodium::impl::send(target, trans, value); } SODIUM_SHARED_PTR<cell_impl> hold(transaction_impl* trans0, const light_ptr& initValue, const stream_& input) { #if defined(SODIUM_CONSTANT_OPTIMIZATION) if (input.is_never()) return SODIUM_SHARED_PTR<cell_impl>(new cell_impl_constant(initValue)); else { #endif SODIUM_SHARED_PTR<cell_impl_concrete<cell_state> > impl( new cell_impl_concrete<cell_state>(input, cell_state(initValue), std::shared_ptr<cell_impl>()) ); SODIUM_WEAK_PTR<cell_impl_concrete<cell_state> > impl_weak(impl); impl->kill = input.listen_raw(trans0, SODIUM_SHARED_PTR<node>(new node(SODIUM_IMPL_RANK_T_MAX)), new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [impl_weak] (const std::shared_ptr<impl::node>& target, transaction_impl* trans, const light_ptr& ptr) { SODIUM_SHARED_PTR<cell_impl_concrete<cell_state> > impl_ = impl_weak.lock(); if (impl_) { bool first = !impl_->state.update; impl_->state.update = boost::optional<light_ptr>(ptr); if (first) trans->last([impl_] () { impl_->state.finalize(); }); send(target, trans, ptr); } }) , false); return impl; #if defined(SODIUM_CONSTANT_OPTIMIZATION) } #endif } SODIUM_SHARED_PTR<cell_impl> hold_lazy(transaction_impl* trans0, const std::function<light_ptr()>& initValue, const stream_& input) { SODIUM_SHARED_PTR<cell_impl_concrete<cell_state_lazy> > impl( new cell_impl_concrete<cell_state_lazy>(input, cell_state_lazy(initValue), std::shared_ptr<cell_impl>()) ); SODIUM_WEAK_PTR<cell_impl_concrete<cell_state_lazy> > w_impl(impl); impl->kill = input.listen_raw(trans0, SODIUM_SHARED_PTR<node>(new node(SODIUM_IMPL_RANK_T_MAX)), new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [w_impl] (const std::shared_ptr<impl::node>& target, transaction_impl* trans, const light_ptr& ptr) { SODIUM_SHARED_PTR<cell_impl_concrete<cell_state_lazy> > impl_ = w_impl.lock(); if (impl_) { bool first = !impl_->state.update; impl_->state.update = boost::optional<light_ptr>(ptr); if (first) trans->last([impl_] () { impl_->state.finalize(); }); send(target, trans, ptr); } }) , false); return static_pointer_cast<cell_impl, cell_impl_concrete<cell_state_lazy>>(impl); } cell_::cell_() { } cell_::cell_(cell_impl* impl_) : impl(impl_) { } cell_::cell_(SODIUM_SHARED_PTR<cell_impl> impl_) : impl(std::move(impl_)) { } cell_::cell_(light_ptr a) : impl(new cell_impl_constant(std::move(a))) { } stream_ cell_::value_(transaction_impl* trans) const { SODIUM_TUPLE<stream_,SODIUM_SHARED_PTR<node> > p = unsafe_new_stream(); const stream_& eSpark = std::get<0>(p); const SODIUM_SHARED_PTR<node>& node = std::get<1>(p); send(node, trans, light_ptr::create<unit>(unit())); stream_ eInitial = eSpark.snapshot_(trans, *this, [] (const light_ptr& a, const light_ptr& b) -> light_ptr { return b; } ); return eInitial.merge_(trans, impl->updates).last_firing_only_(trans); } #if defined(SODIUM_CONSTANT_OPTIMIZATION) /*! * For optimization, if this cell is a constant, then return its value. */ boost::optional<light_ptr> cell_::get_constant_value() const { return impl->updates.is_never() ? boost::optional<light_ptr>(impl->sample()) : boost::optional<light_ptr>(); } #endif struct applicative_state { applicative_state() : fired(false) {} bool fired; boost::optional<light_ptr> f; boost::optional<light_ptr> a; }; cell_ apply(transaction_impl* trans0, const cell_& bf, const cell_& ba) { #if defined(SODIUM_CONSTANT_OPTIMIZATION) boost::optional<light_ptr> ocf = bf.get_constant_value(); if (ocf) { // function is constant auto f = *ocf.get().cast_ptr<std::function<light_ptr(const light_ptr&)>>(NULL); return impl::map_(trans0, f, ba); // map optimizes to a constant where ba is constant } else { boost::optional<light_ptr> oca = ba.get_constant_value(); if (oca) { // 'a' value is constant but function is not const light_ptr& a = oca.get(); return impl::map_(trans0, [a] (const light_ptr& pf) -> light_ptr { const std::function<light_ptr(const light_ptr&)>& f = *pf.cast_ptr<std::function<light_ptr(const light_ptr&)>>(NULL); return f(a); }, bf); } else { #endif // Non-constant case SODIUM_SHARED_PTR<applicative_state> state(new applicative_state); SODIUM_SHARED_PTR<impl::node> in_target(new impl::node); SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = impl::unsafe_new_stream(); const SODIUM_SHARED_PTR<impl::node>& out_target = SODIUM_TUPLE_GET<1>(p); char* h = new char; if (in_target->link(h, out_target)) trans0->to_regen = true; auto output = [state, out_target] (transaction_impl* trans) { auto f = *state->f.get().cast_ptr<std::function<light_ptr(const light_ptr&)>>(NULL); send(out_target, trans, f(state->a.get())); state->fired = false; }; auto kill1 = bf.value_(trans0).listen_raw(trans0, in_target, new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [state, out_target, output] (const std::shared_ptr<impl::node>& target, transaction_impl* trans, const light_ptr& f) { state->f = f; if (state->a) { if (state->fired) return; state->fired = true; trans->prioritized(out_target, output); } } ), false); auto kill2 = ba.value_(trans0).listen_raw(trans0, in_target, new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [state, out_target, output] (const std::shared_ptr<impl::node>& target, transaction_impl* trans, const light_ptr& a) { state->a = a; if (state->f) { if (state->fired) return; state->fired = true; trans->prioritized(out_target, output); } } ), false); auto kill3 = new std::function<void()>([in_target, h] () { in_target->unlink(h); delete h; }); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup(kill1, kill2, kill3).hold_lazy_( trans0, [bf, ba] () -> light_ptr { auto f = *bf.impl->sample().cast_ptr<std::function<light_ptr(const light_ptr&)>>(NULL); return f(ba.impl->sample()); } ); #if defined(SODIUM_CONSTANT_OPTIMIZATION) } } #endif } stream_ stream_::add_cleanup_(transaction_impl* trans, std::function<void()>* cleanup) const { SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = impl::unsafe_new_stream(); auto kill = listen_raw(trans, std::get<1>(p), new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>(send), false); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup(kill, cleanup); } /*! * Map a function over this stream to modify the output value. */ stream_ map_(transaction_impl* trans1, const std::function<light_ptr(const light_ptr&)>& f, const stream_& ev) { SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = impl::unsafe_new_stream(); auto kill = ev.listen_raw(trans1, std::get<1>(p), new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [f] (const std::shared_ptr<impl::node>& target, impl::transaction_impl* trans2, const light_ptr& ptr) { send(target, trans2, f(ptr)); }), false); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup(kill); } cell_ map_(transaction_impl* trans, const std::function<light_ptr(const light_ptr&)>& f, const cell_& beh) { #if defined(SODIUM_CONSTANT_OPTIMIZATION) boost::optional<light_ptr> ca = beh.get_constant_value(); if (ca) return cell_(f(ca.get())); else { #endif auto impl = beh.impl; return map_(trans, f, beh.updates_()).hold_lazy_(trans, [f, impl] () -> light_ptr { return f(impl->sample()); }); #if defined(SODIUM_CONSTANT_OPTIMIZATION) } #endif } stream_ switch_s(transaction_impl* trans0, const cell_& bea) { SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = unsafe_new_stream(); const SODIUM_SHARED_PTR<impl::node>& target1 = SODIUM_TUPLE_GET<1>(p); std::shared_ptr<function<void()>*> pKillInner(new function<void()>*(NULL)); trans0->prioritized(target1, [pKillInner, bea, target1] (transaction_impl* trans) { if (*pKillInner == NULL) *pKillInner = bea.impl->sample().cast_ptr<stream_>(NULL)->listen_raw(trans, target1, NULL, false); }); auto killOuter = bea.updates_().listen_raw(trans0, target1, new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [pKillInner] (const std::shared_ptr<impl::node>& target2, impl::transaction_impl* trans1, const light_ptr& pea) { const stream_& ea = *pea.cast_ptr<stream_>(NULL); trans1->last([pKillInner, ea, target2, trans1] () { KILL_ONCE(pKillInner); *pKillInner = ea.listen_raw(trans1, target2, NULL, true); }); }), false ); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup( new std::function<void()>([pKillInner] { KILL_ONCE(pKillInner); }) , killOuter); } cell_ switch_c(transaction_impl* trans0, const cell_& bba) { auto za = [bba] () -> light_ptr { return bba.impl->sample().cast_ptr<cell_>(NULL)->impl->sample(); }; SODIUM_SHARED_PTR<function<void()>*> pKillInner(new function<void()>*(NULL)); SODIUM_TUPLE<impl::stream_,SODIUM_SHARED_PTR<impl::node> > p = unsafe_new_stream(); auto out_target = SODIUM_TUPLE_GET<1>(p); auto killOuter = bba.value_(trans0).listen_raw(trans0, out_target, new std::function<void(const std::shared_ptr<impl::node>&, transaction_impl*, const light_ptr&)>( [pKillInner] (const std::shared_ptr<impl::node>& target, transaction_impl* trans, const light_ptr& pa) { // Note: If any switch takes place during a transaction, then the // value().listen will always cause a sample to be fetched from the // one we just switched to. The caller will be fetching our output // using value().listen, and value() throws away all firings except // for the last one. Therefore, anything from the old input cell // that might have happened during this transaction will be suppressed. KILL_ONCE(pKillInner); const cell_& ba = *pa.cast_ptr<cell_>(NULL); *pKillInner = ba.value_(trans).listen_raw(trans, target, NULL, false); }) , false); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup( new std::function<void()>([pKillInner] { KILL_ONCE(pKillInner); }) , killOuter).hold_lazy_(trans0, za); } stream_ filter_optional_(transaction_impl* trans1, const stream_& input, const std::function<boost::optional<light_ptr>(const light_ptr&)>& f) { auto p = impl::unsafe_new_stream(); auto kill = input.listen_raw(trans1, std::get<1>(p), new std::function<void(const SODIUM_SHARED_PTR<impl::node>&, impl::transaction_impl*, const light_ptr&)>( [f] (const SODIUM_SHARED_PTR<impl::node>& target, impl::transaction_impl* trans2, const light_ptr& poa) { boost::optional<light_ptr> oa = f(poa); if (oa) impl::send(target, trans2, oa.get()); }) , false); return SODIUM_TUPLE_GET<0>(p).unsafe_add_cleanup(kill); } }; // end namespace impl }; // end namespace sodium
[ "docks.cattlemen.stephen@blacksapphire.com" ]
docks.cattlemen.stephen@blacksapphire.com
a13192faaddca55c24e81645605ac1ca0ec18340
4447608a41fcb78243a2394d909f30eb4b6bf85b
/tests/c/test_freeze.cc
9e3489c86bba898620cf9b1ecb9530babd956d8d
[ "Apache-2.0" ]
permissive
tundra/neutrino
47c1dcb1d2ead9d976cdc3ba1aeeda3295f6e229
69505d3e57c4f14a7a9551963106753af0097e5b
refs/heads/master
2021-01-21T12:07:30.367937
2016-02-17T14:42:42
2016-02-17T14:42:42
10,573,813
6
1
null
2016-02-18T12:04:59
2013-06-08T20:21:32
C
UTF-8
C++
false
false
3,973
cc
//- Copyright 2014 the Neutrino authors (see AUTHORS). //- Licensed under the Apache License, Version 2.0 (see LICENSE). #include "test.hh" BEGIN_C_INCLUDES #include "alloc.h" #include "freeze.h" #include "heap.h" #include "runtime.h" #include "try-inl.h" #include "utils/log.h" #include "value-inl.h" END_C_INCLUDES TEST(freeze, deep_freeze) { CREATE_RUNTIME(); value_t zero = new_integer(0); ASSERT_TRUE(is_frozen(zero)); ASSERT_EQ(true, try_validate_deep_frozen(runtime, zero, NULL)); ASSERT_TRUE(is_frozen(null())); ASSERT_EQ(true, try_validate_deep_frozen(runtime, null(), NULL)); value_t null_arr = new_heap_array(runtime, 2); ASSERT_TRUE(is_mutable(null_arr)); ASSERT_FALSE(is_frozen(null_arr)); value_t offender = whatever(); ASSERT_EQ(false, try_validate_deep_frozen(runtime, null_arr, &offender)); ASSERT_SAME(null_arr, offender); ASSERT_SUCCESS(ensure_shallow_frozen(runtime, null_arr)); ASSERT_FALSE(is_mutable(null_arr)); ASSERT_TRUE(is_frozen(null_arr)); ASSERT_EQ(true, try_validate_deep_frozen(runtime, null_arr, NULL)); value_t mut = new_heap_array(runtime, 2); value_t mut_arr = new_heap_array(runtime, 2); set_array_at(mut_arr, 0, mut); ASSERT_TRUE(is_mutable(mut_arr)); offender = whatever(); ASSERT_EQ(false, try_validate_deep_frozen(runtime, mut_arr, &offender)); ASSERT_VALEQ(mut_arr, offender); ASSERT_SUCCESS(ensure_shallow_frozen(runtime, mut_arr)); ASSERT_FALSE(is_mutable(mut_arr)); offender = whatever(); ASSERT_EQ(false, try_validate_deep_frozen(runtime, mut_arr, &offender)); ASSERT_SAME(mut, offender); offender = whatever(); ASSERT_EQ(false, try_validate_deep_frozen(runtime, mut_arr, &offender)); ASSERT_SAME(mut, offender); ASSERT_SUCCESS(ensure_shallow_frozen(runtime, mut)); ASSERT_EQ(true, try_validate_deep_frozen(runtime, mut_arr, NULL)); value_t circ_arr = new_heap_array(runtime, 2); set_array_at(circ_arr, 0, circ_arr); set_array_at(circ_arr, 1, circ_arr); ASSERT_TRUE(is_mutable(circ_arr)); offender = success(); ASSERT_EQ(false, try_validate_deep_frozen(runtime, circ_arr, &offender)); ASSERT_SAME(circ_arr, offender); ASSERT_SUCCESS(ensure_shallow_frozen(runtime, circ_arr)); ASSERT_FALSE(is_mutable(circ_arr)); ASSERT_EQ(true, try_validate_deep_frozen(runtime, circ_arr, NULL)); DISPOSE_RUNTIME(); } TEST(freeze, ownership_freezing) { CREATE_RUNTIME(); value_t empty_map = new_heap_id_hash_map(runtime, 16); ASSERT_TRUE(is_mutable(empty_map)); ASSERT_SUCCESS(ensure_shallow_frozen(runtime, empty_map)); ASSERT_TRUE(is_frozen(empty_map)); ASSERT_EQ(false, try_validate_deep_frozen(runtime, empty_map, NULL)); ASSERT_SUCCESS(ensure_frozen(runtime, empty_map)); ASSERT_EQ(true, try_validate_deep_frozen(runtime, empty_map, NULL)); value_t mut = new_heap_array(runtime, 2); value_t mut_map = new_heap_id_hash_map(runtime, 16); ASSERT_SUCCESS(try_set_id_hash_map_at(mut_map, new_integer(0), mut, false)); ASSERT_TRUE(is_mutable(mut_map)); ASSERT_SUCCESS(ensure_shallow_frozen(runtime, mut_map)); ASSERT_SUCCESS(ensure_frozen(runtime, mut_map)); value_t offender = new_integer(0); ASSERT_EQ(false, try_validate_deep_frozen(runtime, mut_map, &offender)); ASSERT_SAME(mut, offender); ASSERT_SUCCESS(ensure_frozen(runtime, mut)); ASSERT_EQ(true, try_validate_deep_frozen(runtime, mut_map, NULL)); DISPOSE_RUNTIME(); } TEST(freeze, freeze_cheat) { CREATE_RUNTIME(); value_t cheat = new_heap_freeze_cheat(runtime, new_integer(121)); ASSERT_EQ(true, try_validate_deep_frozen(runtime, cheat, NULL)); ASSERT_VALEQ(new_integer(121), get_freeze_cheat_value(cheat)); set_freeze_cheat_value(cheat, new_integer(212)); ASSERT_EQ(true, try_validate_deep_frozen(runtime, cheat, NULL)); ASSERT_VALEQ(new_integer(212), get_freeze_cheat_value(cheat)); set_freeze_cheat_value(cheat, new_heap_array(runtime, 3)); ASSERT_SUCCESS(runtime_validate(runtime, nothing())); DISPOSE_RUNTIME(); }
[ "c7n@p5r.org" ]
c7n@p5r.org
53632fcfb87bb4e0d3b261320e8f4941490e8869
b1bf8e0f506c4be24cc137fbd570c59883d496df
/HW6/HW06.cpp
ca6ff36df6483c747581fa1e4ad82e9d04e50096
[]
no_license
heathcliffYang/ML_HW_2018
e9d09c87f6edd0fb6e5c35d6516d1c1fc921b4fb
f0b5cf3224ad8b2f40757eeb56c5d51d79a12979
refs/heads/master
2020-04-03T04:49:48.235751
2019-03-08T08:32:52
2019-03-08T08:32:52
155,025,265
0
0
null
null
null
null
UTF-8
C++
false
false
18,207
cpp
#include <iostream> #include <fstream> #include <string> #include <vector> #include <ctime> #include <cmath> #include <algorithm> #include <Eigen/Core> #include <SymEigsSolver.h> using namespace Spectra; using namespace std; typedef struct data_point { double x; double y; int cluster; } data_point; typedef struct cluster_center { double x; double y; int num_of_element; } cluster_center; /* data points record */ vector<data_point> data_points; vector<cluster_center> centers; vector<double> cluster_base(2); int reader(int data_mode) { string line; string file_name; if (data_mode == 0) file_name = "circle.txt"; else file_name = "moon.txt"; ifstream input_file(file_name); data_points.clear(); if (input_file.is_open()) { while (getline(input_file, line, ',')) { data_point input_num; input_num.x = stod(line); getline(input_file, line); input_num.y = stod(line); input_num.cluster = -1; //cout << input_num.x << " " << input_num.y << endl; data_points.push_back(input_num); } input_file.close(); cout << "The # of data is " << data_points.size() << endl; } else { cout << "Cannot open" << endl; return -1; } return 0; }; cluster_center old; bool is_converge() { /* Check out if centers become steady */ static vector<cluster_center> old_centers(centers.size(), old); double error = 0; for (int i = 0; i < centers.size(); i++) { cout << "converge check :" << old_centers[i].x << " " << centers[i].x << endl; error += sqrt(pow(old_centers[i].x - centers[i].x, 2) + pow(old_centers[i].y - centers[i].y, 2)); old_centers[i].y = centers[i].y; old_centers[i].x = centers[i].x; } if (error / centers.size() < 0.00001) { cout << "converge!\n"; return false; } return true; }; int init_centers(int num_of_cl, int init_mode) { switch (init_mode) { case 1: { cout << "CCIA" << endl; vector<double> distribution_x(data_points.size()); vector<int> tag_x(data_points.size()); for (int i = 0; i < data_points.size(); i++) { distribution_x[i] = data_points[i].x; } sort(distribution_x.begin(), distribution_x.end()); for (int i = 0; i < data_points.size(); i++) { if (data_points[i].x < distribution_x[floor(data_points.size() / 2)]) tag_x[i] = 0; else tag_x[i] = 1; } vector<double> distribution_y(data_points.size()); vector<int> tag_y(data_points.size()); for (int i = 0; i < data_points.size(); i++) { distribution_y[i] = data_points[i].x; } sort(distribution_y.begin(), distribution_y.end()); int pattern[2][2] = {}; for (int i = 0; i < data_points.size(); i++) { if (data_points[i].x < distribution_y[floor(data_points.size() / 2)]) { tag_y[i] = 0; pattern[tag_x[i]][tag_y[i]]++; } else { tag_y[i] = 1; pattern[tag_x[i]][tag_y[i]]++; } } ofstream output_file("k-means_cl_ccia.txt", ios::app); output_file << -1; int max_x[2] = {}, max_y[2] = {}, max[2] = {}; for (int k = 0; k < 2; k++) { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (pattern[i][j] > max[k]) { max[k] = pattern[i][j]; max_x[k] = i; max_y[k] = j; } } } pattern[max_x[k]][max_y[k]] = 0; cluster_center center; if (max_x[k] == 0) center.x = distribution_x[int(data_points.size() / 3)]; else center.x = distribution_x[int(data_points.size() * 2 / 3)]; output_file << ',' << center.x; if (max_y[k] == 0) center.y = distribution_y[int(data_points.size() / 3)]; else center.y = distribution_y[int(data_points.size() * 2 / 3)]; output_file << ',' << center.y; center.num_of_element = 0; centers.push_back(center); } output_file << '\n'; output_file.close(); break; } default: cout << "Random" << endl; ofstream output_file("k-means_cl_random.txt", ios::app); output_file << -1; for (int i = 0; i < num_of_cl; i++) { cluster_center center; center.x = (rand() / (double)RAND_MAX) * 2.0 - 1.0; center.y = (rand() / (double)RAND_MAX) * 2.0 - 1.0; output_file << ',' << center.x; output_file << ',' << center.y; center.num_of_element = 0; centers.push_back(center); } output_file << '\n'; output_file.close(); } cout << "End\n" << endl; return 0; }; int K_Means(int num_of_cl, int init_mode, int write_file) { centers.clear(); init_centers(num_of_cl, init_mode); double min = 0, tmp = 0; int belong_index = 0, iter = 0; min = 100; ofstream output_file("k-means_cl_random.txt", ios::app); do { iter++; cout << "iter " << iter << endl; /* E-step: find the nearest center */ for (int i = 0; i < data_points.size(); i++) { for (int j = 0; j < centers.size(); j++) { tmp = sqrt(pow(data_points[i].x - centers[j].x, 2) + pow(data_points[i].y - centers[j].y, 2)); if (min > tmp) { min = tmp; belong_index = j; } } centers[belong_index].num_of_element++; data_points[i].cluster = belong_index; min = 100; } /* M-step: update centers */ for (int j = 0; j < centers.size(); j++) { centers[j].x = 0; centers[j].y = 0; } for (int i = 0; i < data_points.size(); i++) { centers[data_points[i].cluster].x += data_points[i].x; centers[data_points[i].cluster].y += data_points[i].y; /* write the new clustering */ if (write_file == 1) output_file << data_points[i].cluster << '\n'; } if (write_file == 1) output_file << -1; for (int j = 0; j < centers.size(); j++) { centers[j].x /= centers[j].num_of_element; centers[j].y /= centers[j].num_of_element; if (write_file == 1) { output_file << ',' << centers[j].x << ',' << centers[j].y; centers[j].num_of_element = 0; } } if (write_file == 1) output_file << '\n'; } while (is_converge() && write_file == 1); output_file.close(); return 0; }; double RBF(int a, int b, double gamma) { return exp(-gamma * (pow(data_points[a].x - data_points[b].x, 2) + pow(data_points[a].y - data_points[b].y, 2))); }; bool kernel_is_converge() { /* Check cluster base */ static vector<double> old_base(cluster_base.size(), 0.0); double error = 0; for (int i = 0; i < cluster_base.size(); i++) { error += fabs(old_base[i] - cluster_base[i]); old_base[i] = cluster_base[i]; } if (error < 0.000001) { cout << "converge!\n"; return false; } /* Check out if centers become steady */ // static vector<cluster_center> old_centers(centers.size(), old); // int error = 0; // for (int i = 0; i < centers.size(); i++) // { // cout << "converge check :" << old_centers[i].num_of_element << " " << centers[i].num_of_element << endl; // error += abs(old_centers[i].num_of_element - centers[i].num_of_element); // old_centers[i].num_of_element = centers[i].num_of_element; // } // if (error == 0) // { // cout << "converge!\n"; // return false; // } return true; }; int Kernel_k_means(int num_of_cl, double gamma, int init_mode) { vector<double> tmp(num_of_cl, 0.0); cluster_base.assign(num_of_cl, 0.0); vector<int> next_distribution(data_points.size(), 0); vector<double>::iterator min; int belong_index = 0, iter = 0; string file_name; /* initial */ switch (init_mode) { case 1: { cout << "CCIA" << endl; file_name = "kernel-k-means_ccia_c" + to_string(num_of_cl) + "_g" + to_string(int(gamma)); K_Means(num_of_cl, init_mode, 0); break; } default: cout << "Random" << endl; file_name = "kernel-k-means_random_c" + to_string(num_of_cl) + "_g" + to_string(int(gamma)); ofstream output_file(file_name, ios::app); centers.clear(); for (int i = 0; i < num_of_cl; i++) { cluster_center center; center.num_of_element = 0; centers.push_back(center); } int ind = -1; for (int i = 0; i < data_points.size(); i++) { ind = rand() % num_of_cl; centers[ind].num_of_element++; data_points[i].cluster = ind; /* write the new clustering */ output_file << ind << '\n'; } output_file << -1; for (int i = 0; i < num_of_cl; i++) { output_file << "," << centers[i].num_of_element; } output_file << '\n'; output_file.close(); } ofstream output_file(file_name, ios::app); do { iter++; cout << "iter " << iter << endl; cluster_base.assign(num_of_cl, 0); for (int i = 0; i < data_points.size(); i++) { for (int j = 0; j < data_points.size(); j++) { if (data_points[i].cluster == data_points[j].cluster) cluster_base[data_points[i].cluster] += RBF(i, j, gamma); } } for (int i = 0; i < num_of_cl; i++) { cout << "cluster base " << cluster_base[i] << " "; if (centers[i].num_of_element != 0) cluster_base[i] /= pow(centers[i].num_of_element, 2); else cluster_base[i] = 0; cout << i << " contains " << centers[i].num_of_element << " is " << cluster_base[i] << endl; } for (int i = 0; i < data_points.size(); i++) { for (int j = 0; j < data_points.size(); j++) { tmp[data_points[j].cluster] -= RBF(i, j, gamma); } for (int k = 0; k < num_of_cl; k++) { if (centers[k].num_of_element != 0) { tmp[k] /= centers[k].num_of_element; tmp[k] *= 2; tmp[k] += cluster_base[k]; } } min = min_element(tmp.begin(), tmp.end()); next_distribution[i] = distance(tmp.begin(), min); output_file << next_distribution[i] << '\n'; tmp.assign(num_of_cl, 0); } for (int i = 0; i < num_of_cl; i++) { centers[i].num_of_element = 0; } for (int i = 0; i < data_points.size(); i++) { centers[next_distribution[i]].num_of_element++; data_points[i].cluster = next_distribution[i]; } output_file << -1; for (int i = 0; i < num_of_cl; i++) { output_file << "," << centers[i].num_of_element; } output_file << '\n'; if (iter > 50) break; } while (kernel_is_converge()); output_file.close(); return 0; }; int Spectral(int num_of_cl, double gamma, int init_mode) { int num_of_data = data_points.size(); cout << "# of data " << num_of_data << endl; vector<vector<double>> W(num_of_data); /* Calculate W */ for (int i = 0; i < num_of_data; i++) { data_points[i].cluster = 0; W[i] = vector<double>(num_of_data); for (int j = 0; j < num_of_data; j++) { W[i][j] = RBF(i, j, gamma); } } cout << "L start\n"; /* L */ Eigen::MatrixXd L(num_of_data, num_of_data); for (int i = 0; i < num_of_data; i++) { L(i, i) = 0; for (int j = 0; j < num_of_data; j++) { if (i != j) { L(i, j) = -W[i][j]; L(i, i) += W[i][j]; } } } cout << "L end\n"; // Construct matrix operation object using the wrapper class DenseSymMatProd DenseSymMatProd<double> op(L); // Construct eigen solver object, requesting the largest three eigenvalues SymEigsSolver<double, SMALLEST_ALGE, DenseSymMatProd<double>> eigs(&op, num_of_cl + 1, 2 * (num_of_cl + 1)); // Initialize and compute eigs.init(); int nconv = eigs.compute(); // Retrieve results Eigen::VectorXd evalues; Eigen::MatrixXd evectors; if (eigs.info() == SUCCESSFUL) { evalues = eigs.eigenvalues(); evectors = eigs.eigenvectors(); } string file_name = "Spectral_eigenvector_c" + to_string(num_of_cl) + "_g" + to_string(int(gamma)); ofstream output_file(file_name, ios::app); for (int j = 0; j < evectors.cols(); j++) { for (int i = 0; i < evectors.rows(); i++) { output_file << evectors(i, j) << '\n'; } output_file << -1 << '\n'; } output_file.close(); string distri_file_name; cout << "Eigen space K-means!" << endl; /* k-means init remember centers!!! */ switch (init_mode) { case 1: { init_centers(num_of_cl, init_mode); distri_file_name = "Spectral_ccia_c" + to_string(num_of_cl) + "_g" + to_string(int(gamma)); } default: distri_file_name = "Spectral_random_c" + to_string(num_of_cl) + "_g" + to_string(int(gamma)); init_centers(num_of_cl, init_mode); } ofstream distri_output_file(distri_file_name, ios::app); int itr = 0; do { itr++; /* E-step */ double tmp = 0, min = MAXFLOAT; for (int i = 0; i < evectors.rows(); i++) { for (int k = 0; k < num_of_cl; k++) { tmp = sqrt(pow(evectors(i, 0) - centers[k].x, 2) + pow(evectors(i, 1) - centers[k].y, 2)); if (min > tmp) { min = tmp; data_points[i].cluster = k; } } min = MAXFLOAT; centers[data_points[i].cluster].num_of_element++; distri_output_file << data_points[i].cluster << '\n'; } distri_output_file << -1 << '\n'; /* M-step */ for (int i = 0; i < num_of_cl; i++) { centers[i].x = 0; centers[i].y = 0; } for (int i = 0; i < data_points.size(); i++) { centers[data_points[i].cluster].x += evectors(i, 0); centers[data_points[i].cluster].y += evectors(i, 1); } for (int i = 0; i < num_of_cl; i++) { if (centers[i].num_of_element != 0) { centers[i].x /= centers[i].num_of_element; centers[i].y /= centers[i].num_of_element; } } for (int i = 0; i < num_of_cl; i++) { centers[i].num_of_element = 0; } if (itr > 3) break; } while (is_converge()); distri_output_file.close(); return 0; }; int main() { srand(time(NULL)); int data_mode; cin >> data_mode; /* data_mode = 0 means to use circle.txt, 1 is moon.txt */ reader(data_mode); cout << "K-means (1), kernel k-means (2), spectral clustering (3):" << endl; int clustering_mode, num_of_cl, init_mode; cin >> clustering_mode; double n1, n2, step; while (true) { switch (clustering_mode) { case 1: cout << "K-means\nThe # of cluseter you want: \n"; cin >> num_of_cl; cout << "The initialization methods, CCIA (1), random (others): \n"; cin >> init_mode; K_Means(num_of_cl, init_mode, 1); clustering_mode = 4; break; case 2: cout << "Kernel k-means\nThe # of cluseter you want: \n"; cin >> num_of_cl; cout << "The initialization methods, CCIA (1), random (others): \n"; cin >> init_mode; cout << "The gamma search range is from n1 to n2 by step: \n"; cin >> n1 >> n2 >> step; for (double gamma = n1; gamma < n2; gamma += step) { Kernel_k_means(num_of_cl, gamma, init_mode); } clustering_mode = 4; break; case 3: cout << "Spectral clustering\nThe # of cluseter you want: \n"; cin >> num_of_cl; cout << "The initialization methods, CCIA (1), random (others): \n"; cin >> init_mode; cout << "The gamma search range is from n1 to n2 by step: \n"; cin >> n1 >> n2 >> step; for (double gamma = n1; gamma < n2; gamma += step) { Spectral(num_of_cl, gamma, init_mode); } clustering_mode = 4; break; case 4: cout << "K-means (1), kernel k-means (2), spectral clustering (3):" << endl; cin >> clustering_mode; break; default: cout << "End\n"; clustering_mode = 0; } if (clustering_mode > 4 || clustering_mode < 1) break; } return 0; }
[ "ginny0922fc2@gmail.com" ]
ginny0922fc2@gmail.com
a243977d27a8f85fcd20f2e0071baf2cb1463ac5
ddc4ddfa57f0cf231bb3e339e64847f2099b74c8
/03_vectors/dna_consensus.h
ef38f2f48fd4efc6689826dcffd594cba4dfc060
[ "MIT" ]
permissive
acc-cosc-1337-spring-2019/midterm-spring-2019-AndrewExley
5a20698599fccf10af369ccb3f3177a44121e2a5
d7569c16a12a78c8f1b5e7193daec485d8c9fef8
refs/heads/master
2020-04-28T13:25:10.283164
2019-03-20T19:28:50
2019-03-20T19:28:50
175,306,325
0
0
null
null
null
null
UTF-8
C++
false
false
424
h
#include <vector> #include <string> using std::vector; using std::string; string dna_consensus(vector<int> profile_a, vector<int> profile_c, vector<int> profile_g, vector<int> profile_t); vector<int> profile_matrix_a(vector<string> dna_segments); vector<int> profile_matrix_c(vector<string> dna_segments); vector<int> profile_matrix_g(vector<string> dna_segments); vector<int> profile_matrix_t(vector<string> dna_segments);
[ "Paul Exley@LT_COM_EXLEY" ]
Paul Exley@LT_COM_EXLEY
675b4434d02fcd5002d767e6ad2f546dbec19bb6
a6636a9e0cf225ea4bd60db9237cb9ed91c8a370
/EE599HW4/4-3/tests/solution_test.cc
2dd944adefa02fefa82781e6c72a4522d1c72d8c
[ "MIT" ]
permissive
YingnanWang-Ray/EE599
0e8299351ae814460fa93101969408899b3cfd5e
7e870b78b4f61f783077d88d437937e697d7abf0
refs/heads/main
2023-03-21T11:19:24.259470
2021-03-19T00:14:18
2021-03-19T00:14:18
349,252,216
0
0
null
null
null
null
UTF-8
C++
false
false
1,393
cc
#include "src/lib/solution.h" #include "gtest/gtest.h" #include <vector> using namespace std; TEST(Function0, Return0) { vector<int> input = {3,1,6,4,7,8,10,14,13}; BST bst(input); int target = 14; EXPECT_EQ(true, bst.find(target)); EXPECT_EQ(true, bst.erase(target)); EXPECT_EQ(false, bst.find(target)); }//Only has one left child node TEST(Function1, Return1) { vector<int> input = {3,1,6,4,7,8,10,14,13}; BST bst(input); int target = 10; EXPECT_EQ(true, bst.find(target)); EXPECT_EQ(true, bst.erase(target)); EXPECT_EQ(false, bst.find(target)); }//Only has one right child node TEST(Function2, Return2) { vector<int> input = {3,1,6,4,7,8,10,14,13}; BST bst(input); int target = 1; EXPECT_EQ(true, bst.find(target)); EXPECT_EQ(true, bst.erase(target)); EXPECT_EQ(false, bst.find(target)); }//Has no child node TEST(Function3, Return3) { vector<int> input = {3,1,6,4,7,8,10,14,13}; BST bst(input); int target = 8; EXPECT_EQ(true, bst.find(target)); EXPECT_EQ(true, bst.erase(target)); EXPECT_EQ(false, bst.find(target)); }//Has two child node & root TEST(Function4, Return4) { vector<int> input = {3,1,6,4,7,8,10,14,13}; BST bst(input); int target = 6; EXPECT_EQ(true, bst.find(target)); EXPECT_EQ(true, bst.erase(target)); EXPECT_EQ(false, bst.find(target)); }//Has two child node & not root
[ "347930597@qq.com" ]
347930597@qq.com
410246808d74bbae3525fabd0e374fbd6c856f5b
eefd037baf71544d94f19abfdaae59e0af638b02
/gdal-1.11.2/alg/gdal_tps.cpp
c225852a49e003f5b53a1faeb060e99f7737d3ba
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-info-zip-2005-02", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer", "MIT", "SunPro" ]
permissive
avtomaton/gnu-win64
7128b677f4b9a9d1424b0ca44cc7c5fb3ce41fe1
66f7c3cc224f027300f944059262cf70f3f088e8
refs/heads/master
2020-05-17T00:12:03.638953
2015-07-29T14:12:44
2015-07-29T14:12:44
37,531,150
3
0
null
null
null
null
UTF-8
C++
false
false
14,105
cpp
/****************************************************************************** * $Id: gdal_tps.cpp 27729 2014-09-24 00:40:16Z goatbar $ * * Project: High Performance Image Reprojector * Purpose: Thin Plate Spline transformer (GDAL wrapper portion) * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2004, Frank Warmerdam <warmerdam@pobox.com> * Copyright (c) 2011-2013, Even Rouault <even dot rouault at mines-paris dot 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 "thinplatespline.h" #include "gdal_alg.h" #include "gdal_alg_priv.h" #include "gdal_priv.h" #include "cpl_conv.h" #include "cpl_string.h" #include "cpl_atomic_ops.h" #include "cpl_multiproc.h" CPL_CVSID("$Id: gdal_tps.cpp 27729 2014-09-24 00:40:16Z goatbar $"); CPL_C_START CPLXMLNode *GDALSerializeTPSTransformer( void *pTransformArg ); void *GDALDeserializeTPSTransformer( CPLXMLNode *psTree ); CPL_C_END typedef struct { GDALTransformerInfo sTI; VizGeorefSpline2D *poForward; VizGeorefSpline2D *poReverse; int bForwardSolved; int bReverseSolved; int bReversed; int nGCPCount; GDAL_GCP *pasGCPList; volatile int nRefCount; } TPSTransformInfo; /************************************************************************/ /* GDALCloneTPSTransformer() */ /************************************************************************/ void* GDALCloneTPSTransformer( void *hTransformArg ) { VALIDATE_POINTER1( hTransformArg, "GDALCloneTPSTransformer", NULL ); TPSTransformInfo *psInfo = (TPSTransformInfo *) hTransformArg; /* We can just use a ref count, since using the source transformation */ /* is thread-safe */ CPLAtomicInc(&(psInfo->nRefCount)); return psInfo; } /************************************************************************/ /* GDALCreateTPSTransformer() */ /************************************************************************/ /** * Create Thin Plate Spline transformer from GCPs. * * The thin plate spline transformer produces exact transformation * at all control points and smoothly varying transformations between * control points with greatest influence from local control points. * It is suitable for for many applications not well modelled by polynomial * transformations. * * Creating the TPS transformer involves solving systems of linear equations * related to the number of control points involved. This solution is * computed within this function call. It can be quite an expensive operation * for large numbers of GCPs. For instance, for reference, it takes on the * order of 10s for 400 GCPs on a 2GHz Athlon processor. * * TPS Transformers are serializable. * * The GDAL Thin Plate Spline transformer is based on code provided by * Gilad Ronnen on behalf of VIZRT Inc (http://www.visrt.com). Incorporation * of the algorithm into GDAL was supported by the Centro di Ecologia Alpina * (http://www.cealp.it). * * @param nGCPCount the number of GCPs in pasGCPList. * @param pasGCPList an array of GCPs to be used as input. * @param bReversed set it to TRUE to compute the reversed transformation. * * @return the transform argument or NULL if creation fails. */ void *GDALCreateTPSTransformer( int nGCPCount, const GDAL_GCP *pasGCPList, int bReversed ) { return GDALCreateTPSTransformerInt(nGCPCount, pasGCPList, bReversed, NULL); } static void GDALTPSComputeForwardInThread(void* pData) { TPSTransformInfo *psInfo = (TPSTransformInfo *)pData; psInfo->bForwardSolved = psInfo->poForward->solve() != 0; } void *GDALCreateTPSTransformerInt( int nGCPCount, const GDAL_GCP *pasGCPList, int bReversed, char** papszOptions ) { TPSTransformInfo *psInfo; int iGCP; /* -------------------------------------------------------------------- */ /* Allocate transform info. */ /* -------------------------------------------------------------------- */ psInfo = (TPSTransformInfo *) CPLCalloc(sizeof(TPSTransformInfo),1); psInfo->pasGCPList = GDALDuplicateGCPs( nGCPCount, pasGCPList ); psInfo->nGCPCount = nGCPCount; psInfo->bReversed = bReversed; psInfo->poForward = new VizGeorefSpline2D( 2 ); psInfo->poReverse = new VizGeorefSpline2D( 2 ); strcpy( psInfo->sTI.szSignature, "GTI" ); psInfo->sTI.pszClassName = "GDALTPSTransformer"; psInfo->sTI.pfnTransform = GDALTPSTransform; psInfo->sTI.pfnCleanup = GDALDestroyTPSTransformer; psInfo->sTI.pfnSerialize = GDALSerializeTPSTransformer; /* -------------------------------------------------------------------- */ /* Attach all the points to the transformation. */ /* -------------------------------------------------------------------- */ for( iGCP = 0; iGCP < nGCPCount; iGCP++ ) { double afPL[2], afXY[2]; afPL[0] = pasGCPList[iGCP].dfGCPPixel; afPL[1] = pasGCPList[iGCP].dfGCPLine; afXY[0] = pasGCPList[iGCP].dfGCPX; afXY[1] = pasGCPList[iGCP].dfGCPY; if( bReversed ) { psInfo->poReverse->add_point( afPL[0], afPL[1], afXY ); psInfo->poForward->add_point( afXY[0], afXY[1], afPL ); } else { psInfo->poForward->add_point( afPL[0], afPL[1], afXY ); psInfo->poReverse->add_point( afXY[0], afXY[1], afPL ); } } psInfo->nRefCount = 1; int nThreads = 1; if( nGCPCount > 100 ) { const char* pszWarpThreads = CSLFetchNameValue(papszOptions, "NUM_THREADS"); if (pszWarpThreads == NULL) pszWarpThreads = CPLGetConfigOption("GDAL_NUM_THREADS", "1"); if (EQUAL(pszWarpThreads, "ALL_CPUS")) nThreads = CPLGetNumCPUs(); else nThreads = atoi(pszWarpThreads); } if( nThreads > 1 ) { /* Compute direct and reverse transforms in parallel */ void* hThread = CPLCreateJoinableThread(GDALTPSComputeForwardInThread, psInfo); psInfo->bReverseSolved = psInfo->poReverse->solve() != 0; if( hThread != NULL ) CPLJoinThread(hThread); else psInfo->bForwardSolved = psInfo->poForward->solve() != 0; } else { psInfo->bForwardSolved = psInfo->poForward->solve() != 0; psInfo->bReverseSolved = psInfo->poReverse->solve() != 0; } if( !psInfo->bForwardSolved || !psInfo->bReverseSolved ) { GDALDestroyTPSTransformer(psInfo); return NULL; } return psInfo; } /************************************************************************/ /* GDALDestroyTPSTransformer() */ /************************************************************************/ /** * Destroy TPS transformer. * * This function is used to destroy information about a GCP based * polynomial transformation created with GDALCreateTPSTransformer(). * * @param pTransformArg the transform arg previously returned by * GDALCreateTPSTransformer(). */ void GDALDestroyTPSTransformer( void *pTransformArg ) { VALIDATE_POINTER0( pTransformArg, "GDALDestroyTPSTransformer" ); TPSTransformInfo *psInfo = (TPSTransformInfo *) pTransformArg; if( CPLAtomicDec(&(psInfo->nRefCount)) == 0 ) { delete psInfo->poForward; delete psInfo->poReverse; GDALDeinitGCPs( psInfo->nGCPCount, psInfo->pasGCPList ); CPLFree( psInfo->pasGCPList ); CPLFree( pTransformArg ); } } /************************************************************************/ /* GDALTPSTransform() */ /************************************************************************/ /** * Transforms point based on GCP derived polynomial model. * * This function matches the GDALTransformerFunc signature, and can be * used to transform one or more points from pixel/line coordinates to * georeferenced coordinates (SrcToDst) or vice versa (DstToSrc). * * @param pTransformArg return value from GDALCreateTPSTransformer(). * @param bDstToSrc TRUE if transformation is from the destination * (georeferenced) coordinates to pixel/line or FALSE when transforming * from pixel/line to georeferenced coordinates. * @param nPointCount the number of values in the x, y and z arrays. * @param x array containing the X values to be transformed. * @param y array containing the Y values to be transformed. * @param z array containing the Z values to be transformed. * @param panSuccess array in which a flag indicating success (TRUE) or * failure (FALSE) of the transformation are placed. * * @return TRUE. */ int GDALTPSTransform( void *pTransformArg, int bDstToSrc, int nPointCount, double *x, double *y, CPL_UNUSED double *z, int *panSuccess ) { VALIDATE_POINTER1( pTransformArg, "GDALTPSTransform", 0 ); int i; TPSTransformInfo *psInfo = (TPSTransformInfo *) pTransformArg; for( i = 0; i < nPointCount; i++ ) { double xy_out[2]; if( bDstToSrc ) { psInfo->poReverse->get_point( x[i], y[i], xy_out ); x[i] = xy_out[0]; y[i] = xy_out[1]; } else { psInfo->poForward->get_point( x[i], y[i], xy_out ); x[i] = xy_out[0]; y[i] = xy_out[1]; } panSuccess[i] = TRUE; } return TRUE; } /************************************************************************/ /* GDALSerializeTPSTransformer() */ /************************************************************************/ CPLXMLNode *GDALSerializeTPSTransformer( void *pTransformArg ) { VALIDATE_POINTER1( pTransformArg, "GDALSerializeTPSTransformer", NULL ); CPLXMLNode *psTree; TPSTransformInfo *psInfo = static_cast<TPSTransformInfo *>(pTransformArg); psTree = CPLCreateXMLNode( NULL, CXT_Element, "TPSTransformer" ); /* -------------------------------------------------------------------- */ /* Serialize bReversed. */ /* -------------------------------------------------------------------- */ CPLCreateXMLElementAndValue( psTree, "Reversed", CPLString().Printf( "%d", psInfo->bReversed ) ); /* -------------------------------------------------------------------- */ /* Attach GCP List. */ /* -------------------------------------------------------------------- */ if( psInfo->nGCPCount > 0 ) { GDALSerializeGCPListToXML( psTree, psInfo->pasGCPList, psInfo->nGCPCount, NULL ); } return psTree; } /************************************************************************/ /* GDALDeserializeTPSTransformer() */ /************************************************************************/ void *GDALDeserializeTPSTransformer( CPLXMLNode *psTree ) { GDAL_GCP *pasGCPList = 0; int nGCPCount = 0; void *pResult; int bReversed; /* -------------------------------------------------------------------- */ /* Check for GCPs. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psGCPList = CPLGetXMLNode( psTree, "GCPList" ); if( psGCPList != NULL ) { GDALDeserializeGCPListFromXML( psGCPList, &pasGCPList, &nGCPCount, NULL ); } /* -------------------------------------------------------------------- */ /* Get other flags. */ /* -------------------------------------------------------------------- */ bReversed = atoi(CPLGetXMLValue(psTree,"Reversed","0")); /* -------------------------------------------------------------------- */ /* Generate transformation. */ /* -------------------------------------------------------------------- */ pResult = GDALCreateTPSTransformer( nGCPCount, pasGCPList, bReversed ); /* -------------------------------------------------------------------- */ /* Cleanup GCP copy. */ /* -------------------------------------------------------------------- */ GDALDeinitGCPs( nGCPCount, pasGCPList ); CPLFree( pasGCPList ); return pResult; }
[ "arkhipovsky@aifil.ru" ]
arkhipovsky@aifil.ru
9924d5f69997681c9f8ecdb344ebc90e208ea526
06737a708b51c2ca22ffe2fbc3815d49d2830416
/librf24-rpi/librf24-bcm/examples/rpi-hub.cpp
1d4c06e20d6d73c7ef3e90dc69f7f7b6287d1607
[]
no_license
hallard/RF24
42a62231c412311ecf1e4176a830c3c9b0761e6e
decde7848fc23ab335721c1a754f5f77888e9e70
refs/heads/master
2021-01-16T06:36:08.674511
2013-09-25T22:07:59
2013-09-25T22:07:59
8,757,483
1
1
null
null
null
null
UTF-8
C++
false
false
5,557
cpp
/* * * Filename : rpi-hub.cpp * * This program makes the RPi as a hub listening to all six pipes from the remote sensor nodes ( usually Arduino ) * and will return the packet back to the sensor on pipe0 so that the sender can calculate the round trip delays * when the payload matches. * * I encounter that at times, it also receive from pipe7 ( or pipe0 ) with content of FFFFFFFFF that I will not sent * back to the sender * * Refer to RF24/examples/rpi_hub_arduino/ for the corresponding Arduino sketches to work with this code. * * * CE is not used and CSN is GPIO25 (not pinout) * * Refer to RPi docs for GPIO numbers * * Author : Stanley Seow * e-mail : stanleyseow@gmail.com * date : 6th Mar 2013 * * 03/17/2013 : Charles-Henri Hallard (http://hallard.me) * Modified to use with Arduipi board http://hallard.me/arduipi * Changed to use modified bcm2835 and RF24 library * * */ #include <stdio.h> #include <sys/sysinfo.h> #include <unistd.h> #include <time.h> #include <cstdlib> #include <termios.h> #include <iostream> #include <fcntl.h> #include "../RF24.h" // Hardware configuration // CE Pin, CSN Pin, SPI Speed // Setup for GPIO 22 CE and CE1 CSN with SPI Speed @ 4Mhz RF24 radio(RPI_V2_GPIO_P1_15, RPI_V2_GPIO_P1_26, BCM2835_SPI_SPEED_4MHZ); // Radio pipe addresses for the nodes to communicate. // I like string, it talk me more than uint64_t, so cast string to uint64_t // take care that for pipe 2 to end only the last char can be changed, this // is why I set for x before it will not be taken into account const uint64_t pipe_0 = *(reinterpret_cast<const uint64_t *>(&"1000W")); const uint64_t pipe_1 = *(reinterpret_cast<const uint64_t *>(&"1000R")); const uint64_t pipe_2 = *(reinterpret_cast<const uint64_t *>(&"2000R")); const uint64_t pipe_3 = *(reinterpret_cast<const uint64_t *>(&"3000R")); const uint64_t pipe_4 = *(reinterpret_cast<const uint64_t *>(&"4000R")); const uint64_t pipe_b = *(reinterpret_cast<const uint64_t *>(&"B000R")); // Keyboard hit int kbhit(void) { struct termios oldt, newt; int ch, oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if(ch != EOF) { ungetc(ch, stdin); return 1; } return 0; } int main(void) { char receivePayload[32+1]; char hexbuff[64+1]; char asciibuff[32+1]; uint8_t pipe = 0; printf("rpi-hub/\nPress any key to exit\n"); // Setup and configure rf radio, no Debug Info radio.begin(DEBUG_LEVEL_NONE); // avoid listening when configuring radio.stopListening(); // I recommend doing your full configuration again here // not relying on driver init, this will be better in // case of driver change, and you will be sure of what // it is initialized !!!! // enable dynamic payloads // take care, dynamic payload require Auto Ack !!!! radio.enableDynamicPayloads(); // Auto ACK radio.setAutoAck( false ) ; // Increase the delay between retries & # of retries // 15 Retries 16 * 250 us radio.setRetries(15,15); // Set channel used radio.setChannel(76); // Set power level to maximum radio.setPALevel(RF24_PA_MAX); // Then set the data rate to the slowest (and most reliable) speed radio.setDataRate( RF24_250KBPS ) ; // Initialize CRC and request 1-byte (8bit) CRC radio.setCRCLength( RF24_CRC_8 ) ; // Open 6 pipes for readings ( 5 plus pipe0, also can be used for reading ) // Revert pipe 0 and pipe 1 to be able to receive packet from pingtest radio.openWritingPipe( pipe_1); radio.openReadingPipe(1,pipe_0); radio.openReadingPipe(2,pipe_2); radio.openReadingPipe(3,pipe_3); radio.openReadingPipe(4,pipe_4); radio.openReadingPipe(5,pipe_b); // Ok ready to listen radio.startListening(); // display configuration of the rf radio.printDetails(); // loop until key pressed while ( !kbhit() ) { // Display it on screen //printf("Listening\n"); while ( radio.available( &pipe ) ) { // be sure all is fine // usleep(5000); // Get packet payload size uint8_t len = radio.getDynamicPayloadSize(); uint8_t i; char c; // Avoid buffer overflow if (len > 32) len = 32; // Read data received radio.read( receivePayload, len ); // Prepare display in HEX and ASCII format of payload for (i=0 ; i<len; i++ ) { c = receivePayload[i]; sprintf(&hexbuff[i*2], "%02X", c); asciibuff[i] = isprint(c) ? c: '.'; } // end our strings asciibuff[i] = hexbuff[i*2] = '\0'; // Display it on screen printf("Recv[%02d] from pipe %i : payload=0x%s -> %s",len, pipe, hexbuff, asciibuff); // Send back payload to sender radio.stopListening(); // if pipe is 7, do not send it back if ( pipe != 7 ) { // Send back using the same pipe // radio.openWritingPipe(pipes[pipe]); radio.write(receivePayload,len); receivePayload[len]=0; printf("\t Sent back %d bytes to pipe %d\n\r", len, pipe); } else { printf("\n\r"); } // Enable start listening again radio.startListening(); // Increase the pipe outside the while loop pipe++; // reset pipe to 0 if ( pipe > 5 ) pipe = 0; } // May be a good idea not using all CPU into the loop usleep(1000); } return 0 ; }
[ "hallard04@free.fr" ]
hallard04@free.fr
d15095a760d0eee407af81e231533defba528185
0b2db9b65f3cc4b817ce509f83d5045eb7624ee8
/source/godot_bindings/include/gen/Position3D.hpp
e7ba1913e141d44d9129120509ff0cfc0235be9a
[]
no_license
Specialsaucewc/HackathonGodot
00800865c6d3c8073e9dec83b1cf7dd7ae5136af
0a8be6592906c83c3b648e6f79371b35b76a080d
refs/heads/master
2023-02-01T18:55:14.195672
2020-12-17T05:07:12
2020-12-17T05:07:12
321,496,228
1
0
null
null
null
null
UTF-8
C++
false
false
991
hpp
#ifndef GODOT_CPP_POSITION3D_HPP #define GODOT_CPP_POSITION3D_HPP #include <gdnative_api_struct.gen.h> #include <stdint.h> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include "Spatial.hpp" namespace godot { class Position3D : public Spatial { struct ___method_bindings { }; static ___method_bindings ___mb; static void *_detail_class_tag; public: static void ___init_method_bindings(); inline static size_t ___get_id() { return (size_t)_detail_class_tag; } static inline const char *___get_class_name() { return (const char *) "Position3D"; } static inline const char *___get_godot_class_name() { return (const char *) "Position3D"; } static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; } // enums // constants static Position3D *_new(); // methods }; } #endif
[ "specialsaucewc@gmail.com" ]
specialsaucewc@gmail.com
9479b237c3273590dd90ab3296785fdb6b539c56
ece0df2446dae16ed5ff4891379924484e595f1a
/include/Interfaces/ASNIMessenger.h
743414d9c219a25f187bb8f997d689b78567ecf3
[]
no_license
RandomAmbersky/AmberSkyNet
838376d5426254d8ee76bfaa5ab378d5f40d35a1
fb7a10c6edd4691a0e65d06f11c32250df3c5707
refs/heads/master
2020-04-28T21:57:33.823704
2013-06-27T19:22:00
2013-06-27T19:22:00
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
419
h
#ifndef _ASNI_MESSENGER_H #define _ASNI_MESSENGER_H #include "ASN_Params.h" #include "IBaseObject.h" #include "CVector.h" #include "INode.h" #include "ICamera.h" #include "Interfaces/ASNInterface.h" //// Интерфейсный класс мира - уровень игровой логики class ASNIMessenger: public ASNInterface { public: const char* GetType(){ return "ASNIMessenger"; } }; #endif
[ "RandomAmbersky@gmail.com" ]
RandomAmbersky@gmail.com
ace9cd988f079df852735fe11be8ff0be2656b25
c7be52078daa48f8e2efa3102782d3be99bf6478
/Pixart_PMW3360DM/PMW3360DM_Firmware.h
a267a1a903f27f672d333ed29998da184de8c291
[]
no_license
ogatatsu/HID-Playground-Lib
db36d447397ce494ca33cc62f7e6bbabd0c4a249
22d71b98a35446b4762c4d4a1708377cf268a7b3
refs/heads/master
2022-12-07T21:38:55.843618
2022-11-27T08:33:01
2022-11-30T13:59:26
187,300,341
5
1
null
null
null
null
UTF-8
C++
false
false
25,830
h
#pragma once #include <stdint.h> namespace hidpg { // clang-format off // Firmware "PMW3360DM_srom_0x04" constexpr uint8_t PMW3360DM_Firmware[] = { 0x01, 0x04, 0x8e, 0x96, 0x6e, 0x77, 0x3e, 0xfe, 0x7e, 0x5f, 0x1d, 0xb8, 0xf2, 0x66, 0x4e, 0xff, 0x5d, 0x19, 0xb0, 0xc2, 0x04, 0x69, 0x54, 0x2a, 0xd6, 0x2e, 0xbf, 0xdd, 0x19, 0xb0, 0xc3, 0xe5, 0x29, 0xb1, 0xe0, 0x23, 0xa5, 0xa9, 0xb1, 0xc1, 0x00, 0x82, 0x67, 0x4c, 0x1a, 0x97, 0x8d, 0x79, 0x51, 0x20, 0xc7, 0x06, 0x8e, 0x7c, 0x7c, 0x7a, 0x76, 0x4f, 0xfd, 0x59, 0x30, 0xe2, 0x46, 0x0e, 0x9e, 0xbe, 0xdf, 0x1d, 0x99, 0x91, 0xa0, 0xa5, 0xa1, 0xa9, 0xd0, 0x22, 0xc6, 0xef, 0x5c, 0x1b, 0x95, 0x89, 0x90, 0xa2, 0xa7, 0xcc, 0xfb, 0x55, 0x28, 0xb3, 0xe4, 0x4a, 0xf7, 0x6c, 0x3b, 0xf4, 0x6a, 0x56, 0x2e, 0xde, 0x1f, 0x9d, 0xb8, 0xd3, 0x05, 0x88, 0x92, 0xa6, 0xce, 0x1e, 0xbe, 0xdf, 0x1d, 0x99, 0xb0, 0xe2, 0x46, 0xef, 0x5c, 0x07, 0x11, 0x5d, 0x98, 0x0b, 0x9d, 0x94, 0x97, 0xee, 0x4e, 0x45, 0x33, 0x6b, 0x44, 0xc7, 0x29, 0x56, 0x27, 0x30, 0xc6, 0xa7, 0xd5, 0xf2, 0x56, 0xdf, 0xb4, 0x38, 0x62, 0xcb, 0xa0, 0xb6, 0xe3, 0x0f, 0x84, 0x06, 0x24, 0x05, 0x65, 0x6f, 0x76, 0x89, 0xb5, 0x77, 0x41, 0x27, 0x82, 0x66, 0x65, 0x82, 0xcc, 0xd5, 0xe6, 0x20, 0xd5, 0x27, 0x17, 0xc5, 0xf8, 0x03, 0x23, 0x7c, 0x5f, 0x64, 0xa5, 0x1d, 0xc1, 0xd6, 0x36, 0xcb, 0x4c, 0xd4, 0xdb, 0x66, 0xd7, 0x8b, 0xb1, 0x99, 0x7e, 0x6f, 0x4c, 0x36, 0x40, 0x06, 0xd6, 0xeb, 0xd7, 0xa2, 0xe4, 0xf4, 0x95, 0x51, 0x5a, 0x54, 0x96, 0xd5, 0x53, 0x44, 0xd7, 0x8c, 0xe0, 0xb9, 0x40, 0x68, 0xd2, 0x18, 0xe9, 0xdd, 0x9a, 0x23, 0x92, 0x48, 0xee, 0x7f, 0x43, 0xaf, 0xea, 0x77, 0x38, 0x84, 0x8c, 0x0a, 0x72, 0xaf, 0x69, 0xf8, 0xdd, 0xf1, 0x24, 0x83, 0xa3, 0xf8, 0x4a, 0xbf, 0xf5, 0x94, 0x13, 0xdb, 0xbb, 0xd8, 0xb4, 0xb3, 0xa0, 0xfb, 0x45, 0x50, 0x60, 0x30, 0x59, 0x12, 0x31, 0x71, 0xa2, 0xd3, 0x13, 0xe7, 0xfa, 0xe7, 0xce, 0x0f, 0x63, 0x15, 0x0b, 0x6b, 0x94, 0xbb, 0x37, 0x83, 0x26, 0x05, 0x9d, 0xfb, 0x46, 0x92, 0xfc, 0x0a, 0x15, 0xd1, 0x0d, 0x73, 0x92, 0xd6, 0x8c, 0x1b, 0x8c, 0xb8, 0x55, 0x8a, 0xce, 0xbd, 0xfe, 0x8e, 0xfc, 0xed, 0x09, 0x12, 0x83, 0x91, 0x82, 0x51, 0x31, 0x23, 0xfb, 0xb4, 0x0c, 0x76, 0xad, 0x7c, 0xd9, 0xb4, 0x4b, 0xb2, 0x67, 0x14, 0x09, 0x9c, 0x7f, 0x0c, 0x18, 0xba, 0x3b, 0xd6, 0x8e, 0x14, 0x2a, 0xe4, 0x1b, 0x52, 0x9f, 0x2b, 0x7d, 0xe1, 0xfb, 0x6a, 0x33, 0x02, 0xfa, 0xac, 0x5a, 0xf2, 0x3e, 0x88, 0x7e, 0xae, 0xd1, 0xf3, 0x78, 0xe8, 0x05, 0xd1, 0xe3, 0xdc, 0x21, 0xf6, 0xe1, 0x9a, 0xbd, 0x17, 0x0e, 0xd9, 0x46, 0x9b, 0x88, 0x03, 0xea, 0xf6, 0x66, 0xbe, 0x0e, 0x1b, 0x50, 0x49, 0x96, 0x40, 0x97, 0xf1, 0xf1, 0xe4, 0x80, 0xa6, 0x6e, 0xe8, 0x77, 0x34, 0xbf, 0x29, 0x40, 0x44, 0xc2, 0xff, 0x4e, 0x98, 0xd3, 0x9c, 0xa3, 0x32, 0x2b, 0x76, 0x51, 0x04, 0x09, 0xe7, 0xa9, 0xd1, 0xa6, 0x32, 0xb1, 0x23, 0x53, 0xe2, 0x47, 0xab, 0xd6, 0xf5, 0x69, 0x5c, 0x3e, 0x5f, 0xfa, 0xae, 0x45, 0x20, 0xe5, 0xd2, 0x44, 0xff, 0x39, 0x32, 0x6d, 0xfd, 0x27, 0x57, 0x5c, 0xfd, 0xf0, 0xde, 0xc1, 0xb5, 0x99, 0xe5, 0xf5, 0x1c, 0x77, 0x01, 0x75, 0xc5, 0x6d, 0x58, 0x92, 0xf2, 0xb2, 0x47, 0x00, 0x01, 0x26, 0x96, 0x7a, 0x30, 0xff, 0xb7, 0xf0, 0xef, 0x77, 0xc1, 0x8a, 0x5d, 0xdc, 0xc0, 0xd1, 0x29, 0x30, 0x1e, 0x77, 0x38, 0x7a, 0x94, 0xf1, 0xb8, 0x7a, 0x7e, 0xef, 0xa4, 0xd1, 0xac, 0x31, 0x4a, 0xf2, 0x5d, 0x64, 0x3d, 0xb2, 0xe2, 0xf0, 0x08, 0x99, 0xfc, 0x70, 0xee, 0x24, 0xa7, 0x7e, 0xee, 0x1e, 0x20, 0x69, 0x7d, 0x44, 0xbf, 0x87, 0x42, 0xdf, 0x88, 0x3b, 0x0c, 0xda, 0x42, 0xc9, 0x04, 0xf9, 0x45, 0x50, 0xfc, 0x83, 0x8f, 0x11, 0x6a, 0x72, 0xbc, 0x99, 0x95, 0xf0, 0xac, 0x3d, 0xa7, 0x3b, 0xcd, 0x1c, 0xe2, 0x88, 0x79, 0x37, 0x11, 0x5f, 0x39, 0x89, 0x95, 0x0a, 0x16, 0x84, 0x7a, 0xf6, 0x8a, 0xa4, 0x28, 0xe4, 0xed, 0x83, 0x80, 0x3b, 0xb1, 0x23, 0xa5, 0x03, 0x10, 0xf4, 0x66, 0xea, 0xbb, 0x0c, 0x0f, 0xc5, 0xec, 0x6c, 0x69, 0xc5, 0xd3, 0x24, 0xab, 0xd4, 0x2a, 0xb7, 0x99, 0x88, 0x76, 0x08, 0xa0, 0xa8, 0x95, 0x7c, 0xd8, 0x38, 0x6d, 0xcd, 0x59, 0x02, 0x51, 0x4b, 0xf1, 0xb5, 0x2b, 0x50, 0xe3, 0xb6, 0xbd, 0xd0, 0x72, 0xcf, 0x9e, 0xfd, 0x6e, 0xbb, 0x44, 0xc8, 0x24, 0x8a, 0x77, 0x18, 0x8a, 0x13, 0x06, 0xef, 0x97, 0x7d, 0xfa, 0x81, 0xf0, 0x31, 0xe6, 0xfa, 0x77, 0xed, 0x31, 0x06, 0x31, 0x5b, 0x54, 0x8a, 0x9f, 0x30, 0x68, 0xdb, 0xe2, 0x40, 0xf8, 0x4e, 0x73, 0xfa, 0xab, 0x74, 0x8b, 0x10, 0x58, 0x13, 0xdc, 0xd2, 0xe6, 0x78, 0xd1, 0x32, 0x2e, 0x8a, 0x9f, 0x2c, 0x58, 0x06, 0x48, 0x27, 0xc5, 0xa9, 0x5e, 0x81, 0x47, 0x89, 0x46, 0x21, 0x91, 0x03, 0x70, 0xa4, 0x3e, 0x88, 0x9c, 0xda, 0x33, 0x0a, 0xce, 0xbc, 0x8b, 0x8e, 0xcf, 0x9f, 0xd3, 0x71, 0x80, 0x43, 0xcf, 0x6b, 0xa9, 0x51, 0x83, 0x76, 0x30, 0x82, 0xc5, 0x6a, 0x85, 0x39, 0x11, 0x50, 0x1a, 0x82, 0xdc, 0x1e, 0x1c, 0xd5, 0x7d, 0xa9, 0x71, 0x99, 0x33, 0x47, 0x19, 0x97, 0xb3, 0x5a, 0xb1, 0xdf, 0xed, 0xa4, 0xf2, 0xe6, 0x26, 0x84, 0xa2, 0x28, 0x9a, 0x9e, 0xdf, 0xa6, 0x6a, 0xf4, 0xd6, 0xfc, 0x2e, 0x5b, 0x9d, 0x1a, 0x2a, 0x27, 0x68, 0xfb, 0xc1, 0x83, 0x21, 0x4b, 0x90, 0xe0, 0x36, 0xdd, 0x5b, 0x31, 0x42, 0x55, 0xa0, 0x13, 0xf7, 0xd0, 0x89, 0x53, 0x71, 0x99, 0x57, 0x09, 0x29, 0xc5, 0xf3, 0x21, 0xf8, 0x37, 0x2f, 0x40, 0xf3, 0xd4, 0xaf, 0x16, 0x08, 0x36, 0x02, 0xfc, 0x77, 0xc5, 0x8b, 0x04, 0x90, 0x56, 0xb9, 0xc9, 0x67, 0x9a, 0x99, 0xe8, 0x00, 0xd3, 0x86, 0xff, 0x97, 0x2d, 0x08, 0xe9, 0xb7, 0xb3, 0x91, 0xbc, 0xdf, 0x45, 0xc6, 0xed, 0x0f, 0x8c, 0x4c, 0x1e, 0xe6, 0x5b, 0x6e, 0x38, 0x30, 0xe4, 0xaa, 0xe3, 0x95, 0xde, 0xb9, 0xe4, 0x9a, 0xf5, 0xb2, 0x55, 0x9a, 0x87, 0x9b, 0xf6, 0x6a, 0xb2, 0xf2, 0x77, 0x9a, 0x31, 0xf4, 0x7a, 0x31, 0xd1, 0x1d, 0x04, 0xc0, 0x7c, 0x32, 0xa2, 0x9e, 0x9a, 0xf5, 0x62, 0xf8, 0x27, 0x8d, 0xbf, 0x51, 0xff, 0xd3, 0xdf, 0x64, 0x37, 0x3f, 0x2a, 0x6f, 0x76, 0x3a, 0x7d, 0x77, 0x06, 0x9e, 0x77, 0x7f, 0x5e, 0xeb, 0x32, 0x51, 0xf9, 0x16, 0x66, 0x9a, 0x09, 0xf3, 0xb0, 0x08, 0xa4, 0x70, 0x96, 0x46, 0x30, 0xff, 0xda, 0x4f, 0xe9, 0x1b, 0xed, 0x8d, 0xf8, 0x74, 0x1f, 0x31, 0x92, 0xb3, 0x73, 0x17, 0x36, 0xdb, 0x91, 0x30, 0xd6, 0x88, 0x55, 0x6b, 0x34, 0x77, 0x87, 0x7a, 0xe7, 0xee, 0x06, 0xc6, 0x1c, 0x8c, 0x19, 0x0c, 0x48, 0x46, 0x23, 0x5e, 0x9c, 0x07, 0x5c, 0xbf, 0xb4, 0x7e, 0xd6, 0x4f, 0x74, 0x9c, 0xe2, 0xc5, 0x50, 0x8b, 0xc5, 0x8b, 0x15, 0x90, 0x60, 0x62, 0x57, 0x29, 0xd0, 0x13, 0x43, 0xa1, 0x80, 0x88, 0x91, 0x00, 0x44, 0xc7, 0x4d, 0x19, 0x86, 0xcc, 0x2f, 0x2a, 0x75, 0x5a, 0xfc, 0xeb, 0x97, 0x2a, 0x70, 0xe3, 0x78, 0xd8, 0x91, 0xb0, 0x4f, 0x99, 0x07, 0xa3, 0x95, 0xea, 0x24, 0x21, 0xd5, 0xde, 0x51, 0x20, 0x93, 0x27, 0x0a, 0x30, 0x73, 0xa8, 0xff, 0x8a, 0x97, 0xe9, 0xa7, 0x6a, 0x8e, 0x0d, 0xe8, 0xf0, 0xdf, 0xec, 0xea, 0xb4, 0x6c, 0x1d, 0x39, 0x2a, 0x62, 0x2d, 0x3d, 0x5a, 0x8b, 0x65, 0xf8, 0x90, 0x05, 0x2e, 0x7e, 0x91, 0x2c, 0x78, 0xef, 0x8e, 0x7a, 0xc1, 0x2f, 0xac, 0x78, 0xee, 0xaf, 0x28, 0x45, 0x06, 0x4c, 0x26, 0xaf, 0x3b, 0xa2, 0xdb, 0xa3, 0x93, 0x06, 0xb5, 0x3c, 0xa5, 0xd8, 0xee, 0x8f, 0xaf, 0x25, 0xcc, 0x3f, 0x85, 0x68, 0x48, 0xa9, 0x62, 0xcc, 0x97, 0x8f, 0x7f, 0x2a, 0xea, 0xe0, 0x15, 0x0a, 0xad, 0x62, 0x07, 0xbd, 0x45, 0xf8, 0x41, 0xd8, 0x36, 0xcb, 0x4c, 0xdb, 0x6e, 0xe6, 0x3a, 0xe7, 0xda, 0x15, 0xe9, 0x29, 0x1e, 0x12, 0x10, 0xa0, 0x14, 0x2c, 0x0e, 0x3d, 0xf4, 0xbf, 0x39, 0x41, 0x92, 0x75, 0x0b, 0x25, 0x7b, 0xa3, 0xce, 0x39, 0x9c, 0x15, 0x64, 0xc8, 0xfa, 0x3d, 0xef, 0x73, 0x27, 0xfe, 0x26, 0x2e, 0xce, 0xda, 0x6e, 0xfd, 0x71, 0x8e, 0xdd, 0xfe, 0x76, 0xee, 0xdc, 0x12, 0x5c, 0x02, 0xc5, 0x3a, 0x4e, 0x4e, 0x4f, 0xbf, 0xca, 0x40, 0x15, 0xc7, 0x6e, 0x8d, 0x41, 0xf1, 0x10, 0xe0, 0x4f, 0x7e, 0x97, 0x7f, 0x1c, 0xae, 0x47, 0x8e, 0x6b, 0xb1, 0x25, 0x31, 0xb0, 0x73, 0xc7, 0x1b, 0x97, 0x79, 0xf9, 0x80, 0xd3, 0x66, 0x22, 0x30, 0x07, 0x74, 0x1e, 0xe4, 0xd0, 0x80, 0x21, 0xd6, 0xee, 0x6b, 0x6c, 0x4f, 0xbf, 0xf5, 0xb7, 0xd9, 0x09, 0x87, 0x2f, 0xa9, 0x14, 0xbe, 0x27, 0xd9, 0x72, 0x50, 0x01, 0xd4, 0x13, 0x73, 0xa6, 0xa7, 0x51, 0x02, 0x75, 0x25, 0xe1, 0xb3, 0x45, 0x34, 0x7d, 0xa8, 0x8e, 0xeb, 0xf3, 0x16, 0x49, 0xcb, 0x4f, 0x8c, 0xa1, 0xb9, 0x36, 0x85, 0x39, 0x75, 0x5d, 0x08, 0x00, 0xae, 0xeb, 0xf6, 0xea, 0xd7, 0x13, 0x3a, 0x21, 0x5a, 0x5f, 0x30, 0x84, 0x52, 0x26, 0x95, 0xc9, 0x14, 0xf2, 0x57, 0x55, 0x6b, 0xb1, 0x10, 0xc2, 0xe1, 0xbd, 0x3b, 0x51, 0xc0, 0xb7, 0x55, 0x4c, 0x71, 0x12, 0x26, 0xc7, 0x0d, 0xf9, 0x51, 0xa4, 0x38, 0x02, 0x05, 0x7f, 0xb8, 0xf1, 0x72, 0x4b, 0xbf, 0x71, 0x89, 0x14, 0xf3, 0x77, 0x38, 0xd9, 0x71, 0x24, 0xf3, 0x00, 0x11, 0xa1, 0xd8, 0xd4, 0x69, 0x27, 0x08, 0x37, 0x35, 0xc9, 0x11, 0x9d, 0x90, 0x1c, 0x0e, 0xe7, 0x1c, 0xff, 0x2d, 0x1e, 0xe8, 0x92, 0xe1, 0x18, 0x10, 0x95, 0x7c, 0xe0, 0x80, 0xf4, 0x96, 0x43, 0x21, 0xf9, 0x75, 0x21, 0x64, 0x38, 0xdd, 0x9f, 0x1e, 0x95, 0x16, 0xda, 0x56, 0x1d, 0x4f, 0x9a, 0x53, 0xb2, 0xe2, 0xe4, 0x18, 0xcb, 0x6b, 0x1a, 0x65, 0xeb, 0x56, 0xc6, 0x3b, 0xe5, 0xfe, 0xd8, 0x26, 0x3f, 0x3a, 0x84, 0x59, 0x72, 0x66, 0xa2, 0xf3, 0x75, 0xff, 0xfb, 0x60, 0xb3, 0x22, 0xad, 0x3f, 0x2d, 0x6b, 0xf9, 0xeb, 0xea, 0x05, 0x7c, 0xd8, 0x8f, 0x6d, 0x2c, 0x98, 0x9e, 0x2b, 0x93, 0xf1, 0x5e, 0x46, 0xf0, 0x87, 0x49, 0x29, 0x73, 0x68, 0xd7, 0x7f, 0xf9, 0xf0, 0xe5, 0x7d, 0xdb, 0x1d, 0x75, 0x19, 0xf3, 0xc4, 0x58, 0x9b, 0x17, 0x88, 0xa8, 0x92, 0xe0, 0xbe, 0xbd, 0x8b, 0x1d, 0x8d, 0x9f, 0x56, 0x76, 0xad, 0xaf, 0x29, 0xe2, 0xd9, 0xd5, 0x52, 0xf6, 0xb5, 0x56, 0x35, 0x57, 0x3a, 0xc8, 0xe1, 0x56, 0x43, 0x19, 0x94, 0xd3, 0x04, 0x9b, 0x6d, 0x35, 0xd8, 0x0b, 0x5f, 0x4d, 0x19, 0x8e, 0xec, 0xfa, 0x64, 0x91, 0x0a, 0x72, 0x20, 0x2b, 0xbc, 0x1a, 0x4a, 0xfe, 0x8b, 0xfd, 0xbb, 0xed, 0x1b, 0x23, 0xea, 0xad, 0x72, 0x82, 0xa1, 0x29, 0x99, 0x71, 0xbd, 0xf0, 0x95, 0xc1, 0x03, 0xdd, 0x7b, 0xc2, 0xb2, 0x3c, 0x28, 0x54, 0xd3, 0x68, 0xa4, 0x72, 0xc8, 0x66, 0x96, 0xe0, 0xd1, 0xd8, 0x7f, 0xf8, 0xd1, 0x26, 0x2b, 0xf7, 0xad, 0xba, 0x55, 0xca, 0x15, 0xb9, 0x32, 0xc3, 0xe5, 0x88, 0x97, 0x8e, 0x5c, 0xfb, 0x92, 0x25, 0x8b, 0xbf, 0xa2, 0x45, 0x55, 0x7a, 0xa7, 0x6f, 0x8b, 0x57, 0x5b, 0xcf, 0x0e, 0xcb, 0x1d, 0xfb, 0x20, 0x82, 0x77, 0xa8, 0x8c, 0xcc, 0x16, 0xce, 0x1d, 0xfa, 0xde, 0xcc, 0x0b, 0x62, 0xfe, 0xcc, 0xe1, 0xb7, 0xf0, 0xc3, 0x81, 0x64, 0x73, 0x40, 0xa0, 0xc2, 0x4d, 0x89, 0x11, 0x75, 0x33, 0x55, 0x33, 0x8d, 0xe8, 0x4a, 0xfd, 0xea, 0x6e, 0x30, 0x0b, 0xd7, 0x31, 0x2c, 0xde, 0x47, 0xe3, 0xbf, 0xf8, 0x55, 0x42, 0xe2, 0x7f, 0x59, 0xe5, 0x17, 0xef, 0x99, 0x34, 0x69, 0x91, 0xb1, 0x23, 0x8e, 0x20, 0x87, 0x2d, 0xa8, 0xfe, 0xd5, 0x8a, 0xf3, 0x84, 0x3a, 0xf0, 0x37, 0xe4, 0x09, 0x00, 0x54, 0xee, 0x67, 0x49, 0x93, 0xe4, 0x81, 0x70, 0xe3, 0x90, 0x4d, 0xef, 0xfe, 0x41, 0xb7, 0x99, 0x7b, 0xc1, 0x83, 0xba, 0x62, 0x12, 0x6f, 0x7d, 0xde, 0x6b, 0xaf, 0xda, 0x16, 0xf9, 0x55, 0x51, 0xee, 0xa6, 0x0c, 0x2b, 0x02, 0xa3, 0xfd, 0x8d, 0xfb, 0x30, 0x17, 0xe4, 0x6f, 0xdf, 0x36, 0x71, 0xc4, 0xca, 0x87, 0x25, 0x48, 0xb0, 0x47, 0xec, 0xea, 0xb4, 0xbf, 0xa5, 0x4d, 0x9b, 0x9f, 0x02, 0x93, 0xc4, 0xe3, 0xe4, 0xe8, 0x42, 0x2d, 0x68, 0x81, 0x15, 0x0a, 0xeb, 0x84, 0x5b, 0xd6, 0xa8, 0x74, 0xfb, 0x7d, 0x1d, 0xcb, 0x2c, 0xda, 0x46, 0x2a, 0x76, 0x62, 0xce, 0xbc, 0x5c, 0x9e, 0x8b, 0xe7, 0xcf, 0xbe, 0x78, 0xf5, 0x7c, 0xeb, 0xb3, 0x3a, 0x9c, 0xaa, 0x6f, 0xcc, 0x72, 0xd1, 0x59, 0xf2, 0x11, 0x23, 0xd6, 0x3f, 0x48, 0xd1, 0xb7, 0xce, 0xb0, 0xbf, 0xcb, 0xea, 0x80, 0xde, 0x57, 0xd4, 0x5e, 0x97, 0x2f, 0x75, 0xd1, 0x50, 0x8e, 0x80, 0x2c, 0x66, 0x79, 0xbf, 0x72, 0x4b, 0xbd, 0x8a, 0x81, 0x6c, 0xd3, 0xe1, 0x01, 0xdc, 0xd2, 0x15, 0x26, 0xc5, 0x36, 0xda, 0x2c, 0x1a, 0xc0, 0x27, 0x94, 0xed, 0xb7, 0x9b, 0x85, 0x0b, 0x5e, 0x80, 0x97, 0xc5, 0xec, 0x4f, 0xec, 0x88, 0x5d, 0x50, 0x07, 0x35, 0x47, 0xdc, 0x0b, 0x3b, 0x3d, 0xdd, 0x60, 0xaf, 0xa8, 0x5d, 0x81, 0x38, 0x24, 0x25, 0x5d, 0x5c, 0x15, 0xd1, 0xde, 0xb3, 0xab, 0xec, 0x05, 0x69, 0xef, 0x83, 0xed, 0x57, 0x54, 0xb8, 0x64, 0x64, 0x11, 0x16, 0x32, 0x69, 0xda, 0x9f, 0x2d, 0x7f, 0x36, 0xbb, 0x44, 0x5a, 0x34, 0xe8, 0x7f, 0xbf, 0x03, 0xeb, 0x00, 0x7f, 0x59, 0x68, 0x22, 0x79, 0xcf, 0x73, 0x6c, 0x2c, 0x29, 0xa7, 0xa1, 0x5f, 0x38, 0xa1, 0x1d, 0xf0, 0x20, 0x53, 0xe0, 0x1a, 0x63, 0x14, 0x58, 0x71, 0x10, 0xaa, 0x08, 0x0c, 0x3e, 0x16, 0x1a, 0x60, 0x22, 0x82, 0x7f, 0xba, 0xa4, 0x43, 0xa0, 0xd0, 0xac, 0x1b, 0xd5, 0x6b, 0x64, 0xb5, 0x14, 0x93, 0x31, 0x9e, 0x53, 0x50, 0xd0, 0x57, 0x66, 0xee, 0x5a, 0x4f, 0xfb, 0x03, 0x2a, 0x69, 0x58, 0x76, 0xf1, 0x83, 0xf7, 0x4e, 0xba, 0x8c, 0x42, 0x06, 0x60, 0x5d, 0x6d, 0xce, 0x60, 0x88, 0xae, 0xa4, 0xc3, 0xf1, 0x03, 0xa5, 0x4b, 0x98, 0xa1, 0xff, 0x67, 0xe1, 0xac, 0xa2, 0xb8, 0x62, 0xd7, 0x6f, 0xa0, 0x31, 0xb4, 0xd2, 0x77, 0xaf, 0x21, 0x10, 0x06, 0xc6, 0x9a, 0xff, 0x1d, 0x09, 0x17, 0x0e, 0x5f, 0xf1, 0xaa, 0x54, 0x34, 0x4b, 0x45, 0x8a, 0x87, 0x63, 0xa6, 0xdc, 0xf9, 0x24, 0x30, 0x67, 0xc6, 0xb2, 0xd6, 0x61, 0x33, 0x69, 0xee, 0x50, 0x61, 0x57, 0x28, 0xe7, 0x7e, 0xee, 0xec, 0x3a, 0x5a, 0x73, 0x4e, 0xa8, 0x8d, 0xe4, 0x18, 0xea, 0xec, 0x41, 0x64, 0xc8, 0xe2, 0xe8, 0x66, 0xb6, 0x2d, 0xb6, 0xfb, 0x6a, 0x6c, 0x16, 0xb3, 0xdd, 0x46, 0x43, 0xb9, 0x73, 0x00, 0x6a, 0x71, 0xed, 0x4e, 0x9d, 0x25, 0x1a, 0xc3, 0x3c, 0x4a, 0x95, 0x15, 0x99, 0x35, 0x81, 0x14, 0x02, 0xd6, 0x98, 0x9b, 0xec, 0xd8, 0x23, 0x3b, 0x84, 0x29, 0xaf, 0x0c, 0x99, 0x83, 0xa6, 0x9a, 0x34, 0x4f, 0xfa, 0xe8, 0xd0, 0x3c, 0x4b, 0xd0, 0xfb, 0xb6, 0x68, 0xb8, 0x9e, 0x8f, 0xcd, 0xf7, 0x60, 0x2d, 0x7a, 0x22, 0xe5, 0x7d, 0xab, 0x65, 0x1b, 0x95, 0xa7, 0xa8, 0x7f, 0xb6, 0x77, 0x47, 0x7b, 0x5f, 0x8b, 0x12, 0x72, 0xd0, 0xd4, 0x91, 0xef, 0xde, 0x19, 0x50, 0x3c, 0xa7, 0x8b, 0xc4, 0xa9, 0xb3, 0x23, 0xcb, 0x76, 0xe6, 0x81, 0xf0, 0xc1, 0x04, 0x8f, 0xa3, 0xb8, 0x54, 0x5b, 0x97, 0xac, 0x19, 0xff, 0x3f, 0x55, 0x27, 0x2f, 0xe0, 0x1d, 0x42, 0x9b, 0x57, 0xfc, 0x4b, 0x4e, 0x0f, 0xce, 0x98, 0xa9, 0x43, 0x57, 0x03, 0xbd, 0xe7, 0xc8, 0x94, 0xdf, 0x6e, 0x36, 0x73, 0x32, 0xb4, 0xef, 0x2e, 0x85, 0x7a, 0x6e, 0xfc, 0x6c, 0x18, 0x82, 0x75, 0x35, 0x90, 0x07, 0xf3, 0xe4, 0x9f, 0x3e, 0xdc, 0x68, 0xf3, 0xb5, 0xf3, 0x19, 0x80, 0x92, 0x06, 0x99, 0xa2, 0xe8, 0x6f, 0xff, 0x2e, 0x7f, 0xae, 0x42, 0xa4, 0x5f, 0xfb, 0xd4, 0x0e, 0x81, 0x2b, 0xc3, 0x04, 0xff, 0x2b, 0xb3, 0x74, 0x4e, 0x36, 0x5b, 0x9c, 0x15, 0x00, 0xc6, 0x47, 0x2b, 0xe8, 0x8b, 0x3d, 0xf1, 0x9c, 0x03, 0x9a, 0x58, 0x7f, 0x9b, 0x9c, 0xbf, 0x85, 0x49, 0x79, 0x35, 0x2e, 0x56, 0x7b, 0x41, 0x14, 0x39, 0x47, 0x83, 0x26, 0xaa, 0x07, 0x89, 0x98, 0x11, 0x1b, 0x86, 0xe7, 0x73, 0x7a, 0xd8, 0x7d, 0x78, 0x61, 0x53, 0xe9, 0x79, 0xf5, 0x36, 0x8d, 0x44, 0x92, 0x84, 0xf9, 0x13, 0x50, 0x58, 0x3b, 0xa4, 0x6a, 0x36, 0x65, 0x49, 0x8e, 0x3c, 0x0e, 0xf1, 0x6f, 0xd2, 0x84, 0xc4, 0x7e, 0x8e, 0x3f, 0x39, 0xae, 0x7c, 0x84, 0xf1, 0x63, 0x37, 0x8e, 0x3c, 0xcc, 0x3e, 0x44, 0x81, 0x45, 0xf1, 0x4b, 0xb9, 0xed, 0x6b, 0x36, 0x5d, 0xbb, 0x20, 0x60, 0x1a, 0x0f, 0xa3, 0xaa, 0x55, 0x77, 0x3a, 0xa9, 0xae, 0x37, 0x4d, 0xba, 0xb8, 0x86, 0x6b, 0xbc, 0x08, 0x50, 0xf6, 0xcc, 0xa4, 0xbd, 0x1d, 0x40, 0x72, 0xa5, 0x86, 0xfa, 0xe2, 0x10, 0xae, 0x3d, 0x58, 0x4b, 0x97, 0xf3, 0x43, 0x74, 0xa9, 0x9e, 0xeb, 0x21, 0xb7, 0x01, 0xa4, 0x86, 0x93, 0x97, 0xee, 0x2f, 0x4f, 0x3b, 0x86, 0xa1, 0x41, 0x6f, 0x41, 0x26, 0x90, 0x78, 0x5c, 0x7f, 0x30, 0x38, 0x4b, 0x3f, 0xaa, 0xec, 0xed, 0x5c, 0x6f, 0x0e, 0xad, 0x43, 0x87, 0xfd, 0x93, 0x35, 0xe6, 0x01, 0xef, 0x41, 0x26, 0x90, 0x99, 0x9e, 0xfb, 0x19, 0x5b, 0xad, 0xd2, 0x91, 0x8a, 0xe0, 0x46, 0xaf, 0x65, 0xfa, 0x4f, 0x84, 0xc1, 0xa1, 0x2d, 0xcf, 0x45, 0x8b, 0xd3, 0x85, 0x50, 0x55, 0x7c, 0xf9, 0x67, 0x88, 0xd4, 0x4e, 0xe9, 0xd7, 0x6b, 0x61, 0x54, 0xa1, 0xa4, 0xa6, 0xa2, 0xc2, 0xbf, 0x30, 0x9c, 0x40, 0x9f, 0x5f, 0xd7, 0x69, 0x2b, 0x24, 0x82, 0x5e, 0xd9, 0xd6, 0xa7, 0x12, 0x54, 0x1a, 0xf7, 0x55, 0x9f, 0x76, 0x50, 0xa9, 0x95, 0x84, 0xe6, 0x6b, 0x6d, 0xb5, 0x96, 0x54, 0xd6, 0xcd, 0xb3, 0xa1, 0x9b, 0x46, 0xa7, 0x94, 0x4d, 0xc4, 0x94, 0xb4, 0x98, 0xe3, 0xe1, 0xe2, 0x34, 0xd5, 0x33, 0x16, 0x07, 0x54, 0xcd, 0xb7, 0x77, 0x53, 0xdb, 0x4f, 0x4d, 0x46, 0x9d, 0xe9, 0xd4, 0x9c, 0x8a, 0x36, 0xb6, 0xb8, 0x38, 0x26, 0x6c, 0x0e, 0xff, 0x9c, 0x1b, 0x43, 0x8b, 0x80, 0xcc, 0xb9, 0x3d, 0xda, 0xc7, 0xf1, 0x8a, 0xf2, 0x6d, 0xb8, 0xd7, 0x74, 0x2f, 0x7e, 0x1e, 0xb7, 0xd3, 0x4a, 0xb4, 0xac, 0xfc, 0x79, 0x48, 0x6c, 0xbc, 0x96, 0xb6, 0x94, 0x46, 0x57, 0x2d, 0xb0, 0xa3, 0xfc, 0x1e, 0xb9, 0x52, 0x60, 0x85, 0x2d, 0x41, 0xd0, 0x43, 0x01, 0x1e, 0x1c, 0xd5, 0x7d, 0xfc, 0xf3, 0x96, 0x0d, 0xc7, 0xcb, 0x2a, 0x29, 0x9a, 0x93, 0xdd, 0x88, 0x2d, 0x37, 0x5d, 0xaa, 0xfb, 0x49, 0x68, 0xa0, 0x9c, 0x50, 0x86, 0x7f, 0x68, 0x56, 0x57, 0xf9, 0x79, 0x18, 0x39, 0xd4, 0xe0, 0x01, 0x84, 0x33, 0x61, 0xca, 0xa5, 0xd2, 0xd6, 0xe4, 0xc9, 0x8a, 0x4a, 0x23, 0x44, 0x4e, 0xbc, 0xf0, 0xdc, 0x24, 0xa1, 0xa0, 0xc4, 0xe2, 0x07, 0x3c, 0x10, 0xc4, 0xb5, 0x25, 0x4b, 0x65, 0x63, 0xf4, 0x80, 0xe7, 0xcf, 0x61, 0xb1, 0x71, 0x82, 0x21, 0x87, 0x2c, 0xf5, 0x91, 0x00, 0x32, 0x0c, 0xec, 0xa9, 0xb5, 0x9a, 0x74, 0x85, 0xe3, 0x36, 0x8f, 0x76, 0x4f, 0x9c, 0x6d, 0xce, 0xbc, 0xad, 0x0a, 0x4b, 0xed, 0x76, 0x04, 0xcb, 0xc3, 0xb9, 0x33, 0x9e, 0x01, 0x93, 0x96, 0x69, 0x7d, 0xc5, 0xa2, 0x45, 0x79, 0x9b, 0x04, 0x5c, 0x84, 0x09, 0xed, 0x88, 0x43, 0xc7, 0xab, 0x93, 0x14, 0x26, 0xa1, 0x40, 0xb5, 0xce, 0x4e, 0xbf, 0x2a, 0x42, 0x85, 0x3e, 0x2c, 0x3b, 0x54, 0xe8, 0x12, 0x1f, 0x0e, 0x97, 0x59, 0xb2, 0x27, 0x89, 0xfa, 0xf2, 0xdf, 0x8e, 0x68, 0x59, 0xdc, 0x06, 0xbc, 0xb6, 0x85, 0x0d, 0x06, 0x22, 0xec, 0xb1, 0xcb, 0xe5, 0x04, 0xe6, 0x3d, 0xb3, 0xb0, 0x41, 0x73, 0x08, 0x3f, 0x3c, 0x58, 0x86, 0x63, 0xeb, 0x50, 0xee, 0x1d, 0x2c, 0x37, 0x74, 0xa9, 0xd3, 0x18, 0xa3, 0x47, 0x6e, 0x93, 0x54, 0xad, 0x0a, 0x5d, 0xb8, 0x2a, 0x55, 0x5d, 0x78, 0xf6, 0xee, 0xbe, 0x8e, 0x3c, 0x76, 0x69, 0xb9, 0x40, 0xc2, 0x34, 0xec, 0x2a, 0xb9, 0xed, 0x7e, 0x20, 0xe4, 0x8d, 0x00, 0x38, 0xc7, 0xe6, 0x8f, 0x44, 0xa8, 0x86, 0xce, 0xeb, 0x2a, 0xe9, 0x90, 0xf1, 0x4c, 0xdf, 0x32, 0xfb, 0x73, 0x1b, 0x6d, 0x92, 0x1e, 0x95, 0xfe, 0xb4, 0xdb, 0x65, 0xdf, 0x4d, 0x23, 0x54, 0x89, 0x48, 0xbf, 0x4a, 0x2e, 0x70, 0xd6, 0xd7, 0x62, 0xb4, 0x33, 0x29, 0xb1, 0x3a, 0x33, 0x4c, 0x23, 0x6d, 0xa6, 0x76, 0xa5, 0x21, 0x63, 0x48, 0xe6, 0x90, 0x5d, 0xed, 0x90, 0x95, 0x0b, 0x7a, 0x84, 0xbe, 0xb8, 0x0d, 0x5e, 0x63, 0x0c, 0x62, 0x26, 0x4c, 0x14, 0x5a, 0xb3, 0xac, 0x23, 0xa4, 0x74, 0xa7, 0x6f, 0x33, 0x30, 0x05, 0x60, 0x01, 0x42, 0xa0, 0x28, 0xb7, 0xee, 0x19, 0x38, 0xf1, 0x64, 0x80, 0x82, 0x43, 0xe1, 0x41, 0x27, 0x1f, 0x1f, 0x90, 0x54, 0x7a, 0xd5, 0x23, 0x2e, 0xd1, 0x3d, 0xcb, 0x28, 0xba, 0x58, 0x7f, 0xdc, 0x7c, 0x91, 0x24, 0xe9, 0x28, 0x51, 0x83, 0x6e, 0xc5, 0x56, 0x21, 0x42, 0xed, 0xa0, 0x56, 0x22, 0xa1, 0x40, 0x80, 0x6b, 0xa8, 0xf7, 0x94, 0xca, 0x13, 0x6b, 0x0c, 0x39, 0xd9, 0xfd, 0xe9, 0xf3, 0x6f, 0xa6, 0x9e, 0xfc, 0x70, 0x8a, 0xb3, 0xbc, 0x59, 0x3c, 0x1e, 0x1d, 0x6c, 0xf9, 0x7c, 0xaf, 0xf9, 0x88, 0x71, 0x95, 0xeb, 0x57, 0x00, 0xbd, 0x9f, 0x8c, 0x4f, 0xe1, 0x24, 0x83, 0xc5, 0x22, 0xea, 0xfd, 0xd3, 0x0c, 0xe2, 0x17, 0x18, 0x7c, 0x6a, 0x4c, 0xde, 0x77, 0xb4, 0x53, 0x9b, 0x4c, 0x81, 0xcd, 0x23, 0x60, 0xaa, 0x0e, 0x25, 0x73, 0x9c, 0x02, 0x79, 0x32, 0x30, 0xdf, 0x74, 0xdf, 0x75, 0x19, 0xf4, 0xa5, 0x14, 0x5c, 0xf7, 0x7a, 0xa8, 0xa5, 0x91, 0x84, 0x7c, 0x60, 0x03, 0x06, 0x3b, 0xcd, 0x50, 0xb6, 0x27, 0x9c, 0xfe, 0xb1, 0xdd, 0xcc, 0xd3, 0xb0, 0x59, 0x24, 0xb2, 0xca, 0xe2, 0x1c, 0x81, 0x22, 0x9d, 0x07, 0x8f, 0x8e, 0xb9, 0xbe, 0x4e, 0xfa, 0xfc, 0x39, 0x65, 0xba, 0xbf, 0x9d, 0x12, 0x37, 0x5e, 0x97, 0x7e, 0xf3, 0x89, 0xf5, 0x5d, 0xf5, 0xe3, 0x09, 0x8c, 0x62, 0xb5, 0x20, 0x9d, 0x0c, 0x53, 0x8a, 0x68, 0x1b, 0xd2, 0x8f, 0x75, 0x17, 0x5d, 0xd4, 0xe5, 0xda, 0x75, 0x62, 0x19, 0x14, 0x6a, 0x26, 0x2d, 0xeb, 0xf8, 0xaf, 0x37, 0xf0, 0x6c, 0xa4, 0x55, 0xb1, 0xbc, 0xe2, 0x33, 0xc0, 0x9a, 0xca, 0xb0, 0x11, 0x49, 0x4f, 0x68, 0x9b, 0x3b, 0x6b, 0x3c, 0xcc, 0x13, 0xf6, 0xc7, 0x85, 0x61, 0x68, 0x42, 0xae, 0xbb, 0xdd, 0xcd, 0x45, 0x16, 0x29, 0x1d, 0xea, 0xdb, 0xc8, 0x03, 0x94, 0x3c, 0xee, 0x4f, 0x82, 0x11, 0xc3, 0xec, 0x28, 0xbd, 0x97, 0x05, 0x99, 0xde, 0xd7, 0xbb, 0x5e, 0x22, 0x1f, 0xd4, 0xeb, 0x64, 0xd9, 0x92, 0xd9, 0x85, 0xb7, 0x6a, 0x05, 0x6a, 0xe4, 0x24, 0x41, 0xf1, 0xcd, 0xf0, 0xd8, 0x3f, 0xf8, 0x9e, 0x0e, 0xcd, 0x0b, 0x7a, 0x70, 0x6b, 0x5a, 0x75, 0x0a, 0x6a, 0x33, 0x88, 0xec, 0x17, 0x75, 0x08, 0x70, 0x10, 0x2f, 0x24, 0xcf, 0xc4, 0xe9, 0x42, 0x00, 0x61, 0x94, 0xca, 0x1f, 0x3a, 0x76, 0x06, 0xfa, 0xd2, 0x48, 0x81, 0xf0, 0x77, 0x60, 0x03, 0x45, 0xd9, 0x61, 0xf4, 0xa4, 0x6f, 0x3d, 0xd9, 0x30, 0xc3, 0x04, 0x6b, 0x54, 0x2a, 0xb7, 0xec, 0x3b, 0xf4, 0x4b, 0xf5, 0x68, 0x52, 0x26, 0xce, 0xff, 0x5d, 0x19, 0x91, 0xa0, 0xa3, 0xa5, 0xa9, 0xb1, 0xe0, 0x23, 0xc4, 0x0a, 0x77, 0x4d, 0xf9, 0x51, 0x20, 0xa3, 0xa5, 0xa9, 0xb1, 0xc1, 0x00, 0x82, 0x86, 0x8e, 0x7f, 0x5d, 0x19, 0x91, 0xa0, 0xa3, 0xc4, 0xeb, 0x54, 0x0b, 0x75, 0x68, 0x52, 0x07, 0x8c, 0x9a, 0x97, 0x8d, 0x79, 0x70, 0x62, 0x46, 0xef, 0x5c, 0x1b, 0x95, 0x89, 0x71, 0x41, 0xe1, 0x21, 0xa1, 0xa1, 0xa1, 0xc0, 0x02, 0x67, 0x4c, 0x1a, 0xb6, 0xcf, 0xfd, 0x78, 0x53, 0x24, 0xab, 0xb5, 0xc9, 0xf1, 0x60, 0x23, 0xa5, 0xc8, 0x12, 0x87, 0x6d, 0x58, 0x13, 0x85, 0x88, 0x92, 0x87, 0x6d, 0x58, 0x32, 0xc7, 0x0c, 0x9a, 0x97, 0xac, 0xda, 0x36, 0xee, 0x5e, 0x3e, 0xdf, 0x1d, 0xb8, 0xf2, 0x66, 0x2f, 0xbd, 0xf8, 0x72, 0x47, 0xed, 0x58, 0x13, 0x85, 0x88, 0x92, 0x87, 0x8c, 0x7b, 0x55, 0x09, 0x90, 0xa2, 0xc6, 0xef, 0x3d, 0xf8, 0x53, 0x24, 0xab, 0xd4, 0x2a, 0xb7, 0xec, 0x5a, 0x36, 0xee, 0x5e, 0x3e, 0xdf, 0x3c, 0xfa, 0x76, 0x4f, 0xfd, 0x59, 0x30, 0xe2, 0x46, 0xef, 0x3d, 0xf8, 0x53, 0x05, 0x69, 0x31, 0xc1, 0x00, 0x82, 0x86, 0x8e, 0x7f, 0x5d, 0x19, 0xb0, 0xe2, 0x27, 0xcc, 0xfb, 0x74, 0x4b, 0x14, 0x8b, 0x94, 0x8b, 0x75, 0x68, 0x33, 0xc5, 0x08, 0x92, 0x87, 0x8c, 0x9a, 0xb6, 0xcf, 0x1c, 0xba, 0xd7, 0x0d, 0x98, 0xb2, 0xe6, 0x2f, 0xdc, 0x1b, 0x95, 0x89, 0x71, 0x60, 0x23, 0xc4, 0x0a, 0x96, 0x8f, 0x9c, 0xba, 0xf6, 0x6e, 0x3f, 0xfc, 0x5b, 0x15, 0xa8, 0xd2, 0x26, 0xaf, 0xbd, 0xf8, 0x72, 0x66, 0x2f, 0xdc, 0x1b, 0xb4, 0xcb, 0x14, 0x8b, 0x94, 0xaa, 0xb7, 0xcd, 0xf9, 0x51, 0x01, 0x80, 0x82, 0x86, 0x6f, 0x3d, 0xd9, 0x30, 0xe2, 0x27, 0xcc, 0xfb, 0x74, 0x4b, 0x14, 0xaa, 0xb7, 0xcd, 0xf9, 0x70, 0x43, 0x04, 0x6b, 0x35, 0xc9, 0xf1, 0x60, 0x23, 0xa5, 0xc8, 0xf3, 0x45, 0x08, 0x92, 0x87, 0x6d, 0x58, 0x32, 0xe6, 0x2f, 0xbd, 0xf8, 0x72, 0x66, 0x4e, 0x1e, 0xbe, 0xfe, 0x7e, 0x7e, 0x7e, 0x5f, 0x1d, 0x99, 0x91, 0xa0, 0xa3, 0xc4, 0x0a, 0x77, 0x4d, 0x18, 0x93, 0xa4, 0xab, 0xd4, 0x0b, 0x75, 0x49, 0x10, 0xa2, 0xc6, 0xef, 0x3d, 0xf8, 0x53, 0x24, 0xab, 0xb5, 0xe8, 0x33, 0xe4, 0x4a, 0x16, 0xae, 0xde, 0x1f, 0xbc, 0xdb, 0x15, 0xa8, 0xb3, 0xc5, 0x08, 0x73, 0x45, 0xe9, 0x31, 0xc1, 0xe1, 0x21, 0xa1, 0xa1, 0xa1, 0xc0, 0x02, 0x86, 0x6f, 0x5c, 0x3a, 0xd7, 0x0d, 0x98, 0x93, 0xa4, 0xca, 0x16, 0xae, 0xde, 0x1f, 0x9d, 0x99, 0xb0, 0xe2, 0x46, 0xef, 0x3d, 0xf8, 0x72, 0x47, 0x0c, 0x9a, 0xb6, 0xcf, 0xfd, 0x59, 0x11, 0xa0, 0xa3, 0xa5, 0xc8, 0xf3, 0x45, 0x08, 0x92, 0x87, 0x6d, 0x39, 0xf0, 0x43, 0x04, 0x8a, 0x96, 0xae, 0xde, 0x3e, 0xdf, 0x1d, 0x99, 0x91, 0xa0, 0xc2, 0x06, 0x6f, 0x3d, 0xf8, 0x72, 0x47, 0x0c, 0x9a, 0x97, 0x8d, 0x98, 0x93, 0x85, 0x88, 0x73, 0x45, 0xe9, 0x31, 0xe0, 0x23, 0xa5, 0xa9, 0xd0, 0x03, 0x84, 0x8a, 0x96, 0xae, 0xde, 0x1f, 0xbc, 0xdb, 0x15, 0xa8, 0xd2, 0x26, 0xce, 0xff, 0x5d, 0x19, 0x91, 0x81, 0x80, 0x82, 0x67, 0x2d, 0xd8, 0x13, 0xa4, 0xab, 0xd4, 0x0b, 0x94, 0xaa, 0xb7, 0xcd, 0xf9, 0x51, 0x20, 0xa3, 0xa5, 0xc8, 0xf3, 0x45, 0xe9, 0x50, 0x22, 0xc6, 0xef, 0x5c, 0x3a, 0xd7, 0x0d, 0x98, 0x93, 0x85, 0x88, 0x73, 0x64, 0x4a, 0xf7, 0x4d, 0xf9, 0x51, 0x20, 0xa3, 0xc4, 0x0a, 0x96, 0xae, 0xde, 0x3e, 0xfe, 0x7e, 0x7e, 0x7e, 0x5f, 0x3c, 0xfa, 0x76, 0x4f, 0xfd, 0x78, 0x72, 0x66, 0x2f, 0xbd, 0xd9, 0x30, 0xc3, 0xe5, 0x48, 0x12, 0x87, 0x8c, 0x7b, 0x55, 0x28, 0xd2, 0x07, 0x8c, 0x9a, 0x97, 0xac, 0xda, 0x17, 0x8d, 0x79, 0x51, 0x20, 0xa3, 0xc4, 0xeb, 0x54, 0x0b, 0x94, 0x8b, 0x94, 0xaa, 0xd6, 0x2e, 0xbf, 0xfc, 0x5b, 0x15, 0xa8, 0xd2, 0x26, 0xaf, 0xdc, 0x1b, 0xb4, 0xea, 0x37, 0xec, 0x3b, 0xf4, 0x6a, 0x37, 0xcd, 0x18, 0x93, 0x85, 0x69, 0x31, 0xc1, 0xe1, 0x40, 0xe3, 0x25, 0xc8, 0x12, 0x87, 0x8c, 0x9a, 0xb6, 0xcf, 0xfd, 0x59, 0x11, 0xa0, 0xc2, 0x06, 0x8e, 0x7f, 0x5d, 0x38, 0xf2, 0x47, 0x0c, 0x7b, 0x74, 0x6a, 0x37, 0xec, 0x5a, 0x36, 0xee, 0x3f, 0xfc, 0x7a, 0x76, 0x4f, 0x1c, 0x9b, 0x95, 0x89, 0x71, 0x41, 0x00, 0x63, 0x44, 0xeb, 0x54, 0x2a, 0xd6, 0x0f, 0x9c, 0xba, 0xd7, 0x0d, 0x98, 0x93, 0x85, 0x69, 0x31, 0xc1, 0x00, 0x82, 0x86, 0x8e, 0x9e, 0xbe, 0xdf, 0x3c, 0xfa, 0x57, 0x2c, 0xda, 0x36, 0xee, 0x3f, 0xfc, 0x5b, 0x15, 0x89, 0x71, 0x41, 0x00, 0x82, 0x86, 0x8e, 0x7f, 0x5d, 0x38, 0xf2, 0x47, 0xed, 0x58, 0x13, 0xa4, 0xca, 0xf7, 0x4d, 0xf9, 0x51, 0x01, 0x80, 0x63, 0x44, 0xeb, 0x54, 0x2a, 0xd6, 0x2e, 0xbf, 0xdd, 0x19, 0x91, 0xa0, 0xa3, 0xa5, 0xa9, 0xb1, 0xe0, 0x42, 0x06, 0x8e, 0x7f, 0x5d, 0x19, 0x91, 0xa0, 0xa3, 0xc4, 0x0a, 0x96, 0x8f, 0x7d, 0x78, 0x72, 0x47, 0x0c, 0x7b, 0x74, 0x6a, 0x56, 0x2e, 0xde, 0x1f, 0xbc, 0xfa, 0x57, 0x0d, 0x79, 0x51, 0x01, 0x61, 0x21, 0xa1, 0xc0, 0xe3, 0x25, 0xa9, 0xb1, 0xc1, 0xe1, 0x40, 0x02, 0x67, 0x4c, 0x1a, 0x97, 0x8d, 0x98, 0x93, 0xa4, 0xab, 0xd4, 0x2a, 0xd6, 0x0f, 0x9c, 0x9b, 0xb4, 0xcb, 0x14, 0xaa, 0xb7, 0xcd, 0xf9, 0x51, 0x20, 0xa3, 0xc4, 0xeb, 0x35, 0xc9, 0xf1, 0x60, 0x42, 0x06, 0x8e, 0x7f, 0x7c, 0x7a, 0x76, 0x6e, 0x3f, 0xfc, 0x7a, 0x76, 0x6e, 0x5e, 0x3e, 0xfe, 0x7e, 0x5f, 0x3c, 0xdb, 0x15, 0x89, 0x71, 0x41, 0xe1, 0x21, 0xc0, 0xe3, 0x44, 0xeb, 0x54, 0x2a, 0xb7, 0xcd, 0xf9, 0x70, 0x62, 0x27, 0xad, 0xd8, 0x32, 0xc7, 0x0c, 0x7b, 0x74, 0x4b, 0x14, 0xaa, 0xb7, 0xec, 0x3b, 0xd5, 0x28, 0xd2, 0x07, 0x6d, 0x39, 0xd1, 0x20, 0xc2, 0xe7, 0x4c, 0x1a, 0x97, 0x8d, 0x98, 0xb2, 0xc7, 0x0c, 0x59, 0x28, 0xf3, 0x9b}; } // namespace hidpg
[ "ogwrtty@gmail.com" ]
ogwrtty@gmail.com
02e9a2d4d218d98408941a2018a8b21ddc207b49
138119641aeef9239f4c7219539203047891a6fb
/arduino_webserver/sketch_oct04a/sketch_oct04a.ino
2de059dd01239d6c7f90445551818ce6b8a397d6
[]
no_license
andylang8445/COOP2019
383ffccc621a08026d02ed7cdc30680ee956c676
0ff829248a2ec682edf7fd6f6236d6de2c033d22
refs/heads/master
2022-12-22T16:52:38.001103
2021-10-08T22:44:22
2021-10-08T22:44:22
210,962,108
0
0
null
2022-12-13T19:53:57
2019-09-26T00:00:51
C
UTF-8
C++
false
false
1,640
ino
/* Rui Santos Complete project details at https://RandomNerdTutorials.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ // Import required libraries #include <ESP8266WiFi.h> #include <ESPAsyncTCP.h> #include <ESPAsyncWebServer.h> #include <FS.h> #include <Wire.h> // Replace with your network credentials const char* ssid = "theHacksmith"; const char* password = "iamspiderman3"; // Set LED GPIO const int ledPin = 2; // Stores LED state String ledState; // Create AsyncWebServer object on port 80 AsyncWebServer server(80); void setup() { // Serial port for debugging purposes Serial.begin(115200); // Initialize SPIFFS if (!SPIFFS.begin()) { Serial.println("An Error has occurred while mounting SPIFFS"); return; } // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } // Print ESP32 Local IP Address Serial.println(WiFi.localIP()); // Route for root / web page server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) { request->send(SPIFFS, "/index.html", String(), false); Serial.println("html loaded!"); }); server.on("/script.js", HTTP_GET, [](AsyncWebServerRequest * request) { request->send(SPIFFS, "/script.js", "text/javascript"); Serial.println("javascript loaded!"); }); // Start server server.begin(); } void loop() { }
[ "46326335+andylang8445@users.noreply.github.com" ]
46326335+andylang8445@users.noreply.github.com