blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
2ed0c230439d0b74c0c1a8c88dc10fd9c9637b19
d9ca8dee63dc9b1bc5a862c8a34bced18a85afdf
/SharedCode/SharingFacesUtils.h
23c420bdf7445044edff03d76f61a9272daf8763
[ "MIT" ]
permissive
asdlei99/SharingFaces
b03f13f49595e1dc36b152048e58fb4ee7a92711
66af682e4bccf0db2f8924b67112c782285a0599
refs/heads/master
2022-04-15T21:38:26.847046
2020-03-30T01:40:54
2020-03-30T01:40:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,143
h
#pragma once #include "ofxCv.h" #include "ofxFaceTrackerThreaded.h" #include "ofxTiming.h" #include "FaceTrackerData.h" #include "BinnedData.h" #include "FaceCompare.h" #include "ImageSaver.h" #include "FaceOverlay.h" using namespace ofxCv; using namespace cv; void useSharedData() { string dataPathRoot = "../../SharedData/shared"; #ifdef TARGET_OSX dataPathRoot = "../../../" + dataPathRoot; #endif ofSetDataPathRoot(dataPathRoot); } void drawFramerate() { ofDrawBitmapStringHighlight(ofToString((int) ofGetFrameRate()), 10, 20); } float saturationMetric(const ofColor& color) { float y = (color.r + color.g + color.b) / (float) (3); float dr = color.r - y, dg = color.g - y, db = color.b - y; return dr * dr + dg * dg + db * db; } bool bySaturation(const ofColor& a, const ofColor& b) { return saturationMetric(a) < saturationMetric(b); } int brightnessMetric(const ofColor& color) { return (int) color.r + (int) color.g + (int) color.b; } bool byBrightness(const ofColor& a, const ofColor& b) { return brightnessMetric(a) < brightnessMetric(b); } ofVec3f getWhitePoint(ofImage& img) { vector<ofColor> all; int n = img.getWidth(); for(int i = 0; i < n; i++) { ofColor cur = img.getColor(i, 0); all.push_back(cur); } ofSort(all, byBrightness); // sort by brightness all.erase(all.begin(), all.begin() + (n / 4)); // remove first 1/4 all.erase(all.end() - (n / 4), all.end()); // remove last 1/4 ofSort(all, bySaturation); // sort by saturation all.resize(all.size() / 2); // 50% least saturated ofVec3f whitePoint; n = all.size(); for(int i = 0; i < n; i++) { whitePoint[0] += all[i].r; whitePoint[1] += all[i].g; whitePoint[2] += all[i].b; } float top = 0; top = MAX(whitePoint[0], top); top = MAX(whitePoint[1], top); top = MAX(whitePoint[2], top); whitePoint[0] = top / whitePoint[0]; whitePoint[1] = top / whitePoint[1]; whitePoint[2] = top / whitePoint[2]; return whitePoint; } float getMaximumDistance(ofVec2f& position, vector<ofVec2f*> positions) { float maximumDistance = 0; for(int i = 0; i < positions.size(); i++) { float distance = position.squareDistance(*positions[i]); if(distance > maximumDistance) { maximumDistance = distance; } } return sqrt(maximumDistance); } float getMinimumDistance(ofVec2f& position, vector<ofVec2f*> positions) { float minimumDistance = 0; for(int i = 0; i < positions.size(); i++) { float distance = position.squareDistance(*positions[i]); if(i == 0 || distance < minimumDistance) { minimumDistance = distance; } } return sqrt(minimumDistance); } uint64_t startTime; void startTimer() { startTime = ofGetElapsedTimeMillis(); } uint64_t checkTimer() { return ofGetElapsedTimeMillis() - startTime; } void loadMetadata(vector<FaceTrackerData>& data) { startTimer(); ofLog() << "loading metadata..."; ofDirectory allDates("metadata/"); allDates.listDir(); int total = 0; for(int i = 0; i < allDates.size(); i++) { ofDirectory curDate(allDates[i].path()); curDate.listDir(); string curDateName = "metadata/" + allDates[i].getFileName() + "/"; for(int j = 0; j < curDate.size(); j++) { FaceTrackerData curData; string metadataFilename = curDateName + curDate[j].getFileName(); curData.load(metadataFilename); if(ofFile::doesFileExist(curData.getImageFilename())) { data.push_back(curData); total++; } else { ofLogWarning() << "couldn't find " << curData.getImageFilename(); // ofLogWarning() << "removing metadata " << metadataFilename; // ofFile::removeFile(metadataFilename); } } } ofLog() << "done loading " << allDates.size() << " days, " << total << " faces in " << checkTimer() << "ms."; } void loadMetadata(BinnedData<FaceTrackerData>& binned) { vector<FaceTrackerData> data; loadMetadata(data); startTimer(); for(FaceTrackerData& item : data) { binned.add(item.position, item); } ofLog() << "done binning " << data.size() << " faces in " << checkTimer() << "ms."; }
[ "kyle@kylemcdonald.net" ]
kyle@kylemcdonald.net
f5cb3c4629bea2f6d583a41540b320793b5be321
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/components/dom_distiller/content/renderer/distiller_js_render_frame_observer.cc
ac24a1f9d07cef9f3609545e97c18456fc37fc6f
[ "BSD-3-Clause" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
2,565
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/dom_distiller/content/renderer/distiller_js_render_frame_observer.h" #include <utility> #include "base/bind.h" #include "components/dom_distiller/content/common/distiller_page_notifier_service.mojom.h" #include "components/dom_distiller/content/renderer/distiller_page_notifier_service_impl.h" #include "content/public/renderer/render_frame.h" #include "services/shell/public/cpp/interface_registry.h" #include "v8/include/v8.h" namespace dom_distiller { DistillerJsRenderFrameObserver::DistillerJsRenderFrameObserver( content::RenderFrame* render_frame, const int distiller_isolated_world_id) : RenderFrameObserver(render_frame), distiller_isolated_world_id_(distiller_isolated_world_id), is_distiller_page_(false), weak_factory_(this) {} DistillerJsRenderFrameObserver::~DistillerJsRenderFrameObserver() {} void DistillerJsRenderFrameObserver::DidStartProvisionalLoad() { RegisterMojoInterface(); } void DistillerJsRenderFrameObserver::DidFinishLoad() { // If no message about the distilled page was received at this point, there // will not be one; remove the mojom::DistillerPageNotifierService from the // registry. render_frame() ->GetInterfaceRegistry() ->RemoveInterface<mojom::DistillerPageNotifierService>(); } void DistillerJsRenderFrameObserver::DidCreateScriptContext( v8::Local<v8::Context> context, int extension_group, int world_id) { if (world_id != distiller_isolated_world_id_ || !is_distiller_page_) { return; } native_javascript_handle_.reset( new DistillerNativeJavaScript(render_frame())); native_javascript_handle_->AddJavaScriptObjectToFrame(context); } void DistillerJsRenderFrameObserver::RegisterMojoInterface() { render_frame()->GetInterfaceRegistry()->AddInterface(base::Bind( &DistillerJsRenderFrameObserver::CreateDistillerPageNotifierService, weak_factory_.GetWeakPtr())); } void DistillerJsRenderFrameObserver::CreateDistillerPageNotifierService( mojo::InterfaceRequest<mojom::DistillerPageNotifierService> request) { // This is strongly bound to and owned by the pipe. new DistillerPageNotifierServiceImpl(this, std::move(request)); } void DistillerJsRenderFrameObserver::SetIsDistillerPage() { is_distiller_page_ = true; } void DistillerJsRenderFrameObserver::OnDestruct() { delete this; } } // namespace dom_distiller
[ "bino.zh@gmail.com" ]
bino.zh@gmail.com
b60b7c993f3a1a53570064ef04ab5465ef7d91a4
771a5f9d99fdd2431b8883cee39cf82d5e2c9b59
/SDK/bsp_sea_rock_cluster_c_functions.cpp
bada16588d58f81e169fbab2775ae27c95f2a610
[ "MIT" ]
permissive
zanzo420/Sea-Of-Thieves-SDK
6305accd032cc95478ede67d28981e041c154dce
f56a0340eb33726c98fc53eb0678fa2d59aa8294
refs/heads/master
2023-03-25T22:25:21.800004
2021-03-20T00:51:04
2021-03-20T00:51:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,325
cpp
// Name: SeaOfThieves, Version: 2.0.23 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function bsp_sea_rock_cluster_c.bsp_sea_rock_cluster_c_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void Absp_sea_rock_cluster_c_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function bsp_sea_rock_cluster_c.bsp_sea_rock_cluster_c_C.UserConstructionScript"); Absp_sea_rock_cluster_c_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } void Absp_sea_rock_cluster_c_C::AfterRead() { AActor::AfterRead(); READ_PTR_FULL(StaticMeshComponent011, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent010, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent09, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent08, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent07, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent06, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent05, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent04, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent03, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent02, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent01, UStaticMeshComponent); READ_PTR_FULL(StaticMeshComponent0, UStaticMeshComponent); READ_PTR_FULL(SharedRoot, USceneComponent); } void Absp_sea_rock_cluster_c_C::BeforeDelete() { AActor::BeforeDelete(); DELE_PTR_FULL(StaticMeshComponent011); DELE_PTR_FULL(StaticMeshComponent010); DELE_PTR_FULL(StaticMeshComponent09); DELE_PTR_FULL(StaticMeshComponent08); DELE_PTR_FULL(StaticMeshComponent07); DELE_PTR_FULL(StaticMeshComponent06); DELE_PTR_FULL(StaticMeshComponent05); DELE_PTR_FULL(StaticMeshComponent04); DELE_PTR_FULL(StaticMeshComponent03); DELE_PTR_FULL(StaticMeshComponent02); DELE_PTR_FULL(StaticMeshComponent01); DELE_PTR_FULL(StaticMeshComponent0); DELE_PTR_FULL(SharedRoot); } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "40242723+alxalx14@users.noreply.github.com" ]
40242723+alxalx14@users.noreply.github.com
4d71c081d6fb89fbb6e13f9fa1d64e68e31df1e8
c2ec5cfee97b0c0ad1e8e937796a902677d80aa1
/yasp3lib/element/attrib.h
eb7b2723cd92f82486300f09a54c1a8b04fa1fd0
[]
no_license
Jaxo/yaxx
c737f069e90cf3722c3824fc80da88da44d51162
7b9bfc2a4f003c3ce060adf277704c1f10f23249
refs/heads/master
2020-04-06T06:43:36.223556
2014-09-10T16:48:52
2014-09-10T16:48:52
3,884,519
4
0
null
null
null
null
UTF-8
C++
false
false
8,660
h
/* * $Id: attrib.h,v 1.9 2002-04-14 23:26:04 jlatone Exp $ * * Manage attribute lists of elements / data entities */ #if !defined ATTRIB_HEADER && defined __cplusplus #define ATTRIB_HEADER /*---------+ | Includes | +---------*/ #include "../yasp3gendef.h" #include "../../toolslib/Writer.h" #include "../../toolslib/tplist.h" #include "../../toolslib/arglist.h" #include "../parser/yspenum.h" #include "../syntax/delim.h" class SgmlDecl; /*-----------------------------------------------------------------AttlistFlag-+ | Flags seen during the parse of the attlist declaration | +-----------------------------------------------------------------------------*/ struct YASP3_API AttlistFlag { // Attlist decl flag: AttlistFlag(); unsigned int entity : 1; // attlist has ENTITY/ENTITIES unsigned int id : 1; // attlist has ID unsigned int notation : 1; // attlist has NOTATION unsigned int required : 1; // attlist has REQUIRED unsigned int current : 1; // attlist has CURRENT unsigned int conref : 1; // attlist has CONREF }; /* -- INLINES -- */ inline AttlistFlag::AttlistFlag() : entity (0), id(0), notation(0), required(0), current(0), conref(0) {} /*------------------------------------------------------------------Attribute-+ | Represents the declaration for a single attribute in an ATTLIST declaration.| +----------------------------------------------------------------------------*/ class YASP3_API Attribute : public RefdKeyRep { // att friend class Attlist; public: Attribute(); // Nil constructor Attribute( UnicodeString const & ucsName, // attribute name UnicodeString const & ucsSpecArg, // specified value (also for default) ArgListSimple const & arglEnumArg, // if the value is one of an enum e_AttDclVal dclvArg, // type of declared value e_AttDftVal dftvArg, // type of default value unsigned int bSpecifiedArg, // Otherwise, this is the default Delimiter::e_Ix dlmLitArg // one of: LIT, LITA, NOT_FOUND ); Attribute( // no value specified, so far UnicodeString const & ucsName, e_AttDclVal dclv ); UnicodeString const & inqName() const; UnicodeString const & inqValue() const; e_AttDclVal inqTypeDeclaredValue() const; e_AttDftVal inqTypeDefaultValue() const; Delimiter::e_Ix inqDelim() const; bool isSpecified() const; // specified vs. default bool isValidSpec() const; // ucsSpec is valid bool isReportable(bool isFullAttlist) const; operator void *() const; // isOk? bool operator!() const; // is not ok? bool operator==(Attribute const & source) const; bool operator!=(Attribute const & source) const; void extract(Writer & out, SgmlDecl const & sdcl) const; void stringize(Writer & uost) const; UnicodeString const & findToken(UCS_2 const * pUcToken) const; Attribute * clone() const; void setDefaultVal( e_AttDftVal dclvArg ); void setValueSpec( UnicodeString const & ucsSpecArg, Delimiter::e_Ix dlmLitArg, // what lit surrounded the value spec? bool isSpecification = false ); void addToken(UCS_2 const * pUcToken); private: UnicodeString ucsSpec; // specified value (also for default) ArgListSimple arglEnum; // if the value is one of an enum e_AttDclVal dclv; // type of declared value e_AttDftVal dftv; // type of default value unsigned int bSpecified : 1; // Otherwise, this is the default Delimiter::e_Ix dlmLit; // one of: LIT, LITA, NOT_FOUND public: static const Attribute Nil; }; /* -- INLINES -- */ inline Attribute::operator void *() const { if (key().good()) return (void *)this; else return 0; } inline bool Attribute::operator!() const { if (key().good()) return false; else return true; } inline void Attribute::setDefaultVal( e_AttDftVal dftvArg ) { dftv = dftvArg; } inline UnicodeString const & Attribute::inqName() const { return key(); } inline UnicodeString const & Attribute::inqValue() const { return ucsSpec; } inline e_AttDclVal Attribute::inqTypeDeclaredValue() const { return dclv; } inline e_AttDftVal Attribute::inqTypeDefaultValue() const { return dftv; } inline Delimiter::e_Ix Attribute::inqDelim() const { return dlmLit; } inline bool Attribute::isSpecified() const { if (bSpecified) return true; else return false; } inline bool Attribute::isValidSpec() const { if ((!ucsSpec) && (dlmLit == Delimiter::IX_NOT_FOUND)) { return false; }else { return true; } } inline bool Attribute::isReportable(bool isFullAttlist) const { if ((isValidSpec()) && (isFullAttlist || (bSpecified && *key()))) { return true; }else { return false; } } inline UnicodeString const & Attribute::findToken( UCS_2 const * pUcToken ) const { return arglEnum[pUcToken]; } inline void Attribute::addToken(UCS_2 const * pUcToken) { arglEnum += pUcToken; } inline bool Attribute::operator!=(Attribute const & source) const { if (*this == source) return false; else return true; } /*--------------------------------------------------------------------Attlist-+ | Represents the declaration for a single attribute in an ATTLIST declaration.| | | | Note: | | More than one element can point to the same instance of this object | +----------------------------------------------------------------------------*/ class YASP3_API Attlist : public TpKeyList { // attlst public: Attlist() {} Attlist(int iAverageCount) : TpKeyList(iAverageCount) {} Attribute const & operator[](UCS_2 const * pUc) const; Attribute const & operator[](int ix) const; bool isEntity() const; bool isId() const; bool isNotation() const; bool isRequired() const; bool isCurrent() const; bool isConref() const; Attlist copy() const; // deep copy bool operator==(Attlist const & source) const; bool operator!=(Attlist const & source) const; void extract(Writer & out, SgmlDecl const & sdcl) const; void stringize( Writer & uost, bool isFullAttlist = true ) const; Attribute const * findToken(UCS_2 const * pUcToken) const; Attribute const * inqAttributePtr(UCS_2 const * pUcName) const; Attribute const * inqAttributePtr(int ix) const; Attribute * defineAttr( UnicodeString const & ucsName, e_AttDclVal dclv = ADCLV_INVALID ); void setFlag(AttlistFlag bFlagArg); Attribute * replace(Attribute const * pAttSource); bool setValueSpec( UnicodeString const & ucsName, UnicodeString const & ucsSpec, Delimiter::e_Ix dlmLit = Delimiter::IX_NOT_FOUND, e_AttDclVal dclv = ADCLV_CDATA ); bool getFirstEntity(UCS_2 * pUcEntName, UCS_2 ucSpace) const; private: AttlistFlag b; // Attlist decl flag public: static Attlist const Nil; }; /* -- INLINES -- */ inline Attribute const & Attlist::operator[](UCS_2 const * pUc) const { Attribute const * pAtt = (Attribute const *)findData(pUc); if (pAtt) return *pAtt; else return Attribute::Nil; } inline Attribute const & Attlist::operator[](int ix) const { Attribute const * pAtt = (Attribute const *)findDataAt(ix); if (pAtt) return *pAtt; else return Attribute::Nil; } inline void Attlist::setFlag(AttlistFlag bArg) { b = bArg; } inline bool Attlist::isEntity() const { if (b.entity) return true; else return false; } inline bool Attlist::isId() const { if (b.id) return true; else return false; } inline bool Attlist::isNotation() const { if (b.notation) return true; else return false; } inline bool Attlist::isRequired() const { if (b.required) return true; else return false; } inline bool Attlist::isCurrent() const { if (b.current) return true; else return false; } inline bool Attlist::isConref() const { if (b.conref) return true; else return false; } inline bool Attlist::operator!=(Attlist const & source) const { if (*this == source) return false; else return true; } inline Attribute const * Attlist::inqAttributePtr(UCS_2 const * pUc) const { return (Attribute const *)findData(pUc); } inline Attribute const * Attlist::inqAttributePtr(int ix) const { return (Attribute const *)findDataAt(ix); } #endif /* ATTRIB_HEADER ======================================================*/
[ "pgr@jaxo.com" ]
pgr@jaxo.com
17a83b0300a4683c5c636feb1994f0a1bdd9bd48
e8173dedd65c57f51d0ab5637998904c8c2ede3c
/bulmagesplus/bulmafact/plugins/pluginbf_clientefactura/pluginbf_clientefactura.cpp
42e565642daa24041f4a94851dc9e6f3ff9a564d
[]
no_license
BulmagesPlus/BulmagesPlus_Edison
44ceb0599c9269b86eb9989cff607c2ab1d109e0
0cc7d2a37678dbd32337427df1c1eb72a6d07613
refs/heads/master
2021-04-10T21:52:21.931779
2020-03-21T12:30:42
2020-03-21T12:30:42
248,969,531
0
0
null
null
null
null
UTF-8
C++
false
false
8,114
cpp
/*************************************************************************** * Copyright (C) 2005 by Tomeu Borras Riera * * tborras@conetxia.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <stdio.h> #include "pluginbf_clientefactura.h" #include "blplugins.h" #include "bfcompany.h" #include "blfunctions.h" #include "facturaview.h" #include "facturaslist.h" #include "blfixed.h" #include "genfacqtoolbutton.h" FacturasList *g_facturasList = NULL; BfBulmaFact *g_pluginbf_clientefactura = NULL; /// /** \param bges \return **/ int entryPoint ( BfBulmaFact *bges ) { BL_FUNC_DEBUG /// Inicializa el sistema de traducciones 'gettext'. setlocale ( LC_ALL, "" ); blBindTextDomain ( "pluginbf_clientefactura", g_confpr->value( CONF_DIR_TRADUCCION ).toLatin1().constData() ); if ( bges->company()->hasTablePrivilege ( "factura", "SELECT" ) ) { /// Miramos si existe un menu Ventas QMenu *pPluginMenu = bges->newMenu ( _("&Ventas"), "menuVentas", "menuMaestro" ); pPluginMenu->addSeparator(); g_pluginbf_clientefactura = bges; BlAction *accionA = new BlAction ( _ ( "&Facturas a clientes" ), 0 ); accionA->setIcon ( QIcon ( QString::fromUtf8 ( ":/Images/client-invoice-list.png" ) ) ); accionA->setStatusTip ( _ ( "Facturas a clientes" ) ); accionA->setWhatsThis ( _ ( "Facturas a clientes" ) ); accionA->setObjectName("mui_actionFacturasClientes"); pPluginMenu->addAction ( accionA ); bges->Listados->addAction ( accionA ); BlAction *accionB = new BlAction ( _ ( "&Nueva factura a cliente" ), 0 ); accionB->setIcon ( QIcon ( QString::fromUtf8 ( ":/Images/client-invoice.png" ) ) ); accionB->setStatusTip ( _ ( "Nueva factura a cliente" ) ); accionB->setWhatsThis ( _ ( "Nueva factura a cliente" ) ); accionB->setObjectName("mui_actionFacturaClienteNueva"); pPluginMenu->addAction ( accionB ); bges->Fichas->addAction ( accionB ); }// end if return 0; } int BlAction_actionTriggered(BlAction *accion) { if (accion->objectName() == "mui_actionFacturasClientes") { if ( g_facturasList ) { g_facturasList->hide(); g_facturasList->show(); } // end if } // end if if (accion->objectName() == "mui_actionFacturaClienteNueva") { FacturaView * bud = new FacturaView ( g_pluginbf_clientefactura->company(), NULL ); g_pluginbf_clientefactura->company()->m_pWorkspace->addSubWindow ( bud ); bud->inicializar(); bud->show(); } // end if return 0; } int BfCompany_createMainWindows_Post ( BfCompany *comp ) { if ( comp->hasTablePrivilege ( "factura", "SELECT" ) ) { g_facturasList = new FacturasList ( comp, NULL ); comp->m_pWorkspace->addSubWindow ( g_facturasList ); g_facturasList->hide(); } // end if return 0; } int ClienteView_ClienteView_Post ( ClienteView *prov ) { if ( prov->mainCompany()->hasTablePrivilege ( "factura", "SELECT" ) ) { FacturasList *facturasList = new FacturasList ( NULL, 0, BL_SELECT_MODE ); facturasList->setMainCompany(( BfCompany * ) prov->mainCompany() ); facturasList->setEditMode(); facturasList->setObjectName ( "listfacturas" ); facturasList->hideBusqueda(); prov->mui_tab->addTab ( facturasList, "Facturas" ); } // end if return 0; } int ClienteView_cargarPost_Post ( ClienteView *prov ) { if ( prov->mainCompany()->hasTablePrivilege ( "factura", "SELECT" ) ) { FacturasList *facturasList = prov->findChild<FacturasList *> ( "listfacturas" ); facturasList->setidcliente ( prov->dbValue ( "idcliente" ) ); facturasList->presentar(); }// end if return 0; }// end if int BfBuscarReferencia_on_mui_abrirtodo_clicked_Post ( BfBuscarReferencia *ref ) { QString SQLQuery = "SELECT * FROM factura WHERE reffactura = '" + ref->mui_referencia->text() + "'"; BlDbRecordSet *cur = ref->mainCompany() ->loadQuery ( SQLQuery ); while ( !cur->eof() ) { FacturaView * bud = new FacturaView ( ( BfCompany * ) ref->mainCompany(), NULL ); ref->mainCompany() ->m_pWorkspace->addSubWindow ( bud ); bud->load ( cur->value( "idfactura" ) ); bud->show(); cur->nextRecord(); } // end while delete cur; return 0; }// end if /// /** \param l \return **/ int AlbaranClienteView_AlbaranClienteView ( AlbaranClienteView *l ) { BL_FUNC_DEBUG GenFacQToolButton *mui_exporta_efactura2 = new GenFacQToolButton ( l, l->mui_plugbotones ); AgFacQToolButton *mui_exporta_efactura = new AgFacQToolButton ( l, l->mui_plugbotones ); QHBoxLayout *m_hboxLayout1 = l->mui_plugbotones->findChild<QHBoxLayout *> ( "hboxLayout1" ); if ( !m_hboxLayout1 ) { m_hboxLayout1 = new QHBoxLayout ( l->mui_plugbotones ); m_hboxLayout1->setSpacing ( 5 ); m_hboxLayout1->setMargin ( 0 ); m_hboxLayout1->setObjectName ( QString::fromUtf8 ( "hboxLayout1" ) ); }// end if m_hboxLayout1->addWidget ( mui_exporta_efactura2 ); m_hboxLayout1->addWidget ( mui_exporta_efactura ); return 0; } /// /** \param l \return **/ int PedidoClienteView_PedidoClienteView ( PedidoClienteView *l ) { BL_FUNC_DEBUG GenFacQToolButton *mui_exporta_efactura2 = new GenFacQToolButton ( l, l->mui_plugbotones ); QHBoxLayout *m_hboxLayout1 = l->mui_plugbotones->findChild<QHBoxLayout *> ( "hboxLayout1" ); if ( !m_hboxLayout1 ) { m_hboxLayout1 = new QHBoxLayout ( l->mui_plugbotones ); m_hboxLayout1->setSpacing ( 4 ); m_hboxLayout1->setMargin ( 0 ); m_hboxLayout1->setObjectName ( QString::fromUtf8 ( "hboxLayout1" ) ); }// end if m_hboxLayout1->addWidget ( mui_exporta_efactura2 ); return 0; } /// /** \param l \return **/ int PresupuestoView_PresupuestoView ( PresupuestoView *l ) { BL_FUNC_DEBUG GenFacQToolButton *mui_exporta_efactura2 = new GenFacQToolButton ( l, l->mui_plugbotones ); QHBoxLayout *m_hboxLayout1 = l->mui_plugbotones->findChild<QHBoxLayout *> ( "hboxLayout1" ); if ( !m_hboxLayout1 ) { m_hboxLayout1 = new QHBoxLayout ( l->mui_plugbotones ); m_hboxLayout1->setSpacing ( 4 ); m_hboxLayout1->setMargin ( 0 ); m_hboxLayout1->setObjectName ( QString::fromUtf8 ( "hboxLayout1" ) ); }// end if m_hboxLayout1->addWidget ( mui_exporta_efactura2 ); return 0; } /// Esta llamada de plugin es bastante novedosa ya es una llamada que no responde a una funcion /// Sino que se llama desde multiples partes del sistema. int SNewFacturaView ( BfCompany *v ) { FacturaView *h = new FacturaView ( v, 0 ); g_plugParams = h; return 1; }
[ "fcojavmc@todo-redes.com" ]
fcojavmc@todo-redes.com
1c122207e8943f65a8637698689ef170f1aab4ec
ad74f7a42e8dec14ec7576252fcbc3fc46679f27
/AresDataCollector/AresInterdictionTarget.cpp
6b9d3244c12954ca679a4cfce76cb639b7a0324c
[]
no_license
radtek/TrapperKeeper
56fed7afa259aee20d6d81e71e19786f2f0d9418
63f87606ae02e7c29608fedfdf8b7e65339b8e9a
refs/heads/master
2020-05-29T16:49:29.708375
2013-05-15T08:33:23
2013-05-15T08:33:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
577
cpp
#include "StdAfx.h" #include "aresinterdictiontarget.h" #include "..\aresprotector\AresUtilityClass.h" AresInterdictionTarget::AresInterdictionTarget(unsigned int ip, unsigned short port,unsigned int size, const char* hash) { m_ip=ip; m_port=port; m_size=size; for(int j=0;j<20;j++){ char ch1=hash[j*2]; char ch2=hash[j*2+1]; byte val1=AresUtilityClass::ConvertCharToInt(ch1); byte val2=AresUtilityClass::ConvertCharToInt(ch2); byte hash_val=((val1&0xf)<<4)|(val2&0xf); m_hash[j]=hash_val; } } AresInterdictionTarget::~AresInterdictionTarget(void) { }
[ "occupymyday@gmail.com" ]
occupymyday@gmail.com
284cc5db6805455fdfd08972df082ecc4ea7ddd5
1f8b38d012e397f56da9a8e68e098ed79e8ea20f
/SeaBreeze/include/vendors/OceanOptics/protocols/interfaces/WifiConfigurationProtocolInterface.h
8bb5a9a80d3cd6585397fb6855bde75cd6cdd94c
[ "MIT" ]
permissive
jolz/SeaBreeze
e4e33a91d4315679090ba144f46dddc4beeafb6f
f58d7fdf5736654f8d3761031aab6e13cbec55fa
refs/heads/master
2022-04-11T01:28:23.039711
2020-03-26T11:14:31
2020-03-26T11:14:31
250,199,293
1
0
null
null
null
null
UTF-8
C++
false
false
3,749
h
/***************************************************//** * @file WifiConfigurationProtocolInterface.h * @date March 2017 * @author Ocean Optics, Inc. * * This is a generic interface into ethernet configuration * functionality at the protocol level, agnostic to * any particular protocol. Each Protocol offering this * functionality should implement this interface. * * LICENSE: * * SeaBreeze Copyright (C) 2017, Ocean Optics Inc * * 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 WIFICONFIGURATIONPROTOCOLINTERFACE_H #define WIFICONFIGURATIONPROTOCOLINTERFACE_H #include "common/buses/Bus.h" #include "common/exceptions/ProtocolException.h" #include "common/protocols/ProtocolHelper.h" namespace seabreeze { class WifiConfigurationProtocolInterface : public ProtocolHelper { public: WifiConfigurationProtocolInterface(Protocol *protocol); virtual ~WifiConfigurationProtocolInterface(); /** * Get the Wifi mode (0: client, 1: access point, from the device. */ virtual unsigned char getMode(const Bus &bus, unsigned char interfaceIndex) throw (ProtocolException) = 0; /** * Set the Wifi mode (0: client, 1: access point, for the device. */ virtual void setMode(const Bus &bus, unsigned char interfaceIndex, unsigned char mode) throw (ProtocolException) = 0; /** * Get the Wifi security type (0: open, 1: WPA2, from the device. */ virtual unsigned char getSecurityType(const Bus &bus, unsigned char interfaceIndex) throw (ProtocolException) = 0; /** * Get the Wifi security type (0: open, 1: WPA2, from the device. */ virtual void setSecurityType(const Bus &bus, unsigned char interfaceIndex, unsigned char securityType) throw (ProtocolException) = 0; /** * Get the 32 byte SSID from the device. */ virtual std::vector<unsigned char> getSSID(const Bus &bus, unsigned char interfaceIndex) throw (ProtocolException) = 0; /** * Set the SSID . */ virtual void setSSID(const Bus &bus, unsigned char interfaceIndex, const std::vector<unsigned char> ssid_32_bytes) throw (ProtocolException) = 0; /** * Set the pass phrase */ virtual void setPassPhrase(const Bus &bus, unsigned char interfaceIndex, const std::vector<unsigned char> passPhrase) throw (ProtocolException) = 0; }; } #endif /* WIFICONFIGURATIONPROTOCOLINTERFACE_H */
[ "clendinning@26700766-15df-4065-81c8-c36b4089b01e" ]
clendinning@26700766-15df-4065-81c8-c36b4089b01e
7849d49aa05816a5f97c4dfd43641b80ae6f52fd
772ad79922fe4a4780ef13c54fd1e82a190e42d8
/SzeregowanieZadan/utils.h
16686ef3a5b6286b3f637be4d6fa4da432b49019
[]
no_license
RaBuko/SzeregowanieZadan
3aaa4828b5d8fbc8789256336e0424d6646fa262
8b00140134f526d86bf516e07ea5909c2e29e3a0
refs/heads/master
2021-09-07T02:09:58.025544
2018-02-15T15:34:56
2018-02-15T15:34:56
121,645,004
0
0
null
null
null
null
UTF-8
C++
false
false
1,240
h
#pragma once #include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <bitset> #include <map> #include <random> #include <utility> #include <fstream> #include <conio.h> #include <windows.h> #include <ctime> #include <math.h> #include <string> #include "Task.h" using namespace std; const int number_of_digits = 24; // Zwraca kolejnosc zadan jako lancuch znakow string orderToString(vector <Task*> problemData); // Generuje nowa kolejnosc zadan na podstawie podanego zbioru zadan vector<Task*> shuffleOrder(vector <Task*> problemData); // Algorytm przegladu zupelnego dla problemu szeregowania zadan string BruteForce(vector <Task*> & problem_data, bool print); // Generuje zbior zadan dla problemu void generateTasks(vector<Task*>& problem_data, unsigned int n); // Wypisuje w konsoli zbior zadan z parametrami void showTasks(vector <Task*> & data); // Kalkuluje i zwraca sume opoznien (koszt) dla danej kolejnosci zadan int calculateCost(vector <Task*> arrOfTasks); // Wczytuje z podanej nazwy pliku zbior zadan dla problemu i go zwraca vector <Task*> loadFromFile(string filename); // Zapisuje do podanego pliku podany zbior zadan void saveToFile(string filename, vector <Task*> & tasksToSave);
[ "raf.buko@gmail.com" ]
raf.buko@gmail.com
77172294e9880282367a4c8fec618c4a68f50aa0
1ad5f2621a4f6bc255eb0b4bf707df92d72c8e85
/Agsearch/Agsearch/node.cpp
4e923c03867bf73b03c98216ea53b88ce689f9b4
[]
no_license
tommylin1212/AGsearch
12c1cb16e25da40b6e768bdb58730bd4445ea701
51b832773c8bd55bf8192eed668234de57657073
refs/heads/master
2021-01-25T10:21:39.857286
2018-03-03T00:04:21
2018-03-03T00:04:21
123,349,612
0
0
null
null
null
null
UTF-8
C++
false
false
1,037
cpp
#include "node.h" using namespace std; Node::Node() { } Node::Node(Node * p, std::string state, double cost, double h_cost) { if (p != NULL) { parent = p; name = state; ucost = cost; pcost = p->pcost + cost; hcost = h_cost; } else { parent=p; name = state; pcost = 0; cost = 0; hcost = h_cost; } } string Node::getName() const { return name; } double Node::getcost() const { return ucost; } double Node::getpathcost() const{ return pcost; } double Node::gethcost() const { return hcost; } bool Node::operator==(const Node & n1) { return (name == n1.getName()&&pcost==n1.getpathcost()); } bool Node::operator<(const Node & n1) { return (pcost < n1.getpathcost()); } void Node::print() const { cout << name<<"("<<ucost<<")"<<"("<<hcost+pcost<<")"; } void Node::traceBack(bool pc) { if (parent) { parent->traceBack(false); cout << "->"; } cout << name<<"("<<pcost<<")" << "(" << hcost + pcost << ")"; if (pc)cout << " total cost: " << pcost; } void Node::setcost(double a) { ucost = a; }
[ "cwill.i.am.tomlin@gmail.com" ]
cwill.i.am.tomlin@gmail.com
d854187107135108423e0e8cb7a65955fc60cc9a
8f95aa6df6b1d2562cbb84cd2c70814b965c904c
/ChartViewer/mainwindow.cpp
ec2570e16b1248432b82605cc2869b156e8e82d7
[ "MIT" ]
permissive
Predrag-A/qt-ChartViewer
db8297c2f6ef1d373861545bb67dd6f632b5a770
932bfafbaedd033091db0d00bd75fe215b25d984
refs/heads/master
2021-08-30T02:26:49.062734
2017-12-15T18:07:21
2017-12-15T18:07:21
113,430,348
0
0
null
null
null
null
UTF-8
C++
false
false
1,198
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "QFileDialog" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->centralWidget->ptr = &m_chartDoc; connect(&m_chartDoc,SIGNAL(chartDataChanged()),ui->centralWidget,SLOT(onChartDataChanged())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionLoad_triggered() { QString filePath = QFileDialog::getOpenFileName(this, QString(), QString(), "Text Files (*.txt);;All Files (*.*)"); if(!filePath.isEmpty()){ m_chartDoc.loadChartFromFile(filePath); this->setFixedWidth(90 + 160*m_chartDoc.getSize()); } } void MainWindow::on_actionSave_triggered() { QString filePath = QFileDialog::getSaveFileName(this, QString(), QString(), "Text Files (*.txt);;All Files (*.*)"); if(!filePath.isEmpty()) { m_chartDoc.saveChartToFile(filePath); } } void MainWindow::on_action2D_triggered() { ui->centralWidget->view3D = false; emit m_chartDoc.chartDataChanged(); } void MainWindow::on_action3D_triggered() { ui->centralWidget->view3D = true; emit m_chartDoc.chartDataChanged(); }
[ "antanas686@gmail.com" ]
antanas686@gmail.com
2943bc038ee86c84f8b90a31a8ad697873204ebe
40150c4e4199bca594fb21bded192bbc05f8c835
/build/iOS/Preview/include/Uno.UX.Resource.h
d515502781ced96dbed45674c0a1db87ac6b94a6
[]
no_license
thegreatyuke42/fuse-test
af0a863ab8cdc19919da11de5f3416cc81fc975f
b7e12f21d12a35d21a394703ff2040a4f3a35e00
refs/heads/master
2016-09-12T10:39:37.656900
2016-05-20T20:13:31
2016-05-20T20:13:31
58,671,009
0
0
null
null
null
null
UTF-8
C++
false
false
2,214
h
// This file was generated based on '/usr/local/share/uno/Packages/UnoCore/0.27.20/Source/Uno/UX/$.uno#8'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Uno{namespace Collections{struct Dictionary;}}} namespace g{namespace Uno{namespace Collections{struct List;}}} namespace g{namespace Uno{namespace UX{struct Resource;}}} namespace g{ namespace Uno{ namespace UX{ // public sealed class Resource :395 // { uType* Resource_typeof(); void Resource__ctor__fn(Resource* __this, uString* key, uObject* value); void Resource__AddGlobalKeyListener_fn(uDelegate* listener); void Resource__GetGlobalKey_fn(uObject* obj, uString** __retval); void Resource__get_Key_fn(Resource* __this, uString** __retval); void Resource__set_Key_fn(Resource* __this, uString* value); void Resource__New1_fn(uString* key, uObject* value, Resource** __retval); void Resource__RemoveGlobalKeyListener_fn(uDelegate* listener); void Resource__SetGlobalKey_fn(uObject* obj, uString* key); void Resource__TryFindGlobal_fn(uString* key, uDelegate* acceptor, uObject** res, bool* __retval); void Resource__get_Value_fn(Resource* __this, uObject** __retval); void Resource__set_Value_fn(Resource* __this, uObject* value); struct Resource : uObject { static uSStrong< ::g::Uno::Collections::Dictionary*> _globals_; static uSStrong< ::g::Uno::Collections::Dictionary*>& _globals() { return _globals_; } static uSStrong< ::g::Uno::Collections::List*> _listeners_; static uSStrong< ::g::Uno::Collections::List*>& _listeners() { return _listeners_; } uStrong<uString*> _Key; uStrong<uObject*> _Value; void ctor_(uString* key, uObject* value); uString* Key(); void Key(uString* value); uObject* Value(); void Value(uObject* value); static void AddGlobalKeyListener(uDelegate* listener); static uString* GetGlobalKey(uObject* obj); static Resource* New1(uString* key, uObject* value); static void RemoveGlobalKeyListener(uDelegate* listener); static void SetGlobalKey(uObject* obj, uString* key); static bool TryFindGlobal(uString* key, uDelegate* acceptor, uObject** res); }; // } }}} // ::g::Uno::UX
[ "johnrbennett3@gmail.com" ]
johnrbennett3@gmail.com
cce4b50b70c22afda0b0d19398f2b103401e1949
f5ad0edb109ae8334406876408e8a9c874e0d616
/src/rpc/mining.cpp
cf1296d518c0fab38dfc77c06f1b94bd6d516af8
[ "MIT" ]
permissive
rhkdck1/RomanceCoin_1
2d41c07efe054f9b114dc20b5e047d48e236489d
f0deb06a1739770078a51ed153c6550506490196
refs/heads/master
2020-09-14T12:36:48.082891
2019-12-23T10:21:36
2019-12-23T10:21:36
223,129,383
1
0
null
null
null
null
UTF-8
C++
false
false
47,816
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <amount.h> #include <chain.h> #include <chainparams.h> #include <consensus/consensus.h> #include <consensus/params.h> #include <consensus/validation.h> #include <core_io.h> #include <validation.h> #include <key_io.h> #include <miner.h> #include <net.h> #include <policy/fees.h> #include <pow.h> #include <rpc/blockchain.h> #include <rpc/mining.h> #include <rpc/server.h> #include <shutdown.h> #include <txmempool.h> #include <util.h> #include <utilstrencodings.h> #include <validationinterface.h> #include <warnings.h> #include <memory> #include <stdint.h> unsigned int ParseConfirmTarget(const UniValue& value) { int target = value.get_int(); unsigned int max_target = ::feeEstimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE); if (target < 1 || (unsigned int)target > max_target) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u - %u", 1, max_target)); } return (unsigned int)target; } /** * Return average network hashes per second based on the last 'lookup' blocks, * or from the last difficulty change if 'lookup' is nonpositive. * If 'height' is nonnegative, compute the estimate at the time when a given block was found. */ static UniValue GetNetworkHashPS(int lookup, int height) { CBlockIndex *pb = chainActive.Tip(); if (height >= 0 && height < chainActive.Height()) pb = chainActive[height]; if (pb == nullptr || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = Params().GetConsensus().lwmaAveragingWindow; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; CBlockIndex *pb0 = pb; int64_t minTime = pb0->GetBlockTime(); int64_t maxTime = minTime; for (int i = 0; i < lookup; i++) { pb0 = pb0->pprev; int64_t time = pb0->GetBlockTime(); minTime = std::min(time, minTime); maxTime = std::max(time, maxTime); } // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception. if (minTime == maxTime) return 0; arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork; int64_t timeDiff = maxTime - minTime; return workDiff.getdouble() / timeDiff; } static UniValue getnetworkhashps(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 2) throw std::runtime_error( "getnetworkhashps ( nblocks height )\n" "\nReturns the estimated network hashes per second based on the last n blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found.\n" "\nArguments:\n" "1. nblocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n" "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n" "\nResult:\n" "x (numeric) Hashes per second estimated\n" "\nExamples:\n" + HelpExampleCli("getnetworkhashps", "") + HelpExampleRpc("getnetworkhashps", "") ); LOCK(cs_main); return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1); } UniValue generateBlocks(std::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript) { static const int nInnerLoopCount = 0x10000; int nHeightEnd = 0; int nHeight = 0; { // Don't keep cs_main locked LOCK(cs_main); nHeight = chainActive.Height(); nHeightEnd = nHeight+nGenerate; } unsigned int nExtraNonce = 0; UniValue blockHashes(UniValue::VARR); while (nHeight < nHeightEnd && !ShutdownRequested()) { std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript)); if (!pblocktemplate.get()) throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block"); CBlock *pblock = &pblocktemplate->block; { LOCK(cs_main); IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce); } while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !CheckProofOfWork(pblock->GetWorkHash(), pblock->nBits, Params().GetConsensus())) { ++pblock->nNonce; --nMaxTries; } if (nMaxTries == 0) { break; } if (pblock->nNonce == nInnerLoopCount) { continue; } std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock); if (!ProcessNewBlock(Params(), shared_pblock, true, nullptr)) throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted"); ++nHeight; blockHashes.push_back(pblock->GetIndexHash().GetHex()); //mark script as important because it was used at least for one coinbase output if the script came from the wallet if (keepScript) { coinbaseScript->KeepScript(); } } return blockHashes; } static UniValue generatetoaddress(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) throw std::runtime_error( "generatetoaddress nblocks address (maxtries)\n" "\nMine blocks immediately to a specified address (before the RPC call returns)\n" "\nArguments:\n" "1. nblocks (numeric, required) How many blocks are generated immediately.\n" "2. address (string, required) The address to send the newly generated bitcoin to.\n" "3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n" "\nResult:\n" "[ blockhashes ] (array) hashes of blocks generated\n" "\nExamples:\n" "\nGenerate 11 blocks to myaddress\n" + HelpExampleCli("generatetoaddress", "11 \"myaddress\"") ); int nGenerate = request.params[0].get_int(); uint64_t nMaxTries = 1000000; if (!request.params[2].isNull()) { nMaxTries = request.params[2].get_int(); } CTxDestination destination = DecodeDestination(request.params[1].get_str()); if (!IsValidDestination(destination)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address"); } std::shared_ptr<CReserveScript> coinbaseScript = std::make_shared<CReserveScript>(); coinbaseScript->reserveScript = GetScriptForDestination(destination); return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false); } static UniValue getmininginfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getmininginfo\n" "\nReturns a json object containing mining-related information." "\nResult:\n" "{\n" " \"blocks\": nnn, (numeric) The current block\n" " \"currentblockweight\": nnn, (numeric) The last block weight\n" " \"currentblocktx\": nnn, (numeric) The last block transaction\n" " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n" " \"networkhashps\": nnn, (numeric) The network hashes per second\n" " \"pooledtx\": n (numeric) The size of the mempool\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"warnings\": \"...\" (string) any network and blockchain warnings\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmininginfo", "") + HelpExampleRpc("getmininginfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.pushKV("blocks", (int)chainActive.Height()); obj.pushKV("currentblockweight", (uint64_t)nLastBlockWeight); obj.pushKV("currentblocktx", (uint64_t)nLastBlockTx); obj.pushKV("difficulty", (double)GetDifficulty(chainActive.Tip())); obj.pushKV("networkhashps", getnetworkhashps(request)); obj.pushKV("pooledtx", (uint64_t)mempool.size()); obj.pushKV("chain", Params().NetworkIDString()); obj.pushKV("warnings", GetWarnings("statusbar")); return obj; } // NOTE: Unlike wallet RPC (which use RMC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts static UniValue prioritisetransaction(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 3) throw std::runtime_error( "prioritisetransaction <txid> <dummy value> <fee delta>\n" "Accepts the transaction into mined blocks at a higher (or lower) priority\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id.\n" "2. dummy (numeric, optional) API-Compatibility for previous API. Must be zero or null.\n" " DEPRECATED. For forward compatibility use named arguments and omit this parameter.\n" "3. fee_delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n" " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n" " The fee is not actually paid, only the algorithm for selecting transactions into a block\n" " considers the transaction as it would have paid a higher (or lower) fee.\n" "\nResult:\n" "true (boolean) Returns true\n" "\nExamples:\n" + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000") ); LOCK(cs_main); uint256 hash = ParseHashStr(request.params[0].get_str(), "txid"); CAmount nAmount = request.params[2].get_int64(); if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0."); } mempool.PrioritiseTransaction(hash, nAmount); return true; } // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller static UniValue BIP22ValidationResult(const CValidationState& state) { if (state.IsValid()) return NullUniValue; if (state.IsError()) throw JSONRPCError(RPC_VERIFY_ERROR, FormatStateMessage(state)); if (state.IsInvalid()) { std::string strRejectReason = state.GetRejectReason(); if (strRejectReason.empty()) return "rejected"; return strRejectReason; } // Should be impossible return "valid?"; } static std::string gbt_vb_name(const Consensus::DeploymentPos pos) { const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; std::string s = vbinfo.name; if (!vbinfo.gbt_force) { s.insert(s.begin(), '!'); } return s; } static UniValue getblocktemplate(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "getblocktemplate ( TemplateRequest )\n" "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n" "It returns data needed to construct a block to work on.\n" "For full specification, see BIPs 22, 23, 9, and 145:\n" " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n" " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n" " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n" " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n" "\nArguments:\n" "1. template_request (json object, optional) A json object in the following spec\n" " {\n" " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n" " \"capabilities\":[ (array, optional) A list of strings\n" " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n" " ,...\n" " ],\n" " \"rules\":[ (array, optional) A list of strings\n" " \"support\" (string) client side supported softfork deployment\n" " ,...\n" " ]\n" " }\n" "\n" "\nResult:\n" "{\n" " \"version\" : n, (numeric) The preferred block version\n" " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n" " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n" " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n" " ,...\n" " },\n" " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n" " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n" " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n" " {\n" " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n" " \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n" " \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n" " \"depends\" : [ (array) array of numbers \n" " n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n" " ,...\n" " ],\n" " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n" " \"sigops\" : n, (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n" " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n" " }\n" " ,...\n" " ],\n" " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n" " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n" " },\n" " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)\n" " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n" " \"target\" : \"xxxx\", (string) The hash target\n" " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mutable\" : [ (array of string) list of ways the block template may be changed \n" " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n" " ,...\n" " ],\n" " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n" " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n" " \"sizelimit\" : n, (numeric) limit of block size\n" " \"weightlimit\" : n, (numeric) limit of block weight\n" " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n" " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n" " \"height\" : n (numeric) The height of the next block\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblocktemplate", "{\"rules\": [\"segwit\"]}") + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}") ); LOCK(cs_main); std::string strMode = "template"; UniValue lpval = NullUniValue; std::set<std::string> setClientRules; int64_t nMaxVersionPreVB = -1; if (!request.params[0].isNull()) { const UniValue& oparam = request.params[0].get_obj(); const UniValue& modeval = find_value(oparam, "mode"); if (modeval.isStr()) strMode = modeval.get_str(); else if (modeval.isNull()) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); lpval = find_value(oparam, "longpollid"); if (strMode == "proposal") { const UniValue& dataval = find_value(oparam, "data"); if (!dataval.isStr()) throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal"); CBlock block; if (!DecodeHexBlk(block, dataval.get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); uint256 hash = block.GetIndexHash(); const CBlockIndex* pindex = LookupBlockIndex(hash); if (pindex) { if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) return "duplicate"; if (pindex->nStatus & BLOCK_FAILED_MASK) return "duplicate-invalid"; return "duplicate-inconclusive"; } CBlockIndex* const pindexPrev = chainActive.Tip(); // TestBlockValidity only supports blocks built on the current Tip if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return "inconclusive-not-best-prevblk"; CValidationState state; TestBlockValidity(state, Params(), block, pindexPrev, false, true); return BIP22ValidationResult(state); } const UniValue& aClientRules = find_value(oparam, "rules"); if (aClientRules.isArray()) { for (unsigned int i = 0; i < aClientRules.size(); ++i) { const UniValue& v = aClientRules[i]; setClientRules.insert(v.get_str()); } } else { // NOTE: It is important that this NOT be read if versionbits is supported const UniValue& uvMaxVersion = find_value(oparam, "maxversion"); if (uvMaxVersion.isNum()) { nMaxVersionPreVB = uvMaxVersion.get_int64(); } } } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks..."); static unsigned int nTransactionsUpdatedLast; if (!lpval.isNull()) { // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions uint256 hashWatchedChain; std::chrono::steady_clock::time_point checktxtime; unsigned int nTransactionsUpdatedLastLP; if (lpval.isStr()) { // Format: <hashBestChain><nTransactionsUpdatedLast> std::string lpstr = lpval.get_str(); hashWatchedChain.SetHex(lpstr.substr(0, 64)); nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64)); } else { // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier hashWatchedChain = chainActive.Tip()->GetBlockHash(); nTransactionsUpdatedLastLP = nTransactionsUpdatedLast; } // Release the wallet and main lock while waiting LEAVE_CRITICAL_SECTION(cs_main); { checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1); WaitableLock lock(g_best_block_mutex); while (g_best_block == hashWatchedChain && IsRPCRunning()) { if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout) { // Timeout: Check transactions for update if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP) break; checktxtime += std::chrono::seconds(10); } } } ENTER_CRITICAL_SECTION(cs_main); if (!IsRPCRunning()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down"); // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners? } // If the caller is indicating segwit support, then allow CreateNewBlock() // to select witness transactions, after segwit activates (otherwise // don't). bool fSupportsSegwit = setClientRules.find("segwit") != setClientRules.end(); // Update block static CBlockIndex* pindexPrev; static int64_t nStart; static std::unique_ptr<CBlockTemplate> pblocktemplate; // Cache whether the last invocation was with segwit support, to avoid returning // a segwit-block to a non-segwit caller. static bool fLastTemplateSupportsSegwit = true; if (pindexPrev != chainActive.Tip() || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) || fLastTemplateSupportsSegwit != fSupportsSegwit) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = nullptr; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrevNew = chainActive.Tip(); nStart = GetTime(); fLastTemplateSupportsSegwit = fSupportsSegwit; // Create new block CScript scriptDummy = CScript() << OP_TRUE; pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy, fSupportsSegwit); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } assert(pindexPrev); CBlock* pblock = &pblocktemplate->block; // pointer for convenience const Consensus::Params& consensusParams = Params().GetConsensus(); // Update nTime UpdateTime(pblock, consensusParams, pindexPrev); pblock->nNonce = 0; // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration const bool fPreSegWit = false; UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal"); UniValue transactions(UniValue::VARR); std::map<uint256, int64_t> setTxIndex; int i = 0; for (const auto& it : pblock->vtx) { const CTransaction& tx = *it; uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; UniValue entry(UniValue::VOBJ); entry.pushKV("data", EncodeHexTx(tx)); entry.pushKV("txid", txHash.GetHex()); entry.pushKV("hash", tx.GetWitnessHash().GetHex()); UniValue deps(UniValue::VARR); for (const CTxIn &in : tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.pushKV("depends", deps); int index_in_template = i - 1; entry.pushKV("fee", pblocktemplate->vTxFees[index_in_template]); int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template]; if (fPreSegWit) { assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0); nTxSigOps /= WITNESS_SCALE_FACTOR; } entry.pushKV("sigops", nTxSigOps); entry.pushKV("weight", GetTransactionWeight(tx)); transactions.push_back(entry); } UniValue aux(UniValue::VOBJ); aux.pushKV("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())); arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits); UniValue aMutable(UniValue::VARR); aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); UniValue result(UniValue::VOBJ); result.pushKV("capabilities", aCaps); UniValue aRules(UniValue::VARR); UniValue vbavailable(UniValue::VOBJ); if (Params().GetConsensus().nSegwitEnabled) { aRules.push_back("segwit"); } for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) { Consensus::DeploymentPos pos = Consensus::DeploymentPos(j); ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache); switch (state) { case ThresholdState::DEFINED: case ThresholdState::FAILED: // Not exposed to GBT at all break; case ThresholdState::LOCKED_IN: // Ensure bit is set in block version pblock->nVersion |= VersionBitsMask(consensusParams, pos); // FALL THROUGH to get vbavailable set... case ThresholdState::STARTED: { const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit); if (setClientRules.find(vbinfo.name) == setClientRules.end()) { if (!vbinfo.gbt_force) { // If the client doesn't support this, don't indicate it in the [default] version pblock->nVersion &= ~VersionBitsMask(consensusParams, pos); } } break; } case ThresholdState::ACTIVE: { // Add to rules only const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; aRules.push_back(gbt_vb_name(pos)); if (setClientRules.find(vbinfo.name) == setClientRules.end()) { // Not supported by the client; make sure it's safe to proceed if (!vbinfo.gbt_force) { // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name)); } } break; } } } result.pushKV("version", pblock->nVersion); result.pushKV("rules", aRules); result.pushKV("vbavailable", vbavailable); result.pushKV("vbrequired", int(0)); if (nMaxVersionPreVB >= 2) { // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated aMutable.push_back("version/force"); } result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex()); result.pushKV("transactions", transactions); result.pushKV("coinbaseaux", aux); result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue); result.pushKV("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)); result.pushKV("target", hashTarget.GetHex()); result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1); result.pushKV("mutable", aMutable); result.pushKV("noncerange", "00000000ffffffff"); int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST; int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE; if (fPreSegWit) { assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0); nSigOpLimit /= WITNESS_SCALE_FACTOR; assert(nSizeLimit % WITNESS_SCALE_FACTOR == 0); nSizeLimit /= WITNESS_SCALE_FACTOR; } result.pushKV("sigoplimit", nSigOpLimit); result.pushKV("sizelimit", nSizeLimit); if (!fPreSegWit) { result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT); } result.pushKV("curtime", pblock->GetBlockTime()); result.pushKV("bits", strprintf("%08x", pblock->nBits)); result.pushKV("height", (int64_t)(pindexPrev->nHeight+1)); if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) { result.pushKV("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end())); } return result; } class submitblock_StateCatcher : public CValidationInterface { public: uint256 hash; bool found; CValidationState state; explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {} protected: void BlockChecked(const CBlock& block, const CValidationState& stateIn) override { if (block.GetIndexHash() != hash) return; found = true; state = stateIn; } }; static UniValue submitblock(const JSONRPCRequest& request) { // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw std::runtime_error( "submitblock \"hexdata\" ( \"dummy\" )\n" "\nAttempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n" "\nArguments\n" "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n" "2. \"dummy\" (optional) dummy value, for compatibility with BIP22. This value is ignored.\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("submitblock", "\"mydata\"") + HelpExampleRpc("submitblock", "\"mydata\"") ); } std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>(); CBlock& block = *blockptr; if (!DecodeHexBlk(block, request.params[0].get_str())) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase"); } uint256 hash = block.GetIndexHash(); { LOCK(cs_main); const CBlockIndex* pindex = LookupBlockIndex(hash); if (pindex) { if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) { return "duplicate"; } if (pindex->nStatus & BLOCK_FAILED_MASK) { return "duplicate-invalid"; } } } { LOCK(cs_main); const CBlockIndex* pindex = LookupBlockIndex(block.hashPrevBlock); if (pindex) { UpdateUncommittedBlockStructures(block, pindex, Params().GetConsensus()); } } bool new_block; submitblock_StateCatcher sc(block.GetIndexHash()); RegisterValidationInterface(&sc); bool accepted = ProcessNewBlock(Params(), blockptr, /* fForceProcessing */ true, /* fNewBlock */ &new_block); UnregisterValidationInterface(&sc); if (!new_block) { if (!accepted) { // TODO Maybe pass down fNewBlock to AcceptBlockHeader, so it is properly set to true in this case? return "invalid"; } return "duplicate"; } if (!sc.found) { return "inconclusive"; } return BIP22ValidationResult(sc.state); } static UniValue estimatefee(const JSONRPCRequest& request) { throw JSONRPCError(RPC_METHOD_DEPRECATED, "estimatefee was removed in v0.17.\n" "Clients should use estimatesmartfee."); } static UniValue estimatesmartfee(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "estimatesmartfee conf_target (\"estimate_mode\")\n" "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n" "confirmation within conf_target blocks if possible and return the number of blocks\n" "for which the estimate is valid. Uses virtual transaction size as defined\n" "in BIP 141 (witness data is discounted).\n" "\nArguments:\n" "1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n" "2. \"estimate_mode\" (string, optional, default=CONSERVATIVE) The fee estimate mode.\n" " Whether to return a more conservative estimate which also satisfies\n" " a longer history. A conservative estimate potentially returns a\n" " higher feerate and is more likely to be sufficient for the desired\n" " target, but is not as responsive to short term drops in the\n" " prevailing fee market. Must be one of:\n" " \"UNSET\" (defaults to CONSERVATIVE)\n" " \"ECONOMICAL\"\n" " \"CONSERVATIVE\"\n" "\nResult:\n" "{\n" " \"feerate\" : x.x, (numeric, optional) estimate fee rate in " + CURRENCY_UNIT + "/kB\n" " \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n" " \"blocks\" : n (numeric) block number where estimate was found\n" "}\n" "\n" "The request target will be clamped between 2 and the highest target\n" "fee estimation is able to return based on how long it has been running.\n" "An error is returned if not enough transactions and blocks\n" "have been observed to make an estimate for any number of blocks.\n" "\nExample:\n" + HelpExampleCli("estimatesmartfee", "6") ); RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR}); RPCTypeCheckArgument(request.params[0], UniValue::VNUM); unsigned int conf_target = ParseConfirmTarget(request.params[0]); bool conservative = true; if (!request.params[1].isNull()) { FeeEstimateMode fee_mode; if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter"); } if (fee_mode == FeeEstimateMode::ECONOMICAL) conservative = false; } UniValue result(UniValue::VOBJ); UniValue errors(UniValue::VARR); FeeCalculation feeCalc; CFeeRate feeRate = ::feeEstimator.estimateSmartFee(conf_target, &feeCalc, conservative); if (feeRate != CFeeRate(0)) { result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK())); } else { errors.push_back("Insufficient data or no feerate found"); result.pushKV("errors", errors); } result.pushKV("blocks", feeCalc.returnedTarget); return result; } static UniValue estimaterawfee(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "estimaterawfee conf_target (threshold)\n" "\nWARNING: This interface is unstable and may disappear or change!\n" "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n" " implementation of fee estimation. The parameters it can be called with\n" " and the results it returns will change if the internal implementation changes.\n" "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n" "confirmation within conf_target blocks if possible. Uses virtual transaction size as\n" "defined in BIP 141 (witness data is discounted).\n" "\nArguments:\n" "1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n" "2. threshold (numeric, optional) The proportion of transactions in a given feerate range that must have been\n" " confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n" " lower buckets. Default: 0.95\n" "\nResult:\n" "{\n" " \"short\" : { (json object, optional) estimate for short time horizon\n" " \"feerate\" : x.x, (numeric, optional) estimate fee rate in " + CURRENCY_UNIT + "/kB\n" " \"decay\" : x.x, (numeric) exponential decay (per block) for historical moving average of confirmation data\n" " \"scale\" : x, (numeric) The resolution of confirmation targets at this time horizon\n" " \"pass\" : { (json object, optional) information about the lowest range of feerates to succeed in meeting the threshold\n" " \"startrange\" : x.x, (numeric) start of feerate range\n" " \"endrange\" : x.x, (numeric) end of feerate range\n" " \"withintarget\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed within target\n" " \"totalconfirmed\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed at any point\n" " \"inmempool\" : x.x, (numeric) current number of txs in mempool in the feerate range unconfirmed for at least target blocks\n" " \"leftmempool\" : x.x, (numeric) number of txs over history horizon in the feerate range that left mempool unconfirmed after target\n" " },\n" " \"fail\" : { ... }, (json object, optional) information about the highest range of feerates to fail to meet the threshold\n" " \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n" " },\n" " \"medium\" : { ... }, (json object, optional) estimate for medium time horizon\n" " \"long\" : { ... } (json object) estimate for long time horizon\n" "}\n" "\n" "Results are returned for any horizon which tracks blocks up to the confirmation target.\n" "\nExample:\n" + HelpExampleCli("estimaterawfee", "6 0.9") ); RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true); RPCTypeCheckArgument(request.params[0], UniValue::VNUM); unsigned int conf_target = ParseConfirmTarget(request.params[0]); double threshold = 0.95; if (!request.params[1].isNull()) { threshold = request.params[1].get_real(); } if (threshold < 0 || threshold > 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold"); } UniValue result(UniValue::VOBJ); for (FeeEstimateHorizon horizon : {FeeEstimateHorizon::SHORT_HALFLIFE, FeeEstimateHorizon::MED_HALFLIFE, FeeEstimateHorizon::LONG_HALFLIFE}) { CFeeRate feeRate; EstimationResult buckets; // Only output results for horizons which track the target if (conf_target > ::feeEstimator.HighestTargetTracked(horizon)) continue; feeRate = ::feeEstimator.estimateRawFee(conf_target, threshold, horizon, &buckets); UniValue horizon_result(UniValue::VOBJ); UniValue errors(UniValue::VARR); UniValue passbucket(UniValue::VOBJ); passbucket.pushKV("startrange", round(buckets.pass.start)); passbucket.pushKV("endrange", round(buckets.pass.end)); passbucket.pushKV("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0); passbucket.pushKV("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0); passbucket.pushKV("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0); passbucket.pushKV("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0); UniValue failbucket(UniValue::VOBJ); failbucket.pushKV("startrange", round(buckets.fail.start)); failbucket.pushKV("endrange", round(buckets.fail.end)); failbucket.pushKV("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0); failbucket.pushKV("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0); failbucket.pushKV("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0); failbucket.pushKV("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0); // CFeeRate(0) is used to indicate error as a return value from estimateRawFee if (feeRate != CFeeRate(0)) { horizon_result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK())); horizon_result.pushKV("decay", buckets.decay); horizon_result.pushKV("scale", (int)buckets.scale); horizon_result.pushKV("pass", passbucket); // buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output if (buckets.fail.start != -1) horizon_result.pushKV("fail", failbucket); } else { // Output only information that is still meaningful in the event of error horizon_result.pushKV("decay", buckets.decay); horizon_result.pushKV("scale", (int)buckets.scale); horizon_result.pushKV("fail", failbucket); errors.push_back("Insufficient data or no feerate found which meets threshold"); horizon_result.pushKV("errors",errors); } result.pushKV(StringForFeeEstimateHorizon(horizon), horizon_result); } return result; } static UniValue setgenerate(const JSONRPCRequest& request) { printf("여기 타나\n"); printf("request.params[0] : %s \n", request.params[0]); if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) throw std::runtime_error( "setgenerate generate ( genproclimit )\n" "\nSet 'generate' true or false to turn generation on or off.\n" "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n" "See the getgenerate call for the current setting.\n" "\nArguments:\n" "1. generate (boolean, required) Set to true to turn on generation, false to turn off.\n" "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n" "\nExamples:\n" "\nSet the generation on with a limit of one processor\n" + HelpExampleCli("setgenerate", "true 1") + "\nCheck the setting\n" + HelpExampleCli("getgenerate", "") + "\nTurn off generation\n" + HelpExampleCli("setgenerate", "false") + "\nUsing json rpc\n" + HelpExampleRpc("setgenerate", "true, 1") ); if (Params().MineBlocksOnDemand()) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Use the generate method instead of setgenerate on this network"); bool fGenerate = true; if (!request.params[0].isNull()) { fGenerate = request.params[0].get_bool(); } int nGenProcLimit = 1; if (!request.params[1].isNull()) { nGenProcLimit = request.params[1].get_int(); if (nGenProcLimit == 0) fGenerate = false; } printf("fGenerate = %d \n", fGenerate); printf("nGenProcLimit = %d \n", nGenProcLimit); GenerateSolo(fGenerate, nGenProcLimit, Params(), *g_connman); return fGenerate ? std::string("Mining started") : std::string("Mining stopped"); } static const CRPCCommand commands[] = { // category name actor (function) argNames // --------------------- ------------------------ ----------------------- ---------- { "mining", "getnetworkhashps", &getnetworkhashps, {"nblocks","height"} }, { "mining", "getmininginfo", &getmininginfo, {} }, { "mining", "prioritisetransaction", &prioritisetransaction, {"txid","dummy","fee_delta"} }, { "mining", "getblocktemplate", &getblocktemplate, {"template_request"} }, { "mining", "submitblock", &submitblock, {"hexdata","dummy"} }, { "mining", "setgenerate", &setgenerate, {"generate", "genproclimit"} }, { "generating", "generatetoaddress", &generatetoaddress, {"nblocks","address","maxtries"} }, { "hidden", "estimatefee", &estimatefee, {} }, { "util", "estimatesmartfee", &estimatesmartfee, {"conf_target", "estimate_mode"} }, { "hidden", "estimaterawfee", &estimaterawfee, {"conf_target", "threshold"} }, }; void RegisterMiningRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
[ "rhkdck1@gmail.com" ]
rhkdck1@gmail.com
d52ca5c5c9647d7d90bd0433a939141b958a46be
d7da5f1b2d391a1025570082bfaaece0d93a80ed
/ofxMyPJcontrol/src/ofxPjMgr.cpp
6a4ca5699d5114842f2ff1b91eea7890e0d81410
[]
no_license
LYHSH/ofx_adddon_2017
d3dda589df432b9a54f918be703ae19cbee9a33d
4487148b47686cbc7e88d7b96324e14bce6c3c71
refs/heads/master
2021-08-07T16:54:26.637448
2020-07-16T23:39:54
2020-07-16T23:39:54
201,904,688
0
0
null
null
null
null
UTF-8
C++
false
false
3,176
cpp
#include "ofxPjMgr.h" #include "ofxXmlSettings.h" ofxPjMgr::ofxPjMgr() { } ofxPjMgr::~ofxPjMgr() { for (int i = 0; i < controler.size(); i++) { auto & arrObj = controler[i]; for each (auto var in arrObj) { delete var; var = NULL; } } controler.clear(); } void ofxPjMgr::setup(const string & _filename) { ofxXmlSettings xml; xml.load(_filename); int nums = xml.getNumTags("group"); controler.resize(nums); for (int i = 0; i < controler.size(); i++) { xml.pushTag("group", i); int pjNums = xml.getNumTags("project"); for (int pjIndex = 0; pjIndex < pjNums; pjIndex++) { xml.pushTag("project", pjIndex); int type = xml.getValue("type",0); string nameStr = ""; if (xml.tagExists("IP")) { nameStr = xml.getValue("IP", ""); } else if (xml.tagExists("COM")) { nameStr = "COM" + ofToString(xml.getValue("COM", 0)); } ofxPJcontrolBase * pjObject = ofxPJcontrolFactory::createPJbyType( (PROJECT_TYPE)type, nameStr); controler[i].push_back(pjObject); xml.popTag(); } xml.popTag(); } ofLogNotice(OF_FUNCTION_NAME) << "PJ NUMS:" << controler.size() << endl; } void ofxPjMgr::setOn(int _index) { if (!checkOut(_index))return; auto & arrObj = controler[_index]; for each (auto var in arrObj) { var->setOn(); Sleep(1000); } } void ofxPjMgr::setOff(int _index) { if (!checkOut(_index))return; auto & arrObj = controler[_index]; for each (auto var in arrObj) { var->setOff(); Sleep(1000); } } void ofxPjMgr::setAllOn() { for (int i = 0; i < controler.size(); i++) { auto & arrObj = controler[i]; for each (auto var in arrObj) { var->setOn(); Sleep(1000); } } } void ofxPjMgr::setAllOff() { for (int i = 0; i < controler.size(); i++) { auto & arrObj = controler[i]; for each (auto var in arrObj) { var->setOff(); Sleep(1000); } } } void ofxPjMgr::setDVI(int _index) { if (!checkOut(_index))return; auto & arrObj = controler[_index]; for each (auto var in arrObj) { var->setDVI(); Sleep(1000); } } void ofxPjMgr::setRGB2(int _index) { if (!checkOut(_index))return; auto & arrObj = controler[_index]; for each (auto var in arrObj) { var->setRGB2(); Sleep(1000); } } void ofxPjMgr::setHMDI1(int _index) { if (!checkOut(_index))return; auto & arrObj = controler[_index]; for each (auto var in arrObj) { var->setHDMI1(); Sleep(1000); } } void ofxPjMgr::setHMDI2(int _index) { if (!checkOut(_index))return; auto & arrObj = controler[_index]; for each (auto var in arrObj) { var->setHDMI2(); Sleep(1000); } } string ofxPjMgr::getIP(int _index)const { if (!checkOut(_index))return ""; return controler[_index][0]->getName(); } vector<string> ofxPjMgr::getIPs(int _index)const { vector<string> strVec; if (!checkOut(_index)) return strVec; auto & macGroup = controler[_index]; for (auto iter = macGroup.begin(); iter != macGroup.end(); iter++) { strVec.push_back((*iter)->getName()); } return strVec; } int ofxPjMgr::size()const { return controler.size(); } bool ofxPjMgr::checkOut(int _index)const { bool res = true; res &= (_index >= 0); res &= (_index < size()); return res; }
[ "243505075@qq.com" ]
243505075@qq.com
ed0bd01eae020e0731aede11fb182fe72d5b1db0
6f49cc2d5112a6b97f82e7828f59b201ea7ec7b9
/apiwdbe/PnlWdbeUntRec.cpp
6efb8e83f12de1903e761cc99ca18c73c919fe22
[ "MIT" ]
permissive
mpsitech/wdbe-WhizniumDBE
d3702800d6e5510e41805d105228d8dd8b251d7a
89ef36b4c86384429f1e707e5fa635f643e81240
refs/heads/master
2022-09-28T10:27:03.683192
2022-09-18T22:04:37
2022-09-18T22:04:37
282,705,449
5
0
null
null
null
null
UTF-8
C++
false
false
16,863
cpp
/** * \file PnlWdbeUntRec.cpp * API code for job PnlWdbeUntRec (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 5 Dec 2020 */ // IP header --- ABOVE #include "PnlWdbeUntRec.h" using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlWdbeUntRec::VecVDo ******************************************************************************/ uint PnlWdbeUntRec::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butminimizeclick") return BUTMINIMIZECLICK; if (s == "butregularizeclick") return BUTREGULARIZECLICK; return(0); }; string PnlWdbeUntRec::VecVDo::getSref( const uint ix ) { if (ix == BUTMINIMIZECLICK) return("ButMinimizeClick"); if (ix == BUTREGULARIZECLICK) return("ButRegularizeClick"); return(""); }; /****************************************************************************** class PnlWdbeUntRec::ContInf ******************************************************************************/ PnlWdbeUntRec::ContInf::ContInf( const string& TxtRef ) : Block() { this->TxtRef = TxtRef; mask = {TXTREF}; }; bool PnlWdbeUntRec::ContInf::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContInfWdbeUntRec"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemInfWdbeUntRec"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtRef", TxtRef)) add(TXTREF); }; return basefound; }; set<uint> PnlWdbeUntRec::ContInf::comm( const ContInf* comp ) { set<uint> items; if (TxtRef == comp->TxtRef) insert(items, TXTREF); return(items); }; set<uint> PnlWdbeUntRec::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TXTREF}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWdbeUntRec::StatApp ******************************************************************************/ PnlWdbeUntRec::StatApp::StatApp( const bool initdoneDetail , const bool initdone1NTarget , const bool initdone1NInterrupt , const bool initdone1NPeripheral , const bool initdoneSil1NUnit , const bool initdoneFwd1NController , const bool initdone1NBank , const bool initdoneHk1NModule , const bool initdoneHk1NVector , const bool initdoneRef1NSignal , const bool initdoneRef1NError , const bool initdoneRef1NCommand ) : Block() { this->initdoneDetail = initdoneDetail; this->initdone1NTarget = initdone1NTarget; this->initdone1NInterrupt = initdone1NInterrupt; this->initdone1NPeripheral = initdone1NPeripheral; this->initdoneSil1NUnit = initdoneSil1NUnit; this->initdoneFwd1NController = initdoneFwd1NController; this->initdone1NBank = initdone1NBank; this->initdoneHk1NModule = initdoneHk1NModule; this->initdoneHk1NVector = initdoneHk1NVector; this->initdoneRef1NSignal = initdoneRef1NSignal; this->initdoneRef1NError = initdoneRef1NError; this->initdoneRef1NCommand = initdoneRef1NCommand; mask = {INITDONEDETAIL, INITDONE1NTARGET, INITDONE1NINTERRUPT, INITDONE1NPERIPHERAL, INITDONESIL1NUNIT, INITDONEFWD1NCONTROLLER, INITDONE1NBANK, INITDONEHK1NMODULE, INITDONEHK1NVECTOR, INITDONEREF1NSIGNAL, INITDONEREF1NERROR, INITDONEREF1NCOMMAND}; }; bool PnlWdbeUntRec::StatApp::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppWdbeUntRec"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemAppWdbeUntRec"; if (basefound) { if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneDetail", initdoneDetail)) add(INITDONEDETAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdone1NTarget", initdone1NTarget)) add(INITDONE1NTARGET); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdone1NInterrupt", initdone1NInterrupt)) add(INITDONE1NINTERRUPT); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdone1NPeripheral", initdone1NPeripheral)) add(INITDONE1NPERIPHERAL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneSil1NUnit", initdoneSil1NUnit)) add(INITDONESIL1NUNIT); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneFwd1NController", initdoneFwd1NController)) add(INITDONEFWD1NCONTROLLER); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdone1NBank", initdone1NBank)) add(INITDONE1NBANK); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneHk1NModule", initdoneHk1NModule)) add(INITDONEHK1NMODULE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneHk1NVector", initdoneHk1NVector)) add(INITDONEHK1NVECTOR); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneRef1NSignal", initdoneRef1NSignal)) add(INITDONEREF1NSIGNAL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneRef1NError", initdoneRef1NError)) add(INITDONEREF1NERROR); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneRef1NCommand", initdoneRef1NCommand)) add(INITDONEREF1NCOMMAND); }; return basefound; }; set<uint> PnlWdbeUntRec::StatApp::comm( const StatApp* comp ) { set<uint> items; if (initdoneDetail == comp->initdoneDetail) insert(items, INITDONEDETAIL); if (initdone1NTarget == comp->initdone1NTarget) insert(items, INITDONE1NTARGET); if (initdone1NInterrupt == comp->initdone1NInterrupt) insert(items, INITDONE1NINTERRUPT); if (initdone1NPeripheral == comp->initdone1NPeripheral) insert(items, INITDONE1NPERIPHERAL); if (initdoneSil1NUnit == comp->initdoneSil1NUnit) insert(items, INITDONESIL1NUNIT); if (initdoneFwd1NController == comp->initdoneFwd1NController) insert(items, INITDONEFWD1NCONTROLLER); if (initdone1NBank == comp->initdone1NBank) insert(items, INITDONE1NBANK); if (initdoneHk1NModule == comp->initdoneHk1NModule) insert(items, INITDONEHK1NMODULE); if (initdoneHk1NVector == comp->initdoneHk1NVector) insert(items, INITDONEHK1NVECTOR); if (initdoneRef1NSignal == comp->initdoneRef1NSignal) insert(items, INITDONEREF1NSIGNAL); if (initdoneRef1NError == comp->initdoneRef1NError) insert(items, INITDONEREF1NERROR); if (initdoneRef1NCommand == comp->initdoneRef1NCommand) insert(items, INITDONEREF1NCOMMAND); return(items); }; set<uint> PnlWdbeUntRec::StatApp::diff( const StatApp* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {INITDONEDETAIL, INITDONE1NTARGET, INITDONE1NINTERRUPT, INITDONE1NPERIPHERAL, INITDONESIL1NUNIT, INITDONEFWD1NCONTROLLER, INITDONE1NBANK, INITDONEHK1NMODULE, INITDONEHK1NVECTOR, INITDONEREF1NSIGNAL, INITDONEREF1NERROR, INITDONEREF1NCOMMAND}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWdbeUntRec::StatShr ******************************************************************************/ PnlWdbeUntRec::StatShr::StatShr( const uint ixWdbeVExpstate , const string& scrJrefDetail , const string& scrJref1NTarget , const string& scrJref1NInterrupt , const string& scrJref1NPeripheral , const string& scrJrefSil1NUnit , const bool pnlsil1nunitAvail , const string& scrJrefFwd1NController , const string& scrJref1NBank , const string& scrJrefHk1NModule , const string& scrJrefHk1NVector , const string& scrJrefRef1NSignal , const string& scrJrefRef1NError , const string& scrJrefRef1NCommand , const bool ButRegularizeActive ) : Block() { this->ixWdbeVExpstate = ixWdbeVExpstate; this->scrJrefDetail = scrJrefDetail; this->scrJref1NTarget = scrJref1NTarget; this->scrJref1NInterrupt = scrJref1NInterrupt; this->scrJref1NPeripheral = scrJref1NPeripheral; this->scrJrefSil1NUnit = scrJrefSil1NUnit; this->pnlsil1nunitAvail = pnlsil1nunitAvail; this->scrJrefFwd1NController = scrJrefFwd1NController; this->scrJref1NBank = scrJref1NBank; this->scrJrefHk1NModule = scrJrefHk1NModule; this->scrJrefHk1NVector = scrJrefHk1NVector; this->scrJrefRef1NSignal = scrJrefRef1NSignal; this->scrJrefRef1NError = scrJrefRef1NError; this->scrJrefRef1NCommand = scrJrefRef1NCommand; this->ButRegularizeActive = ButRegularizeActive; mask = {IXWDBEVEXPSTATE, SCRJREFDETAIL, SCRJREF1NTARGET, SCRJREF1NINTERRUPT, SCRJREF1NPERIPHERAL, SCRJREFSIL1NUNIT, PNLSIL1NUNITAVAIL, SCRJREFFWD1NCONTROLLER, SCRJREF1NBANK, SCRJREFHK1NMODULE, SCRJREFHK1NVECTOR, SCRJREFREF1NSIGNAL, SCRJREFREF1NERROR, SCRJREFREF1NCOMMAND, BUTREGULARIZEACTIVE}; }; bool PnlWdbeUntRec::StatShr::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string srefIxWdbeVExpstate; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrWdbeUntRec"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemShrWdbeUntRec"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxWdbeVExpstate", srefIxWdbeVExpstate)) { ixWdbeVExpstate = VecWdbeVExpstate::getIx(srefIxWdbeVExpstate); add(IXWDBEVEXPSTATE); }; if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefDetail", scrJrefDetail)) add(SCRJREFDETAIL); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJref1NTarget", scrJref1NTarget)) add(SCRJREF1NTARGET); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJref1NInterrupt", scrJref1NInterrupt)) add(SCRJREF1NINTERRUPT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJref1NPeripheral", scrJref1NPeripheral)) add(SCRJREF1NPERIPHERAL); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefSil1NUnit", scrJrefSil1NUnit)) add(SCRJREFSIL1NUNIT); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "pnlsil1nunitAvail", pnlsil1nunitAvail)) add(PNLSIL1NUNITAVAIL); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefFwd1NController", scrJrefFwd1NController)) add(SCRJREFFWD1NCONTROLLER); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJref1NBank", scrJref1NBank)) add(SCRJREF1NBANK); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefHk1NModule", scrJrefHk1NModule)) add(SCRJREFHK1NMODULE); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefHk1NVector", scrJrefHk1NVector)) add(SCRJREFHK1NVECTOR); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefRef1NSignal", scrJrefRef1NSignal)) add(SCRJREFREF1NSIGNAL); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefRef1NError", scrJrefRef1NError)) add(SCRJREFREF1NERROR); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefRef1NCommand", scrJrefRef1NCommand)) add(SCRJREFREF1NCOMMAND); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButRegularizeActive", ButRegularizeActive)) add(BUTREGULARIZEACTIVE); }; return basefound; }; set<uint> PnlWdbeUntRec::StatShr::comm( const StatShr* comp ) { set<uint> items; if (ixWdbeVExpstate == comp->ixWdbeVExpstate) insert(items, IXWDBEVEXPSTATE); if (scrJrefDetail == comp->scrJrefDetail) insert(items, SCRJREFDETAIL); if (scrJref1NTarget == comp->scrJref1NTarget) insert(items, SCRJREF1NTARGET); if (scrJref1NInterrupt == comp->scrJref1NInterrupt) insert(items, SCRJREF1NINTERRUPT); if (scrJref1NPeripheral == comp->scrJref1NPeripheral) insert(items, SCRJREF1NPERIPHERAL); if (scrJrefSil1NUnit == comp->scrJrefSil1NUnit) insert(items, SCRJREFSIL1NUNIT); if (pnlsil1nunitAvail == comp->pnlsil1nunitAvail) insert(items, PNLSIL1NUNITAVAIL); if (scrJrefFwd1NController == comp->scrJrefFwd1NController) insert(items, SCRJREFFWD1NCONTROLLER); if (scrJref1NBank == comp->scrJref1NBank) insert(items, SCRJREF1NBANK); if (scrJrefHk1NModule == comp->scrJrefHk1NModule) insert(items, SCRJREFHK1NMODULE); if (scrJrefHk1NVector == comp->scrJrefHk1NVector) insert(items, SCRJREFHK1NVECTOR); if (scrJrefRef1NSignal == comp->scrJrefRef1NSignal) insert(items, SCRJREFREF1NSIGNAL); if (scrJrefRef1NError == comp->scrJrefRef1NError) insert(items, SCRJREFREF1NERROR); if (scrJrefRef1NCommand == comp->scrJrefRef1NCommand) insert(items, SCRJREFREF1NCOMMAND); if (ButRegularizeActive == comp->ButRegularizeActive) insert(items, BUTREGULARIZEACTIVE); return(items); }; set<uint> PnlWdbeUntRec::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {IXWDBEVEXPSTATE, SCRJREFDETAIL, SCRJREF1NTARGET, SCRJREF1NINTERRUPT, SCRJREF1NPERIPHERAL, SCRJREFSIL1NUNIT, PNLSIL1NUNITAVAIL, SCRJREFFWD1NCONTROLLER, SCRJREF1NBANK, SCRJREFHK1NMODULE, SCRJREFHK1NVECTOR, SCRJREFREF1NSIGNAL, SCRJREFREF1NERROR, SCRJREFREF1NCOMMAND, BUTREGULARIZEACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWdbeUntRec::Tag ******************************************************************************/ PnlWdbeUntRec::Tag::Tag( const string& Cpt ) : Block() { this->Cpt = Cpt; mask = {CPT}; }; bool PnlWdbeUntRec::Tag::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagWdbeUntRec"); else basefound = checkXPath(docctx, basexpath); string itemtag = "TagitemWdbeUntRec"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT); }; return basefound; }; /****************************************************************************** class PnlWdbeUntRec::DpchAppDo ******************************************************************************/ PnlWdbeUntRec::DpchAppDo::DpchAppDo( const string& scrJref , const uint ixVDo , const set<uint>& mask ) : DpchAppWdbe(VecWdbeVDpch::DPCHAPPWDBEUNTRECDO, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO}; else this->mask = mask; this->ixVDo = ixVDo; }; string PnlWdbeUntRec::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWdbeUntRec::DpchAppDo::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWdbeUntRecDo"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wdbe"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo)); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWdbeUntRec::DpchEngData ******************************************************************************/ PnlWdbeUntRec::DpchEngData::DpchEngData() : DpchEngWdbe(VecWdbeVDpch::DPCHENGWDBEUNTRECDATA) { }; string PnlWdbeUntRec::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(CONTINF)) ss.push_back("continf"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(TAG)) ss.push_back("tag"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWdbeUntRec::DpchEngData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngWdbeUntRecData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF); if (continf.readXML(docctx, basexpath, true)) add(CONTINF); if (statapp.readXML(docctx, basexpath, true)) add(STATAPP); if (statshr.readXML(docctx, basexpath, true)) add(STATSHR); if (tag.readXML(docctx, basexpath, true)) add(TAG); } else { continf = ContInf(); statapp = StatApp(); statshr = StatShr(); tag = Tag(); }; };
[ "aw@mpsitech.com" ]
aw@mpsitech.com
245e4e0a0cdada62623b8ab460736126ae047226
b2531eced9be01fe6c8daf6949633454f24db47f
/Алгоритмы_обработки_данных/Деравья поиска/search_tree.cpp
ac21d9a1eb82ccf4cb89f3e1197fa51e18f2d981
[]
no_license
CheretaevIvan/VisualStudioProjects
6f7575c97ead4b118a21d70c5a3ba1895e955cb5
abdcac001e0d73387e2f7a704b8ea69e30ade2be
refs/heads/master
2021-01-10T18:17:30.379719
2016-03-20T21:10:21
2016-03-20T21:10:21
54,338,383
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,230
cpp
#include "search_tree.h" int CompareData(Data a, Data b){ return a.data - b.data; } void PrintData(Data* data){ printf("%"PRIi32, (*data).data); } void MakeTree(PNode *Head, Data data){ AddNode(Head, data); } void AddNode(PNode *Head, Data data){ PNode newNode = (PNode)malloc(sizeof(Node)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; newNode->parent = NULL; PNode parentNode = NULL; PNode p = *Head; while (p){ parentNode = p; if (CompareData(data, p->data) < 0) p = p->left; else p = p->right; } if (!parentNode){ *Head = newNode; } else{ newNode->parent = parentNode; if (CompareData(data, parentNode->data) < 0){ parentNode->left = newNode; } else{ parentNode->right = newNode; } } } void PrintNode(PNode *Tree){ if (*Tree){ printf("Элемент: "); PrintData(&(*Tree)->data); if ((*Tree)->left){ printf(" Л: "); PrintData(&(*Tree)->left->data); } else printf(" Л: *"); if ((*Tree)->right){ printf(" П: "); PrintData(&(*Tree)->right->data); } else printf(" П: *"); printf("\n"); if ((*Tree)->left){ PrintNode(&(*Tree)->left); } if ((*Tree)->right){ PrintNode(&((*Tree)->right)); } } } void DelNode(PNode *Head, PNode node){ if (!node || !Head) return; PNode y = NULL; PNode x = NULL; if (!node->left || !node->right) y = node; else y = Next(node); if (y->left) x = y->left; else x = y->right; if (x) x->parent = y->parent; if (y == y->parent->left){ y->parent->left = x; } else y->parent->right = x; if (y != node){ node->data = y->data; DelNode(Head, y); } free(y); } PNode Max(PNode *Tree){ if (!Tree) return NULL; PNode p = *Tree; while (p->right) p = p->right; return p; } PNode Min(PNode *Tree){ if (!Tree) return NULL; PNode p = *Tree; while (p->left) p = p->left; return p; } PNode Next(PNode node){ return Min(&node->right); } PNode Prev(PNode node){ return Max(&node->left); } PNode Find(PNode *Tree, Data data){ if (!*Tree) return NULL; if (CompareData(data, (*Tree)->data) == 0) return *Tree; else if (CompareData(data, (*Tree)->data) < 0) return Find(&(*Tree)->left, data); else return Find(&(*Tree)->right, data); }
[ "ivan_cheretaev@inbox.ru" ]
ivan_cheretaev@inbox.ru
8c16e834588af2a047b283be17b653bbde5109d0
4763e7411bfbac0b3be8698e6ab42d16be749529
/carditem.cpp
ec0c09115c3d883ba7add73fdf9dedd23cbb83d7
[]
no_license
kouyk/DDZ
8732403c34d974b77c3bd8b04605e047f9515b4f
86ac5aaebd3bc0e0e009a2e13ab787a172bc34b5
refs/heads/master
2022-12-15T03:58:33.452926
2020-09-13T06:33:31
2020-09-13T06:33:31
293,142,174
1
0
null
null
null
null
UTF-8
C++
false
false
1,138
cpp
#include "carditem.h" CardItem::CardItem(DDZ::CardType card_type, QGraphicsItem *parent) : QGraphicsObject(parent) , c_type(card_type) , selected(false) { setAcceptedMouseButtons(Qt::LeftButton); pixmap.load(QString(QLatin1Literal(":/images/%1.svg")).arg(DDZ::cardToString(c_type))); } QRectF CardItem::boundingRect() const { return QRectF(-pixmap.width() / 2, -pixmap.height() / 2, pixmap.width(), pixmap.height()); } void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); if (!pixmap.isNull()) { painter->drawPixmap(QPointF(-pixmap.width() / 2, -pixmap.height() / 2), pixmap); // put a colour overlay if the current card is being selected if (selected) { QPainterPath path; path.addRoundedRect(boundingRect(), 9, 9); painter->fillPath(path, QBrush(QColor(128, 128, 255, 128))); } } else painter->drawRoundedRect(-111, -162, 223, 324, 5, 5); } void CardItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { Q_UNUSED(event) }
[ "skykinetic@stevenkou.xyz" ]
skykinetic@stevenkou.xyz
d40c12fc768b50baf07bb6b1a454f1edb8bd08ce
245ead46f526416d8e77042126c0c2485fe8041f
/src/exceptions/fatal_exception.hpp
38fe56af3ec2dd59ba5fd80815f7cc67cb6a2c77
[ "MIT" ]
permissive
minijackson/cssq
3fc73e044aa36ab6d645331b7688dc6bfa4d8ab7
32e887f87ffcf08ade3828399da991bf60749aaf
refs/heads/master
2020-05-07T14:20:23.496345
2015-07-24T16:17:45
2015-07-24T16:17:45
37,865,847
0
0
null
null
null
null
UTF-8
C++
false
false
490
hpp
#ifndef FATAL_EXCEPTION_HPP #define FATAL_EXCEPTION_HPP #include <exception> #include <system_error> /*! * \brief Basically an exception with an error code. */ class FatalException : public std::exception { public: FatalException(const char* errorMsg, std::error_code errorCode); FatalException(const FatalException& other) = default; virtual const char* what() const noexcept; std::error_code getCode() const; private: const char* errorMsg; std::error_code errorCode; }; #endif
[ "minijackson@riseup.net" ]
minijackson@riseup.net
040abbcb5bb0409121c12433257293336159ff2b
171f526da7797dedfc0430ed01639af89210116b
/src/ofxFpsSlider.h
907b919b451550f55d964348ff9071efde24a06e
[ "MIT" ]
permissive
Pitchless/annoianoids
14c938b6dcc2e598b6fbd64df0a73603b66cbf36
b041e4ff57ec314a230fcb6b89d39a30e029dfc7
refs/heads/master
2020-12-27T15:15:24.446186
2017-03-12T01:36:12
2017-03-12T01:36:12
46,178,665
0
0
null
null
null
null
UTF-8
C++
false
false
920
h
#pragma once #include "ofMain.h" #include "ofxBaseGui.h" class ofxFpsSlider: public ofxBaseGui { public: ofxFpsSlider(){} virtual ~ofxFpsSlider(){} ofxFpsSlider * setup( string _fpsName, float _max, float width = defaultWidth, float height = defaultHeight ); ofAbstractParameter & getParameter(){ return fps; } // Abstract methods we must implement virtual bool mouseMoved(ofMouseEventArgs & args){ return false; } virtual bool mousePressed(ofMouseEventArgs & args){ return false; } virtual bool mouseDragged(ofMouseEventArgs & args){ return false; } virtual bool mouseReleased(ofMouseEventArgs & args){ return false; } virtual bool setValue(float mx, float my, bool bCheckBounds){ return false; } virtual bool mouseScrolled(ofMouseEventArgs & args) { return false; } virtual void generateDraw() { } protected: float min, max; ofParameter<float> fps; virtual void render(); };
[ "markpitchless@gmail.com" ]
markpitchless@gmail.com
6b1ef4ab393200c15e708b157635af1fdc7a67d8
5bc07308cd2632244828012f68aa8044b91b6e2e
/practices/level1/p07_encrypt_decrypt/Level1P07_encrypt_decrypt.cpp
56689705ca652011807a540d7bd68b0d1fcd728d
[]
no_license
wuchiuwong/CCpp2016
be2be61fb1f94bcf29dcddf8cf3b8615e9d0ac4d
9ab2db6fc7a51d7500adfe33810b19e2803f9b94
refs/heads/master
2021-01-15T17:08:07.169392
2016-05-05T01:05:32
2016-05-05T01:05:32
53,306,010
0
0
null
2016-03-07T07:47:35
2016-03-07T07:47:35
null
GB18030
C++
false
false
1,248
cpp
//============================================================================ // Name : Level1P07_encrypt_decrypt.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <string> using namespace std; void showTitle(); void encrypt(int length,const char *p); void decrypt(int length,const char *p); int main() { showTitle(); return 0; } void showTitle(){ cout << "输入要操作的句子:" << endl; string tempWords; cin >> tempWords; const char *words = tempWords.data(); int length = strlen(words); cout << "请选择: 1.加密 2.解密" << endl; int choice; cin >> choice; switch(choice){ case 1: encrypt(length,words); break; case 2: decrypt(length,words); break; default: break; } } void encrypt(int length,const char *p){ cout << "加密内容:"; for(int i = 0;i < length;i++){ cout << char(p[i] + 1); } cout << "\n加密完毕" << endl; } void decrypt(int length,const char*p){ cout << "解密内容:"; for(int i = 0;i < length;i++){ cout << char(p[i] - 1); } cout << "\n解密完毕" << endl; }
[ "hycsoge@sina.com" ]
hycsoge@sina.com
60ccad864e06e65b85e85d69feae502cc7360065
7dc6ae44724954c1da0167d184051afef86965d7
/src/qt/sendcoinsentry.cpp
8b8e152bf818b0265b3fece6e6e38468bb6c8e2f
[ "MIT" ]
permissive
manishcoindevl/soloscoin
e1636c784f93f4bf6489dcb719a2f08846ac5c2f
d166fb50fcdcde8566ae8a81c314e682c20343e8
refs/heads/master
2021-07-10T22:51:22.235062
2017-10-10T09:22:08
2017-10-10T09:22:08
106,389,366
0
0
null
null
null
null
UTF-8
C++
false
false
4,447
cpp
#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> #include <QPainter> 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 valid SolosCoin address")); #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); } 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()); } } void SendCoinsEntry::paintEvent(QPaintEvent* evt) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); }
[ "deewakaar@gmail.com" ]
deewakaar@gmail.com
5fdf16a3c0344c40ea35ac42cf1918d0e5318cbe
a1f60f65f8d92f89bdb0bce03c12a588279267ca
/src/ui_interface.h
619b0e3d999657546819e3ab124cc7cb7ab8b5a1
[ "MIT" ]
permissive
IngenuityCoin/Ingenuity
e262eadc29e4485336dd04e978869e1501ff28f1
475289926e435a9939358c695f4f10d1503bfa0c
refs/heads/master
2020-04-04T19:14:51.892964
2019-03-11T12:11:49
2019-03-11T12:11:49
156,198,049
4
5
null
null
null
null
UTF-8
C++
false
false
4,653
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2012-2014 The Bitcoin developers // Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2018-2019 The Ingenuity developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UI_INTERFACE_H #define BITCOIN_UI_INTERFACE_H #include <stdint.h> #include <string> #include <boost/signals2/last_value.hpp> #include <boost/signals2/signal.hpp> class CBasicKeyStore; class CWallet; class uint256; /** General change type (added, updated, removed). */ enum ChangeType { CT_NEW, CT_UPDATED, CT_DELETED }; /** Signals for UI communication. */ class CClientUIInterface { public: /** Flags for CClientUIInterface::ThreadSafeMessageBox */ enum MessageBoxFlags { ICON_INFORMATION = 0, ICON_WARNING = (1U << 0), ICON_ERROR = (1U << 1), /** * Mask of all available icons in CClientUIInterface::MessageBoxFlags * This needs to be updated, when icons are changed there! */ ICON_MASK = (ICON_INFORMATION | ICON_WARNING | ICON_ERROR), /** These values are taken from qmessagebox.h "enum StandardButton" to be directly usable */ BTN_OK = 0x00000400U, // QMessageBox::Ok BTN_YES = 0x00004000U, // QMessageBox::Yes BTN_NO = 0x00010000U, // QMessageBox::No BTN_ABORT = 0x00040000U, // QMessageBox::Abort BTN_RETRY = 0x00080000U, // QMessageBox::Retry BTN_IGNORE = 0x00100000U, // QMessageBox::Ignore BTN_CLOSE = 0x00200000U, // QMessageBox::Close BTN_CANCEL = 0x00400000U, // QMessageBox::Cancel BTN_DISCARD = 0x00800000U, // QMessageBox::Discard BTN_HELP = 0x01000000U, // QMessageBox::Help BTN_APPLY = 0x02000000U, // QMessageBox::Apply BTN_RESET = 0x04000000U, // QMessageBox::Reset /** * Mask of all available buttons in CClientUIInterface::MessageBoxFlags * This needs to be updated, when buttons are changed there! */ BTN_MASK = (BTN_OK | BTN_YES | BTN_NO | BTN_ABORT | BTN_RETRY | BTN_IGNORE | BTN_CLOSE | BTN_CANCEL | BTN_DISCARD | BTN_HELP | BTN_APPLY | BTN_RESET), /** Force blocking, modal message box dialog (not just OS notification) */ MODAL = 0x10000000U, /** Do not print contents of message to debug log */ SECURE = 0x40000000U, /** Predefined combinations for certain default usage cases */ MSG_INFORMATION = ICON_INFORMATION, MSG_WARNING = (ICON_WARNING | BTN_OK | MODAL), MSG_ERROR = (ICON_ERROR | BTN_OK | MODAL) }; /** Show message box. */ boost::signals2::signal<bool(const std::string& message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeMessageBox; /** Progress message during initialization. */ boost::signals2::signal<void(const std::string& message)> InitMessage; /** Translate a message to the native language of the user. */ boost::signals2::signal<std::string(const char* psz)> Translate; /** Number of network connections changed. */ boost::signals2::signal<void(int newNumConnections)> NotifyNumConnectionsChanged; /** * New, updated or cancelled alert. * @note called with lock cs_mapAlerts held. */ boost::signals2::signal<void(const uint256& hash, ChangeType status)> NotifyAlertChanged; /** A wallet has been loaded. */ boost::signals2::signal<void(CWallet* wallet)> LoadWallet; /** Show progress e.g. for verifychain */ boost::signals2::signal<void(const std::string& title, int nProgress)> ShowProgress; /** New block has been accepted */ boost::signals2::signal<void(const uint256& hash)> NotifyBlockTip; /** New block has been accepted and is over a certain size */ boost::signals2::signal<void(int size, const uint256& hash)> NotifyBlockSize; /** Banlist did change. */ boost::signals2::signal<void (void)> BannedListChanged; }; extern CClientUIInterface uiInterface; /** * Translation function: Call Translate signal on UI interface, which returns a boost::optional result. * If no translation slot is registered, nothing is returned, and simply return the input. */ inline std::string _(const char* psz) { boost::optional<std::string> rv = uiInterface.Translate(psz); return rv ? (*rv) : psz; } #endif // BITCOIN_UI_INTERFACE_H
[ "44764450+IngenuityCoin@users.noreply.github.com" ]
44764450+IngenuityCoin@users.noreply.github.com
6ff34b7c6b398b47df77ffec5593d79d240abfb9
1e3e6526a92b721d378ae8d36a0709f7b8c541ed
/SimDisk/SimDisk/dir.cpp
83242dac53b1a7b387410cfbe2175c4f18972386
[ "Apache-2.0" ]
permissive
J-CIC/SimDisk
5c73a80537c3170b3e63782c653b2a93327801c8
b4d131b0728402150c81b529254b803b882f98ca
refs/heads/master
2021-03-27T14:28:38.761036
2018-02-26T12:53:20
2018-02-26T12:53:20
118,877,969
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
229
cpp
#include "stdafx.h" #include "dir.h" dir::dir() { } dir::~dir() { } dir::dir(string name, unsigned int id) { //¸´ÖÆÃû×Ö strncpy_s(dir_name, name.c_str(), 123); dir_name[123] = '\0';//×Ô¶¯½Ø¶Ï ino = id; }
[ "791863347@qq.com" ]
791863347@qq.com
c5c3cd657463b5687ae868b0eeefc435312b496a
05b144cbfdc8ddd4a5b48b19a8d2899f71901a79
/Binary Search/Graphical/Prog.cpp
5e9bffe3e49b8ce9357f54307eff4334b7f2fb3f
[]
no_license
sinairv/Cpp-Tutorial-Samples
6ce1a80d4f2acdfa58e9f6ac8c88469ea00ca3b6
13c177d4f1b87653d9ac8c7bd32ca2577bce10bb
refs/heads/master
2022-08-09T05:44:35.190486
2022-08-01T03:22:38
2022-08-01T03:22:38
3,058,213
357
218
null
2020-10-01T05:42:02
2011-12-27T18:36:25
C++
UTF-8
C++
false
false
1,891
cpp
#include <iostream> #include <iomanip> using namespace std; int binarySearch( int [], int, int, int, int ); void printHeader( int ); void printRow( int [], int, int, int, int ); int main() { const int arraySize = 15; int a[ arraySize ], key, result; for ( int i = 0; i < arraySize; i++ ) a[ i ] = 2 * i; // place some data in array cout << "Enter a number between 0 and 28: "; cin >> key; printHeader( arraySize ); result = binarySearch( a, key, 0, arraySize - 1, arraySize ); if ( result != -1 ) cout << '\n' << key << " found in array element " << result << endl; else cout << '\n' << key << " not found" << endl; return 0; } // Binary search int binarySearch( int b[], int searchKey, int low, int high, int size ) { int middle; while ( low <= high ) { middle = ( low + high ) / 2; printRow( b, low, middle, high, size ); if ( searchKey == b[ middle ] ) // match return middle; else if ( searchKey < b[ middle ] ) high = middle - 1; // search low end of array else low = middle + 1; // search high end of array } return -1; // searchKey not found } // Print a header for the output void printHeader( int size ) { cout << "\nSubscripts:\n"; for ( int i = 0; i < size; i++ ) cout << setw( 3 ) << i << ' '; cout << '\n'; for (int i = 1; i <= 4 * size; i++ ) cout << '-'; cout << endl; } // Print one row of output showing the current // part of the array being processed. void printRow( int b[], int low, int mid, int high, int size ) { for ( int i = 0; i < size; i++ ) if ( i < low || i > high ) cout << " "; else if ( i == mid ) // mark middle value cout << setw( 3 ) << b[ i ] << '*'; else cout << setw( 3 ) << b[ i ] << ' '; cout << endl; }
[ "sina.iravanian@gmail.com" ]
sina.iravanian@gmail.com
fd1288bd8a224070a24039be8e8e50ba9bbdaddd
cfec501e7ce2a36c91596757a98f8521d277af5b
/src/Solaris.NBody.Cuda/options.h
da7dae0c70c85b5e51b0f0fa9780c071d976c9ce
[]
no_license
suliaron/solaris.cuda
5bbb8a9a95d1e2758cee19d2aa82282aa08631da
d0ade67398986e6938a3e5a769f66f11e1cecbd6
refs/heads/master
2020-12-25T18:31:54.120573
2014-08-01T09:28:22
2014-08-01T09:28:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,876
h
#pragma once #include <cstdlib> #include "config.h" #include "integrator.h" #include "nbody.h" #include "ode.h" #include "pp_disk.h" class gas_disk; class number_of_bodies; class pp_disk; using namespace std; typedef enum frame_center { FRAME_CENTER_BARY, FRAME_CENTER_ASTRO } frame_center_t; typedef enum threshold { THRESHOLD_HIT_CENTRUM_DISTANCE, THRESHOLD_EJECTION_DISTANCE, THRESHOLD_COLLISION_FACTOR, THRESHOLD_N } threshold_t; class options { public: typedef enum integrator_type { INTEGRATOR_EULER, INTEGRATOR_RUNGEKUTTA2, INTEGRATOR_OPT_RUNGEKUTTA2, INTEGRATOR_RUNGEKUTTA4, INTEGRATOR_OPT_RUNGEKUTTA4, INTEGRATOR_RUNGEKUTTAFEHLBERG78, INTEGRATOR_RUNGEKUTTANYSTROM, INTEGRATOR_OPT_RUNGEKUTTANYSTROM } integrator_type_t; public: bool verbose; //!< print more information to the screen or log file int n; // Number of bodies ttt_t dt; // Initial time step var_t buffer_radius; // collision buffer bool_t printout; // Printout enabled bool_t printoutToFile; // Printout to file ttt_t printoutPeriod; // Printout period ttt_t printoutStep; // Printout step size ttt_t printoutLength; // Printout length string printoutDir; // Printout directory string filename; // Input file name number_of_bodies *nBodies; gas_disk *gasDisk; bool_t adaptive; // Adaptive step size bool_t file; // Input file supplied int filen; // Number of entries in input file bool_t random; // Generate random data //! holds the path of the file containing the parameters of the simulation string parameters_filename; string parameters_path; //! holds the path of the file containing the parameters of the nebula string gasdisk_filename; string gasDisk_path; //! holds the path of the file containing the data of the bodies string bodylist_filename; string bodylist_path; //! holds a copy of the file containing the parameters of the simulation string parameters_str; //! holds a copy of the file containing the parameters of the nebula string gasDisk_str; //! name of the simulation string sim_name; //! description of the simulation string sim_desc; //! the center of the reference frame (bary or astro centric frame) frame_center_t fr_cntr; //! type of the integrator integrator_type_t inttype; //! tolerance/eps/accuracy of the simulation var_t tolerance; //! start time of the simulation [day] ttt_t start_time; //! length of the simulation [day] ttt_t sim_length; //! stop time of the simulation [day] (= start_time + sim_length) ttt_t stop_time; //! interval between two succesive output epoch [day] ttt_t output_interval; //! the hit centrum distance: inside this limit the body is considered to have hitted the central body and removed from the simulation [AU] //! the ejection distance: beyond this limit the body is removed from the simulation [AU] //! two bodies collide when their mutual distance is smaller than the sum of their radii multiplied by this number. Real physical collision corresponds to the value of 1.0. //! Contains the threshold values: hit_centrum_dst, ejection_dst, collision_factor var_t h_cst_common[THRESHOLD_N]; public: options(int argc, const char** argv); ~options(); static void print_usage(); ode* create_ode(); nbody* create_nbody(); pp_disk* create_pp_disk(); integrator* create_integrator(ode* f); private: void create_default_options(); void parse_options(int argc, const char** argv); void parse_params(string &input, void *data, void (*setter)(string& key, string& value, void* data, bool verbose)); void load(string& path, string& result); void get_number_of_bodies(string& path); void initial_condition(nbody* nb); };
[ "a.suli@astro.elte.hu" ]
a.suli@astro.elte.hu
b0c3c182858ce10c48c0abdd62d23d40a0a21149
d93159d0784fc489a5066d3ee592e6c9563b228b
/RecoJets/JetProducers/interface/JetSpecific.h
42635a4bf29190aeaeaeeba4b04da378afec8b28
[]
permissive
simonecid/cmssw
86396e31d41a003a179690f8c322e82e250e33b2
2559fdc9545b2c7e337f5113b231025106dd22ab
refs/heads/CAallInOne_81X
2021-08-15T23:25:02.901905
2016-09-13T08:10:20
2016-09-13T08:53:42
176,462,898
0
1
Apache-2.0
2019-03-19T08:30:28
2019-03-19T08:30:24
null
UTF-8
C++
false
false
3,310
h
#ifndef RecoJets_JetProducers_interface_JetSpecific_h #define RecoJets_JetProducers_interface_JetSpecific_h #include "DataFormats/Candidate/interface/Candidate.h" #include "DataFormats/JetReco/interface/CaloJet.h" #include "DataFormats/JetReco/interface/PFJet.h" #include "DataFormats/JetReco/interface/GenJet.h" #include "DataFormats/JetReco/interface/TrackJet.h" #include "DataFormats/JetReco/interface/PFClusterJet.h" #include "DataFormats/JetReco/interface/BasicJet.h" #include "DataFormats/HcalDetId/interface/HcalSubdetector.h" #include "FWCore/Framework/interface/EventSetup.h" #include "Geometry/CaloTopology/interface/HcalTopology.h" class CaloSubdetectorGeometry; namespace reco { //______________________________________________________________________________ // Helper methods to write out specific types /// Make CaloJet specifics. Assumes PseudoJet is made from CaloTowerCandidates bool makeSpecific(std::vector<reco::CandidatePtr> const & towers, const CaloSubdetectorGeometry& towerGeometry, reco::CaloJet::Specific* caloJetSpecific, const HcalTopology &topology); void writeSpecific(reco::CaloJet & jet, reco::Particle::LorentzVector const & p4, reco::Particle::Point const & point, std::vector<reco::CandidatePtr> const & constituents, edm::EventSetup const & c ); /// Make PFlowJet specifics. Assumes PseudoJet is made from ParticleFlowCandidates bool makeSpecific(std::vector<reco::CandidatePtr> const & particles, reco::PFJet::Specific* pfJetSpecific); void writeSpecific(reco::PFJet & jet, reco::Particle::LorentzVector const & p4, reco::Particle::Point const & point, std::vector<reco::CandidatePtr> const & constituents, edm::EventSetup const & c ); /// Make GenJet specifics. Assumes PseudoJet is made from HepMCCandidate bool makeSpecific(std::vector<reco::CandidatePtr> const & mcparticles, reco::GenJet::Specific* genJetSpecific); void writeSpecific(reco::GenJet & jet, reco::Particle::LorentzVector const & p4, reco::Particle::Point const & point, std::vector<reco::CandidatePtr> const & constituents, edm::EventSetup const & c ); /// Make TrackJet. Assumes constituents point to tracks, through RecoChargedCandidates. void writeSpecific(reco::TrackJet & jet, reco::Particle::LorentzVector const & p4, reco::Particle::Point const & point, std::vector<reco::CandidatePtr> const & constituents, edm::EventSetup const & c ); /// Make PFClusterJet. Assumes PseudoJet is made from PFCluster void writeSpecific(reco::PFClusterJet & jet, reco::Particle::LorentzVector const & p4, reco::Particle::Point const & point, std::vector<reco::CandidatePtr> const & constituents, edm::EventSetup const & c ); /// Make BasicJet. Assumes nothing about the jet. void writeSpecific(reco::BasicJet & jet, reco::Particle::LorentzVector const & p4, reco::Particle::Point const & point, std::vector<reco::CandidatePtr> const & constituents, edm::EventSetup const & c ); /// converts eta to the corresponding HCAL subdetector. HcalSubdetector hcalSubdetector(int iEta, const HcalTopology &topology); } #endif
[ "giulio.eulisse@gmail.com" ]
giulio.eulisse@gmail.com
48a15351c660b3a4c7403111614f4414ba69339f
3cf9e141cc8fee9d490224741297d3eca3f5feff
/C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-6492.cpp
3453b74c1190eb37700fffd03f0a08bef57b8815
[]
no_license
TeamVault/tauCFI
e0ac60b8106fc1bb9874adc515fc01672b775123
e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10
refs/heads/master
2023-05-30T20:57:13.450360
2021-06-14T09:10:24
2021-06-14T09:10:24
154,563,655
0
1
null
null
null
null
UTF-8
C++
false
false
2,798
cpp
struct c0; void __attribute__ ((noinline)) tester0(c0* p); struct c0 { bool active0; c0() : active0(true) {} virtual ~c0() { tester0(this); active0 = false; } virtual void f0(){} }; void __attribute__ ((noinline)) tester0(c0* p) { p->f0(); } struct c1; void __attribute__ ((noinline)) tester1(c1* p); struct c1 { bool active1; c1() : active1(true) {} virtual ~c1() { tester1(this); active1 = false; } virtual void f1(){} }; void __attribute__ ((noinline)) tester1(c1* p) { p->f1(); } struct c2; void __attribute__ ((noinline)) tester2(c2* p); struct c2 : virtual c0 { bool active2; c2() : active2(true) {} virtual ~c2() { tester2(this); c0 *p0_0 = (c0*)(c2*)(this); tester0(p0_0); active2 = false; } virtual void f2(){} }; void __attribute__ ((noinline)) tester2(c2* p) { p->f2(); if (p->active0) p->f0(); } struct c3; void __attribute__ ((noinline)) tester3(c3* p); struct c3 : c1, virtual c0 { bool active3; c3() : active3(true) {} virtual ~c3() { tester3(this); c0 *p0_0 = (c0*)(c3*)(this); tester0(p0_0); c1 *p1_0 = (c1*)(c3*)(this); tester1(p1_0); active3 = false; } virtual void f3(){} }; void __attribute__ ((noinline)) tester3(c3* p) { p->f3(); if (p->active1) p->f1(); if (p->active0) p->f0(); } struct c4; void __attribute__ ((noinline)) tester4(c4* p); struct c4 : virtual c3, c2, virtual c0 { bool active4; c4() : active4(true) {} virtual ~c4() { tester4(this); c0 *p0_0 = (c0*)(c3*)(c4*)(this); tester0(p0_0); c0 *p0_1 = (c0*)(c2*)(c4*)(this); tester0(p0_1); c0 *p0_2 = (c0*)(c4*)(this); tester0(p0_2); c1 *p1_0 = (c1*)(c3*)(c4*)(this); tester1(p1_0); c2 *p2_0 = (c2*)(c4*)(this); tester2(p2_0); c3 *p3_0 = (c3*)(c4*)(this); tester3(p3_0); active4 = false; } virtual void f4(){} }; void __attribute__ ((noinline)) tester4(c4* p) { p->f4(); if (p->active1) p->f1(); if (p->active2) p->f2(); if (p->active0) p->f0(); if (p->active3) p->f3(); } int __attribute__ ((noinline)) inc(int v) {return ++v;} int main() { c0* ptrs0[25]; ptrs0[0] = (c0*)(new c0()); ptrs0[1] = (c0*)(c2*)(new c2()); ptrs0[2] = (c0*)(c3*)(new c3()); ptrs0[3] = (c0*)(c3*)(c4*)(new c4()); ptrs0[4] = (c0*)(c2*)(c4*)(new c4()); ptrs0[5] = (c0*)(c4*)(new c4()); for (int i=0;i<6;i=inc(i)) { tester0(ptrs0[i]); delete ptrs0[i]; } c1* ptrs1[25]; ptrs1[0] = (c1*)(new c1()); ptrs1[1] = (c1*)(c3*)(new c3()); ptrs1[2] = (c1*)(c3*)(c4*)(new c4()); for (int i=0;i<3;i=inc(i)) { tester1(ptrs1[i]); delete ptrs1[i]; } c2* ptrs2[25]; ptrs2[0] = (c2*)(new c2()); ptrs2[1] = (c2*)(c4*)(new c4()); for (int i=0;i<2;i=inc(i)) { tester2(ptrs2[i]); delete ptrs2[i]; } c3* ptrs3[25]; ptrs3[0] = (c3*)(new c3()); ptrs3[1] = (c3*)(c4*)(new c4()); for (int i=0;i<2;i=inc(i)) { tester3(ptrs3[i]); delete ptrs3[i]; } c4* ptrs4[25]; ptrs4[0] = (c4*)(new c4()); for (int i=0;i<1;i=inc(i)) { tester4(ptrs4[i]); delete ptrs4[i]; } return 0; }
[ "ga72foq@mytum.de" ]
ga72foq@mytum.de
3b7deb6c3bc569f4b0981ec8e5d82490093f5530
ee77e33c0078e580566250c4566faefa7038feec
/projets_decomposés/color_tracking/color_tracking.cpp
8da5e58eb59f8913e70d550f8b11429f6465a472
[ "BSD-3-Clause" ]
permissive
AresRobotic/Vision
527116f970b55e8904b81af4b8a852b075765b93
7fde7f411ab85efd7f2e88a53157f6e373a41b3f
refs/heads/master
2021-01-17T17:00:35.134653
2014-04-15T21:06:14
2014-04-15T21:06:14
13,880,818
2
0
null
null
null
null
UTF-8
C++
false
false
4,836
cpp
/*#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp>*/ #include "opencv2/opencv.hpp" #include "../myfunctions.hpp" #include <iostream> #include <sstream> #include <string> #include <iostream> #include <fstream> using namespace std; using namespace cv; int main(int argc, char* argv[]) { cout << "OpenCV version : " << CV_VERSION << endl; int h1 = 0; int s1 = 115; int v1 = 144; int h2 = 12 ; int s2 = 255; int v2 = 255; //x and y values for the location of the object image int u = 0, v = 0; //Real point value //int X,Y = 0; // If object if found bool objectFound ; bool trackObjects = true; bool useErodeAndDilate = true; //matrix storage for HSV image, input and filtered Mat HSV, cameraFeed, threshold ; /*imagePoints = Generate2DPoints(); objectPoints = Generate3DPoints(); GenerateExtrinsecMatrix("intrinsec.yml",imagePoints,objectPoints,tvec,rvec,rotationMatrix, cameraMatrix) ; */ //some boolean variables for different functionality within this //program /*if( argc < 2 ){ printf( "\n Error! No video data!!! \n" ); return -1; }*/ //video capture object to acquire webcam feed camera 1 VideoCapture capture; capture.open(1); if (!capture.isOpened()) // if not success, try default cam { cout << "Camera 1 is not here ; try camera 0" << endl; capture.open(0); if (!capture.isOpened()) { cout << "Cannot open the video cam" << endl; return -1; } } //set height and width of capture frame //capture.set(CV_CAP_PROP_FRAME_WIDTH,FRAME_WIDTH); //capture.set(CV_CAP_PROP_FRAME_HEIGHT,FRAME_HEIGHT); //initialisation for chessboard calibration std::vector<Point3f> objectPoints ; std::vector<Point2f> ptvec ; Mat tvec(3,1,DataType<double>::type); Mat rvec(3,1,DataType<double>::type); Mat cameraMatrix(3,3,cv::DataType<double>::type) ; Mat rotationMatrix(3,3,cv::DataType<double>::type); //Chessboard size Size chessSize = cvSize(9,6) ; //Generate 3D points that correspond to the chessboard generate3DPointsFromCheesboard(chessSize,2.3,objectPoints); /*while(waitKey(30) != 27){ capture.read(cameraFeed); String text = "Put the chessboard and press echap" ; //cout << text ; drawSimpleText(cameraFeed,text) ; //putText(cameraFeed,"Pressez echap après avoir placé le damier",Point(0,50),1,2,Scalar(0,0,255),2); imshow("Waiting for chessboard", cameraFeed); }*/ destroyWindow("Waiting for chessboard" ); //Loop while not finding a chessboard of size "chessSize" and not pressed "echap" /*while(waitKey(30) != 27){ capture.read(cameraFeed); bool found = generate2DPointsFromCheesboard(cameraFeed,chessSize,ptvec) ; imshow("Image View", cameraFeed); if (found) { cout << "chessboard found" << endl; break; } // 0.5 s delay //waitKey(100) ; //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop } //Generate extrinsec parameter GenerateExtrinsecMatrix("intrinsec.yml",ptvec,objectPoints,tvec,rvec,rotationMatrix, cameraMatrix) ; */ // Loop for the tracking while(1){ //create slider bars for HSV filtering createHSVTrackbars("Trackbars",&h1,&h2,&s1,&s2,&v1,&v2); //store image to matrix capture.read(cameraFeed); //convert frame from BGR to HSV colorspace cvtColor(cameraFeed,HSV,COLOR_BGR2HSV); //filter HSV image between values and store filtered image to threshold matrix inRange(HSV,Scalar(h1,s1,v1),Scalar(h2,s2,v2),threshold); //perform morphological operations on thresholded image to eliminate noise and emphasize the filtered object(s) if(useErodeAndDilate) erodeAndDilate(threshold); //pass in thresholded frame to our object tracking function //this function will return the x and y coordinates of the //filtered object if(trackObjects) { objectFound = trackFilteredObject(u,v,threshold,cameraFeed); if (objectFound) { Point2f uv(u,v) ; Point3f projectedObjectPoints = generate3DFrom2DPoints(Point2f(u,v), rotationMatrix,cameraMatrix,tvec,0) ; putText(cameraFeed,"Tracking Object",Point(0,50),2,1,Scalar(0,125,125),1); //draw object location on screen drawTarget(u,v,projectedObjectPoints.x,projectedObjectPoints.y,cameraFeed); //drawTarget(u,v,1,2,cameraFeed); } } //show frames imshow("Thresholded Image",threshold); imshow("Original Image",cameraFeed); //Ajout couleur par la souris //SetMouseCallback("Original Image", getObjectColor); //"After Morphological Operations" //delay 30ms so that screen can refresh. //image will not appear without this waitKey() command waitKey(10); /*int c = cvWaitKey(15); //If 'ESC' is pressed, break the loop if((char)c==27 ){ break; }*/ } return 0; }
[ "theo.segonds@gmail.com" ]
theo.segonds@gmail.com
d597061dbdc6583b566e40a1ec421cfb07077eee
7ede4710c51ee2cad90589e274a5bd587cfcd706
/lsystem-main/rectangle.h
5d502954231b78efdfab17104c5b7f66173138ff
[]
no_license
sid1980/l-system-for-osg
7809b0315d4fd7bcfd49fd11129a273f49ea51d1
4931cc1cb818ee7c9d4d25d17ffdaa567a93e8fa
refs/heads/master
2023-03-16T00:21:40.562005
2011-01-09T16:33:46
2011-01-09T16:33:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
401
h
#ifndef RECTANGLE_H_ #define RECTANGLE_H_ #include "movingturtle.h" namespace AP_LSystem { class Rectangle : public MovingTurtle { private: public: Rectangle(void){}; ~Rectangle(void){}; virtual int drawStep( double ); virtual int initialize( ) {return LS_OK;} virtual int finalize( ) {return LS_OK;} // virtual void setProperties( TurtleProperties p ); }; } #endif
[ "marek@pasicnyk.com@3a20e578-abf7-dd4e-6256-36cca5c9e6b5" ]
marek@pasicnyk.com@3a20e578-abf7-dd4e-6256-36cca5c9e6b5
7cef661f5e20e5725eac9ed7a060385f86248d50
0d8754038e3d4de11ccb39690be9cb18754b892f
/Game/Source/States/Playing.cpp
6c045e327539a54e8cbd78ed24cbc052613d880c
[]
no_license
Florian-Heringa/Minecraft-CPP-OpenGL
50496929085e5046c450034f132cd9f67973ce0a
b35d22a880a3be21047d58aa31fb278aec25b22a
refs/heads/master
2021-01-18T19:33:29.506294
2017-09-26T22:34:26
2017-09-26T22:34:35
100,533,234
0
0
null
null
null
null
UTF-8
C++
false
false
1,115
cpp
#include "Playing.h" #include <iostream> #include <SFML/System/Clock.hpp> std::vector<GLfloat> vertexPositions = { 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, }; std::vector<GLfloat> textureCoords = { 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, }; std::vector<GLuint> indices = { 0, 1, 2, 2, 3, 0 }; namespace State { sf::Clock clock; Playing::Playing(Application& application) : Game_State (application) , m_model (vertexPositions, textureCoords, indices) { m_texture.load("4-letters"); } void Playing::input() { } void Playing::update() { } void Playing::draw() { // First bind shader, before uniform variable can be set m_shader.bind(); // Set uniform time variable m_shader.setTime(clock.getElapsedTime().asSeconds()); m_model.bind(); m_texture.bind(); glDrawElements(GL_TRIANGLES, m_model.getIndicesCount(), GL_UNSIGNED_INT, nullptr); m_model.unbind(); m_shader.unbind(); m_texture.unbind(); } }
[ "florian_music@hotmail.com" ]
florian_music@hotmail.com
4b0480eee2c582f6ca067a1d83522cb50ce7800b
8f838e4daa59321e8283d17dc4635c26649cb594
/UFU 3° Terceira Lista/atividade 9.cpp
8f9e3364067cafd7edbc833aac2fac6036a2b941
[]
no_license
Izabela-dsn/Listas-UFU
28c67cd75586bdc8165d79e37be1653252a5e905
a711fa8f2fc73c23ae4fe278e8aec3bcd2c98ac7
refs/heads/master
2023-03-10T03:39:32.078341
2021-02-25T00:46:34
2021-02-25T00:46:34
136,973,159
0
0
null
null
null
null
ISO-8859-1
C++
false
false
343
cpp
#include <stdio.h> #include <conio.h> #include <locale.h> int main(){ setlocale(LC_ALL,"portuguese"); int i=0, n, h=1; printf("Digite quantos números ímpares deseja mostrar: "); scanf("%d", &n); printf("\nEsses são os números:\n"); while(n>0 && i<n){ printf("%d\t", h); i++; h=h+2; } return 0; getch(); }
[ "izabeladasilva10@gmail.com" ]
izabeladasilva10@gmail.com
6f8513f43c352b1935a3f7a7cd800600b82e584b
a1474c1206834c7668e44189b9580aab70fd818b
/examples/For PRO users/BLE_scan/src/main.cpp
7b88b0960d204203529aa19e313e0c4345e6adf9
[]
no_license
Qmobot/qchip
98eaa9fb78c53fcf67181daa394d93c9b473afb6
ee25202d0627d53595b5f41b5ec249f8f78ee9f8
refs/heads/master
2021-09-11T07:13:51.480556
2021-08-26T12:31:07
2021-08-26T12:31:07
223,148,993
0
0
null
null
null
null
UTF-8
C++
false
false
1,050
cpp
#include "qmobot.h" int scanTime = 5; //In seconds BLEScan* pBLEScan; class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { void onResult(BLEAdvertisedDevice advertisedDevice) { Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str()); } }; void setup() { Serial.begin(115200); Serial.println("Scanning..."); BLEDevice::init(""); pBLEScan = BLEDevice::getScan(); //create new scan pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster pBLEScan->setInterval(100); pBLEScan->setWindow(99); // less or equal setInterval value } void loop() { // put your main code here, to run repeatedly: BLEScanResults foundDevices = pBLEScan->start(scanTime, false); Serial.print("Devices found: "); Serial.println(foundDevices.getCount()); Serial.println("Scan done!"); pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory delay(2000); }
[ "dr.cleverest@gmail.com" ]
dr.cleverest@gmail.com
08cd86a2d94557bae86b98cced05ee9625484d5d
27b926e35657a35cc29b8a525ca5a662ad66b1de
/DotWars2/DotWars2/source/Actor/ActorManager.cpp
1958d82dd7fcff655cbec6fbb60328be3ab7be35
[]
no_license
KataSin/DotWars2Project
210cfa6809fdb44a6cd946ba1d478f1e19083262
aa21e429906c4e26a7ad3d5a3f35a0074030edc2
refs/heads/master
2021-01-01T18:35:06.906622
2018-04-27T06:23:00
2018-04-27T06:23:00
98,367,050
0
0
null
null
null
null
UTF-8
C++
false
false
693
cpp
#include "ActorManager.h" #include <algorithm> ActorManager::ActorManager() { } ActorManager::~ActorManager() { } void ActorManager::Add(ActorPtr actor) { mActors.push_back(actor); } std::list<ActorPtr> ActorManager::GetActors() { return mActors; } void ActorManager::Start() { std::for_each(mActors.begin(), mActors.end(), [](ActorPtr actor) {actor->Start(); }); } void ActorManager::Update() { std::for_each(mActors.begin(), mActors.end(), [](ActorPtr actor) {actor->Update(); }); mActors.remove_if([](ActorPtr actor) {return actor->GetIsDead(); }); } void ActorManager::Draw() const { std::for_each(mActors.begin(), mActors.end(), [](ActorPtr actor) {actor->Draw(); }); }
[ "ktok223@gmail.com" ]
ktok223@gmail.com
5c6215ea8854a403fdd175b1164642a534620284
dc1003ed0cb7e87ffff7c4f4f8f3b102f14b37d2
/robot/include/SimulationBridge.h
07dafd619346bd8718462e7fd0f626321e3d1b05
[ "MIT" ]
permissive
slovak194/cheetah-software-change
4cd67376fd9d5952e6916189cb6704f12456b79f
e33ada2dc1ba6638ba82cd2801169883b6e27ef2
refs/heads/master
2022-12-08T11:32:18.443177
2020-09-07T11:43:48
2020-09-07T11:43:48
295,845,799
23
7
MIT
2020-09-15T20:48:22
2020-09-15T20:48:21
null
UTF-8
C++
false
false
1,448
h
/*! @file SimulationBridge.h * @brief The SimulationBridge runs a RobotController and connects it to a * Simulator, using shared memory. It is the simulation version of the * HardwareBridge. */ #ifndef PROJECT_SIMULATIONDRIVER_H #define PROJECT_SIMULATIONDRIVER_H #include <thread> #include "ControlParameters/RobotParameters.h" #include "RobotRunner.h" #include "SimUtilities/SimulatorMessage.h" #include "Types.h" #include "Utilities/PeriodicTask.h" #include "Utilities/SharedMemory.h" #include "gamepad/Gamepad.hpp" class SimulationBridge { public: explicit SimulationBridge(RobotController* robot_ctrl){ _fakeTaskManager = new PeriodicTaskManager; _robotRunner = new RobotRunner(robot_ctrl, _fakeTaskManager, 0, "robot-task"); _userParams = robot_ctrl->getUserControlParameters(); } void run(); void handleControlParameters(); void runRobotControl(); ~SimulationBridge() { delete _fakeTaskManager; delete _robotRunner; } private: PeriodicTaskManager taskManager; Gamepad _gamepad; //游戏手柄 bool _firstControllerRun = true; PeriodicTaskManager* _fakeTaskManager = nullptr; RobotRunner* _robotRunner = nullptr; SimulatorMode _simMode; SharedMemoryObject<SimulatorSyncronizedMessage> _sharedMemory; RobotControlParameters _robotParams; ControlParameters* _userParams = nullptr; u64 _iterations = 0; }; #endif // PROJECT_SIMULATIONDRIVER_H
[ "18813176186@163.com" ]
18813176186@163.com
96994e1aef95cafd224026820fae70b66da35386
83915113ecde3481d6532a83cbfecb982187eab8
/templates/philanda.cpp
f07a6c9aa7456d38d3b7cb0ea4bf635814f0b9ff
[]
no_license
bansalshubh/Url-Shortener
d8b439ce72028decca56d270ebef519fc396c83a
8536af83b861d7aaf7faa9550fd42faee57da3f1
refs/heads/master
2023-06-12T04:52:20.784746
2021-07-07T03:41:47
2021-07-07T03:41:47
383,664,757
2
0
null
null
null
null
UTF-8
C++
false
false
65,885
cpp
<!-- saved from url=(0065)https://www.tcscodevita.com/CodevitaV9/OpenCodeEditor?problemid=A --> <html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <link rel="stylesheet" href="./philanda_files/code_editor.css"> <link rel="stylesheet" href="./philanda_files/codemirror.css"> <link rel="stylesheet" href="./philanda_files/simplescrollbars.css"> <script src="./philanda_files/jquery-2.0.3.js.download"></script> <link rel="stylesheet" href="./philanda_files/notifications.css"> <script src="./philanda_files/notifications.js.download"></script> <script src="./philanda_files/codemirror.js.download"></script> <script src="./philanda_files/editor_main_script.js.download"></script> <script src="./philanda_files/simplescrollbars.js.download"></script> <script src="./philanda_files/show-hint.js.download"></script> <script src="./philanda_files/anyword-hint.js.download"></script> <script> var problemID = 'A'; var userid = '2947799'; var contestEndTime = '2020-06-20 00:05:23'; var prefix = ``; var suffix = ``; </script> <script> var countdownInterval = undefined; function counter(timeString){ endTime = new Date(timeString); var localtime=new Date(); var offset=localtime.getTimezoneOffset(); var serveroffset=-330; var difference=serveroffset-offset; // In minutes var offsetInMilliseconds=difference*60*1000; //In Milliseconds var longTime = ((endTime.getTime()+ offsetInMilliseconds)- localtime.getTime()) / 1000; if(longTime >=0){ $('.timer #second').html( ((longTime % 60 < 10) ? "0" : "") + parseInt(longTime % 60)); longTime /= 60; $('.timer #minute').html( ((longTime % 60 < 10) ? "0" : "") + parseInt(longTime % 60)); longTime /=60; $('.timer #hour').html( ((longTime % 24 < 10) ? "0" : "") + parseInt(longTime % 24)); } else{ $('.timer #hour').html("00"); $('.timer #minute').html("00"); $('.timer #second').html("00"); clearInterval(countdownInterval); } } $(document).ready(()=>{ counter(contestEndTime); countdownInterval = setInterval(()=>{ counter(contestEndTime); },500); }); </script> <link href="./philanda_files/jquery.tagit.css" rel="stylesheet" type="text/css"> <link href="./philanda_files/tagit.ui-zendesk.css" rel="stylesheet" type="text/css"> <!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> --> <script src="./philanda_files/jquery-ui.min.js.download" type="text/javascript" charset="utf-8"></script> <script src="./philanda_files/tag-it.js.download" type="text/javascript" charset="utf-8"></script> <!-- <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css"> --> <script type="text/javascript"> $(document).ready(function() { initializeAttributionsUI(); }); //Below code by Mitul to disable Left Click (ultimately inspect element) and disable firebug (F12) /*$(document).keydown(function(event){ if(event.keyCode==123){ alert('F12 is disabled'); return false; } else if (event.ctrlKey && event.shiftKey && event.keyCode==73){ alert('This is disabled'); return false; } }); $(document).on("contextmenu",function(e){ alert('right click is disabled'); e.preventDefault(); });*/ </script> <!-- <link rel="stylesheet" href="css/code_editor/tagify.css"> <link rel="stylesheet" href="css/code_editor/tagifysync.css"> <script src="JS/code_editor/tagify.min.js"></script> <script src="JS/code_editor/jQuery.tagify.min.js"></script> <script data-name="textarea"> (function(){ var input = document.querySelector('textarea[name=tags2]'), tagify = new Tagify(input, { enforceWhitelist : true, callbacks : { add : console.log, // callback when adding a tag remove : console.log // callback when removing a tag } }); })() </script> <style> p{ line-height:1.4; } code{ padding:2px 3px; background:lightyellow; } pre code{ background:none; padding:0; } .forkLink{ top:1em; right:1em; } section > .rightSide{ position: sticky; top: 1em; align-self: start; } .tagify{ min-width:400px; max-width:600px; margin: 1.5em 0; } /* for disabling the script */ label{ position:fixed; bottom:10px; right:10px; cursor:pointer; font:600 .8em Arial; } .disabled tags{ max-width:none; min-width:0; border:0; } .disabled tags tag, .disabled tags div{ display:none !important; } .disabled tags + input, .disabled tags + textarea{ display:initial; border:1px inset; } /* Outside of the box */ .tagify--outside{ border: 0; padding: 0; margin: 0; } .tagify__input--outside{ display: block; max-width: 600px; border: 1px solid #DDD; margin-top: 1.5em; } /* Countries' flags */ .tagify__dropdown.extra-properties .tagify__dropdown__item{ color:#777; } .tagify__dropdown.extra-properties .tagify__dropdown__item:hover{ color:black; background:#F1F1F1; } .tagify__dropdown.extra-properties .tagify__dropdown__item > img{ display: inline-block; vertical-align: middle; height: 20px; transform: scale(.75); margin-right: 5px; border-radius: 2px; transition: .12s ease-out; } .tagify__dropdown.extra-properties .tagify__dropdown__item--active > img, .tagify__dropdown.extra-properties .tagify__dropdown__item:hover > img{ transform: none; margin-right: 12px; } .tagify.countries .tagify__input{ min-width:175px; } .tagify.countries tag{ white-space:nowrap; } .tagify.countries tag img{ display: inline-block; height: 16px; margin-right: 3px; border-radius: 2px; } /* .tagify.readonlyMix > tag:not([readonly]) div::before{ background:#d3e2e2; } */ .tagify__input .borderd-blue > div::before{ border:2px solid #8DAFFA; } </style> --> <script class="resource_syntax_highlight">// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function Context(indented, column, type, info, align, prev) { this.indented = indented; this.column = column; this.type = type; this.info = info; this.align = align; this.prev = prev; } function pushContext(state, col, type, info) { var indent = state.indented; if (state.context && state.context.type == "statement" && type != "statement") indent = state.context.indented; return state.context = new Context(indent, col, type, info, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } function typeBefore(stream, state, pos) { if (state.prevToken == "variable" || state.prevToken == "type") return true; if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true; if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true; } function isTopScope(context) { for (;;) { if (!context || context.type == "top") return true; if (context.type == "}" && context.prev.info != "namespace") return false; context = context.prev; } } CodeMirror.defineMode("clike", function(config, parserConfig) { var indentUnit = config.indentUnit, statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, dontAlignCalls = parserConfig.dontAlignCalls, keywords = parserConfig.keywords || {}, types = parserConfig.types || {}, builtin = parserConfig.builtin || {}, blockKeywords = parserConfig.blockKeywords || {}, defKeywords = parserConfig.defKeywords || {}, atoms = parserConfig.atoms || {}, hooks = parserConfig.hooks || {}, multiLineStrings = parserConfig.multiLineStrings, indentStatements = parserConfig.indentStatements !== false, indentSwitch = parserConfig.indentSwitch !== false, namespaceSeparator = parserConfig.namespaceSeparator, isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/, numberStart = parserConfig.numberStart || /[\d\.]/, number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i, isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/, isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/; var curPunc, isDefKeyword; function tokenBase(stream, state) { var ch = stream.next(); if (hooks[ch]) { var result = hooks[ch](stream, state); if (result !== false) return result; } if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (isPunctuationChar.test(ch)) { curPunc = ch; return null; } if (numberStart.test(ch)) { stream.backUp(1) if (stream.match(number)) return "number" stream.next() } if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {} return "operator"; } stream.eatWhile(isIdentifierChar); if (namespaceSeparator) while (stream.match(namespaceSeparator)) stream.eatWhile(isIdentifierChar); var cur = stream.current(); if (contains(keywords, cur)) { if (contains(blockKeywords, cur)) curPunc = "newstatement"; if (contains(defKeywords, cur)) isDefKeyword = true; return "keyword"; } if (contains(types, cur)) return "type"; if (contains(builtin, cur)) { if (contains(blockKeywords, cur)) curPunc = "newstatement"; return "builtin"; } if (contains(atoms, cur)) return "atom"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) {end = true; break;} escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = null; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return "comment"; } function maybeEOL(stream, state) { if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context)) state.typeAtEndOfLine = typeBefore(stream, state, stream.pos) } // Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false), indented: 0, startOfLine: true, prevToken: null }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) { maybeEOL(stream, state); return null; } curPunc = isDefKeyword = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment" || style == "meta") return style; if (ctx.align == null) ctx.align = true; if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false))) while (state.context.type == "statement") popContext(state); else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "}") { while (ctx.type == "statement") ctx = popContext(state); if (ctx.type == "}") ctx = popContext(state); while (ctx.type == "statement") ctx = popContext(state); } else if (curPunc == ctx.type) popContext(state); else if (indentStatements && (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") || (ctx.type == "statement" && curPunc == "newstatement"))) { pushContext(state, stream.column(), "statement", stream.current()); } if (style == "variable" && ((state.prevToken == "def" || (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) && isTopScope(state.context) && stream.match(/^\s*\(/, false))))) style = "def"; if (hooks.token) { var result = hooks.token(stream, state, style); if (result !== undefined) style = result; } if (style == "def" && parserConfig.styleDefs === false) style = "variable"; state.startOfLine = false; state.prevToken = isDefKeyword ? "def" : style || curPunc; maybeEOL(stream, state); return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass; var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; if (parserConfig.dontIndentStatements) while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info)) ctx = ctx.prev if (hooks.indent) { var hook = hooks.indent(state, ctx, textAfter); if (typeof hook == "number") return hook } var closing = firstChar == ctx.type; var switchBlock = ctx.prev && ctx.prev.info == "switch"; if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) { while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev return ctx.indented } if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1); if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit; return ctx.indented + (closing ? 0 : indentUnit) + (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0); }, electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/, blockCommentStart: "/*", blockCommentEnd: "*/", blockCommentContinue: " * ", lineComment: "//", fold: "brace" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } function contains(words, word) { if (typeof words === "function") { return words(word); } else { return words.propertyIsEnumerable(word); } } var cKeywords = "auto if break case register continue return default do sizeof " + "static else struct switch extern typedef union for goto while enum const volatile"; var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t"; function cppHook(stream, state) { if (!state.startOfLine) return false for (var ch, next = null; ch = stream.peek();) { if (ch == "\\" && stream.match(/^.$/)) { next = cppHook break } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) { break } stream.next() } state.tokenize = next return "meta" } function pointerHook(_stream, state) { if (state.prevToken == "type") return "type"; return false; } function cpp14Literal(stream) { stream.eatWhile(/[\w\.']/); return "number"; } function cpp11StringHook(stream, state) { stream.backUp(1); // Raw strings. if (stream.match(/(R|u8R|uR|UR|LR)/)) { var match = stream.match(/"([^\s\\()]{0,16})\(/); if (!match) { return false; } state.cpp11RawStringDelim = match[1]; state.tokenize = tokenRawString; return tokenRawString(stream, state); } // Unicode strings/chars. if (stream.match(/(u8|u|U|L)/)) { if (stream.match(/["']/, /* eat */ false)) { return "string"; } return false; } // Ignore this hook. stream.next(); return false; } function cppLooksLikeConstructor(word) { var lastTwo = /(\w+)::~?(\w+)$/.exec(word); return lastTwo && lastTwo[1] == lastTwo[2]; } // C#-style strings where "" escapes a quote. function tokenAtString(stream, state) { var next; while ((next = stream.next()) != null) { if (next == '"' && !stream.eat('"')) { state.tokenize = null; break; } } return "string"; } // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where // <delim> can be a string up to 16 characters long. function tokenRawString(stream, state) { // Escape characters that have special regex meanings. var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&'); var match = stream.match(new RegExp(".*?\\)" + delim + '"')); if (match) state.tokenize = null; else stream.skipToEnd(); return "string"; } function def(mimes, mode) { if (typeof mimes == "string") mimes = [mimes]; var words = []; function add(obj) { if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) words.push(prop); } add(mode.keywords); add(mode.types); add(mode.builtin); add(mode.atoms); if (words.length) { mode.helperType = mimes[0]; CodeMirror.registerHelper("hintWords", mimes[0], words); } for (var i = 0; i < mimes.length; ++i) CodeMirror.defineMIME(mimes[i], mode); } def(["text/x-csrc", "text/x-c", "text/x-chdr"], { name: "clike", keywords: words(cKeywords), types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " + "int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " + "uint32_t uint64_t"), blockKeywords: words("case do else for if switch while struct"), defKeywords: words("struct"), typeFirstDefinitions: true, atoms: words("NULL true false"), hooks: {"#": cppHook, "*": pointerHook}, modeProps: {fold: ["brace", "include"]} }); def(["text/x-c++src", "text/x-c++hdr"], { name: "clike", keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try explicit new " + "static_cast typeid catch operator template typename class friend private " + "this using const_cast inline public throw virtual delete mutable protected " + "alignas alignof constexpr decltype nullptr noexcept thread_local final " + "static_assert override"), types: words(cTypes + " bool wchar_t"), blockKeywords: words("catch class do else finally for if struct switch try while"), defKeywords: words("class namespace struct enum union"), typeFirstDefinitions: true, atoms: words("true false NULL"), dontIndentStatements: /^template$/, isIdentifierChar: /[\w\$_~\xa1-\uffff]/, hooks: { "#": cppHook, "*": pointerHook, "u": cpp11StringHook, "U": cpp11StringHook, "L": cpp11StringHook, "R": cpp11StringHook, "0": cpp14Literal, "1": cpp14Literal, "2": cpp14Literal, "3": cpp14Literal, "4": cpp14Literal, "5": cpp14Literal, "6": cpp14Literal, "7": cpp14Literal, "8": cpp14Literal, "9": cpp14Literal, token: function(stream, state, style) { if (style == "variable" && stream.peek() == "(" && (state.prevToken == ";" || state.prevToken == null || state.prevToken == "}") && cppLooksLikeConstructor(stream.current())) return "def"; } }, namespaceSeparator: "::", modeProps: {fold: ["brace", "include"]} }); def("text/x-java", { name: "clike", keywords: words("abstract assert break case catch class const continue default " + "do else enum extends final finally float for goto if implements import " + "instanceof interface native new package private protected public " + "return static strictfp super switch synchronized this throw throws transient " + "try volatile while @interface"), types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " + "Integer Long Number Object Short String StringBuffer StringBuilder Void"), blockKeywords: words("catch class do else finally for if switch try while"), defKeywords: words("class interface enum @interface"), typeFirstDefinitions: true, atoms: words("true false null"), number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, hooks: { "@": function(stream) { // Don't match the @interface keyword. if (stream.match('interface', false)) return false; stream.eatWhile(/[\w\$_]/); return "meta"; } }, modeProps: {fold: ["brace", "import"]} }); def("text/x-csharp", { name: "clike", keywords: words("abstract as async await base break case catch checked class const continue" + " default delegate do else enum event explicit extern finally fixed for" + " foreach goto if implicit in interface internal is lock namespace new" + " operator out override params private protected public readonly ref return sealed" + " sizeof stackalloc static struct switch this throw try typeof unchecked" + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + " global group into join let orderby partial remove select set value var yield"), types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + " UInt64 bool byte char decimal double short int long object" + " sbyte float string ushort uint ulong"), blockKeywords: words("catch class do else finally for foreach if struct switch try while"), defKeywords: words("class interface namespace struct var"), typeFirstDefinitions: true, atoms: words("true false null"), hooks: { "@": function(stream, state) { if (stream.eat('"')) { state.tokenize = tokenAtString; return tokenAtString(stream, state); } stream.eatWhile(/[\w\$_]/); return "meta"; } } }); function tokenTripleString(stream, state) { var escaped = false; while (!stream.eol()) { if (!escaped && stream.match('"""')) { state.tokenize = null; break; } escaped = stream.next() == "\\" && !escaped; } return "string"; } function tokenNestedComment(depth) { return function (stream, state) { var ch while (ch = stream.next()) { if (ch == "*" && stream.eat("/")) { if (depth == 1) { state.tokenize = null break } else { state.tokenize = tokenNestedComment(depth - 1) return state.tokenize(stream, state) } } else if (ch == "/" && stream.eat("*")) { state.tokenize = tokenNestedComment(depth + 1) return state.tokenize(stream, state) } } return "comment" } } def("text/x-scala", { name: "clike", keywords: words( /* scala */ "abstract case catch class def do else extends final finally for forSome if " + "implicit import lazy match new null object override package private protected return " + "sealed super this throw trait try type val var while with yield _ " + /* package scala */ "assert assume require print println printf readLine readBoolean readByte readShort " + "readChar readInt readLong readFloat readDouble" ), types: words( "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " + "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " + "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " + "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " + /* package java.lang */ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" ), multiLineStrings: true, blockKeywords: words("catch class enum do else finally for forSome if match switch try while"), defKeywords: words("class enum def object package trait type val var"), atoms: words("true false null"), indentStatements: false, indentSwitch: false, isOperatorChar: /[+\-*&%=<>!?|\/#:@]/, hooks: { "@": function(stream) { stream.eatWhile(/[\w\$_]/); return "meta"; }, '"': function(stream, state) { if (!stream.match('""')) return false; state.tokenize = tokenTripleString; return state.tokenize(stream, state); }, "'": function(stream) { stream.eatWhile(/[\w\$_\xa1-\uffff]/); return "atom"; }, "=": function(stream, state) { var cx = state.context if (cx.type == "}" && cx.align && stream.eat(">")) { state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev) return "operator" } else { return false } }, "/": function(stream, state) { if (!stream.eat("*")) return false state.tokenize = tokenNestedComment(1) return state.tokenize(stream, state) } }, modeProps: {closeBrackets: {triples: '"'}} }); function tokenKotlinString(tripleString){ return function (stream, state) { var escaped = false, next, end = false; while (!stream.eol()) { if (!tripleString && !escaped && stream.match('"') ) {end = true; break;} if (tripleString && stream.match('"""')) {end = true; break;} next = stream.next(); if(!escaped && next == "$" && stream.match('{')) stream.skipTo("}"); escaped = !escaped && next == "\\" && !tripleString; } if (end || !tripleString) state.tokenize = null; return "string"; } } def("text/x-kotlin", { name: "clike", keywords: words( /*keywords*/ "package as typealias class interface this super val operator " + "var fun for is in This throw return annotation " + "break continue object if else while do try when !in !is as? " + /*soft keywords*/ "file import where by get set abstract enum open inner override private public internal " + "protected catch finally out final vararg reified dynamic companion constructor init " + "sealed field property receiver param sparam lateinit data inline noinline tailrec " + "external annotation crossinline const operator infix suspend actual expect setparam" ), types: words( /* package java.lang */ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray " + "ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy " + "LazyThreadSafetyMode LongArray Nothing ShortArray Unit" ), intendSwitch: false, indentStatements: false, multiLineStrings: true, number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, blockKeywords: words("catch class do else finally for if where try while enum"), defKeywords: words("class val var object interface fun"), atoms: words("true false null this"), hooks: { '"': function(stream, state) { state.tokenize = tokenKotlinString(stream.match('""')); return state.tokenize(stream, state); } }, modeProps: {closeBrackets: {triples: '"'}} }); def(["x-shader/x-vertex", "x-shader/x-fragment"], { name: "clike", keywords: words("sampler1D sampler2D sampler3D samplerCube " + "sampler1DShadow sampler2DShadow " + "const attribute uniform varying " + "break continue discard return " + "for while do if else struct " + "in out inout"), types: words("float int bool void " + "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " + "mat2 mat3 mat4"), blockKeywords: words("for while do if else struct"), builtin: words("radians degrees sin cos tan asin acos atan " + "pow exp log exp2 sqrt inversesqrt " + "abs sign floor ceil fract mod min max clamp mix step smoothstep " + "length distance dot cross normalize ftransform faceforward " + "reflect refract matrixCompMult " + "lessThan lessThanEqual greaterThan greaterThanEqual " + "equal notEqual any all not " + "texture1D texture1DProj texture1DLod texture1DProjLod " + "texture2D texture2DProj texture2DLod texture2DProjLod " + "texture3D texture3DProj texture3DLod texture3DProjLod " + "textureCube textureCubeLod " + "shadow1D shadow2D shadow1DProj shadow2DProj " + "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " + "dFdx dFdy fwidth " + "noise1 noise2 noise3 noise4"), atoms: words("true false " + "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " + "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " + "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " + "gl_FogCoord gl_PointCoord " + "gl_Position gl_PointSize gl_ClipVertex " + "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " + "gl_TexCoord gl_FogFragCoord " + "gl_FragCoord gl_FrontFacing " + "gl_FragData gl_FragDepth " + "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " + "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " + "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " + "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " + "gl_ProjectionMatrixInverseTranspose " + "gl_ModelViewProjectionMatrixInverseTranspose " + "gl_TextureMatrixInverseTranspose " + "gl_NormalScale gl_DepthRange gl_ClipPlane " + "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " + "gl_FrontLightModelProduct gl_BackLightModelProduct " + "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " + "gl_FogParameters " + "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " + "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " + "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " + "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " + "gl_MaxDrawBuffers"), indentSwitch: false, hooks: {"#": cppHook}, modeProps: {fold: ["brace", "include"]} }); def("text/x-nesc", { name: "clike", keywords: words(cKeywords + "as atomic async call command component components configuration event generic " + "implementation includes interface module new norace nx_struct nx_union post provides " + "signal task uses abstract extends"), types: words(cTypes), blockKeywords: words("case do else for if switch while struct"), atoms: words("null true false"), hooks: {"#": cppHook}, modeProps: {fold: ["brace", "include"]} }); def("text/x-objectivec", { name: "clike", keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginary BOOL Class bycopy byref id IMP in " + "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"), types: words(cTypes), atoms: words("YES NO NULL NILL ON OFF true false"), hooks: { "@": function(stream) { stream.eatWhile(/[\w\$]/); return "keyword"; }, "#": cppHook, indent: function(_state, ctx, textAfter) { if (ctx.type == "statement" && /^@\w/.test(textAfter)) return ctx.indented } }, modeProps: {fold: "brace"} }); def("text/x-squirrel", { name: "clike", keywords: words("base break clone continue const default delete enum extends function in class" + " foreach local resume return this throw typeof yield constructor instanceof static"), types: words(cTypes), blockKeywords: words("case catch class else for foreach if switch try while"), defKeywords: words("function local class"), typeFirstDefinitions: true, atoms: words("true false null"), hooks: {"#": cppHook}, modeProps: {fold: ["brace", "include"]} }); // Ceylon Strings need to deal with interpolation var stringTokenizer = null; function tokenCeylonString(type) { return function(stream, state) { var escaped = false, next, end = false; while (!stream.eol()) { if (!escaped && stream.match('"') && (type == "single" || stream.match('""'))) { end = true; break; } if (!escaped && stream.match('``')) { stringTokenizer = tokenCeylonString(type); end = true; break; } next = stream.next(); escaped = type == "single" && !escaped && next == "\\"; } if (end) state.tokenize = null; return "string"; } } def("text/x-ceylon", { name: "clike", keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" + " exists extends finally for function given if import in interface is let module new" + " nonempty object of out outer package return satisfies super switch then this throw" + " try value void while"), types: function(word) { // In Ceylon all identifiers that start with an uppercase are types var first = word.charAt(0); return (first === first.toUpperCase() && first !== first.toLowerCase()); }, blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"), defKeywords: words("class dynamic function interface module object package value"), builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" + " native optional sealed see serializable shared suppressWarnings tagged throws variable"), isPunctuationChar: /[\[\]{}\(\),;\:\.`]/, isOperatorChar: /[+\-*&%=<>!?|^~:\/]/, numberStart: /[\d#$]/, number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i, multiLineStrings: true, typeFirstDefinitions: true, atoms: words("true false null larger smaller equal empty finished"), indentSwitch: false, styleDefs: false, hooks: { "@": function(stream) { stream.eatWhile(/[\w\$_]/); return "meta"; }, '"': function(stream, state) { state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single"); return state.tokenize(stream, state); }, '`': function(stream, state) { if (!stringTokenizer || !stream.match('`')) return false; state.tokenize = stringTokenizer; stringTokenizer = null; return state.tokenize(stream, state); }, "'": function(stream) { stream.eatWhile(/[\w\$_\xa1-\uffff]/); return "atom"; }, token: function(_stream, state, style) { if ((style == "variable" || style == "type") && state.prevToken == ".") { return "variable-2"; } } }, modeProps: { fold: ["brace", "import"], closeBrackets: {triples: '"'} } }); }); </script></head> <body style=""> <!-- --> <div class="container"> <div class="settings"> <div class="timer"> <span class="num" id="hour">04</span><span class="desc">Hr</span> <span class="num" id="minute">14</span><span class="desc">Min</span> <span class="num" id="second">20</span><span class="desc">Sec</span> </div> </div> <!-- <ul id="myTags"> Existing list items will be pre-added to the tags <li>Tag1</li> <li>Tag2</li> </ul> --> <!-- <textarea name='tags2' placeholder='Movie names'>The Matrix, Pulp Fiction, Mad Max</textarea> --> <div> <div class="main-content module"> <div class="settings_editor"> <h1>Editor - {A}</h1> <div class="menu"> <select id="prog_mode"> <option value="c">C</option> <option value="cpp">C ++</option> <option value="cs">C #</option> <option value="java">Java (8)</option> <!-- <option value="java7">Java (7)</option>--> <!-- <option value="javascript">Javascript</option> --> <option value="php">PHP</option> <option value="perl">Perl</option> <option value="python3">Python 3</option> <option value="ruby">Ruby</option> </select> </div> </div> <div class="editor"><div class="CodeMirror cm-s-default CodeMirror-simplescroll CodeMirror-focused" style="width: 100%; height: 500px;"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 140.8px; left: 141.225px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;" tabindex="0"></textarea></div><div class="CodeMirror-simplescroll-horizontal" cm-not-content="true" style="display: none;"><div></div></div><div class="CodeMirror-simplescroll-vertical" cm-not-content="true" style="display: block; bottom: 0px;"><div style="height: 418.567px; top: 0.651466px;"></div></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1" draggable="false"><div class="CodeMirror-sizer" style="margin-left: 30px; margin-bottom: -17px; border-right-width: 13px; min-height: 601px; min-width: 221.463px; padding-right: 8px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre>x</pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-cursors" style=""><div class="CodeMirror-cursor" style="left: 111.225px; top: 136.8px; height: 15.2px;">&nbsp;</div></div><div class="CodeMirror-code" role="presentation" style=""><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">1</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-variable">#include</span><span class="cm-operator">&lt;</span><span class="cm-variable">stdio</span>.<span class="cm-variable">h</span><span class="cm-operator">&gt;</span></span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">2</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-type">int</span> <span class="cm-def">pow</span>(<span class="cm-type">int</span> <span class="cm-variable">p</span>)</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">3</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">{</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">4</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-type">int</span> <span class="cm-variable">i</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">5</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-type">int</span> <span class="cm-variable">power</span><span class="cm-operator">=</span><span class="cm-number">1</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">6</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">for</span>(<span class="cm-variable">i</span><span class="cm-operator">=</span><span class="cm-number">0</span>;<span class="cm-variable">i</span><span class="cm-operator">&lt;</span><span class="cm-variable">p</span>;<span class="cm-variable">i</span><span class="cm-operator">++</span>)</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">7</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> {</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">8</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">power</span><span class="cm-operator">=</span><span class="cm-number">2</span><span class="cm-operator">*</span><span class="cm-variable">power</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">9</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> }</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">10</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">power</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">11</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">}</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">12</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="">&#8203;</span></span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">13</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-type">int</span> <span class="cm-def">main</span>()</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">14</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">{</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">15</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-type">int</span> <span class="cm-variable">i</span>,<span class="cm-variable">k</span>,<span class="cm-variable">sum</span><span class="cm-operator">=</span><span class="cm-number">0</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">16</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-type">int</span> <span class="cm-variable">j</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">17</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-type">int</span> <span class="cm-variable">T</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">18</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">scanf</span>(<span class="cm-string">"%d"</span>,<span class="cm-operator">&amp;</span><span class="cm-variable">T</span>);</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">19</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-type">int</span> <span class="cm-variable">N</span>[<span class="cm-variable">T</span>];</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">20</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">for</span>(<span class="cm-variable">i</span><span class="cm-operator">=</span><span class="cm-number">0</span>;<span class="cm-variable">i</span><span class="cm-operator">&lt;</span><span class="cm-variable">T</span>;<span class="cm-variable">i</span><span class="cm-operator">++</span>)</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">21</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> {</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">22</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">scanf</span>(<span class="cm-string">"%d"</span>,<span class="cm-operator">&amp;</span><span class="cm-variable">N</span>[<span class="cm-variable">i</span>]);</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">23</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> }</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">24</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">for</span>(<span class="cm-variable">i</span><span class="cm-operator">=</span><span class="cm-number">0</span>;<span class="cm-variable">i</span><span class="cm-operator">&lt;</span><span class="cm-variable">T</span>;<span class="cm-variable">i</span><span class="cm-operator">++</span>)</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">25</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> {</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">26</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="">&#8203;</span></span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">27</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">j</span><span class="cm-operator">=</span><span class="cm-number">0</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">28</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">k</span><span class="cm-operator">=</span><span class="cm-number">0</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">29</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">sum</span><span class="cm-operator">=</span><span class="cm-number">0</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">30</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">while</span>(<span class="cm-variable">sum</span><span class="cm-operator">&lt;</span><span class="cm-variable">N</span>[<span class="cm-variable">i</span>])</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">31</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> {</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">32</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">sum</span><span class="cm-operator">=</span><span class="cm-variable">sum</span><span class="cm-operator">+</span><span class="cm-variable">pow</span>(<span class="cm-variable">j</span>);</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">33</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">j</span><span class="cm-operator">++</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">34</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">k</span><span class="cm-operator">++</span>;</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">35</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> }</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">36</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">printf</span>(<span class="cm-string">"%d\n"</span>,<span class="cm-variable">k</span>);</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">37</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> }</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">38</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">}</span></pre></div><div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -30px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 21px;">39</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="">&#8203;</span></span></pre></div></div></div></div></div></div><div style="position: absolute; height: 13px; width: 1px; border-bottom: 0px solid transparent; top: 601px;"></div><div class="CodeMirror-gutters" style="height: 614px; left: 0px;"><div class="CodeMirror-gutter CodeMirror-linenumbers" style="width: 29px;"></div></div></div></div></div> <div class="pre-submission-container"> <div class="file-name-settings"> <div class="form-group"> <input type="text" id="prg_name"> <label for="prg_name">Program Name</label> </div> <span>.</span> <div class="form-group"> <input type="text" id="ext" readonly="readonly"> <label for="ext">Extension</label> </div> </div> <div class="action-buttons-section"> <button class="button" id="save" onclick="save()">Saved!</button> <button class="button" id="compile" onclick="compile()">Compile &amp; Run</button> </div> <div class="attribution_section_container disabled" style="margin-top: 5px; grid-column: span 1; padding: 5px 0 10px 0"> <div class="attribution_section" style="grid-column: span 2; padding: 5px 0 10px 0"> <input type="checkbox" id="attributions"> <label for="attributions">Took help from online sources (attributions)</label> </div> <div class="attribution_section text"> <label>Links (Copy paste / Drag-Drop from source window): </label> <!-- <textarea id="links"></textarea> --> <ul id="links" class="tagit ui-widget ui-widget-content ui-corner-all"><li class="tagit-new"><input type="text" class="ui-widget-content ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true"></li></ul> </div> <div class="attribution_section text"> <label>Comments : </label> <textarea id="comments"></textarea> </div> </div> </div> <div class="post-sub-result-details" style="display: none;"><div class="table"><div class="row"><span class="col">TestCase no</span><span class="col">Status</span><span class="col">Expected Output</span></div><div class="row"><span class="col">1</span><span class="col">Accepted</span><pre><span class="col">4 3 </span></pre></div><div class="row"><span class="col">2</span><span class="col">Accepted</span><pre><span class="col">4 3 </span></pre></div></div><section class="accepted"><h1>Accepted</h1><button class="submit_answer_button" onclick="finalSubmit()">Submit (Final)</button></section></div> <div class="hidden-loader"> <div class="loader-1"> <div class="clock"></div> <span class="text">Compiling ...</span> </div> </div> <div class="hidden-pre-sub-content"> <div class="file-name-settings"> <div class="form-group"> <input type="text" id="prg_name"> <label for="prg_name">Program Name</label> </div> <span>.</span> <div class="form-group"> <input type="text" id="ext" readonly="readonly"> <label for="ext">Extension</label> </div> </div> <div class="action-buttons-section"> <button class="button" id="save" onclick="save()">Saved!</button> <button class="button" id="compile" onclick="compile()">Compile &amp; Run</button> </div> <div class="attribution_section_container disabled" style="margin-top: 5px; grid-column: span 1; padding: 5px 0 10px 0"> <div class="attribution_section" style="grid-column: span 2; padding: 5px 0 10px 0"> <input type="checkbox" id="attributions"> <label for="attributions">Took help from online sources (attributions)</label> </div> <div class="attribution_section text"> <label>Links (Copy paste / Drag-Drop from source window): </label> <!-- <textarea id="links"></textarea> --> <ul id="links"></ul> </div> <div class="attribution_section text"> <label>Comments : </label> <textarea id="comments"></textarea> </div> </div> </div> <div class="hidden-post-submission-summary" style="display: none"> <div class="submission_notification success"> <div class="graphic"><img src="./philanda_files/happy.svg"><div class="short-msg"></div></div> <div class="info"> <h2></h2> <div class="actions"> <div class="other-info"></div> <div class="buttons"></div> </div> </div> </div> </div> </div> </div> <ul id="myTags"></ul> </div> <ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all tagit-autocomplete" role="listbox" aria-activedescendant="ui-active-menuitem" style="z-index: 1; top: 0px; left: 0px; display: none;"></ul></body></html>
[ "bansalshubham.cse21@gmail.com" ]
bansalshubham.cse21@gmail.com
6f29e7d1b1edd6d195f589992d5eea47867cb52e
7ba1a1fa3997176a3a7a92128378f68595e67b80
/Life.hpp
cdd3585fb768ed2cbdbaf318aa4f341b5b908183
[]
no_license
jorenga/LIFE
50b1260b914a029b775cf5196b57bdecf17034fe
4e5861cad53be3def5d5149768c79c9efbed9071
refs/heads/master
2022-09-29T14:45:01.288943
2017-10-10T17:37:02
2017-10-10T17:37:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
622
hpp
#ifndef LIFE_HPP # define LIFE_HPP # include <cstdlib> # include <ctime> # include <vector> # include <iostream> # include <unistd.h> /* * is_alive ? (4+ || 1- neighbours -> death) : (3 neighbours -> life) */ class Life { public: Life(); ~Life(); void genesis(); private: void _initWorld(int nb_cells); void _display_world(std::vector<bool> &grid); int _getIndex(int width_pos, int height_pos); bool _evalCell(std::vector<bool> &grid, int pos); private: std::vector<bool> _world; int _world_size; int _width; int _height; }; #endif
[ "renoufjoseph@gmail.com" ]
renoufjoseph@gmail.com
b65fc7dce4f5bf9c2c37929cfecb78d2f3eb52bf
e43548aa992ff92482d51efcb0549ea89ee4ca42
/engine/FbxAnm.cpp
99a53bf6591dfe8764f1e917e3b3273e157caf8d
[]
no_license
BB-Cat/-
7b0d0a9c7c487b1e6c62b5a51b6dd46281b17841
1cf9e8741601bb537dd779fc65da0943e5233ec4
refs/heads/main
2023-02-27T19:42:05.746205
2021-02-05T11:40:07
2021-02-05T11:40:07
310,175,460
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
8,291
cpp
#include "FbxAnm.h" #include <string> Fbx_Anm::Fbx_Anm(const wchar_t* full_path, MyFbxManager* fbx_manager, bool looping, bool interruptable, int interruptable_frame, bool idles, int idle_frame, bool try_preloaded_txt) : m_loops(looping), m_interruptable(interruptable), m_interruptable_frame(interruptable_frame), m_idles(idles), m_idle_frame(idle_frame) { m_file_location = full_path; if (!(try_preloaded_txt && tryLoadAnimationTxt(full_path))) { fbx_manager->loadAnimationData(full_path, m_skeletons, 60); } } Fbx_Anm::Fbx_Anm(const wchar_t* full_path, MyFbxManager* fbx_manager, bool looping, bool interruptable, float interruptable_percent, bool idles, float idle_percent, bool try_preloaded_txt) : m_loops(looping), m_interruptable(interruptable), m_idles(idles) { m_file_location = full_path; //if (!try_preloaded_txt || !tryLoadAnimationTxt(full_path)) //{ int updates_per_second = 60; fbx_manager->loadAnimationData(full_path, m_skeletons, updates_per_second); m_interruptable_frame = (int)(interruptable_percent * m_skeletons.size()); m_idle_frame = (int)(idle_percent * m_skeletons.size()); //save the loaded data for next time //outputAnimationData(); //} } Fbx_Anm::~Fbx_Anm() { m_hitboxes.clear(); Skeletal_Animation m_skeletons; for (int i = 0; i < m_skeletons.size(); i++) m_skeletons[i].m_bones.clear(); m_skeletons.clear(); } bool Fbx_Anm::tryLoadAnimationTxt(const wchar_t* full_path) { std::wstring txt_file_path(full_path); UINT path_len = wcslen(full_path); //cut off the .fbx at the end of the path and replace it with .txt txt_file_path.resize(path_len - 3); txt_file_path += L"txt"; //std::string file = filename; std::ifstream fin; //fin = std::ifstream("..\\Assets\\SceneData\\" + file); fin = std::ifstream(txt_file_path); //_ASSERT_EXPR(fin.is_open(), L"Scene Data file not found!"); if (!fin.is_open()) return false; //int num_tex; //int num_prefabs; //std::string tempname = {}; //wchar_t tempwchar[128] = {}; //std::string tempfile = {}; //fin >> num_tex; std::string in; //m_loops fin >> m_loops; //m_interruptable fin >> m_interruptable; //m_interruptable_frame fin >> m_interruptable_frame; //m_idles fin >> m_idles; //m_idle_frame fin >> m_idle_frame; //HITBOXES //number of hitboxes int num_hitboxes; fin >> num_hitboxes; int active_frames[2] = {}; int damage = 0; Collider* col; for (int i = 0; i < num_hitboxes; i++) { //active frames fin >> active_frames[0]; fin >> active_frames[1]; //damage //collider } //SKELETONS //number of skeletons return true; } bool Fbx_Anm::outputAnimationData() { std::wstring txt_file_path(m_file_location); txt_file_path.resize(m_file_location.size() - 3); txt_file_path += L"txt"; std::ofstream outfile(txt_file_path.c_str()); //m_loops if (m_loops) outfile << std::to_string(1); else outfile << std::to_string(0); //m_interruptable if (m_interruptable) outfile << std::to_string(1); else outfile << std::to_string(0); //m_interruptable_frame outfile << std::to_string(m_interruptable_frame) << " "; //m_idles if (m_idles) outfile << std::to_string(1); else outfile << std::to_string(0); //m_idle_frame outfile << std::to_string(m_idle_frame) << " "; //HITBOXES //number of hitboxes int num_hitboxes = m_hitboxes.size(); outfile << std::to_string(num_hitboxes) << " "; for (int i = 0; i < num_hitboxes; i++) { //active frames outfile << std::to_string(m_hitboxes[i]->m_active_frames[0]) + " " + std::to_string(m_hitboxes[i]->m_active_frames[1]); //damage outfile << std::to_string(m_hitboxes[i]->m_damage_value) + " "; //collider outputColliderData(m_hitboxes[i]->m_collider.get(), &outfile); } //SKELETONS //number of skeletons outputSkeletonData(&outfile); outfile.close(); return true; } bool Fbx_Anm::outputColliderData(Collider* c, std::ofstream* stream) { //determine type of collider //TODO: add support for other colliders besides capsules if (c->getType() != ColliderTypes::Capsule) return false; CapsuleCollider* c1 = reinterpret_cast<CapsuleCollider*>(c); //output appropriate data// //radius (*stream) << c1->getRadius() << " "; //core length (*stream) << c1->getCoreLength() << " "; //rotation Vec3 temp = c1->getRotation(); (*stream) << std::to_string(temp.x) << " "; (*stream) << std::to_string(temp.y) << " "; (*stream) << std::to_string(temp.z) << " "; return true; } bool Fbx_Anm::outputSkeletonData(std::ofstream* stream) { int num_skeletons = m_skeletons.size(); //output the number of skeletons (*stream) << std::to_string(num_skeletons) + " "; if (num_skeletons == 0) return false; //output the number of bones in the skeleton /* WE ARE ASSUMING THE NUMBER OF BONES NEVER CHANGES HERE */ int num_bones = m_skeletons[0].m_bones.size(); (*stream) << std::to_string(num_bones) + " "; Matrix4x4 mat; for (int i = 0; i < m_skeletons.size(); i++) { //output the matrix for each bone for (int j = 0; j < num_bones; j++) { for (int k = 0; k < 4; k++) { for (int l = 0; l < 4; l++) { (*stream) << std::to_string(m_skeletons[i].m_bones[j].transform.m_mat[l][k]) << " "; } } } } return true; } bool Fbx_Anm::update(float delta) { //待機状態を持つアニメーションであれば、更新出来るかを判定する。待機を持っていない場合はいつも更新する if (m_idles == true) { if (m_frame < m_idle_frame || m_trigger_finish == true) { m_skeletons.animation_tick += delta; } } else m_skeletons.animation_tick += delta; //calculate which frame is next m_frame = m_skeletons.animation_tick / m_skeletons.sampling_time; if (m_idles == true) return updateIdling(); else if (m_loops == false) return updateNonLooping(); else if (m_loops == true) return updateLooping(); else return false; } bool Fbx_Anm::updatedByPercentage(float percent) { float tick_increase = percent * (m_skeletons.sampling_time * m_skeletons.size()); //待機状態を持つアニメーションであれば、更新出来るかを判定する。待機を持たない場合はいつも更新する if (m_idles == true) { if (m_frame < m_idle_frame || m_trigger_finish == true) { m_skeletons.animation_tick += tick_increase; } } else m_skeletons.animation_tick += tick_increase; //calculate which frame is next m_frame = m_skeletons.animation_tick / m_skeletons.sampling_time; if (m_idles == true) return updateIdling(); else if (m_loops == false) return updateNonLooping(); else if (m_loops == true) return updateLooping(); else return false; } bool Fbx_Anm::updateLooping() { //reset the animation if we passed the last frame if (m_frame > m_skeletons.size() - 1) { m_frame = 0; m_skeletons.animation_tick = 0; } return true; } bool Fbx_Anm::updateNonLooping() { //if the animation is finished return false if (m_frame > m_skeletons.size() - 1) { m_frame = 0; m_skeletons.animation_tick = 0; return false; } return true; } bool Fbx_Anm::updateIdling() { //if the animation is finished return false if (m_frame > m_skeletons.size() - 1) { m_frame = 0; m_skeletons.animation_tick = 0; m_trigger_finish = false; return false; } return true; } bool Fbx_Anm::getIfInterruptable() { //if the animation is interruptable and at the frame where it can be interrupted, return true return ((m_interruptable && m_frame >= m_interruptable_frame)); } bool Fbx_Anm::getIfFinished() { return (m_frame == m_skeletons.size() - 1); } float Fbx_Anm::getTotalTime() { return (m_skeletons.sampling_time * m_skeletons.size()); } float Fbx_Anm::getPercentCompletion() { return m_skeletons.animation_tick / (m_skeletons.sampling_time * m_skeletons.size()); } void Fbx_Anm::reset() { m_frame = 0; m_trigger_finish = false; m_skeletons.animation_tick = 0; } void Fbx_Anm::setFrame(int frame) { m_frame = frame; } void Fbx_Anm::setFrame(float percent) { m_frame = (int)(percent * m_skeletons.size()); } void Fbx_Anm::setFinishTrigger(bool trigger) { m_trigger_finish = trigger; } Skeleton Fbx_Anm::getPose() { return m_skeletons.at(m_frame); } Skeleton Fbx_Anm::getPoseAtPercent(float percent) { return m_skeletons.at((int)(percent * m_skeletons.size())); }
[ "rockmanrollforte@outlook.com" ]
rockmanrollforte@outlook.com
ba7dc71ed0ab9491d70dac10e8d17a49924ce264
a75feff03ca2f3236e20bf6eeb303be3e6bf89c2
/BusBar-Qt/setting/setthreshold/setkey.h
30c78e00489b3f5194f12efb5c0464e9aa19e24c
[]
no_license
luozhiyong131/BusBar
50b446c00fadff0a56a454de413dd80ad8ce4b6b
e9119903134276e866a68f7e70fad2ddb2770f8a
refs/heads/master
2021-06-23T14:27:06.610207
2019-05-20T07:19:57
2019-05-20T07:19:57
92,152,932
3
1
null
null
null
null
UTF-8
C++
false
false
560
h
#ifndef SETKEY_H #define SETKEY_H #include <QDialog> #include <QSignalMapper> namespace Ui { class SetKey; } class SetKey : public QDialog { Q_OBJECT public: explicit SetKey(QWidget *parent = 0, double value = 0, QString tit = "修改值:"); ~SetKey(); double getNuber(); public slots: void keyPress(int value); protected: void initKey(void); private slots: void on_timeSet_but_clicked(); void on_quitBtn_clicked(); private: QSignalMapper *m; double mNuber; private: Ui::SetKey *ui; }; #endif // SETKEY_H
[ "luozhiyong131@qq.com" ]
luozhiyong131@qq.com
87f061d713c5412eca7480248e47e9b980bbf715
cb14914838d2fd47183bd1015a7535918e3d0b8c
/include/eggs/type_patterns/detail/match.hpp
36958d6c5795e163686cb3ca65d778c1a834f0f2
[ "BSL-1.0" ]
permissive
eggs-cpp/type_patterns
7b29b983623527d25d9376fcc54d754531861b00
3d36d1768832eedae2c6a9a4f771757a8a4667c8
refs/heads/master
2020-06-02T19:56:02.323601
2013-05-13T22:52:48
2013-05-13T22:52:48
9,992,867
7
0
null
null
null
null
ISO-8859-2
C++
false
false
6,188
hpp
/** * Eggs.TypePatterns <eggs/type_patterns/detail/match.hpp> * * Copyright Agustín Bergé, Fusion Fenix 2013 * * 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) * * Library home page: https://github.com/eggs-cpp/type_patterns */ #ifndef EGGS_TYPE_PATTERNS_DETAIL_MATCH_HPP #define EGGS_TYPE_PATTERNS_DETAIL_MATCH_HPP #include <eggs/type_patterns/detail/match_bool.hpp> #include <eggs/type_patterns/match_fwd.hpp> #include <eggs/type_patterns/metafunction.hpp> #include <eggs/type_patterns/placeholders.hpp> #include <boost/mpl/at.hpp> #include <boost/mpl/has_key.hpp> #include <boost/mpl/map.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/insert.hpp> #include <boost/mpl/pair.hpp> #include <boost/type_traits/is_same.hpp> namespace eggs { namespace type_patterns { namespace detail { template< typename Pattern, typename Type, typename State > struct match; template< typename ...T > struct linear; // terminal template< typename P, typename T, typename S > struct match : boost::mpl::if_< is_metafunction< P, match_context< T, S > > , call< P, match_context< T, S > > , match_bool< boost::is_same< P, T > , S > >::type {}; // placeholders template< typename T, typename S > struct match< _, T, S > : match_true< S > {}; template< int P, typename T, typename S > struct match< placeholder< P >, T, S > : boost::mpl::if_< boost::mpl::has_key< S, placeholder< P > > , match_bool< boost::is_same< typename boost::mpl::at< S, placeholder< P > >::type , T > , S > , match_true< typename boost::mpl::insert< S , boost::mpl::pair< placeholder< P >, T > >::type > >::type {}; // cv-qualifiers template< typename P, typename T, typename S > struct match< P const, T const, S > : match< P, T, S > {}; template< typename P, typename T, typename S > struct match< P volatile, T volatile, S > : match< P, T, S > {}; template< typename P, typename T, typename S > struct match< P const volatile, T const volatile, S > : match< P, T, S > {}; // pointers template< typename P, typename T, typename S > struct match< P*, T*, S > : match< P, T, S > {}; template< typename P, typename PO, typename T, typename TO, typename S > struct match< P PO::*, T TO::*, S > : match< linear< P, PO >, linear< T, TO >, S > {}; // references template< typename P, typename T, typename S > struct match< P&, T&, S > : match< P, T, S > {}; template< typename P, typename T, typename S > struct match< P&&, T&&, S > : match< P, T, S > {}; // arrays template< typename P, typename T, typename S > struct match< P[], T[], S > : match< P, T, S > {}; template< typename P, typename T, int Size, typename S > struct match< P[ Size ], T[ Size ], S > : match< P, T, S > {}; template< typename P, typename T, int Size, typename S > struct match< P[ N ], T[ Size ], S > : match< P, T, S > {}; // functions template< typename PR, typename ...PA, typename TR, typename ...TA, typename S > struct match< PR( PA... ), TR( TA... ), S > : match< linear< PR, PA... >, linear< TR, TA... >, S > {}; template< typename PR, typename ...PA, typename TR, typename ...TA, typename S > struct match< PR( PA... ), TR( TA..., ... ), S > : match< linear< PR, PA... >, linear< TR, TA..., ellipsis >, S > {}; template< typename PR, typename ...PA, typename TR, typename ...TA, typename S > struct match< PR( PA..., ... ), TR( TA..., ... ), S > : match< linear< PR, PA..., ellipsis >, linear< TR, TA..., ellipsis >, S > {}; // templates template< template< typename... > class U, typename ...P, typename ...T, typename S > struct match< U< P... >, U< T... >, S > : boost::mpl::if_< is_metafunction< U< P... >, match_context< T, S > > , call< U< P... >, match_context< T, S > > , match< linear< P... >, linear< T... >, S > >::type {}; template< template< typename... > class U, typename ...P, typename T, typename S > struct match< U< P... >, T, S > : boost::mpl::if_< is_metafunction< U< P... >, match_context< T, S > > , call< U< P... >, match_context< T, S > > , match_false< S > >::type {}; // linear match template< typename P, typename T, typename S > struct linear_match; template< typename P, typename T, typename S > struct linear_match< linear< P >, linear< T >, S > : match< P, T, S > {}; template< typename T, typename S > struct linear_match< linear< varargs >, linear< T >, S > : match_true< S > {}; template< typename P, typename ...PT, typename T, typename ...TT, typename S > struct linear_match< linear< P, PT... >, linear< T, TT... >, S > : boost::mpl::if_< match< P, T, S > , linear_match< linear< PT... >, linear< TT... > , typename match< P, T, S >::state > , match_false< S > >::type {}; template< typename ...T, typename S > struct linear_match< linear< varargs >, linear< T... >, S > : match_true< S > {}; //~ we need this specialization or MSVC gets confused template< typename ...P, typename ...T, typename S > struct match< linear< P... >, linear< T... >, S > : linear_match< linear< P... >, linear< T... >, S > {}; } } } // namespace eggs::type_patterns::detail #endif /*EGGS_TYPE_PATTERNS_DETAIL_MATCH_HPP*/
[ "k@fusionfenix.com" ]
k@fusionfenix.com
443b94b8a8e63c26be9190d729a9ade645335038
a9bbd2b7b72e62c4b84c0a6b37f8a2611c07e7bf
/src/slg/engines/rtpathocl/rtpathoclthread.cpp
915eb0e9696235796998b8cbdc9600eb04dcba73
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Alpistinho/LuxCore
a0acdc5ef811dd422b2c29ff0d5bbed692231c82
55645af0e10714b027be70c39c41e5f8d5fe1722
refs/heads/master
2021-06-20T15:43:18.429604
2019-10-25T03:16:34
2019-10-25T03:16:34
213,797,974
0
0
Apache-2.0
2019-10-09T02:04:17
2019-10-09T02:04:17
null
UTF-8
C++
false
false
9,989
cpp
/*************************************************************************** * Copyright 1998-2018 by authors (see AUTHORS.txt) * * * * This file is part of LuxCoreRender. * * * * 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. * ***************************************************************************/ #if !defined(LUXRAYS_DISABLE_OPENCL) #include "luxrays/core/oclintersectiondevice.h" #include "slg/slg.h" #include "slg/kernels/kernels.h" #include "slg/film/imagepipeline/plugins/gammacorrection.h" #include "slg/film/imagepipeline/plugins/tonemaps/linear.h" #include "slg/engines/rtpathocl/rtpathocl.h" using namespace std; using namespace luxrays; using namespace slg; //------------------------------------------------------------------------------ // RTPathOCLRenderThread //------------------------------------------------------------------------------ RTPathOCLRenderThread::RTPathOCLRenderThread(const u_int index, OpenCLIntersectionDevice *device, TilePathOCLRenderEngine *re) : TilePathOCLRenderThread(index, device, re) { } RTPathOCLRenderThread::~RTPathOCLRenderThread() { } void RTPathOCLRenderThread::Interrupt() { } void RTPathOCLRenderThread::BeginSceneEdit() { } void RTPathOCLRenderThread::EndSceneEdit(const EditActionList &editActions) { } string RTPathOCLRenderThread::AdditionalKernelOptions() { RTPathOCLRenderEngine *engine = (RTPathOCLRenderEngine *)renderEngine; stringstream ss; ss.precision(6); ss << scientific << TilePathOCLRenderThread::AdditionalKernelOptions() << " -D PARAM_RTPATHOCL_PREVIEW_RESOLUTION_REDUCTION=" << engine->previewResolutionReduction << " -D PARAM_RTPATHOCL_PREVIEW_RESOLUTION_REDUCTION_STEP=" << engine->previewResolutionReductionStep << " -D PARAM_RTPATHOCL_RESOLUTION_REDUCTION=" << engine->resolutionReduction; return ss.str(); } void RTPathOCLRenderThread::UpdateOCLBuffers(const EditActionList &updateActions) { RTPathOCLRenderEngine *engine = (RTPathOCLRenderEngine *)renderEngine; //-------------------------------------------------------------------------- // Update OpenCL buffers //-------------------------------------------------------------------------- CompiledScene *cscene = engine->compiledScene; if (cscene->wasCameraCompiled) { // Update Camera InitCamera(); } if (cscene->wasGeometryCompiled) { // Update Scene Geometry InitGeometry(); } if (cscene->wasImageMapsCompiled) { // Update Image Maps InitImageMaps(); } if (cscene->wasMaterialsCompiled) { // Update Scene Textures and Materials InitTextures(); InitMaterials(); } if (cscene->wasSceneObjectsCompiled) { // Update Mesh <=> Material relation InitSceneObjects(); } if (cscene->wasLightsCompiled) { // Update Scene Lights InitLights(); } //-------------------------------------------------------------------------- // Recompile Kernels if required //-------------------------------------------------------------------------- // The following actions can require a kernel re-compilation: // - Dynamic code generation of textures and materials; // - Material types edit; // - Light types edit; // - Image types edit; // - Geometry type edit; // - etc. InitKernels(); SetKernelArgs(); if (updateActions.Has(MATERIAL_TYPES_EDIT) || updateActions.Has(LIGHT_TYPES_EDIT)) { // Execute initialization kernels. Initialize OpenCL structures. // NOTE: I can only after having compiled and set arguments. cl::CommandQueue &initQueue = intersectionDevice->GetOpenCLQueue(); RTPathOCLRenderEngine *engine = (RTPathOCLRenderEngine *)renderEngine; initQueue.enqueueNDRangeKernel(*initSeedKernel, cl::NullRange, cl::NDRange(engine->taskCount), cl::NDRange(initWorkGroupSize)); } // Reset statistics in order to be more accurate intersectionDevice->ResetPerformaceStats(); } void RTPathOCLRenderThread::RenderThreadImpl() { //SLG_LOG("[RTPathOCLRenderThread::" << threadIndex << "] Rendering thread started"); // Boost barriers are supposed to be not interruptible but they are // and seem to be missing a way to reset them. So better to disable // interruptions. boost::this_thread::disable_interruption di; RTPathOCLRenderEngine *engine = (RTPathOCLRenderEngine *)renderEngine; boost::barrier *frameBarrier = engine->frameBarrier; // To synchronize the start of all threads frameBarrier->wait(); const u_int taskCount = engine->taskCount; try { //---------------------------------------------------------------------- // Execute initialization kernels //---------------------------------------------------------------------- cl::CommandQueue &initQueue = intersectionDevice->GetOpenCLQueue(); // Initialize OpenCL structures initQueue.enqueueNDRangeKernel(*initSeedKernel, cl::NullRange, cl::NDRange(taskCount), cl::NDRange(initWorkGroupSize)); //---------------------------------------------------------------------- // Rendering loop //---------------------------------------------------------------------- bool pendingFilmClear = false; tileWork.Reset(); while (!boost::this_thread::interruption_requested()) { cl::CommandQueue &currentQueue = intersectionDevice->GetOpenCLQueue(); //------------------------------------------------------------------ // Render the tile (there is only one tile for each device // in RTPATHOCL) //------------------------------------------------------------------ engine->tileRepository->NextTile(engine->film, engine->filmMutex, tileWork, threadFilms[0]->film); // tileWork can be NULL after a scene edit if (tileWork.HasWork()) { //const double t0 = WallClockTime(); //SLG_LOG("[RTPathOCLRenderThread::" << threadIndex << "] TileWork: " << tileWork); RenderTileWork(tileWork, 0); // Async. transfer of GPU task statistics currentQueue.enqueueReadBuffer( *(taskStatsBuff), CL_FALSE, 0, sizeof(slg::ocl::pathoclbase::GPUTaskStats) * taskCount, gpuTaskStats); currentQueue.finish(); //const double t1 = WallClockTime(); //SLG_LOG("[RTPathOCLRenderThread::" << threadIndex << "] Tile rendering time: " + ToString((u_int)((t1 - t0) * 1000.0)) + "ms"); } //------------------------------------------------------------------ frameBarrier->wait(); //------------------------------------------------------------------ if (threadIndex == 0) { //const double t0 = WallClockTime(); if (pendingFilmClear) { boost::unique_lock<boost::mutex> lock(*(engine->filmMutex)); engine->film->Reset(); pendingFilmClear = false; } // Now I can splat the tile on the tile repository. It is done now to // not obliterate the CHANNEL_IMAGEPIPELINE while the screen refresh // thread is probably using it to draw the screen. // It is also done by thread #0 for all threads. for (u_int i = 0; i < engine->renderOCLThreads.size(); ++i) { RTPathOCLRenderThread *thread = (RTPathOCLRenderThread *)(engine->renderOCLThreads[i]); if (thread->tileWork.HasWork()) { engine->tileRepository->NextTile(engine->film, engine->filmMutex, thread->tileWork, thread->threadFilms[0]->film); // There is only one tile for each device in RTPATHOCL thread->tileWork.Reset(); } } //const double t1 = WallClockTime(); //SLG_LOG("[RTPathOCLRenderThread::" << threadIndex << "] Tile splatting time: " + ToString((u_int)((t1 - t0) * 1000.0)) + "ms"); } //------------------------------------------------------------------ frameBarrier->wait(); //------------------------------------------------------------------ //------------------------------------------------------------------ // Update OpenCL buffers if there is any edit action. It is done by // thread #0 for all threads. //------------------------------------------------------------------ if (threadIndex == 0) { if (engine->updateActions.HasAnyAction()) { // Update all threads for (u_int i = 0; i < engine->renderOCLThreads.size(); ++i) { RTPathOCLRenderThread *thread = (RTPathOCLRenderThread *)(engine->renderOCLThreads[i]); thread->UpdateOCLBuffers(engine->updateActions); } // Reset updateActions engine->updateActions.Reset(); // Clear the film pendingFilmClear = true; } } //------------------------------------------------------------------ frameBarrier->wait(); //------------------------------------------------------------------ // Time to render a new frame } //SLG_LOG("[RTPathOCLRenderThread::" << threadIndex << "] Rendering thread halted"); } catch (boost::thread_interrupted) { SLG_LOG("[RTPathOCLRenderThread::" << threadIndex << "] Rendering thread halted"); } catch (cl::Error &err) { SLG_LOG("[RTPathOCLRenderThread::" << threadIndex << "] Rendering thread ERROR: " << err.what() << "(" << oclErrorString(err.err()) << ")"); } intersectionDevice->GetOpenCLQueue().finish(); threadDone = true; } #endif
[ "dade916@gmail.com" ]
dade916@gmail.com
412842a1f7468627d5be54cd0dffb0fd04eab178
8dc84558f0058d90dfc4955e905dab1b22d12c08
/chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.cc
57e1df9c63c39ac0dc6b1e13a46a0d9bac509801
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
38,422
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.h" #include <math.h> #include <stddef.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/process/process_info.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_util.h" #include "base/task_scheduler/post_task.h" #include "base/task_scheduler/task_traits.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/incident_reporting/environment_data_collection.h" #include "chrome/browser/safe_browsing/incident_reporting/extension_data_collection.h" #include "chrome/browser/safe_browsing/incident_reporting/incident.h" #include "chrome/browser/safe_browsing/incident_reporting/incident_receiver.h" #include "chrome/browser/safe_browsing/incident_reporting/incident_report_uploader_impl.h" #include "chrome/browser/safe_browsing/incident_reporting/preference_validation_delegate.h" #include "chrome/browser/safe_browsing/incident_reporting/state_store.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/safe_browsing/proto/csd.pb.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/notification_service.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/preferences/public/mojom/tracked_preference_validation_delegate.mojom.h" namespace safe_browsing { const base::Feature kIncidentReportingEnableUpload { "IncidentReportingEnableUpload", #if defined(GOOGLE_CHROME_BUILD) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; namespace { // The action taken for an incident; used for user metrics (see // LogIncidentDataType). enum IncidentDisposition { RECEIVED, DROPPED, ACCEPTED, PRUNED, DISCARDED, NO_DOWNLOAD, NUM_DISPOSITIONS }; // The state persisted for a specific instance of an incident to enable pruning // of previously-reported incidents. struct PersistentIncidentState { // The type of the incident. IncidentType type; // The key for a specific instance of an incident. std::string key; // A hash digest representing a specific instance of an incident. uint32_t digest; }; // The amount of time the service will wait to collate incidents. const int64_t kDefaultUploadDelayMs = 1000 * 60; // one minute // The amount of time between running delayed analysis callbacks. const int64_t kDefaultCallbackIntervalMs = 1000 * 20; // Logs the type of incident in |incident_data| to a user metrics histogram. void LogIncidentDataType(IncidentDisposition disposition, const Incident& incident) { static const char* const kHistogramNames[] = { "SBIRS.ReceivedIncident", "SBIRS.DroppedIncident", "SBIRS.Incident", "SBIRS.PrunedIncident", "SBIRS.DiscardedIncident", "SBIRS.NoDownloadIncident", }; static_assert(arraysize(kHistogramNames) == NUM_DISPOSITIONS, "Keep kHistogramNames in sync with enum IncidentDisposition."); DCHECK_GE(disposition, 0); DCHECK_LT(disposition, NUM_DISPOSITIONS); base::LinearHistogram::FactoryGet( kHistogramNames[disposition], 1, // minimum static_cast<int32_t>(IncidentType::NUM_TYPES), // maximum static_cast<size_t>(IncidentType::NUM_TYPES) + 1, // bucket_count base::HistogramBase::kUmaTargetedHistogramFlag)->Add( static_cast<int32_t>(incident.GetType())); } // Computes the persistent state for an incident. PersistentIncidentState ComputeIncidentState(const Incident& incident) { PersistentIncidentState state = { incident.GetType(), incident.GetKey(), incident.ComputeDigest(), }; return state; } // Returns the shutdown behavior for the task runners of the incident reporting // service. Current metrics suggest that CONTINUE_ON_SHUTDOWN will reduce the // number of browser hangs on shutdown. base::TaskShutdownBehavior GetShutdownBehavior() { return base::FeatureList::IsEnabled(features::kBrowserHangFixesExperiment) ? base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN : base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN; } // Returns a task runner for blocking tasks in the background. scoped_refptr<base::TaskRunner> GetBackgroundTaskRunner() { return base::CreateTaskRunnerWithTraits({base::TaskPriority::BACKGROUND, GetShutdownBehavior(), base::MayBlock()}); } } // namespace struct IncidentReportingService::ProfileContext { ProfileContext(); ~ProfileContext(); // Returns true if the profile has incidents to be uploaded or cleared. bool HasIncidents() const; // The incidents collected for this profile pending creation and/or upload. // Will contain null values for pruned incidents. std::vector<std::unique_ptr<Incident>> incidents; // The incidents data of which should be cleared. std::vector<std::unique_ptr<Incident>> incidents_to_clear; // State storage for this profile; null until PROFILE_ADDED notification is // received. std::unique_ptr<StateStore> state_store; // False until PROFILE_ADDED notification is received. bool added; private: DISALLOW_COPY_AND_ASSIGN(ProfileContext); }; class IncidentReportingService::UploadContext { public: typedef std::map<ProfileContext*, std::vector<PersistentIncidentState>> PersistentIncidentStateCollection; explicit UploadContext(std::unique_ptr<ClientIncidentReport> report); ~UploadContext(); // The report being uploaded. std::unique_ptr<ClientIncidentReport> report; // The uploader in use. std::unique_ptr<IncidentReportUploader> uploader; // A mapping of profile contexts to the data to be persisted upon successful // upload. PersistentIncidentStateCollection profiles_to_state; private: DISALLOW_COPY_AND_ASSIGN(UploadContext); }; // An IncidentReceiver that is weakly-bound to the service and transparently // bounces process-wide incidents back to the main thread for handling. class IncidentReportingService::Receiver : public IncidentReceiver { public: explicit Receiver(const base::WeakPtr<IncidentReportingService>& service); ~Receiver() override; // IncidentReceiver methods: void AddIncidentForProfile(Profile* profile, std::unique_ptr<Incident> incident) override; void AddIncidentForProcess(std::unique_ptr<Incident> incident) override; void ClearIncidentForProcess(std::unique_ptr<Incident> incident) override; private: static void AddIncidentOnMainThread( const base::WeakPtr<IncidentReportingService>& service, Profile* profile, std::unique_ptr<Incident> incident); static void ClearIncidentOnMainThread( const base::WeakPtr<IncidentReportingService>& service, Profile* profile, std::unique_ptr<Incident> incident); base::WeakPtr<IncidentReportingService> service_; scoped_refptr<base::SingleThreadTaskRunner> thread_runner_; DISALLOW_COPY_AND_ASSIGN(Receiver); }; IncidentReportingService::Receiver::Receiver( const base::WeakPtr<IncidentReportingService>& service) : service_(service), thread_runner_(base::ThreadTaskRunnerHandle::Get()) { } IncidentReportingService::Receiver::~Receiver() { } void IncidentReportingService::Receiver::AddIncidentForProfile( Profile* profile, std::unique_ptr<Incident> incident) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(profile); AddIncidentOnMainThread(service_, profile, std::move(incident)); } void IncidentReportingService::Receiver::AddIncidentForProcess( std::unique_ptr<Incident> incident) { if (thread_runner_->BelongsToCurrentThread()) { AddIncidentOnMainThread(service_, nullptr, std::move(incident)); } else { thread_runner_->PostTask( FROM_HERE, base::BindOnce( &IncidentReportingService::Receiver::AddIncidentOnMainThread, service_, nullptr, std::move(incident))); } } void IncidentReportingService::Receiver::ClearIncidentForProcess( std::unique_ptr<Incident> incident) { if (thread_runner_->BelongsToCurrentThread()) { ClearIncidentOnMainThread(service_, nullptr, std::move(incident)); } else { thread_runner_->PostTask( FROM_HERE, base::BindOnce( &IncidentReportingService::Receiver::ClearIncidentOnMainThread, service_, nullptr, std::move(incident))); } } bool IncidentReportingService::HasIncidentsToUpload() const { for (const auto& profile_and_context : profiles_) { if (!profile_and_context.second->incidents.empty()) return true; } return false; } // static void IncidentReportingService::Receiver::AddIncidentOnMainThread( const base::WeakPtr<IncidentReportingService>& service, Profile* profile, std::unique_ptr<Incident> incident) { if (service) service->AddIncident(profile, std::move(incident)); else LogIncidentDataType(DISCARDED, *incident); } // static void IncidentReportingService::Receiver::ClearIncidentOnMainThread( const base::WeakPtr<IncidentReportingService>& service, Profile* profile, std::unique_ptr<Incident> incident) { if (service) service->ClearIncident(profile, std::move(incident)); } IncidentReportingService::ProfileContext::ProfileContext() : added(false) { } IncidentReportingService::ProfileContext::~ProfileContext() { for (const auto& incident : incidents) { if (incident) LogIncidentDataType(DISCARDED, *incident); } } bool IncidentReportingService::ProfileContext::HasIncidents() const { return !incidents.empty() || !incidents_to_clear.empty(); } IncidentReportingService::UploadContext::UploadContext( std::unique_ptr<ClientIncidentReport> report) : report(std::move(report)) {} IncidentReportingService::UploadContext::~UploadContext() { } // static bool IncidentReportingService::IsEnabledForProfile(Profile* profile) { if (profile->IsOffTheRecord()) return false; if (!profile->GetPrefs()->GetBoolean(prefs::kSafeBrowsingEnabled)) return false; return IsExtendedReportingEnabled(*profile->GetPrefs()); } IncidentReportingService::IncidentReportingService( SafeBrowsingService* safe_browsing_service) : url_loader_factory_(safe_browsing_service ? safe_browsing_service->GetURLLoaderFactory() : nullptr), collect_environment_data_fn_(&CollectEnvironmentData), environment_collection_task_runner_(GetBackgroundTaskRunner()), environment_collection_pending_(), collation_timeout_pending_(), collation_timer_(FROM_HERE, base::TimeDelta::FromMilliseconds(kDefaultUploadDelayMs), this, &IncidentReportingService::OnCollationTimeout), delayed_analysis_callbacks_( base::TimeDelta::FromMilliseconds(kDefaultCallbackIntervalMs), GetBackgroundTaskRunner()), receiver_weak_ptr_factory_(this), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); notification_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_ADDED, content::NotificationService::AllSources()); notification_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED, content::NotificationService::AllSources()); DownloadProtectionService* download_protection_service = (safe_browsing_service ? safe_browsing_service->download_protection_service() : nullptr); if (download_protection_service) { client_download_request_subscription_ = download_protection_service->RegisterClientDownloadRequestCallback( base::Bind(&IncidentReportingService::OnClientDownloadRequest, base::Unretained(this))); } } IncidentReportingService::~IncidentReportingService() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); CancelIncidentCollection(); // Cancel all internal asynchronous tasks. weak_ptr_factory_.InvalidateWeakPtrs(); CancelEnvironmentCollection(); CancelDownloadCollection(); CancelAllReportUploads(); } std::unique_ptr<IncidentReceiver> IncidentReportingService::GetIncidentReceiver() { return std::make_unique<Receiver>(receiver_weak_ptr_factory_.GetWeakPtr()); } std::unique_ptr<prefs::mojom::TrackedPreferenceValidationDelegate> IncidentReportingService::CreatePreferenceValidationDelegate(Profile* profile) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (profile->IsOffTheRecord()) return std::unique_ptr<prefs::mojom::TrackedPreferenceValidationDelegate>(); return std::make_unique<PreferenceValidationDelegate>(profile, GetIncidentReceiver()); } void IncidentReportingService::RegisterDelayedAnalysisCallback( const DelayedAnalysisCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // |callback| will be run on the blocking pool. The receiver will bounce back // to the origin thread if needed. delayed_analysis_callbacks_.RegisterCallback( base::Bind(callback, base::Passed(GetIncidentReceiver()))); // Start running the callbacks if any profiles are participating in safe // browsing extended reporting. If none are now, running will commence if/when // such a profile is added. if (FindEligibleProfile()) delayed_analysis_callbacks_.Start(); } void IncidentReportingService::AddDownloadManager( content::DownloadManager* download_manager) { download_metadata_manager_.AddDownloadManager(download_manager); } IncidentReportingService::IncidentReportingService( SafeBrowsingService* safe_browsing_service, base::TimeDelta delayed_task_interval, const scoped_refptr<base::TaskRunner>& delayed_task_runner) : collect_environment_data_fn_(&CollectEnvironmentData), environment_collection_task_runner_(GetBackgroundTaskRunner()), environment_collection_pending_(), collation_timeout_pending_(), collation_timer_(FROM_HERE, base::TimeDelta::FromMilliseconds(kDefaultUploadDelayMs), this, &IncidentReportingService::OnCollationTimeout), delayed_analysis_callbacks_(delayed_task_interval, delayed_task_runner), receiver_weak_ptr_factory_(this), weak_ptr_factory_(this) { notification_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_ADDED, content::NotificationService::AllSources()); notification_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED, content::NotificationService::AllSources()); } void IncidentReportingService::SetCollectEnvironmentHook( CollectEnvironmentDataFn collect_environment_data_hook, const scoped_refptr<base::TaskRunner>& task_runner) { if (collect_environment_data_hook) { collect_environment_data_fn_ = collect_environment_data_hook; environment_collection_task_runner_ = task_runner; } else { collect_environment_data_fn_ = &CollectEnvironmentData; environment_collection_task_runner_ = GetBackgroundTaskRunner(); } } void IncidentReportingService::DoExtensionCollection( ClientIncidentReport_ExtensionData* extension_data) { CollectExtensionData(extension_data); } void IncidentReportingService::OnProfileAdded(Profile* profile) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // Track the addition of all profiles even when no report is being assembled // so that the service can determine whether or not it can evaluate a // profile's preferences at the time of incident addition. ProfileContext* context = GetOrCreateProfileContext(profile); DCHECK(!context->added); context->added = true; context->state_store.reset(new StateStore(profile)); bool enabled_for_profile = IsEnabledForProfile(profile); // Drop all incidents associated with this profile that were received prior to // its addition if incident reporting is not enabled for it. if (!context->incidents.empty() && !enabled_for_profile) { for (const auto& incident : context->incidents) LogIncidentDataType(DROPPED, *incident); context->incidents.clear(); } if (enabled_for_profile) { // Start processing delayed analysis callbacks if incident reporting is // enabled for this new profile. Start is idempotent, so this is safe even // if they're already running. delayed_analysis_callbacks_.Start(); // Start a new report if there are process-wide incidents, or incidents for // this profile. if ((GetProfileContext(nullptr) && GetProfileContext(nullptr)->HasIncidents()) || context->HasIncidents()) { BeginReportProcessing(); } } // TODO(grt): register for pref change notifications to start delayed analysis // and/or report processing if sb is currently disabled but subsequently // enabled. // Nothing else to do if a report is not being assembled. if (!report_) return; // Environment collection is deferred until at least one profile for which the // service is enabled is added. Re-initiate collection now in case this is the // first such profile. BeginEnvironmentCollection(); // Take another stab at finding the most recent download if a report is being // assembled and one hasn't been found yet (the LastDownloadFinder operates // only on profiles that have been added to the ProfileManager). BeginDownloadCollection(); } std::unique_ptr<LastDownloadFinder> IncidentReportingService::CreateDownloadFinder( const LastDownloadFinder::LastDownloadCallback& callback) { return LastDownloadFinder::Create( base::Bind(&DownloadMetadataManager::GetDownloadDetails, base::Unretained(&download_metadata_manager_)), callback); } std::unique_ptr<IncidentReportUploader> IncidentReportingService::StartReportUpload( const IncidentReportUploader::OnResultCallback& callback, const ClientIncidentReport& report) { return IncidentReportUploaderImpl::UploadReport(callback, url_loader_factory_, report); } bool IncidentReportingService::IsProcessingReport() const { return report_ != nullptr; } IncidentReportingService::ProfileContext* IncidentReportingService::GetOrCreateProfileContext(Profile* profile) { std::unique_ptr<ProfileContext>& context = profiles_[profile]; if (!context) context = std::make_unique<ProfileContext>(); return context.get(); } IncidentReportingService::ProfileContext* IncidentReportingService::GetProfileContext(Profile* profile) { auto it = profiles_.find(profile); return it != profiles_.end() ? it->second.get() : nullptr; } void IncidentReportingService::OnProfileDestroyed(Profile* profile) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto it = profiles_.find(profile); if (it == profiles_.end()) return; // Take ownership of the context. std::unique_ptr<ProfileContext> context = std::move(it->second); it->second = nullptr; // TODO(grt): Persist incidents for upload on future profile load. // Remove the association with this profile context from all pending uploads. for (const auto& upload : uploads_) upload->profiles_to_state.erase(context.get()); // Forget about this profile. Incidents not yet sent for upload are lost. // No new incidents will be accepted for it. profiles_.erase(it); } Profile* IncidentReportingService::FindEligibleProfile() const { for (const auto& scan : profiles_) { // Skip over profiles that have yet to be added to the profile manager. // This will also skip over the NULL-profile context used to hold // process-wide incidents. if (!scan.second->added) continue; if (IsEnabledForProfile(scan.first)) return scan.first; } return nullptr; } void IncidentReportingService::AddIncident(Profile* profile, std::unique_ptr<Incident> incident) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // Ignore incidents from off-the-record profiles. if (profile && profile->IsOffTheRecord()) return; ProfileContext* context = GetOrCreateProfileContext(profile); // If this is a process-wide incident, the context must not indicate that the // profile (which is NULL) has been added to the profile manager. DCHECK(profile || !context->added); LogIncidentDataType(RECEIVED, *incident); // Drop the incident immediately if the profile has already been added to the // manager and does not have incident reporting enabled. Preference evaluation // is deferred until OnProfileAdded() otherwise. if (context->added && !IsEnabledForProfile(profile)) { LogIncidentDataType(DROPPED, *incident); return; } // Take ownership of the incident. context->incidents.push_back(std::move(incident)); // Remember when the first incident for this report arrived. if (first_incident_time_.is_null()) first_incident_time_ = base::Time::Now(); // Log the time between the previous incident and this one. if (!last_incident_time_.is_null()) { UMA_HISTOGRAM_TIMES("SBIRS.InterIncidentTime", base::TimeTicks::Now() - last_incident_time_); } last_incident_time_ = base::TimeTicks::Now(); // Persist the incident data. // Start assembling a new report if this is the first incident ever or the // first since the last upload. BeginReportProcessing(); } void IncidentReportingService::ClearIncident( Profile* profile, std::unique_ptr<Incident> incident) { ProfileContext* context = GetOrCreateProfileContext(profile); context->incidents_to_clear.push_back(std::move(incident)); // Begin processing to handle cleared incidents following collation. BeginReportProcessing(); } void IncidentReportingService::BeginReportProcessing() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // Creates a new report if needed. if (!report_) report_.reset(new ClientIncidentReport()); // Ensure that collection tasks are running (calls are idempotent). BeginIncidentCollation(); BeginEnvironmentCollection(); BeginDownloadCollection(); } void IncidentReportingService::BeginIncidentCollation() { // Restart the delay timer to send the report upon expiration. collation_timeout_pending_ = true; collation_timer_.Reset(); } bool IncidentReportingService::WaitingToCollateIncidents() { return collation_timeout_pending_; } void IncidentReportingService::CancelIncidentCollection() { collation_timeout_pending_ = false; last_incident_time_ = base::TimeTicks(); report_.reset(); } void IncidentReportingService::OnCollationTimeout() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // Exit early if collection was cancelled. if (!collation_timeout_pending_) return; // Wait another round if profile-bound incidents have come in from a profile // that has yet to complete creation. for (const auto& scan : profiles_) { if (scan.first && !scan.second->added && scan.second->HasIncidents()) { collation_timer_.Reset(); return; } } collation_timeout_pending_ = false; ProcessIncidentsIfCollectionComplete(); } void IncidentReportingService::BeginEnvironmentCollection() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(report_); // Nothing to do if environment collection is pending or has already // completed, if there are no incidents to process, or if there is no eligible // profile. if (environment_collection_pending_ || report_->has_environment() || !HasIncidentsToUpload() || !FindEligibleProfile()) { return; } environment_collection_begin_ = base::TimeTicks::Now(); ClientIncidentReport_EnvironmentData* environment_data = new ClientIncidentReport_EnvironmentData(); environment_collection_pending_ = environment_collection_task_runner_->PostTaskAndReply( FROM_HERE, base::BindOnce(collect_environment_data_fn_, environment_data), base::BindOnce(&IncidentReportingService::OnEnvironmentDataCollected, weak_ptr_factory_.GetWeakPtr(), base::WrapUnique(environment_data))); // Posting the task will fail if the runner has been shut down. This should // never happen since the blocking pool is shut down after this service. DCHECK(environment_collection_pending_); } bool IncidentReportingService::WaitingForEnvironmentCollection() { return environment_collection_pending_; } void IncidentReportingService::CancelEnvironmentCollection() { environment_collection_begin_ = base::TimeTicks(); environment_collection_pending_ = false; if (report_) report_->clear_environment(); } void IncidentReportingService::OnEnvironmentDataCollected( std::unique_ptr<ClientIncidentReport_EnvironmentData> environment_data) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(environment_collection_pending_); DCHECK(report_ && !report_->has_environment()); environment_collection_pending_ = false; // CurrentProcessInfo::CreationTime() is missing on some platforms. #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX) base::TimeDelta uptime = first_incident_time_ - base::CurrentProcessInfo::CreationTime(); environment_data->mutable_process()->set_uptime_msec(uptime.InMilliseconds()); #endif report_->set_allocated_environment(environment_data.release()); UMA_HISTOGRAM_TIMES("SBIRS.EnvCollectionTime", base::TimeTicks::Now() - environment_collection_begin_); environment_collection_begin_ = base::TimeTicks(); ProcessIncidentsIfCollectionComplete(); } void IncidentReportingService::BeginDownloadCollection() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(report_); // Nothing to do if a search for the most recent download is already pending, // if one has already been found, or if there are no incidents to process. if (last_download_finder_ || report_->has_download() || !HasIncidentsToUpload()) { return; } last_download_begin_ = base::TimeTicks::Now(); last_download_finder_ = CreateDownloadFinder( base::Bind(&IncidentReportingService::OnLastDownloadFound, weak_ptr_factory_.GetWeakPtr())); // No instance is returned if there are no eligible loaded profiles. Another // search will be attempted in OnProfileAdded() if another profile appears on // the scene. if (!last_download_finder_) last_download_begin_ = base::TimeTicks(); } bool IncidentReportingService::WaitingForMostRecentDownload() { DCHECK(report_); // Only call this when a report is being assembled. // The easy case: not waiting if a download has already been found. if (report_->has_download()) return false; // The next easy case: waiting if the finder is operating. if (last_download_finder_) return true; // Harder case 1: not waiting if there are no incidents to upload (only // incidents to clear). if (!HasIncidentsToUpload()) return false; // Harder case 2: waiting if a non-NULL profile has not yet been added. for (const auto& scan : profiles_) { if (scan.first && !scan.second->added) return true; } // There is no most recent download and there's nothing more to wait for. return false; } void IncidentReportingService::CancelDownloadCollection() { last_download_finder_.reset(); last_download_begin_ = base::TimeTicks(); if (report_) report_->clear_download(); } void IncidentReportingService::OnLastDownloadFound( std::unique_ptr<ClientIncidentReport_DownloadDetails> last_binary_download, std::unique_ptr<ClientIncidentReport_NonBinaryDownloadDetails> last_non_binary_download) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(report_); UMA_HISTOGRAM_TIMES("SBIRS.FindDownloadedBinaryTime", base::TimeTicks::Now() - last_download_begin_); last_download_begin_ = base::TimeTicks(); // Harvest the finder. last_download_finder_.reset(); if (last_binary_download) report_->set_allocated_download(last_binary_download.release()); if (last_non_binary_download) { report_->set_allocated_non_binary_download( last_non_binary_download.release()); } ProcessIncidentsIfCollectionComplete(); } void IncidentReportingService::ProcessIncidentsIfCollectionComplete() { DCHECK(report_); // Bail out if there are still outstanding collection tasks. Completion of any // of these will start another upload attempt. if (WaitingForEnvironmentCollection() || WaitingToCollateIncidents() || WaitingForMostRecentDownload()) { return; } // Take ownership of the report and clear things for future reports. std::unique_ptr<ClientIncidentReport> report(std::move(report_)); first_incident_time_ = base::Time(); last_incident_time_ = base::TimeTicks(); ClientIncidentReport_EnvironmentData_Process* process = report->mutable_environment()->mutable_process(); process->set_metrics_consent( ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled()); // Associate process-wide incidents with any eligible profile. If there is no // eligible profile, drop the incidents. ProfileContext* null_context = GetProfileContext(nullptr); if (null_context && null_context->HasIncidents()) { Profile* eligible_profile = FindEligibleProfile(); if (eligible_profile) { ProfileContext* eligible_context = GetProfileContext(eligible_profile); // Move the incidents to the target context. for (auto& incident : null_context->incidents) { eligible_context->incidents.push_back(std::move(incident)); } null_context->incidents.clear(); for (auto& incident : null_context->incidents_to_clear) eligible_context->incidents_to_clear.push_back(std::move(incident)); null_context->incidents_to_clear.clear(); } else { for (const auto& incident : null_context->incidents) LogIncidentDataType(DROPPED, *incident); null_context->incidents.clear(); } } // Clear incidents data where needed. for (auto& profile_and_context : profiles_) { // Bypass process-wide incidents that have not yet been associated with a // profile and profiles with no incidents to clear. if (!profile_and_context.first || profile_and_context.second->incidents_to_clear.empty()) { continue; } ProfileContext* context = profile_and_context.second.get(); StateStore::Transaction transaction(context->state_store.get()); for (const auto& incident : context->incidents_to_clear) transaction.Clear(incident->GetType(), incident->GetKey()); context->incidents_to_clear.clear(); } // Abandon report if there are no incidents to upload. if (!HasIncidentsToUpload()) return; bool has_download = report->has_download() || report->has_non_binary_download(); // Collect incidents across all profiles participating in safe browsing // extended reporting. // Associate the profile contexts and their incident data with the upload. UploadContext::PersistentIncidentStateCollection profiles_to_state; for (auto& profile_and_context : profiles_) { // Bypass process-wide incidents that have not yet been associated with a // profile. if (!profile_and_context.first) continue; ProfileContext* context = profile_and_context.second.get(); if (context->incidents.empty()) continue; // Drop all incidents collected for the profile if it stopped participating // before collection completed. if (!IsEnabledForProfile(profile_and_context.first)) { for (const auto& incident : context->incidents) LogIncidentDataType(DROPPED, *incident); context->incidents.clear(); continue; } StateStore::Transaction transaction(context->state_store.get()); std::vector<PersistentIncidentState> states; // Prep persistent data and prune any incidents already sent. for (const auto& incident : context->incidents) { const PersistentIncidentState state = ComputeIncidentState(*incident); if (context->state_store->HasBeenReported(state.type, state.key, state.digest)) { LogIncidentDataType(PRUNED, *incident); } else if (!has_download) { LogIncidentDataType(NO_DOWNLOAD, *incident); // Drop the incident and mark for future pruning since no executable // download was found. transaction.MarkAsReported(state.type, state.key, state.digest); } else { LogIncidentDataType(ACCEPTED, *incident); // Ownership of the payload is passed to the report. ClientIncidentReport_IncidentData* data = incident->TakePayload().release(); DCHECK(data->has_incident_time_msec()); report->mutable_incident()->AddAllocated(data); data = nullptr; states.push_back(state); } } context->incidents.clear(); profiles_to_state[context].swap(states); } const int count = report->incident_size(); // Abandon the request if all incidents were pruned or otherwise dropped. if (!count) { if (!has_download) { UMA_HISTOGRAM_ENUMERATION("SBIRS.UploadResult", IncidentReportUploader::UPLOAD_NO_DOWNLOAD, IncidentReportUploader::NUM_UPLOAD_RESULTS); } return; } UMA_HISTOGRAM_COUNTS_100("SBIRS.IncidentCount", count); // Perform final synchronous collection tasks for the report. DoExtensionCollection(report->mutable_extension_data()); std::unique_ptr<UploadContext> context(new UploadContext(std::move(report))); context->profiles_to_state.swap(profiles_to_state); UploadContext* temp_context = context.get(); uploads_.push_back(std::move(context)); IncidentReportingService::UploadReportIfUploadingEnabled(temp_context); } void IncidentReportingService::CancelAllReportUploads() { for (size_t i = 0; i < uploads_.size(); ++i) { UMA_HISTOGRAM_ENUMERATION("SBIRS.UploadResult", IncidentReportUploader::UPLOAD_CANCELLED, IncidentReportUploader::NUM_UPLOAD_RESULTS); } uploads_.clear(); } void IncidentReportingService::UploadReportIfUploadingEnabled( UploadContext* context) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!base::FeatureList::IsEnabled(kIncidentReportingEnableUpload)) { OnReportUploadResult(context, IncidentReportUploader::UPLOAD_SUPPRESSED, std::unique_ptr<ClientIncidentResponse>()); return; } // Initiate the upload. context->uploader = StartReportUpload( base::Bind(&IncidentReportingService::OnReportUploadResult, weak_ptr_factory_.GetWeakPtr(), context), *context->report); if (!context->uploader) { OnReportUploadResult(context, IncidentReportUploader::UPLOAD_INVALID_REQUEST, std::unique_ptr<ClientIncidentResponse>()); } } void IncidentReportingService::HandleResponse(const UploadContext& context) { // Mark each incident as reported in its corresponding profile's state store. for (const auto& context_and_states : context.profiles_to_state) { StateStore::Transaction transaction( context_and_states.first->state_store.get()); for (const auto& state : context_and_states.second) transaction.MarkAsReported(state.type, state.key, state.digest); } } void IncidentReportingService::OnReportUploadResult( UploadContext* context, IncidentReportUploader::Result result, std::unique_ptr<ClientIncidentResponse> response) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); UMA_HISTOGRAM_ENUMERATION( "SBIRS.UploadResult", result, IncidentReportUploader::NUM_UPLOAD_RESULTS); // The upload is no longer outstanding, so take ownership of the context (from // the collection of outstanding uploads) in this scope. auto it = std::find_if(uploads_.begin(), uploads_.end(), [context](const std::unique_ptr<UploadContext>& value) { return value.get() == context; }); DCHECK(it != uploads_.end()); std::unique_ptr<UploadContext> upload(std::move(*it)); uploads_.erase(it); if (result == IncidentReportUploader::UPLOAD_SUCCESS) HandleResponse(*upload); // else retry? } void IncidentReportingService::OnClientDownloadRequest( download::DownloadItem* download, const ClientDownloadRequest* request) { if (content::DownloadItemUtils::GetBrowserContext(download) && !content::DownloadItemUtils::GetBrowserContext(download) ->IsOffTheRecord()) { download_metadata_manager_.SetRequest(download, request); } } void IncidentReportingService::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_PROFILE_ADDED: { Profile* profile = content::Source<Profile>(source).ptr(); if (!profile->IsOffTheRecord()) OnProfileAdded(profile); break; } case chrome::NOTIFICATION_PROFILE_DESTROYED: { Profile* profile = content::Source<Profile>(source).ptr(); if (!profile->IsOffTheRecord()) OnProfileDestroyed(profile); break; } default: break; } } } // namespace safe_browsing
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
46f0488237d843908ca136d3d8f9d6b35304af83
75af55c073d572d50e49b771e32b5b75d877e609
/day3/code/course/bfs.cpp
d7840e93209e48e7076b09538a2d9472172bb33d
[]
no_license
xtlsoft/JSOI2018
5e8305dc806475dc0d350980392f595eea22de76
7c9c2de74f989a2fe6268b7f65d1603e7d86f2cc
refs/heads/master
2020-03-22T04:37:09.398633
2018-08-24T13:11:54
2018-08-24T13:11:54
139,509,818
0
0
null
null
null
null
UTF-8
C++
false
false
1,344
cpp
#include <iostream> #include <cstring> #include <queue> using namespace std; const int INF = 0x3f3f3f3f; const int BORDER = 1000000; const int MAXN = BORDER; bool flag; int n, k; struct Node { int x, steps; Node(int x_input, int steps_input) : x(x_input), steps(steps_input) {}; }; queue<Node> q; bool vis[MAXN]; int min(int a, int b) { if (a < b) return a; else return b; } void bfs() { q.push(Node(n, 0)); // 初始状态入队。农夫初始位置,steps = 0。 vis[n] = true; // 起点判重 while(!q.empty()){ // 判断队列非空 Node curr = q.front(); // 存储队首 q.pop(); // 已保存,可出队。不能忘记。 if(curr.x == k) { // 当找到时 cout << curr.steps << endl; break; // 第一个一定是最优的; } else for (int i = 1; i <= 3; ++ i ) { int nx; if(i == 1) nx = curr.x - 1; if(i == 2) nx = curr.x + 1; if(i == 3) nx = curr.x * 2; if(nx >= 0 && nx <= BORDER && !vis[nx]) { vis[nx] = true; q.push(Node(nx, curr.steps + 1)); } } } } int main () { cin >> n >> k; bfs(); return 0; } /* x-1 x+1 2*x -> 1 分钟 5 17 4 */
[ "xtlsoft@126.com" ]
xtlsoft@126.com
6d62c2dc963aab5fedb1de266d04ed888d5638a5
f396af9e3728e0acbc40c2674028031bd8b446f9
/cmake-build-debug/Backpack.h
0d4349a6032eb27df0dd7492247a3db0c0e95b70
[]
no_license
Cschwalb/VIrus
514e301ff6f0e6446b8a7f8b1a2fac0c53b36b57
7a201a568e451d2fc890a0f269a22eb2feb95210
refs/heads/master
2023-01-10T14:39:34.005949
2020-11-02T10:21:56
2020-11-02T10:21:56
307,868,041
0
0
null
null
null
null
UTF-8
C++
false
false
888
h
// // Created by calebs on 10/26/2020. // #ifndef HACKERSIM_BACKPACK_H #define HACKERSIM_BACKPACK_H #include "string" #include "../VIrus.h" #include "list" class Backpack { // usb stick? public: Backpack(); // copy method? bool addItem(VIrus); // need to add a virus bool takeItem(VIrus); double getCash(); void addCash(double dCash); int countVirus(std::basic_string<char>); double getMaxStorage(){ return this->m_nMaxStorage; } double getCurrentStorage(){ return this->m_nCurrentStorage; } // basicall a usb stick. const std::string toString(); std::string dumpCurrentItems(); inline int countWritten(){ return this->m_lViruses.size(); } private: double m_nMaxStorage; double m_nCurrentStorage; double m_nTotalCash; std::list<VIrus> m_lViruses; }; #endif //HACKERSIM_BACKPACK_H
[ "calebschwalb@gmail.com" ]
calebschwalb@gmail.com
7136912a242a5bd719078e402952e68aceca3fe4
c6a94b66d3c23d8dac78c2f76e70825e10ad8b44
/cpp/system.cpp
663ee03c29f2fe4aef999f9f985eaddbff50f9cb
[]
no_license
eddiewangjian/basic_sample
ddcef8a0fcdf78e476118a8bc9398d9df9364529
895033fb69453459fd9c132f5fc6149cf7b51737
refs/heads/master
2020-03-23T16:16:56.069393
2019-01-01T14:25:18
2019-01-01T14:25:18
141,802,107
0
0
null
null
null
null
UTF-8
C++
false
false
520
cpp
#include <thread> #include <iostream> #include <stdlib.h> #include <string> #include <unistd.h> void system_run(const char *command) { int ret = system(command); std::cout << "ret=" << ret << std::endl; } void detach_system_run(const char *command) { std::thread(&system_run, command).detach(); while (true) { sleep(10); std::cout << "main alive" << std::endl; } } int main(int argc, char** argv) { //system_run("sh run_2s.sh"); detach_system_run("sh run_2s.sh"); }
[ "376613599@qq.com" ]
376613599@qq.com
1bc0a9b17cc96efba60599151b5c5bba0f08ec39
55347c4e118221df5640f553210eb0fef002c416
/labs/lab04/src/robot_land.h
061132edfb12b6ee454db64e7a11686f3699b60c
[]
no_license
Icirain/test
2246812ded536ef0f8a406e2b87b6b0da90a5ccb
b6e925f44847af830d9169d5a6f6c1ed328b8186
refs/heads/master
2020-03-07T07:07:38.391591
2018-03-22T23:45:40
2018-03-22T23:45:40
127,340,434
0
0
null
null
null
null
UTF-8
C++
false
false
4,948
h
/** * @file robot_land.h * * @copyright 2017 3081 Staff, All rights reserved. */ #ifndef LABS_LAB04_SRC_ROBOT_LAND_H_ #define LABS_LAB04_SRC_ROBOT_LAND_H_ /******************************************************************************* * Includes ******************************************************************************/ #include <cmath> #include <iostream> #include "robot.h" /******************************************************************************* * Class Definitions ******************************************************************************/ /** * @brief The main class for the simulation of a 2D world with many robots * running * around. * * RobotViewer or Tests call \ref set_time and \ref advance_time to control the * simulation and use the get*() functions to read out the current state of the * simulation (i.e., the current positions and orientations of robots and * obstacles). * * For now, RobotLand is hard coded to run a simulation of two robots running * around in a circle. You can see their sensors, but they don't yet respond * to each other or to obstacles. */ class RobotLand { public: RobotLand(void) {} /** * @brief Set the simulation time for \ref RobotLand. * * This function will be used mainly for testing purposes, as time flows in a * steady forward direction in general simulation. * * @param[in] t The new simulation time. */ void set_time(double t) { sim_time_ = t; std::cout << "Setting simulation time to " << sim_time_ << std::endl; } /** * @brief Advance the simulation by the specified # of steps. * * @param[in] dt The # of steps to increment by. */ // Once the robot class is created, this should call a robot method to // advance its position and set the velocity based on dt void advance_time(double dt) { sim_time_ += dt; std::cout << "Advancing simulation time to " << sim_time_ << std::endl; } /** * @brief Get the current simulation time. */ double get_current_time(void) { return sim_time_; } /* * @brief Get the current # of robots in the arena. Currently a stub. * * @todo: Actually implement this. */ int get_num_robots(void); /** * @brief Get the current position of the specified robot. Currently a stub. * * @todo: Actually implement this. * * @param[in] id The ID of the robot. * @param[out] x_pos The X position of the robot. * @param[out] y_pos The Y position of the robot. * * @return @todo: What does this mean? */ bool get_robot_pos(int id, double *x_pos, double *y_pos); /** * @brief Get the current velocity of the specified robot. Currently a stub. * * @todo Actually implement this. * * @param[in] id The ID of the robot. * @param[out] x_vel The X component of velocity. * @param[out] y_vel The Y component of velocity. * * @return @todo what does this mean? */ bool get_robot_vel(int id, double *x_vel, double *y_vel); /** * @brief Get the radius of the specified robot. Currently a stub. * * @todo: Actually implement this. * * @param[in] id The ID of the robot. * * @return The robot's radius. */ double get_robot_radius(int id); /** * @brief Get the angle of the specified robots sensor, in radians. Currently * a stub. * * @todo: Actually implement this. * * @param id The ID of the robot. * * @return The sensor angle in radians, */ double get_robot_sensor_angle(int id); /** * @brief Get the distance of a specified robot's sensor. Currently a stub. * * @todo: Actually implement this. * * @param[in] id The ID of the robot. * * @return The sensor distance. */ double get_robot_sensor_distance(int id); /** * @brief Get the # of obstacles currently in RobotLand. Currently a stub. * * @todo: Actually implement this. * * @return The # of obstacles. */ int get_num_obstacles(void); /** * @brief Get the position of the specified obstacle. Currently a stub. * * @todo: Actually implement this. * * @param[in] id The ID of the obstacle. * @param[out] x_pos The X component of the position. * @param[out] y_pos The Y component of the position. * * @return @todo What does this mean? */ bool get_obstacle_pos(int id, double *x_pos, double *y_pos); /** * @brief Get the radius of the specified obstacle. * * @param[in] id The ID of the obstacle. * * @return The obstacle's radius. */ double get_obstacle_radius(int id); private: // Hard coding these robots to move in a circle double circle_x(double t) { return 512 + 200.0 * cos(t); } double circle_y(double t) { return 350 + 200.0 * sin(t); } double sim_time_{1.0}; csci3081::Robot* test1 = new csci3081::Robot(40, 512, 350); csci3081::Robot* test2 = new csci3081::Robot(100, 512, 350); }; #endif // LABS_LAB04_SRC_ROBOT_LAND_H_
[ "zuoxx067@umn.edu" ]
zuoxx067@umn.edu
38ccae7146567e1bc74301413ed5698788fa157f
a190458c32197f554bb66bf4b13b5a855c577566
/19list/main.cpp
9e41a5db6c9972036ceba9732037bb3985ab2904
[]
no_license
YunaLin/cplusplus
5d162da9e4da2048eb72238ec66c0e2b4fb3a79b
14c7f26e6c7a6176336ec3dfbb78d4fde48fb8d0
refs/heads/master
2020-12-24T10:16:12.089351
2016-11-07T15:43:25
2016-11-07T15:43:25
73,088,396
0
0
null
null
null
null
UTF-8
C++
false
false
839
cpp
#include <iostream> #include <string> #include "list.hpp" using std::cin; using std::cout; using std::endl; using std::string; int main() { list li; int n; cin >> n; for (int i = 0, data, pos; i < n; i++) { cin >> pos >> data; li.insert(pos, data); } cout << li.toString() << " size: " << li.size() << endl; list li2(li); list li3; li = li3 = li2 = li; cout << li.toString() << " size: " << li.size() << endl; cout << li2.toString() << " size: " << li2.size() << endl; cout << li3.toString() << " size: " << li3.size() << endl; int m; cin >> m; for (int i = 0, pos; i < m; i++) { cin >> pos; li.erase(pos); } cout << li.toString() << endl; cout << li.sort().toString() << endl; cout << li2.sort().toString() << endl; cout << li3.sort().toString() << endl; return 0; }
[ "linzy28@mail2.sysu.edu.cn" ]
linzy28@mail2.sysu.edu.cn
0eadadcfcee0aab21a6d6b17df929fb993ab7c18
163bad17c2ba0aeeb05e29d1a7f870e675ee28eb
/hikyuu_cpp/hikyuu/indicator/imp/IAbs.h
0887fc68b5350cc9d53c3616c522d1863acfee9f
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
fasiondog/hikyuu
8b7bc4fd99ff915c621586a480c3663ef3fae464
86b0fa5b0e847d9a04905bca93660a7a33fc9fc2
refs/heads/master
2023-09-03T15:04:33.983389
2023-09-03T11:17:46
2023-09-03T11:17:46
5,103,141
1,884
547
MIT
2023-09-06T16:53:51
2012-07-18T23:21:42
C++
UTF-8
C++
false
false
402
h
/* * IAbs.h * * Created on: 2019-4-2 * Author: fasiondog */ #pragma once #ifndef INDICATOR_IMP_IABS_H_ #define INDICATOR_IMP_IABS_H_ #include "../Indicator.h" namespace hku { class IAbs : public IndicatorImp { INDICATOR_IMP(IAbs) INDICATOR_IMP_NO_PRIVATE_MEMBER_SERIALIZATION public: IAbs(); virtual ~IAbs(); }; } /* namespace hku */ #endif /* INDICATOR_IMP_IABS_H_ */
[ "fasiondog@163.com" ]
fasiondog@163.com
faa6f228e6d0ae071ac712e6f807b53a669285e2
c411d88bf5b2ef61cb8e5f2c934d18b5d2757a0e
/src/test/base64_tests.cpp
b40c030f5897834e6c85296ea2eae500ad27e798
[ "MIT" ]
permissive
goodthebest/saros
d0f3c557668ccfc8eaf8c0fed9997791deea493b
8e1dd0142c8d26db2c614d2066fcf9a485e5899b
refs/heads/master
2021-04-03T01:33:37.871796
2018-03-12T23:32:28
2018-03-12T23:32:28
124,943,940
0
0
MIT
2018-03-12T19:57:37
2018-03-12T19:57:37
null
UTF-8
C++
false
false
882
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "utilstrencodings.h" #include "test/test_saros.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(base64_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(base64_testvectors) { static const std::string vstrIn[] = {"","f","fo","foo","foob","fooba","foobar"}; static const std::string vstrOut[] = {"","Zg==","Zm8=","Zm9v","Zm9vYg==","Zm9vYmE=","Zm9vYmFy"}; for (unsigned int i=0; i<sizeof(vstrIn)/sizeof(vstrIn[0]); i++) { std::string strEnc = EncodeBase64(vstrIn[i]); BOOST_CHECK(strEnc == vstrOut[i]); std::string strDec = DecodeBase64(strEnc); BOOST_CHECK(strDec == vstrIn[i]); } } BOOST_AUTO_TEST_SUITE_END()
[ "root@guest" ]
root@guest
860c2e47656b963316fe3e43ce1505ee2f7d5146
b6e0c18357e447480b731e776d1fffe2d1b00a31
/lynx/render/render_tree_host_impl.cpp
1f80b78d131720fca8dfe4ff796c83a9b0cf90ee
[ "MIT" ]
permissive
Neilcc/lynx-native
df94361afc0dfc25d1710cee8bce8875108be3df
5a909f783c2ce9ff158d1114105c435e294d9382
refs/heads/master
2021-07-06T21:43:55.330729
2017-09-25T02:49:52
2017-09-25T02:49:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,946
cpp
// Copyright 2017 The Lynx Authors. All rights reserved. #include "render/render_tree_host_impl.h" #include "render/render_object.h" #include "render/impl/render_object_impl.h" #include "render/render_tree_host.h" namespace lynx { RenderTreeHostImpl::RenderTreeHostImpl( jscore::ThreadManager* thread_manager, RenderTreeHost* host, RenderObjectImpl* root) : render_state_(RENDER_STATE_NONE), thread_manager_(thread_manager), render_tree_host_(host), render_root_(root), is_parse_finished_(false), is_first_layouted_(false){ } RenderTreeHostImpl::~RenderTreeHostImpl() { } void RenderTreeHostImpl::NextAction() { if (render_state_ == RENDER_STATE_NONE) { render_state_ = RENDER_STATE_BEGIN_FRAME; } else if (render_state_ == RENDER_STATE_BEGIN_FRAME_COMPLETE) { render_state_ = RENDER_STATE_COMMIT; } else if (render_state_ == RENDER_STATE_COMMIT_COMPLETE) { render_state_ = RENDER_STATE_NONE; } else if(render_state_ == RENDER_STATE_COMPLETE) { render_state_ = RENDER_STATE_NONE; } } void RenderTreeHostImpl::DoRenderAction() { NextAction(); switch (render_state_) { case RENDER_STATE_BEGIN_FRAME: BeginFrame(); break; case RENDER_STATE_COMMIT: Commit(); break; default: break; } } bool RenderTreeHostImpl::FirstLayout() { if(is_parse_finished_ && !is_first_layouted_) { render_tree_host_->ForceLayout(0, 0, viewport_.width_, viewport_.height_); render_tree_host_->ForceFlushCommands(); base::ScopedRefPtr<RenderTreeHost> ref(render_tree_host_); thread_manager_->RunOnJSThread( base::Bind(&RenderTreeHost::TreeSync, ref)); is_first_layouted_ = true; } return is_first_layouted_; } void RenderTreeHostImpl::UpdateViewport(int width, int height) { viewport_.width_ = width; viewport_.height_ = height; BeginFrame(); } void RenderTreeHostImpl::BeginFrame() { if(!FirstLayout()) { return; } RenderTreeHost::BeginFrameData data; data.viewport_ = viewport_; data.client_ = this; base::ScopedRefPtr<RenderTreeHost> ref(render_tree_host_); thread_manager_->RunOnJSThread( base::Bind(&RenderTreeHost::DoBeginFrame, ref, data)); } void RenderTreeHostImpl::NotifyBeginFrameComplete() { base::ScopedRefPtr<RenderTreeHostImpl> ref(this); thread_manager_->RunOnUIThread( base::Bind(&RenderTreeHostImpl::BeginFrameComplete, ref)); } void RenderTreeHostImpl::BeginFrameComplete() { // next action do commit //render_state_ = RENDER_STATE_BEGIN_FRAME_COMPLETE; // next action do noting wait next frame render_state_ = RENDER_STATE_COMPLETE; DoRenderAction(); } void RenderTreeHostImpl::Commit() { render_tree_host_->DoCommit(); render_state_ = RENDER_STATE_COMMIT_COMPLETE; NextAction(); } } // namespace lynx
[ "lidong0227@gmail.com" ]
lidong0227@gmail.com
9d71e9b07ba8f1257798cb33a168250ad365c8e3
ef55551d534793537e696a41346ea940a35fc93d
/ProjectX/Avi/Avivids.cpp
9e25b87857025cb150ac5f4eb190aae6de9da815
[ "MIT" ]
permissive
ForsakenW/forsaken
c4be662be9a9a22b6973b7439cf462dc60b8c502
f06e2b9031e96a9fd219ab1326ad4eacbab37d44
refs/heads/master
2016-09-09T20:44:50.131393
2015-06-25T23:32:36
2015-06-25T23:32:36
37,788,466
11
0
null
null
null
null
UTF-8
C++
false
false
8,962
cpp
// aviVids.cpp : Implementation of video for the CAviMovie class // // This code and information is provided "as is" without warranty of // any kind, either expressed or implied, including but not limited to // the implied warranties of merchantability and/or fitness for a // particular purpose. // Copyright (C) 1995 Intel Corporation. All rights reserved. // #include <windows.h> #include <windowsx.h> #include "aviMovie.h" extern "C" { #include "XMem.h" } #ifdef _DEBUG #include <stdio.h> #include <assert.h> #define ASSERT assert #else #define ASSERT / ## / #endif void EndProcess (int); /////////////////////////////////////////////////////////////////////////////// // Video Operations // Open and init VIDS // long CAviMovie::vidsVideoOpen () { if (!m_paviVideo) return (VIDSERR_NOVIDEO); // Check if opening w/o closing if (m_pVCM) vidsVideoClose (); m_timePlayStart = -1L; // Get stream info AVISTREAMINFO avis; AVIStreamInfo (m_paviVideo, &avis, sizeof (avis)); m_vidsFirst = m_vidsCurrent = avis.dwStart; m_vidsLast = avis.dwStart + avis.dwLength - 1; m_vidsPrevious = m_vidsCurrent-1; // Read first frame to get source info long cb, rval; BITMAPINFOHEADER biFormat; AVIStreamFormatSize (m_paviVideo, 0, &cb); if (cb != sizeof (BITMAPINFOHEADER)) return (-1L); rval = AVIStreamReadFormat (m_paviVideo, 0, &biFormat, &cb); // Initiate VCM m_pVCM = (CVideoVCM *) new CVideoVCM (); // Open VCM for this instance if (m_pVCM->vcmOpen (avis.fccHandler, &biFormat)) { vidsVideoClose (); return (VIDSERR_VCM); } // Create temporary buffer m_cbvBuf = biFormat.biHeight * ALIGNULONG (biFormat.biWidth) * biFormat.biBitCount/8; m_pvBuf = (unsigned char *) malloc( m_cbvBuf); if (!m_pvBuf) EndProcess (ERROR_NOT_ENOUGH_MEMORY); // Reset internal skip count m_play_fskipped = 0; return (VIDSERR_OK); } // Close VIDS // long CAviMovie::vidsVideoClose () { if (m_pvBuf) { free(m_pvBuf); m_pvBuf = 0L; } if (m_pVCM) { delete m_pVCM; m_pVCM = 0L; } return (VIDSERR_OK); } // Start video, note that all decode/draw is done in vidsDraw() // // If fStart < 0, then start on current frame // long CAviMovie::vidsVideoStart (HDC hdc, long fStart /* = -1L */) { if (!m_pVCM) return (VIDSERR_VCM); if (!hdc) return (VIDSERR_DC); m_hdc = hdc; if (fStart >= 0) m_vidsCurrent = fStart; // Begin VCM if (m_pVCM->vcmBegin (hdc, m_frate)) { vidsVideoStop (); return (VIDSERR_VCM); } // Pass seperate start message to VCM only when playing if (m_bPlaying) m_pVCM->vcmDrawStart (m_frate); // Get start time m_timePlayStart = timeGetTime (); m_timePlayStartPos = AVIStreamSampleToTime (m_paviVideo, m_vidsCurrent); // Init play stats m_play_fprev = m_vidsCurrent; return (VIDSERR_OK); } // Stop video // long CAviMovie::vidsVideoStop () { if (!m_hdc) return (VIDSERR_DC); m_pVCM->vcmDrawStop (); m_pVCM->vcmEnd (); m_timePlayStart = -1L; // Not responsible for releasing DC m_hdc = 0; return (VIDSERR_OK); } // Draw current frame of video // long CAviMovie::vidsVideoDraw () { if (!m_pVCM) return (VIDSERR_VCM); // Check if started if (m_timePlayStart < 0) return (VIDSERR_NOTSTARTED); // Simple synchronization to the audio stream here: // just query the audio driver the sample it is on then draw // the video frame that corresponds to it. if (m_bPlaying) { long lTime = audsGetTime (); // Sync to absolute time if no audio playing // this could also occur if the audio card is reporting incorrect timing info if (lTime < 0) lTime = m_timePlayStartPos + (timeGetTime () - m_timePlayStart); m_vidsCurrent = vidsTimeToSample (lTime); if (m_vidsCurrent > m_vidsLast) m_vidsCurrent = m_vidsLast; if (m_vidsCurrent == m_vidsPrevious) { // Going too fast! Should actually return a ms // count so calling app can Sleep() if desired. return (VIDSERR_OK); } } else { if (m_vidsCurrent > m_vidsLast) m_vidsCurrent = m_vidsLast; if (m_vidsCurrent == m_vidsPrevious) { vidsResetDraw (); } } if (!vidsSync ()) return (VIDSERR_OK); // don't draw this frame long rval = AVIStreamRead (m_paviVideo, m_vidsCurrent, 1, m_pvBuf, m_cbvBuf, NULL, NULL); if (rval) { return (VIDSERR_READ); } /* if(rval = m_pBMP->bmpDraw(&m_Rect)) return (VIDERR_VCM); */ if (rval = m_pVCM->vcmDraw (m_pvBuf)) return (VIDSERR_VCM); m_vidsPrevious = m_vidsCurrent; if (m_bPlaying) { m_play_fskipped += (m_vidsCurrent-m_play_fprev-1); m_play_fprev = m_vidsCurrent; } return (VIDSERR_OK); } // Convert ms to sample (frame) long CAviMovie::vidsTimeToSample (long lTime) { long lSamp = AVIStreamTimeToSample (m_paviVideo, lTime); return (lSamp); } // Convert sample (frame) to ms long CAviMovie::vidsSampleToTime (long lSamp) { long lTime = AVIStreamSampleToTime (m_paviVideo, lSamp); return (lTime); } // TURE if frame is KEY, if frame < 0 then check current frame BOOL CAviMovie::vidsIsKey (long frame /* = -1 */) { if (!m_paviVideo) return FALSE; if (frame < 0) frame = m_vidsCurrent; return AVIStreamIsKeyFrame (m_paviVideo, frame); } /////////////////////////////////////////////////////////////////////////////// // Internal video routines // Synchronization and Keyframe Management: // pretty simple plan, don't do anything too fancy. BOOL CAviMovie::vidsSync () { #define dist(x,y) ((x)-(y)) #define ABS_(x) (x<0 ? (-(x)) : (x)) if (m_vidsCurrent < m_vidsPrevious) // seeked back - reset draw m_vidsPrevious = -1; if (dist (m_vidsCurrent, m_vidsPrevious) == 1) { // normal situation // fall thru and draw } else { // SKIPPED if (AVIStreamIsKeyFrame (m_paviVideo, m_vidsCurrent)) { // we are on KF boundry just reset and start here m_vidsPrevKey = m_vidsCurrent; m_vidsNextKey = AVIStreamNextKeyFrame (m_paviVideo, m_vidsCurrent); // fall thru and draw } else if (dist (m_vidsCurrent, m_vidsPrevious) == 2) { // one frame off - just draw vidsCatchup (); // fall thru and draw } else { // We are greater than one frame off: // if we went past a K frame, update K frame info then: // if we are closer to previous frame than catchup and draw // if we are closer to next KEY frame than don't draw if ( (m_vidsNextKey < m_vidsCurrent) || (m_vidsPrevKey > m_vidsCurrent) ) // seeked past previous key frame { // went past a K frame m_vidsPrevKey = AVIStreamPrevKeyFrame (m_paviVideo, m_vidsCurrent); m_vidsNextKey = AVIStreamNextKeyFrame (m_paviVideo, m_vidsCurrent); } if ( ABS_(dist (m_vidsCurrent, m_vidsPrevKey)) <= ABS_(dist (m_vidsCurrent, m_vidsNextKey))) { vidsCatchup (); // fall thru and draw } else { if (m_bPlaying) return (FALSE); // m_vidsPrev NOT updated else vidsCatchup (); // if not playing than we want to // draw the current frame } } } return (TRUE); } // Readies to draw (but doesn't draw) m_vidsCurrent. // We just ICDECOMPRESS_HURRYUP frames from m_vidsPrevious or // m_vidsPrevKey, whichever is closer. // Updates m_vidsPrevious. // void CAviMovie::vidsCatchup () { if (m_vidsPrevious < m_vidsPrevKey) m_vidsPrevious = m_vidsPrevKey-1; long catchup = m_vidsPrevious+1; while (catchup < m_vidsCurrent) { long rval = AVIStreamRead (m_paviVideo, catchup, 1, m_pvBuf, m_cbvBuf, NULL, NULL); if (rval) { break; } if (!m_bPlaying ) m_pVCM->vcmDrawIn (m_pvBuf); else m_pVCM->vcmDrawIn (m_pvBuf, ICDECOMPRESS_HURRYUP); m_vidsPrevious = catchup++; } }
[ "tl@toddlucas.net" ]
tl@toddlucas.net
906c3e2e6f0b2ec9046dd092c534a49864be919c
d1cc8770839f711bfb67bf80d9bddbe1d74da134
/groups/bdl/bdlt/bdlt_localtimeoffset.cpp
b182c69e9580bfbdb79713cf5e393d9711bdb834
[ "Apache-2.0" ]
permissive
phalpern/bde-allocator-benchmarks
9024db005e648c128559fd87d190a50e2a6a4a0d
3d231b2444aa50b85ab4c8dea13f7a23421b7a17
refs/heads/master
2022-04-30T19:29:45.740990
2022-03-10T21:33:34
2022-03-10T21:33:34
174,750,415
1
0
Apache-2.0
2019-03-09T21:55:05
2019-03-09T21:55:05
null
UTF-8
C++
false
false
2,586
cpp
// bdlt_localtimeoffset.cpp -*-C++-*- #include <bdlt_localtimeoffset.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdlt_localtimeoffset_cpp,"$Id$ $CSID$") #include <bdlt_datetime.h> #include <bdlt_datetimeinterval.h> #include <bdlt_datetimeutil.h> #include <bdlt_epochutil.h> #include <bsls_platform.h> #include <bsl_c_time.h> namespace BloombergLP { namespace bdlt { // --------------------- // class LocalTimeOffset // --------------------- // DATA bsls::AtomicOperations::AtomicTypes::Pointer LocalTimeOffset::s_localTimeOffsetCallback_p = { reinterpret_cast<void *>(LocalTimeOffset::localTimeOffsetDefault) }; // CLASS METHODS // ** default callback ** bsls::TimeInterval LocalTimeOffset:: localTimeOffsetDefault(const Datetime& utcDatetime) { bsl::time_t currentTime; int status = EpochUtil::convertToTimeT(&currentTime, utcDatetime); BSLS_ASSERT(0 == status); struct tm localTm; struct tm gmtTm; #if defined(BSLS_PLATFORM_OS_WINDOWS) || ! defined(BDE_BUILD_TARGET_MT) // Note that the Windows implementation of localtime and gmttime, when // using multithreaded libraries, are thread-safe. localTm = *localtime(&currentTime); gmtTm = *gmtime(&currentTime); #else localtime_r(&currentTime, &localTm); gmtime_r(&currentTime, &gmtTm); #endif Datetime localDatetime; Datetime gmtDatetime; DatetimeUtil::convertFromTm(&localDatetime, localTm); DatetimeUtil::convertFromTm( &gmtDatetime, gmtTm); return bsls::TimeInterval((localDatetime - gmtDatetime).totalSeconds(), 0); } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
[ "abeels@bloomberg.net" ]
abeels@bloomberg.net
1a82566d670121d2200dbfc3522d9de29ff66eca
bffd5dc31df8f0de9792f112a22d3909908d8aed
/File/LabProject(Software Renderer)/LabProject02/Camera.cpp
511e649a452d60c85da77ce9ef33cf8c479e23b1
[]
no_license
kth4540/3DGP
41a53cc16f6b6e4a574b431f66f87a0a5d1e47b7
43a48ab09e3a13d81a3356b2508a1fba356860ab
refs/heads/main
2023-04-17T01:29:28.866366
2021-04-26T01:01:54
2021-04-26T01:01:54
344,543,634
0
0
null
null
null
null
UTF-8
C++
false
false
5,609
cpp
#include "stdafx.h" #include "Camera.h" #include "Mesh.h" #include "Player.h" ///////////////////////////////////////////////////////////////////////////////////////////////////// // void CViewport::SetViewport(int nLeft, int nTop, int nWidth, int nHeight) { m_nLeft = nLeft; m_nTop = nTop; m_nWidth = nWidth; m_nHeight = nHeight; } CCamera::CCamera() { } CCamera::~CCamera() { } void CCamera::GenerateViewMatrix() { XMVECTOR xmvLook = XMVector3Normalize(XMLoadFloat3(&m_xmf3Look)); XMVECTOR xmvUp = XMVector3Normalize(XMLoadFloat3(&m_xmf3Up)); XMVECTOR xmvRight = XMVector3Normalize(XMVector3Cross(xmvUp, xmvLook)); xmvUp = XMVector3Normalize(XMVector3Cross(xmvLook, xmvRight)); XMStoreFloat3(&m_xmf3Look, xmvLook); XMStoreFloat3(&m_xmf3Right, xmvRight); XMStoreFloat3(&m_xmf3Up, xmvUp); m_xmf4x4View._11 = m_xmf3Right.x; m_xmf4x4View._12 = m_xmf3Up.x; m_xmf4x4View._13 = m_xmf3Look.x; m_xmf4x4View._21 = m_xmf3Right.y; m_xmf4x4View._22 = m_xmf3Up.y; m_xmf4x4View._23 = m_xmf3Look.y; m_xmf4x4View._31 = m_xmf3Right.z; m_xmf4x4View._32 = m_xmf3Up.z; m_xmf4x4View._33 = m_xmf3Look.z; XMVECTOR xmvPosition = XMLoadFloat3(&m_xmf3Position); m_xmf4x4View._41 = -XMVectorGetX(XMVector3Dot(xmvPosition, xmvRight)); m_xmf4x4View._42 = -XMVectorGetX(XMVector3Dot(xmvPosition, xmvUp)); m_xmf4x4View._43 = -XMVectorGetX(XMVector3Dot(xmvPosition, xmvLook)); XMStoreFloat4x4(&m_xmf4x4ViewPerspectiveProject, XMMatrixMultiply(XMLoadFloat4x4(&m_xmf4x4View), XMLoadFloat4x4(&m_xmf4x4PerspectiveProject))); } void CCamera::SetLookAt(XMFLOAT3& xmf3Position, XMFLOAT3& xmf3LookAt, XMFLOAT3& xmf3Up) { m_xmf3Position = xmf3Position; XMStoreFloat4x4(&m_xmf4x4View, XMMatrixLookAtLH(XMLoadFloat3(&m_xmf3Position), XMLoadFloat3(&xmf3LookAt), XMLoadFloat3(&xmf3Up))); XMVECTORF32 xmf32vRight = { m_xmf4x4View._11, m_xmf4x4View._21, m_xmf4x4View._31, 0.0f }; XMVECTORF32 xmf32vUp = { m_xmf4x4View._12, m_xmf4x4View._22, m_xmf4x4View._32, 0.0f }; XMVECTORF32 xmf32vLook = { m_xmf4x4View._13, m_xmf4x4View._23, m_xmf4x4View._33, 0.0f }; XMStoreFloat3(&m_xmf3Right, XMVector3Normalize(xmf32vRight)); XMStoreFloat3(&m_xmf3Up, XMVector3Normalize(xmf32vUp)); XMStoreFloat3(&m_xmf3Look, XMVector3Normalize(xmf32vLook)); } void CCamera::SetLookAt(XMFLOAT3& xmf3LookAt, XMFLOAT3& xmf3Up) { SetLookAt(m_xmf3Position, xmf3LookAt, xmf3Up); } void CCamera::SetViewport(int nLeft, int nTop, int nWidth, int nHeight) { m_Viewport.SetViewport(nLeft, nTop, nWidth, nHeight); m_fAspectRatio = float(m_Viewport.m_nWidth) / float(m_Viewport.m_nHeight); } void CCamera::SetFOVAngle(float fFOVAngle) { m_fFOVAngle = fFOVAngle; m_fProjectRectDistance = float(1.0f / tan(XMConvertToRadians(fFOVAngle * 0.5f))); } void CCamera::GeneratePerspectiveProjectionMatrix(float fNearPlaneDistance, float fFarPlaneDistance, float fFOVAngle) { float fAspectRatio = (float(m_Viewport.m_nWidth) / float(m_Viewport.m_nHeight)); XMStoreFloat4x4(&m_xmf4x4PerspectiveProject, XMMatrixPerspectiveFovLH(XMConvertToRadians(fFOVAngle), fAspectRatio, fNearPlaneDistance, fFarPlaneDistance)); } void CCamera::Move(XMFLOAT3& xmf3Shift) { XMStoreFloat3(&m_xmf3Position, XMVectorAdd(XMLoadFloat3(&m_xmf3Position), XMLoadFloat3(&xmf3Shift))); } void CCamera::Move(float x, float y, float z) { Move(XMFLOAT3(x, y, z)); } void CCamera::Rotate(float fPitch, float fYaw, float fRoll) { if (fPitch != 0.0f) { XMMATRIX xmmtxRotate = XMMatrixRotationAxis(XMLoadFloat3(&m_xmf3Right), XMConvertToRadians(fPitch)); XMStoreFloat3(&m_xmf3Look, XMVector3TransformNormal(XMLoadFloat3(&m_xmf3Look), xmmtxRotate)); XMStoreFloat3(&m_xmf3Up, XMVector3TransformNormal(XMLoadFloat3(&m_xmf3Up), xmmtxRotate)); } if (fYaw != 0.0f) { XMMATRIX xmmtxRotate = XMMatrixRotationAxis(XMLoadFloat3(&m_xmf3Up), XMConvertToRadians(fYaw)); XMStoreFloat3(&m_xmf3Look, XMVector3TransformNormal(XMLoadFloat3(&m_xmf3Look), xmmtxRotate)); XMStoreFloat3(&m_xmf3Right, XMVector3TransformNormal(XMLoadFloat3(&m_xmf3Right), xmmtxRotate)); } if (fRoll != 0.0f) { XMMATRIX xmmtxRotate = XMMatrixRotationAxis(XMLoadFloat3(&m_xmf3Look), XMConvertToRadians(fRoll)); XMStoreFloat3(&m_xmf3Up, XMVector3TransformNormal(XMLoadFloat3(&m_xmf3Up), xmmtxRotate)); XMStoreFloat3(&m_xmf3Right, XMVector3TransformNormal(XMLoadFloat3(&m_xmf3Right), xmmtxRotate)); } } void CCamera::Update(CPlayer* pPlayer, XMFLOAT3& xmf3LookAt, float fTimeElapsed) { XMMATRIX xmmtx4Rotate; xmmtx4Rotate.r[0] = XMVectorSet(pPlayer->m_xmf3Right.x, pPlayer->m_xmf3Right.y, pPlayer->m_xmf3Right.z, 0.0f); xmmtx4Rotate.r[1] = XMVectorSet(pPlayer->m_xmf3Up.x, pPlayer->m_xmf3Up.y, pPlayer->m_xmf3Up.z, 0.0f); xmmtx4Rotate.r[2] = XMVectorSet(pPlayer->m_xmf3Look.x, pPlayer->m_xmf3Look.y, pPlayer->m_xmf3Look.z, 0.0f); xmmtx4Rotate.r[3] = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f); XMVECTOR xmvPosition = XMLoadFloat3(&m_xmf3Position); XMVECTOR xmvOffset = XMVector3TransformCoord(XMLoadFloat3(&pPlayer->m_xmf3CameraOffset), xmmtx4Rotate); XMVECTOR xmvNewPosition = XMVectorAdd(XMLoadFloat3(&pPlayer->m_xmf3Position), xmvOffset); XMVECTOR xmvDirection = XMVectorSubtract(xmvNewPosition, xmvPosition); float fLength = XMVectorGetX(XMVector3Length(xmvDirection)); xmvDirection = XMVector3Normalize(xmvDirection); float fTimeLagScale = fTimeElapsed * 4.0f; float fDistance = fLength * fTimeLagScale; if (fDistance > fLength) fDistance = fLength; if (fLength < 0.01f) fDistance = fLength; if (fDistance > 0) { XMStoreFloat3(&m_xmf3Position, XMVectorAdd(xmvPosition, XMVectorScale(xmvDirection, fDistance))); SetLookAt(pPlayer->m_xmf3Position, pPlayer->m_xmf3Up); } }
[ "harypoteck@naver.com" ]
harypoteck@naver.com
db9ba64ba58f10bd9177ee828101c5d5fe732687
dd80a584130ef1a0333429ba76c1cee0eb40df73
/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.4.3/i686-linux/include/c++/4.4.3/parallel/omp_loop.h
66f6d44bccc59f3b734d3b38d42838cee41da74a
[ "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
3,996
h
// -*- C++ -*- // Copyright (C) 2007, 2008, 2009 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // 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 // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file parallel/omp_loop.h * @brief Parallelization of embarrassingly parallel execution by * means of an OpenMP for loop. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_OMP_LOOP_H #define _GLIBCXX_PARALLEL_OMP_LOOP_H 1 #include <omp.h> #include <parallel/settings.h> #include <parallel/basic_iterator.h> #include <parallel/base.h> namespace __gnu_parallel { /** @brief Embarrassingly parallel algorithm for random access * iterators, using an OpenMP for loop. * * @param begin Begin iterator of element sequence. * @param end End iterator of element sequence. * @param o User-supplied functor (comparator, predicate, adding * functor, etc.). * @param f Functor to "process" an element with op (depends on * desired functionality, e. g. for std::for_each(), ...). * @param r Functor to "add" a single result to the already * processed elements (depends on functionality). * @param base Base value for reduction. * @param output Pointer to position where final result is written to * @param bound Maximum number of elements processed (e. g. for * std::count_n()). * @return User-supplied functor (that may contain a part of the result). */ template<typename RandomAccessIterator, typename Op, typename Fu, typename Red, typename Result> Op for_each_template_random_access_omp_loop(RandomAccessIterator begin, RandomAccessIterator end, Op o, Fu& f, Red r, Result base, Result& output, typename std::iterator_traits <RandomAccessIterator>:: difference_type bound) { typedef typename std::iterator_traits<RandomAccessIterator>::difference_type difference_type; difference_type length = end - begin; thread_index_t num_threads = __gnu_parallel::min<difference_type>(get_max_threads(), length); Result *thread_results; # pragma omp parallel num_threads(num_threads) { # pragma omp single { num_threads = omp_get_num_threads(); thread_results = new Result[num_threads]; for (thread_index_t i = 0; i < num_threads; ++i) thread_results[i] = Result(); } thread_index_t iam = omp_get_thread_num(); # pragma omp for schedule(dynamic, _Settings::get().workstealing_chunk_size) for (difference_type pos = 0; pos < length; ++pos) thread_results[iam] = r(thread_results[iam], f(o, begin+pos)); } //parallel for (thread_index_t i = 0; i < num_threads; ++i) output = r(output, thread_results[i]); delete [] thread_results; // Points to last element processed (needed as return value for // some algorithms like transform). f.finish_iterator = begin + length; return o; } } // end namespace #endif /* _GLIBCXX_PARALLEL_OMP_LOOP_H */
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
fcfdb816528694eebb7483d6b997d4d7b898c1a8
671ef594c3a043b32900864b3f5bf13bbcdab0aa
/src/Pigs/PigSrv/PigEventOwner.h
fd48a17b42706a19e4ebb14ed0d1f62fcb03b10b
[ "MIT" ]
permissive
VSitoianu/Allegiance
bae7206b874d02fdbf4c9c746e9834c7ef93154e
6f3213b78f793c6f77fd397c280cd2dd80c46396
refs/heads/master
2021-05-07T17:15:01.811214
2017-10-22T18:18:44
2017-10-22T18:18:44
108,667,678
1
0
null
2017-10-28T17:02:26
2017-10-28T17:02:26
null
UTF-8
C++
false
false
2,194
h
///////////////////////////////////////////////////////////////////////////// // PigEventOwner.h : Declaration of the CPigEventOwner class. #ifndef __PigEventOwner_h__ #define __PigEventOwner_h__ #pragma once #include "PigSrv.h" ///////////////////////////////////////////////////////////////////////////// // Forward Declarations class CPigEvent; class ImodelIGC; ///////////////////////////////////////////////////////////////////////////// // class ATL_NO_VTABLE CPigEventOwner { // Construction public: CPigEventOwner(); // Attributes public: long GetNextEventNumber(); // Operations public: void AddEvent(CPigEvent* pEvent); void RemoveEvent(CPigEvent* pEvent); void RemoveEvents(); void PulseEvents(); void ModelTerminated(ImodelIGC* pModelIGC); // Overrides public: virtual void LockT() = 0; virtual void UnlockT() = 0; virtual void OnExpiration(CPigEvent* pEvent); virtual void OnInterruption(CPigEvent* pEvent); virtual STDMETHODIMP get_Properties(IDictionary** ppProperties); // Types protected: typedef std::vector<CPigEvent*> XEvents; typedef XEvents::iterator XEventIt; // Data Members protected: XEvents m_Events; long m_nNextEventNumber; }; ///////////////////////////////////////////////////////////////////////////// // Construction inline CPigEventOwner::CPigEventOwner() : m_nNextEventNumber(0) { } ///////////////////////////////////////////////////////////////////////////// // template <class T> class ATL_NO_VTABLE CPigEventOwnerImpl : public CPigEventOwner { // Overrides public: virtual void LockT(); virtual void UnlockT(); // Types public: typedef CPigEventOwnerImpl<T> CPigEventOwnerImplBase; }; ///////////////////////////////////////////////////////////////////////////// // Overrides template <class T> void CPigEventOwnerImpl<T>::LockT () { static_cast<T*>(this)->Lock(); } template <class T> void CPigEventOwnerImpl<T>::UnlockT() { static_cast<T*>(this)->Unlock(); } ///////////////////////////////////////////////////////////////////////////// #endif // !__PigEventOwner_h__
[ "kgersen@hotmail.com" ]
kgersen@hotmail.com
ed76bfaf28170afe01c5a955367ab487b928703a
f684104e0ce2492ccc0d82c212784e78872e87c1
/src/flute/flute4nthuroute.cpp
53d668e467df9591c91336f65a27d6198dce491a
[]
no_license
boenset/nthu-route
c223032f8cd8e899bc085090625d590d69ec268b
30d0b5e3e4b3fb84a6cea0018461a0ea8757c862
refs/heads/master
2022-02-11T14:46:29.660328
2019-08-05T15:28:01
2019-08-05T15:28:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,062
cpp
#include "flute4nthuroute.h" #include "misc/debug.h" Flute::Flute () :x_(NULL), y_(NULL) { readLUT(); //Read in the binary lookup table - POWVFILE, POSTFILE } Flute::~Flute () { } void Flute::routeNet (const PinptrList& pinList, Tree& routingTree) { int pinNumber = pinList.size(); x_ = new DTYPE[pinNumber]; //int array used as input of FLUTE y_ = new DTYPE[pinNumber]; //int array used as input of FLUTE // insert 2D-coordinate of pins of a net into x_ and y_ for (int pinId = 0; pinId < pinNumber; ++pinId) { x_[pinId] = pinList[pinId]->x(); y_[pinId] = pinList[pinId]->y(); } // obtain the routing tree by FLUTE routingTree = flute(pinNumber, x_, y_, ACCURACY); if (x_ != NULL) { delete[] x_; x_ = NULL; } if (y_ != NULL) { delete[] y_; y_ = NULL; } } void Flute::printTree (Tree& routingTree) { printtree(routingTree); } int Flute::treeWireLength (Tree& routingTree) { return static_cast<int>( wirelength(routingTree) ); }
[ "jacky860226@yahoo.com.tw" ]
jacky860226@yahoo.com.tw
4f694008b51d065ba532f07b59dfd7c508b94223
9f4d78761c9d187b8eb049530ce0ec4c2b9b2d78
/Paradigms/MetaGME/BONExtender/Rep/FolderRep.h
739b4a308787b449b0c68ea99a501d8340cc7f50
[]
no_license
ksmyth/GME
d16c196632fbeab426df0857d068809a9b7c4ec9
873f0e394cf8f9a8178ffe406e3dd3b1093bf88b
refs/heads/master
2023-01-25T03:33:59.342181
2023-01-23T19:22:37
2023-01-23T19:22:37
119,058,056
0
1
null
2019-11-26T20:54:31
2018-01-26T14:01:52
C++
UTF-8
C++
false
false
2,366
h
#ifndef FOLDERREP_H #define FOLDERREP_H #include "Any.h" #include "FCO.h" #include "FolderRep.h" #include "ModelRep.h" #include "AtomRep.h" #include "ConnectionRep.h" #include "SetRep.h" #include "ReferenceRep.h" #include "FcoRep.h" #include "list" #include "vector" /* class FolderElem { FolderElem( const Any * m_ptr, const std::string &m_card); bool operator==( const FolderElem& peer); Any * getElem() const; const std::string & getCard() const; private: const FolderElem& operator=(const FolderElem& peer); FolderElem( const FolderElem&); Any * m_elem; std::string m_card; }; */ class FolderRep : public Any { public: // types typedef std::vector<FCO*>::iterator FCO_Iterator; typedef std::vector<FolderRep*>::iterator SubFolder_Iterator; typedef std::vector<FolderRep*>::const_iterator SubFolder_ConstIterator; public: /* A FolderRep is created by using the id, ptr and resp_ptr which is the object selected using the SameFolder Selection Mechanism when SameFolder relation is met. That is why a folder has to redefine the getName operations */ FolderRep( BON::FCO& ptr, BON::FCO& resp_ptr); ~FolderRep(); /*virtual*/ Any::KIND_TYPE getMyKind() const { return Any::FOLDER; } /*virtual*/ std::string getName() const; void addFCO( FCO * ptr, const std::string & card); bool isFCOContained( FCO * otr); void addSubFolderRep( FolderRep * ptr, const std::string & card); void extendMembership(); std::string doDump(); void addMethod(Method& m) { m_methods.push_back( m); } void createMethods(); static std::string subFolderGetterMethodName(FolderRep * fold, const std::string& diff_nmsp); static std::string kindGetterMethodName( FCO * fco, const std::string& diff_nmsp); protected: std::vector<FCO *> m_fcoList; std::vector<std::string> m_fcoCardList; /** * contains all subfolders (including itself) */ std::vector<FolderRep*> m_subFolderList; /* Cardinality for the folders above */ std::vector<std::string> m_subCardList; /** * This pointer is in charge of the aspect name, * may point to a Folder or a SameFolder operator */ BON::FCO m_respPointer; std::vector<Method> m_methods; private: // forbiding copy FolderRep( const FolderRep&); const FolderRep& operator=( const FolderRep&); }; #endif //FOLDERREP_H
[ "volgy@b35830b6-564f-0410-ac5f-b387e50cb686" ]
volgy@b35830b6-564f-0410-ac5f-b387e50cb686
dcf2015eeddcc2cbd5b78d665c9cb3ca5b486fef
eed93391779d2c7b11c8ac2d5a803861b685a36b
/lab1/clock/mainwindow.cpp
ef28e12f3021d6d40fb78f5609ea695c7f9addc8
[]
no_license
nininini123/OS-exp
579782a2eb897ccd01f52d7b330b4c8c847b97cc
1a507fbd297f6f4b5a84fc2dbf95402857de753d
refs/heads/master
2021-04-09T13:03:02.682473
2018-03-21T00:01:58
2018-03-21T00:01:58
125,476,756
0
0
null
null
null
null
UTF-8
C++
false
false
795
cpp
#include <unistd.h> #include "mainwindow.h" #include "ui_mainwindow.h" #include <QFile> #include <QDateTime> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QDateTime curTime ; curTime = QDateTime::currentDateTime(); ui->label->setText(curTime.toString("yyyy-MM-dd hh:mm:ss")); timer = new QTimer(this); timer->start(1000); connect(timer,SIGNAL(timeout()),this,SLOT(updateTime())); // update(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionexit_triggered() { close(); } void MainWindow::updateTime() { QDateTime curTime ; curTime = QDateTime::currentDateTime(); ui->label->setText(curTime.toString("yyyy-MM-dd hh:mm:ss")); }
[ "nichurui@foxmail.com" ]
nichurui@foxmail.com
2247ef4c5643e64dbbb4719a9b6bd6d9b40d5d02
77aeb718f319a633479010d7d285247ef44d04f3
/src/con4/indexservicetablemodel.cpp
52f6920e7a64003902e22014a7972dadc8e7e8cd
[ "MIT" ]
permissive
riccioclista/con4
84b7a315a8eb0e441d576456ec88b3908c174eb0
0522f45f20381b566fe23722070a1acb96ec9629
refs/heads/master
2021-05-27T15:14:27.949273
2013-05-30T10:50:26
2013-05-30T10:50:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,277
cpp
/* * indexservicetablemodel.cpp * * Author: * Antonius Riha <antoniusriha@gmail.com> * * Copyright (c) 2013 Antonius Riha * * 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 "indexservicetablemodel.h" IndexServiceTableModel::IndexServiceTableModel(IndexServiceList &list, QObject *parent) : QAbstractTableModel(parent), _list(list) { connect(&list, SIGNAL(creating(IndexService*,int)), this, SLOT(_creating(IndexService*,int))); connect(&list, SIGNAL(created(IndexService*,int)), this, SLOT(_created(IndexService*,int))); connect(&list, SIGNAL(deleting(IndexService*,int)), this, SLOT(_deleting(IndexService*,int))); connect(&list, SIGNAL(deletedAt(int)), this, SLOT(_deletedAt(int))); } int IndexServiceTableModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return _list.size(); } int IndexServiceTableModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return 3; } QVariant IndexServiceTableModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || role != Qt::DisplayRole || index.row() < 0 || index.row() >= _list.size() || index.column() < 0) return QVariant::Invalid; IndexService *item = _list.at(index.row()); if (index.column() == 0) return item->name(); else if (index.column() == 1) return item->ipAddress().toString(); else if (index.column() == 2) return item->port(); return QVariant::Invalid; } QVariant IndexServiceTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation != Qt::Horizontal || section < 0 || section > 2 || role != Qt::DisplayRole) return QVariant::Invalid; if (section == 0) return "Name"; else if (section == 1) return "IP Address"; else if (section == 2) return "Port"; return QVariant::Invalid; } void IndexServiceTableModel::_creating(IndexService *, int index) { beginInsertRows(QModelIndex(), index, index); } void IndexServiceTableModel::_created(IndexService *, int) { endInsertRows(); } void IndexServiceTableModel::_deleting(IndexService *, int index) { beginRemoveRows(QModelIndex(), index, index); } void IndexServiceTableModel::_deletedAt(int) { endRemoveRows(); }
[ "antoniusriha@gmail.com" ]
antoniusriha@gmail.com
4bc8e2fc9c7292b77a1831595284bf09e223410a
859dc889396d508de02ad97d96ebda4d60da7c23
/nacionalcontroller.cpp
476efa33ea512b6d5c458771cd52765971a0e1b3
[]
no_license
Eluchon/Voto-electronico-prueba
87d4ec84a9f56c8b70db7482c527f65cb601115d
65bd14a059b928b9730c61ccbaf9d58e1d90ea0f
refs/heads/master
2020-03-26T22:37:15.865338
2018-08-20T21:48:19
2018-08-20T21:48:19
145,473,932
0
0
null
null
null
null
UTF-8
C++
false
false
1,404
cpp
/* * nacionalcontroller.cpp * * Created on: 23 feb. 2018 * Author: luis */ #include "nacionalcontroller.h" nacionalcontroller::nacionalcontroller() { // TODO Auto-generated constructor stub } nacionalcontroller::~nacionalcontroller() { // TODO Auto-generated destructor stub } void nacionalcontroller::voto() { (new nacionalviewer())->htmlVoto((new nacionaldao())->collection()); } void nacionalcontroller::cargar() { (new nacionalviewer())->htmlCargar((new nacionaldao())->collection()); } void nacionalcontroller::modificar(){ (new nacionalviewer())->htmlModificar((new nacionaldao())->collection()); } void nacionalcontroller::eliminar(){ (new nacionalviewer())->htmlEliminar((new nacionaldao())->collection()); } void nacionalcontroller::fin(){ (new nacionalviewer())->htmlfin((new nacionaldao())->collectionfin()); } void nacionalcontroller::cargardao(string lista, string nombre, string partido){ nacionaldao::add(lista,nombre,partido); } void nacionalcontroller::modificardao(string lista, string nombre, string partido){ nacionaldao::update(lista,nombre,partido); } void nacionalcontroller::eliminardao(string lista){ nacionaldao::remove(lista); } void nacionalcontroller::estadistica(){ (new nacionalviewer())->htmlestadistica((new nacionaldao())->collectionfin()); } bool nacionalcontroller::exist(string lista){ return nacionaldao::exist(lista); }
[ "luigonzarat@gmail.com" ]
luigonzarat@gmail.com
af32e17cba9ad23813a5eb8934f9cd2acabd842d
5bda817435e5d5fa26d3a3b6b7ef756d2ae43e8d
/Ex5_Chrispens_Gahbiche/mutex-example.cpp
778ed691ec0cf90e4ce09242798c15c240a5b6b9
[]
no_license
rufreakde/CPP
82f639b5a4b572b9eaf8835fceb0d7dc477f7bc4
2e61c1ceae1e956fcd2f942c7ee6a7bc54c97e21
refs/heads/master
2021-09-04T22:24:43.603469
2018-01-22T17:43:41
2018-01-22T17:43:41
110,279,122
0
0
null
null
null
null
UTF-8
C++
false
false
2,728
cpp
#include <optional> #include <deque> #include <vector> #include <type_traits> #include <memory> #include <thread> #include <mutex> #include <condition_variable> #include <iostream> template <typename T> class MulticastMutexTransport { private: struct SourceData { std::deque<T> elements; }; std::vector<SourceData> sources; std::mutex mutex; std::condition_variable cv; bool productionCompleted = false; public: using SourceId = std::size_t; MulticastMutexTransport(void) = default; SourceId addSource(void) { std::unique_lock<std::mutex> lock(mutex); sources.push_back(SourceData()); return sources.size() - 1; } void push(T value) { std::unique_lock<std::mutex> lock(mutex); for (auto& source : sources) source.elements.push_back(value); cv.notify_all(); } void signifyCompletion(void) { std::unique_lock<std::mutex> lock(mutex); productionCompleted = true; cv.notify_all(); } std::optional<T> tryPull(SourceId sourceId) { std::unique_lock<std::mutex> lock(mutex); auto& elements = sources.at(sourceId).elements; while (!productionCompleted && elements.empty()) cv.wait(lock); if (elements.empty()) return std::nullopt; T result = std::move(elements.front()); elements.pop_front(); return result; } }; void testProducerConsumerQueue(std::size_t nMax) { // set up transport, add source for ourselves auto transport = std::make_shared<MulticastMutexTransport<int>>(); auto sourceId = transport->addSource(); // start producer // (be sure to capture by value when detaching the thread and to use a shared_ptr<> // so the thread can keep the transport alive) std::thread([=] { for (std::size_t n = 1; n <= nMax; ++n) transport->push(static_cast<int>(n)); transport->signifyCompletion(); }).detach(); // consume produced elements std::size_t sum = 0; while (auto next = transport->tryPull(sourceId)) sum += *next; // verify result if (sum != (nMax * (nMax + 1)) / 2) throw std::logic_error("unexpected result"); } int main(int argc, char* argv[]) { try { testProducerConsumerQueue(10000000); std::cout << "All tests ran successfully." << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } }
[ "Chrispens@stud.uni-heidelberg.de" ]
Chrispens@stud.uni-heidelberg.de
a32344bc5a01de7fe2f32d108a17aad3f4fa9aea
c4cfc6bf5447549e0826ea24bcf831b5945ac070
/A1/client.h
ee0025f4a5cc6228e1ec335cfd6e125d377e6b6d
[]
no_license
CerberusOne/7005_a1
4aaedf36a3c6d7c10e12fe07b5d9b2c9a32002ca
dea9870a439cbb62dee8cccaf956e1eb64151d17
refs/heads/master
2020-04-18T14:55:49.752192
2019-01-25T19:24:36
2019-01-25T19:24:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
511
h
#ifndef CLIENT_H #define CLIENT_H #include "socketwrappers.h" #include <netinet/in.h> #include <iostream> #include <strings.h> #include <stdlib.h> #include <cstring> using namespace std; class Client { public: Client(const char* ip, int port); Client(struct sockaddr_in *bindaddr, struct sockaddr_in *transferaddr); ~Client() { cout << "Closing client" << endl << endl; } bool SendCmd(Cmd cmd); private: int servfd, cmdfd, transferfd; struct sockaddr_in servaddr, cmdaddr; }; #endif
[ "aingaran2003@gmail.com" ]
aingaran2003@gmail.com
97ded585b760de09a5f797eb3d6c526ae05f3453
3d40eaaa6be158c54d0d5a148d698fd3e285ac41
/priority_queue的初识/priority_queue的初识/源.cpp
a9aef4f921eafecb9c0e7ba6267a2e0023331b98
[]
no_license
yi1978045947/Hide-on-library
a7c9a5da45efea5306d195f9ce366dedb2c41fb9
ce3730309669c0955fa16ad8fade148d63a45cc2
refs/heads/master
2023-09-04T02:40:10.545014
2021-10-20T15:48:29
2021-10-20T15:48:29
312,789,626
3
0
null
null
null
null
UTF-8
C++
false
false
462
cpp
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> #include<queue> #include<functional> using namespace std; void test_priority_queue() { //priority_queue<int> pq; priority_queue<int, vector<int>, greater<int>> pq; pq.push(1); pq.push(2); pq.push(3); pq.push(4); cout << pq.size() << endl; cout << pq.empty() << endl; while (!pq.empty()) { cout << pq.top() << " "; pq.pop(); } cout << endl; } int main() { test_priority_queue(); return 0; }
[ "1978045947@qq.com" ]
1978045947@qq.com
492508335cdd1d28cc383fc38e6a4eae5dacbc7c
ac45cdcfd189871ac7a3daf2e5f4d3daa9753ff2
/main.cpp
c40f3ffb7917f933356dc87483af48fecad4914e
[]
no_license
IlyaLaska/OOP_Lab6
ba1f9474cce7cc73ee24f2db6d7adf54bfb0736d
b798e4c5bc474edcc090eb7a6a66e8e26e030811
refs/heads/master
2020-04-08T05:08:33.164122
2018-12-10T07:51:22
2018-12-10T07:51:22
159,048,157
0
0
null
null
null
null
UTF-8
C++
false
false
3,404
cpp
//DONE// Write correct division and remainder functions and multiplication //DONE// Write reverse matrix calculator //DONE// Write 4 basic operations in short form //this - func obj or left operand? #include <iostream> #include <vector> #include <string> #include "Bignum.h" #include "Fraction.h" #include "Matrix.h" #include "Exception.h" #include "InputException.h" #include "MathException.h" #include "DivideByZeroException.h" void fillMatrix(Matrix &mat); using namespace std; int main() { try { // Bignum a = Bignum("q");//Input Exception // Fraction b(Bignum("1"), Bignum("0"));//MathException - DivideByZeroException while (true) { try { Matrix c(1,1); fillMatrix(c); break; } catch (InputException<std::string> &e) { cout << "Error: " << e.what() << ": " << e.getInput() << endl; cout << "Now do it again, PROPERLY this time!" << endl; } } } catch (InputException<std::string> &e) { cout << "Error: " << e.what() << ": " << e.getInput() << endl; } catch (DivideByZeroException<int> &e) { cout << "Error: " << e.what() << ": " << e.getError() << " with first operand being: " << e.showFirstOperand() << endl; } catch (MathException<int> &e) { cout << "Error: " << e.what() << ": " << e.getError() << endl; } catch (Exception &e) { cout << "Error: " << '9' - 48 <<e.what() << endl; } catch (...) { cout << "Unknown error" << endl; }; cout << "That's all folks!" << endl; // try { // Matrix matr(1,1); // fillMatrix(matr); // } catch (InputException &e) { // cout << "Error: " << e.what() << ": " << e.getInput() << endl; // } // Bignum a = (string)"60"; // cout << "Bignum a: " << a << endl; // Bignum b = (string)"10"; // cout << "Bignum b: " << b << endl; // cout << "a + b: " << a + b << endl; // cout << "a - b: " << a - b << endl; // cout << "a * b: " << a * b << endl; // cout << "a / b: " << a / b << endl; // // // Fraction fr(Bignum("1"), Bignum("2")); // cout << "Fraction fr:" << fr << endl; // Fraction fra(Bignum("4"), Bignum("2")); // cout << "Fraction fra:" << fra << endl; // cout << "fr * fra:" << fr * fra << endl; // // // Matrix m(2, 2); // fillMatrix(m); // cout << m << endl; // Matrix mat = !m; // cout << "!m:" << endl; // cout << mat << endl; // Matrix ma = m + 2; // cout << "m + 2: " << ma << endl; return 0; } void fillMatrix(Matrix &mat) { int Y = 1; int X = 1; // std::cout << "LENFTT " << mat.length << std::endl; for (auto &i : mat.matrix) { std::cout << "Element " << Y << ", " << X << ": "; std::string temp; std::getline(std::cin, temp); std::string::size_type pos = temp.find('/'); if(pos == std::string::npos) throw InputException<std::string>("Wrong input", temp); // return fillMatrix(mat); //std::cout << "AAAAAAAAAAAAAAAAAAAAAAAAA" << std::endl; std::string denom = temp.substr(pos+1); // std::cout << "Denom: " << denom << std::endl; temp.erase(pos); std::string numer = temp; i = Fraction(Bignum(numer), Bignum(denom)); if(X%mat.length == 0) { X = 1; Y++; } else X++; } }
[ "IlyaLaska@users.noreply.github.com" ]
IlyaLaska@users.noreply.github.com
2719a6acf6690b1aa075e8d251ba10d56e516840
b46d4f0a7e806b175de55214dfd3909e5bcb6687
/stat/model_t.cc
526a7337ed7cde00b57a33fe45644b52643aa33d
[ "Apache-2.0" ]
permissive
Mu2e/Stntuple
23fa5550288586b0e0909aa3be7439fd41cf9511
766b735ae2fabf391e6f935c67f7245995378e87
refs/heads/main
2023-08-23T17:52:41.537174
2023-08-16T15:01:21
2023-08-16T15:01:21
218,061,235
0
9
Apache-2.0
2023-09-14T01:44:36
2019-10-28T14:07:19
C++
UTF-8
C++
false
false
5,301
cc
//////////////////////////////////////////////////////////////////////////////// // verbose = 0: default // = 1: fill histogram // = 2: print value // > 2: more detailed printout //////////////////////////////////////////////////////////////////////////////// #include "TFile.h" #include "Stntuple/stat/model_t.hh" namespace stntuple { model_t::model_t(const char* name) : TNamed(name,name) { fListOfChannels = new TObjArray(); fListOfChannels->SetOwner(kTRUE); fListOfParameters = new TObjArray(); fListOfParameters->SetOwner(kTRUE); fRng = new ROOT::Math::RandomRanLux(); fHistNullPDF = new TH1D(Form("h_model_%s_null_pdf",name),"Null PDF" ,50,0,50); fHistS0BPDF = new TH1D(Form("h_model_%s_s0b_pdf" ,name),"S+B PDF" ,50,0,50); fHistS1BPDF = new TH1D(Form("h_model_%s_s1b_pdf" ,name),"S(mean)+B PDF",50,0,50); fNPExp = 1000000; } model_t::~model_t() { delete fListOfChannels; delete fListOfParameters; delete fRng; delete fHistNullPDF; delete fHistS0BPDF; delete fHistS1BPDF; } //----------------------------------------------------------------------------- // get total expected fluctuated (!) Poisson mean (background only) //----------------------------------------------------------------------------- double model_t::GetNullValue() { int nc = fListOfChannels->GetEntriesFast(); double val = 0; for (int i=0; i<nc; i++) { channel_t* ch = GetChannel(i); if (ch->Signal() == 0) { val += ch->GetValue(); } } return val; } //----------------------------------------------------------------------------- // get total expected Poisson mean (background, no fluctuations of the nuisance parameters) //----------------------------------------------------------------------------- double model_t::GetBackgroundMean() { int nc = fListOfChannels->GetEntriesFast(); double val = 0; for (int i=0; i<nc; i++) { channel_t* ch = GetChannel(i); if (ch->Signal() == 0) { val += ch->Process()->Mean(); } } return val; } //----------------------------------------------------------------------------- // get total expected Poisson mean, including signal //----------------------------------------------------------------------------- double model_t::GetValue() { int nc = fListOfChannels->GetEntriesFast(); double val = 0; for (int i=0; i<nc; i++) { channel_t* ch = GetChannel(i); val += ch->GetValue(); } return val; } int model_t::GeneratePDF() { fMuB = 0; fMuBx = 0; fMuS = 0; fMuSx = 0; for (int i=0; i<fNPExp; i++) { // step 1: initalize all parameters InitParameters(); // for now, val is the total expected background double null_val = GetNullValue(); // this returns the fluctuated background mean double x_null = fRng->Poisson(null_val); fHistNullPDF->Fill(x_null); fMuB += null_val; fMuBx += x_null; // account for correlations channel_t* sig = SignalChannel(); double s0 = sig->fProcess->Mean(); // this is a fixed (not fluctuated) mean value. double x_s0 = fRng->Poisson(s0); double x_s0b = x_null+x_s0; fHistS0BPDF->Fill(x_s0b); // in the calculation of the s1b value, sig and background are fluctuated in GetValue() // with parameters defining the signal also fluctuated double s1 = sig->GetValue(); // this is a fluctuated mean value double x_s1 = fRng->Poisson(s1); // use that mean for sampling a Poisson distribution double x_s1b = x_null+x_s1; fHistS1BPDF->Fill(x_s1b); fMuS += s1; fMuSx += x_s1; } fMuB = fMuB /fNPExp; fMuBx = fMuBx/fNPExp; fMuS = fMuS /fNPExp; fMuSx = fMuSx/fNPExp; return 0; } int model_t::InitParameters() { int np = fListOfParameters->GetEntriesFast(); for (int i=0; i<np; i++) { parameter_t* p = GetParameter(i); p->InitValue(); } return 0; } int model_t::SaveHist(const char* Filename) { TFile* f = new TFile(Filename,"recreate"); fHistNullPDF->Write(); fHistS0BPDF->Write(); fHistS1BPDF->Write(); // hUL->Write(); // hULR->Write(); // hDisc->Write(); // hDiscR->Write(); // if (gr_Disc) { // gr_Disc->Write(); // gr_DiscR->Write(); // } int np = fListOfParameters->GetEntries(); printf("model_t::%s: np = %2i\n",__func__,np); for (int i=0; i<np; i++) { parameter_t* p = (parameter_t*) fListOfParameters->At(i); p->GetHistPDF()->Write(); } int nch = fListOfChannels->GetEntries(); printf("model_t::%s: nch = %2i\n",__func__,nch); for (int i=0; i<nch; i++) { channel_t* ch = (channel_t*) fListOfChannels->At(i); ch->GetHistPDF()->Write(); } f->Close(); delete f; return 0; } void model_t::Print(const Option_t* Opt) const { printf("fMuB = %10.4f\n",fMuB ); printf("fMuBx = %10.4f\n",fMuBx); printf("fMuS = %10.4f\n",fMuS ); printf("fMuSx = %10.4f\n",fMuSx); model_t* m = (model_t*) this; printf("<MuB> : %8.5f\n",m->GetBackgroundMean()); } }
[ "pavel.murat@gmail.com" ]
pavel.murat@gmail.com
f1f5f88aae6ed9296af0d8e62a5fa9716e0ff6f7
bdfe965225a849fcb126623be1556bf059de7df6
/UVA_299_TrainSwaping.cpp
45194bc55bfd7ea293c0ec59145ad1062fe487ac
[]
no_license
rabelhmd/UVA-Solutions
84607f333a8145fedccb73dd0fa694c25516d4ca
562d90fdf075f75d8e0669c749aa865c57d690d6
refs/heads/master
2021-07-15T16:01:21.697126
2017-10-20T07:01:26
2017-10-20T07:01:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
818
cpp
#include <stdio.h> #include <iostream> #include <stdlib.h> #include <algorithm> using namespace std; void bubble(int data[], int N) { int k, ptr, temp; int Count=0; for(k=1; k<=N-1; k++) { ptr = 1; while (ptr <= N-k) { if (data[ptr] > data[ ptr +1 ]) { temp = data [ptr]; data [ptr] = data[ptr+1]; data [ptr+1] = temp; Count++; } ptr = ptr + 1; } } printf("Optimal train swapping takes %d swaps.\n",Count); return; } int main() { int i, N, T,data[1000]; cin>>T; while(T--) { cin>>N; for(i=1; i<=N; i++) { cin>>data[i]; } bubble(data, N); } return 0; }
[ "rabelhmd@gmail.com" ]
rabelhmd@gmail.com
fdbabe652dbb532d057a7afb6f06463206753489
db016c6266fb8c5cf3938c98b24fde21d4c231d0
/TNAFN/WeaponHand.h
5cc7d40c8a2bdd1a16d169f18164d25a1628dfc1
[]
no_license
cydney9/Nightingale
e77b4a69c7e8d4f21891a487d490135dfc26ec20
4239ac6dd74b20d75ff3a73bccc9fde6a808a07e
refs/heads/master
2021-02-19T07:53:44.619247
2020-04-04T23:56:41
2020-04-04T23:56:41
245,292,929
1
0
null
null
null
null
UTF-8
C++
false
false
140
h
#include "Transform.h" #include "JSON.h" class WeaponHand : public Transform { public: WeaponHand(int x, int y,int z); void Update(); };
[ "happychanjin@yahoo.com.hk" ]
happychanjin@yahoo.com.hk
af2d62ef16b41eff9af56a70c2b48092a32c4b00
60193311299ad70a697da3a65699fcd8b63bf264
/Orge-Study/ogre_src_v1-8-0/RenderSystems/GLES2/include/OgreGLES2HardwareBufferManager.h
becef468ba3991e438761385c22e626c74cd40e6
[]
no_license
DGHeroin/Mirror-GLSL-Study
cd6fac3967173f9bf77d8d32776508fa81a98d86
9df468c5d8cc77bd89f4185230fd0b34c3721cad
refs/heads/master
2021-09-23T23:30:59.336825
2017-07-03T16:14:42
2017-07-03T16:14:42
96,129,238
0
0
null
null
null
null
UTF-8
C++
false
false
5,648
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2012 Torus Knot Software Ltd 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 __GLES2HardwareBufferManager_H__ #define __GLES2HardwareBufferManager_H__ #include "OgreGLES2Prerequisites.h" #include "OgreHardwareBufferManager.h" namespace Ogre { // Default threshold at which glMapBuffer becomes more efficient than glBufferSubData (32k?) # define OGRE_GL_DEFAULT_MAP_BUFFER_THRESHOLD (1024 * 32) /** Implementation of HardwareBufferManager for OpenGL ES. */ class _OgreGLES2Export GLES2HardwareBufferManagerBase : public HardwareBufferManagerBase { protected: char* mScratchBufferPool; OGRE_MUTEX(mScratchMutex) size_t mMapBufferThreshold; public: GLES2HardwareBufferManagerBase(); virtual ~GLES2HardwareBufferManagerBase(); /// Creates a vertex buffer HardwareVertexBufferSharedPtr createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false); /// Create a hardware vertex buffer HardwareIndexBufferSharedPtr createIndexBuffer( HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer = false); /// Create a render to vertex buffer RenderToVertexBufferSharedPtr createRenderToVertexBuffer(); /// Utility function to get the correct GL usage based on HBU's static GLenum getGLUsage(unsigned int usage); /// Utility function to get the correct GL type based on VET's static GLenum getGLType(unsigned int type); /** Allocator method to allow us to use a pool of memory as a scratch area for hardware buffers. This is because glMapBuffer is incredibly inefficient, seemingly no matter what options we give it. So for the period of lock/unlock, we will instead allocate a section of a local memory pool, and use glBufferSubDataARB / glGetBufferSubDataARB instead. */ void* allocateScratch(uint32 size); /// @see allocateScratch void deallocateScratch(void* ptr); /** Threshold after which glMapBuffer is used and not glBufferSubData */ size_t getGLMapBufferThreshold() const; void setGLMapBufferThreshold( const size_t value ); }; /// GLES2HardwareBufferManagerBase as a Singleton class _OgreGLES2Export GLES2HardwareBufferManager : public HardwareBufferManager { public: GLES2HardwareBufferManager() : HardwareBufferManager(OGRE_NEW GLES2HardwareBufferManagerBase()) { } ~GLES2HardwareBufferManager() { OGRE_DELETE mImpl; } /// Utility function to get the correct GL usage based on HBU's static GLenum getGLUsage(unsigned int usage) { return GLES2HardwareBufferManagerBase::getGLUsage(usage); } /// Utility function to get the correct GL type based on VET's static GLenum getGLType(unsigned int type) { return GLES2HardwareBufferManagerBase::getGLType(type); } /** Allocator method to allow us to use a pool of memory as a scratch area for hardware buffers. This is because glMapBuffer is incredibly inefficient, seemingly no matter what options we give it. So for the period of lock/unlock, we will instead allocate a section of a local memory pool, and use glBufferSubDataARB / glGetBufferSubDataARB instead. */ void* allocateScratch(uint32 size) { return static_cast<GLES2HardwareBufferManagerBase*>(mImpl)->allocateScratch(size); } /// @see allocateScratch void deallocateScratch(void* ptr) { static_cast<GLES2HardwareBufferManagerBase*>(mImpl)->deallocateScratch(ptr); } /** Threshold after which glMapBuffer is used and not glBufferSubData */ size_t getGLMapBufferThreshold() const { return static_cast<GLES2HardwareBufferManagerBase*>(mImpl)->getGLMapBufferThreshold(); } void setGLMapBufferThreshold( const size_t value ) { static_cast<GLES2HardwareBufferManagerBase*>(mImpl)->setGLMapBufferThreshold(value); } }; } #endif
[ "ade.li.indie@gmail.com" ]
ade.li.indie@gmail.com
39cee3963ae210ba84b6125b57686a0ac5edbd2d
9b33ce74b72108f761bf5590f223add85cf88107
/DrawInterWindow.h
0b237ef77a1affac7c0c518d5d78dd30399c2d11
[]
no_license
Xapulc/RotationIntersectionOfCube
06df4d7a3b79f779931a7d4b2a7d51b5daf247b3
67cae7b2597169b2361e877845f988507cea0fdb
refs/heads/master
2020-03-31T22:01:25.238463
2018-11-14T10:11:05
2018-11-14T10:11:05
152,602,426
1
0
null
null
null
null
UTF-8
C++
false
false
687
h
#ifndef DRAWINTERWINDOW_H #define DRAWINTERWINDOW_H #include "gwindow.h" #include "R3Graph.h" #include "Rotation.h" #include <iostream> class DrawInterWindow: public GWindow { private: InterPlane plane; I2Point curMousePos; Rotation curRot; I2Point project(R3Point &pt); I2Point winSize = I2Point(getWindowRect().width(), getWindowRect().height()); public: virtual void onExpose(XEvent& event); virtual void onKeyPress(XEvent& event); virtual void onMotionNotify(XEvent& event); virtual void onButtonPress(XEvent& event); void setPlane(const InterPlane &plane); void draw(); void drawAxes(); void drawCube(); void drawInter(); void static printHelp(); }; #endif
[ "xarik1999@gmail.com" ]
xarik1999@gmail.com
15021d13775cefbb4f695a0ae5c4bb96492fe26b
bd1abf2a42a251ce67cbba226647ef59c4a84fde
/src/ball.h
69c4c7ad99917ad3bb42b469da88cbc349e5d85f
[]
no_license
iverson777/URG_Mapping_Tool
b6146387debaa94deb5014c3ae7960f33d245e91
2c4a084871ec3e1e518835f78fc6698e749c0842
refs/heads/master
2020-05-07T19:36:43.325350
2015-08-20T05:07:11
2015-08-20T05:07:11
41,074,745
0
1
null
null
null
null
UTF-8
C++
false
false
592
h
// // ball.h // myWhiteParty // // Created by Hu Chin Hsiang on 2015/7/28. // // #include "ofMain.h" class ball { public: ball(); void update(); void draw(); void setPos(float x,float y, float z, bool r); ofVec3f targetPos; ofSpherePrimitive sphere; int currentPosX; int currentPosY; int currentPosZ; float speed,speed2; float alpha; ofImage circle; bool reverseTF; int rotateDeg; string color; };
[ "iverson.hu@gmail.com" ]
iverson.hu@gmail.com
391a3060c2ca07ccb382e77bfd07655ddc8c4580
5255ccb2d904f2d5e53c2cbf2e510905d2d2517a
/regressions/parameters/context_params8.cpp
419ce3d1a241b69b3bd4c63fbb610aa5ce9af3a7
[]
no_license
ahorn/z3test
7d0f321001a446e837de23d1ae4c0fb0d9618756
47e6295e5942bf9a20a3a68c9a9db10952ba58ac
refs/heads/master
2021-01-16T21:57:31.261777
2015-06-17T02:09:23
2015-06-17T02:09:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
211
cpp
#include<iostream> #include<sstream> #include<z3++.h> using namespace z3; int main() { config cfg; cfg.set("trace_file_name", "abc"); // OK cfg.set("trace_file_name", 123); // OK? context ctx(cfg); }
[ "cwinter@microsoft.com" ]
cwinter@microsoft.com
f88f90e7a031adb30bff235ec841cf2ea57ff157
d2241838244257729d5632d1eea423f31279b596
/welcompage.cpp
2ab6ad8d757bd72e2531311d8051437f99de42a7
[]
no_license
Myzhencai/HeatControl
38a392e49b47bfba2ad500fae9b3ece0885f56ea
8e1e1d63a0bafb90f872ec7a4e70b67b55a35f3b
refs/heads/master
2023-05-30T01:49:14.362244
2021-06-11T03:55:25
2021-06-11T03:55:25
375,895,746
0
0
null
null
null
null
UTF-8
C++
false
false
288
cpp
#include "welcompage.h" #include "ui_welcompage.h" WelcomPage::WelcomPage(QWidget *parent) : QWidget(parent), ui(new Ui::WelcomPage) { ui->setupUi(this); } WelcomPage::~WelcomPage() { delete ui; } void WelcomPage::on_pushButton_clicked() { emit Creatfirstone(); }
[ "Myzhencai@hotmail.com" ]
Myzhencai@hotmail.com
29f98ccd79d8b598a7b499f0507d19f691f883c2
a2c90d183ac66f39401cd8ece5207c492c811158
/cpp/hello.cpp
8075a01c01f9d90bbd722923d394f35daf647305
[]
no_license
kwoneyng/TIL
0498cfc4dbebbb1f2c193cb7c9459aab7ebad02a
c6fbaa609b2e805f298b17b1f9504fd12cb63e8a
refs/heads/master
2020-06-17T11:53:38.685202
2020-03-18T01:29:36
2020-03-18T01:29:36
195,916,103
0
0
null
null
null
null
UTF-8
C++
false
false
106
cpp
#include <iostream> using namespace std; int main() { cout << "Hello, World!" << endl; return 0; }
[ "nan308@naver.com" ]
nan308@naver.com
0410bd6ea358d22b642a18469d7fecb12b802814
ba836fd1a0857393adea62bdc6bbec4e8195f1e4
/src/common/random_generator.hpp
74cfcb9e5caa643255291bbe61c4a2c758587df4
[]
no_license
campisano/cpp_tdd_2048_game
c926d3171294cea341fb6e3021139a34f03e82f8
0467c3cd1401f69c36d7d1e5adc7ea83456f5d7d
refs/heads/master
2022-06-26T03:13:45.518828
2022-06-16T00:50:44
2022-06-16T00:50:44
219,365,783
0
0
null
null
null
null
UTF-8
C++
false
false
443
hpp
#ifndef RANDOM_GENERATOR__HPP__ #define RANDOM_GENERATOR__HPP__ #include <random> class RandomGenerator { public: static RandomGenerator & instance() { static RandomGenerator instance; return instance; } RandomGenerator(RandomGenerator const &) = delete; void operator=(RandomGenerator const &) = delete; std::mt19937 & get(); private: RandomGenerator(); std::mt19937 m_engine; }; #endif
[ "riccardo.campisano@gmail.com" ]
riccardo.campisano@gmail.com
41b169f41d315f498d6542202da3ba1717aa9a22
1e3bd9fff42ae2b5a21e626b1cacd80e448416e2
/RWM_P5/RWM_P5/include/SeeSaw.h
6fe001b8b915c7d84bbdb246d353719c34a8de4c
[]
no_license
RonanFarrell/PortaLESS
941a4cef6ba35130429ec92559e8bc59650870aa
fc0fc8e7f7a6bde3a950b92edee7b1620943d19c
refs/heads/master
2016-09-05T11:38:09.766408
2013-08-16T20:19:32
2013-08-16T20:19:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
616
h
#pragma once #include "stdafx.h" #include "Physics/Dynamics/Constraint/Bilateral/LimitedHinge/hkpLimitedHingeConstraintData.h" #include "Physics/Dynamics/Constraint/Bilateral/Hinge/hkpHingeConstraintData.h" using namespace Ogre; static int numSeeSaw = 0; class SeeSaw { private: // Havok stuff hkpRigidBody * mFixedBody; hkpRigidBody * mMoveablebody; hkpWorld * mWorld; // Ogre stuff Entity * mMesh; SceneNode * mNode; SceneManager * mSceneMgr; public: SeeSaw(Vector3 position, Vector3 size, Vector3 axis, Vector3 pivotOffset, hkpWorld * world, SceneManager * sceneMgr); ~SeeSaw(); void update(); };
[ "ronan.farrell@hotmail.com" ]
ronan.farrell@hotmail.com
aee59a40815434f25bebaebab719d4ef78414808
7341ae2f777358bd2b214cbdc37e3d71d70abd06
/Source/QuickStart/FloatingActor.h
d09cdc222258707b87d669601d949bc739a6a1e7
[]
no_license
seriys/ue4-quickstart
3618128377cd0d165aff8b7668b70bedccb1558a
80cc62e99ce805a016b716b2d9f7d63c1dfb6715
refs/heads/master
2020-03-11T07:38:59.607568
2018-04-17T07:31:01
2018-04-17T07:31:01
129,862,379
0
0
null
null
null
null
UTF-8
C++
false
false
614
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "FloatingActor.generated.h" UCLASS() class QUICKSTART_API AFloatingActor : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AFloatingActor(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; float RunningTime; UPROPERTY(EditAnywhere) float MovementMagnitude = 20.0f; };
[ "seriyshr@gmail.com" ]
seriyshr@gmail.com
fd5cea33d137522f61d6310021cf8ac3011e3d8a
ae38b75f48e9ec6848487e716d452a6f2793b8cc
/include/f/device/utility/value_extractor.hpp
60227f498541629c8baaa1917206d884061d785e
[]
no_license
fengwang/larbed-refinement
d69bdcff22e6b2dc210c2936747c882dea7df39b
f8843ada81ac8da7908dd20a30d52bb683cf59e1
refs/heads/master
2021-01-19T00:37:06.103868
2019-10-09T13:37:38
2019-10-09T13:37:38
45,386,516
1
1
null
null
null
null
UTF-8
C++
false
false
1,068
hpp
#ifndef UDBOMPPSKHABPCFLXOULDRKIAGUGRMPPSLOTQUYOBTOMAQVCSOFVWYWEJOARYTTUFGMDBNOVV #define UDBOMPPSKHABPCFLXOULDRKIAGUGRMPPSLOTQUYOBTOMAQVCSOFVWYWEJOARYTTUFGMDBNOVV #include <type_traits> #include <complex> namespace f { namespace value_extractor_private { template< typename T > struct the_value_extractor { typedef T value_type; }; template< typename T > struct the_value_extractor< std::complex<T> > { typedef T value_type; }; }//namespace value_extractor_private template< typename T > struct value_extractor { typedef typename std::remove_reference<T>::type type0; typedef typename std::remove_pointer<type0>::type type1; typedef typename std::remove_cv<type1>::type type; typedef typename value_extractor_private::the_value_extractor<type>::value_type value_type; }; }//namespace f #endif//UDBOMPPSKHABPCFLXOULDRKIAGUGRMPPSLOTQUYOBTOMAQVCSOFVWYWEJOARYTTUFGMDBNOVV
[ "wang_feng@live.com" ]
wang_feng@live.com
2e4dd4340d013b3d896e1b914a08543c486ccdd3
ba21128a37a03b8af193eec525923b8b5d2c8569
/acm/zoj/ZOJ1409.cpp
4b9c418f930daf7f14fa514ebc324abc4d390fe9
[]
no_license
lzmcode/lzmcode
786b8a11669d9435209fad4168b0ce56b16a36c4
4fdb9172cc81daef33853e6f968b44fe568e68d9
refs/heads/master
2021-01-21T15:53:38.191361
2019-03-28T13:37:46
2019-03-28T13:37:46
95,399,440
1
0
null
null
null
null
UTF-8
C++
false
false
1,205
cpp
#include <iostream> #include <cstdio> #include <set> #include <algorithm> using namespace std; set <int> s; set <int> ::iterator it; int band[105][105], price[105][105], m[105]; int main() { int T, n, i, j; scanf("%d",&T); while(T--) { scanf("%d",&n); s.clear(); for(i = 0; i < n; i++) { scanf("%d",&m[i]); for(j = 0; j < m[i]; j++) { scanf("%d%d",&band[i][j], &price[i][j]); s.insert(band[i][j]); } } double rate = 0; for(it = s.begin(); it != s.end(); it++) { int k = *it, sum_price = 0; for(i = 0; i < n; i++) { int min_price = 0x3fffff; for(j = 0; j < m[i]; j++) { if(band[i][j] >= k && price[i][j] < min_price) { min_price = price[i][j]; } } sum_price += min_price; } if(k * 1.0 / sum_price > rate) rate = k * 1.0 / sum_price; } printf("%.3lf\n",rate); } return 0; }
[ "707364882@qq.com" ]
707364882@qq.com
181c0ffe708e069731064488ff05361cd6a446ab
9daef1f90f0d8d9a7d6a02860d7f44912d9c6190
/Competitions/LeetCode/30_day_leetcoding_challenge/49_group_anagrams_04062020.cpp
bf88baaa5c760a6d09ffe7404b80ba740d526535
[]
no_license
gogokigen/Cpp17-DataStructure-and-Algorithm
b3a149fe3cb2a2a96f8a013f1fe32407a80f3cb8
5261178e17dce6c67edf436bfa3c0add0c5eb371
refs/heads/master
2023-08-06T10:27:58.347674
2021-02-04T13:27:37
2021-02-04T13:27:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,364
cpp
/******************************************************************* * https://leetcode.com/problems/group-anagrams/ * Medium * * Conception: * 1. set * 2. sorting char * * Given an array of strings, group anagrams together. * * * Example: * Input: ["eat", "tea", "tan", "ate", "nat", "bat"], * Output: * [ * ["ate","eat","tea"], * ["nat","tan"], * ["bat"] * ] * * Key: * 1. * * Advanced: * 1. * * Reference: * 1. * *******************************************************************/ class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { multiset<string> category; unordered_map <string,vector<string>> table; for (auto str: strs) { string strCopy = str; sort(strCopy.begin(), strCopy.end()); table[strCopy].push_back(str); } //for(auto i:strs){ // table[strSort(i)].push_back(i); //} vector<vector<string>> ret; for(auto i:table){ ret.push_back(i.second); } return ret; } private: string strSort(string s) { int n = s.size(), counter[26] = {0}; for (char c : s) { counter[c - 'a']++; } string t; for (int c = 0; c < 26; c++) { t += string(counter[c], c + 'a'); } return t; } };
[ "ziv.wang.tw@gmail.com" ]
ziv.wang.tw@gmail.com
a5260e3801915c69daa933657371a7d6c96d1d81
9907672fcd81ab73ac63b2a83422a82bf31eadde
/hackerrank/doublylinkedlist.cpp
dd8b58f2c63e180aafb0f86f6ba7a6ef50668c69
[ "0BSD" ]
permissive
cielavenir/procon
bbe1974b9bddb51b76d58722a0686a5b477c4456
746e1a91f574f20647e8aaaac0d9e6173f741176
refs/heads/master
2023-06-21T23:11:24.562546
2023-06-11T13:15:15
2023-06-11T13:15:15
7,557,464
137
136
null
2020-10-20T09:35:52
2013-01-11T09:40:26
C++
UTF-8
C++
false
false
713
cpp
#include <iostream> #include <cstdio> #include <cstdlib> using namespace std; struct Node{ int data; Node *next; Node *prev; }; Node* SortedInsert(Node *head,int data){ Node *add=new Node(); add->data=data; add->prev=NULL; add->next=NULL; if(!head)return add; if(data<head->data){ add->next=head; head->prev=add; return add; } Node *ret=head; for(;head&&head->data<data;)add->prev=head,head=head->next; if(head)head->prev=add; add->prev->next=add; add->next=head; return ret; } Node* Reverse(Node* head){ if(!head)return head; Node *next,*prev; for(;head;){ next=head->next; prev=head->prev; head->next=prev; head->prev=next; head=next; } return prev->prev; } int main(){}
[ "cielartisan@gmail.com" ]
cielartisan@gmail.com
d17fb9e4b772af009be7ab2f64e0bcb11db30b77
40fa23afb9687afd9a051bbdd93a79739fa0ded8
/RTUtil/ImgGUI.hpp
3358fcd4b06b68f00b3c4fcab2035b1e4b614c2b
[]
no_license
lichristina118/Simple_Rasterizer
cbbc6c9af4c1b18524a34af877718510ad26e01a
6f8bae69d4caba91fbd0e911b3af67a62eb49417
refs/heads/main
2023-06-01T02:46:51.837096
2021-06-29T16:03:17
2021-06-29T16:03:17
377,891,510
0
0
null
null
null
null
UTF-8
C++
false
false
3,095
hpp
/* * Cornell CS5625 * RTUtil library * * A class that simplifies setting up a Nanogui application that displays a high dynamic * range image. * * Author: srm, Spring 2020 */ #ifndef ImgGUI_hpp #define ImgGUI_hpp #include <nanogui/screen.h> #include "common.hpp" // Forward Declarations namespace GLWrap { class Texture2D; class Program; class Mesh; } namespace RTUtil { /* * ImgGUI * * This is a base class for simple Nanogui-based apps that want to display an image that * is computed on the CPU. To make such an app, a derived class just has to override the * computeImage() member function with code to update the floating-point image stored in * img_data. It will be converted to sRGB in the process of displaying it. * * This class provides a simple keyboard-based UI for adjusting exposure (using the up * and down arrow keys), and provides for adding additional event handling by overriding * the event handlers originally defined in nanogui::Widget. */ class RTUTIL_EXPORT ImgGUI : public nanogui::Screen { public: /// Constructor that sets the fixed size of the window. ImgGUI(int width, int height); virtual ~ImgGUI(); /// Keyboard event handler; provides quit-on-ESC, exposure adjustment, and can be /// overridden to add additional behavior. /// @arg key The GLFW key value of the event (GLFW_KEY_A, etc.). /// @arg scancode The scancode of the event; unique for every key. /// @arg action The GLFW action value of the event (GLFW_PRESS, etc.). /// @arg modifiers GLFW modifier flags for any active modifiers (GLFW_MOD_SHIFT, etc.). virtual bool keyboardEvent(int key, int scancode, int action, int modifiers) override; /// Draws the UI and all child windows with the given context. virtual void draw(NVGcontext *ctx) override { Screen::draw(ctx); } /// Draws the background of this window. /// This is where all OpenGL calls for this window happen. virtual void drawContents() override; /// Compute the image to be displayed. Derived classes must override this to provide /// content. The job of this method is to update the pixel values in @c img_data. virtual void computeImage() = 0; protected: /// The width and height of the application window in nominal pixels. /// These are also the dimensions of the displayed image. /// They may differ from the actual screen resolution on high dpi displays. int windowWidth, windowHeight; // Storage for displayed floating-point image in a flat // row-major array. Pixel (i,j), channel k is at // img_data[3 * (windowWidth * iy + ix) + k] Eigen::VectorXf img_data; // Exposure for HDR -> LDR conversion float exposure = 1.0f; private: // Simple shader for writing out image data std::unique_ptr<GLWrap::Program> srgbShader; // Texture to hold rendered image std::unique_ptr<GLWrap::Texture2D> imgTex; // Mesh for full screen quad std::unique_ptr<GLWrap::Mesh> fsqMesh; }; } #endif /* ImgGUI_hpp */
[ "cgl53@cornell.edu" ]
cgl53@cornell.edu
0d509505f822bf8f9b41fe05ed62686034dbf843
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/chrome/browser/subresource_redirect/subresource_redirect_observer.cc
a153df8cee9c6b339f5a63b335652c0d4d5c71a9
[ "BSD-3-Clause" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
5,977
cc
// Copyright 2020 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 "chrome/browser/subresource_redirect/subresource_redirect_observer.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" #include "components/optimization_guide/optimization_guide_decider.h" #include "components/optimization_guide/proto/performance_hints_metadata.pb.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/mojom/loader/previews_resource_loading_hints.mojom.h" #include "url/gurl.h" namespace subresource_redirect { namespace { // Returns the OptimizationGuideDecider when LiteMode and the subresource // redirect feature are enabled. optimization_guide::OptimizationGuideDecider* GetOptimizationGuideDeciderFromWebContents(content::WebContents* web_contents) { DCHECK(base::FeatureList::IsEnabled(blink::features::kSubresourceRedirect)); if (!web_contents) return nullptr; if (Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext())) { if (data_reduction_proxy::DataReductionProxySettings:: IsDataSaverEnabledByUser(profile->IsOffTheRecord(), profile->GetPrefs())) { return OptimizationGuideKeyedServiceFactory::GetForProfile(profile); } } return nullptr; } // Pass down the |images_hints| to |render_frame_host|. void SetResourceLoadingImageHints( content::RenderFrameHost* render_frame_host, blink::mojom::CompressPublicImagesHintsPtr images_hints) { mojo::AssociatedRemote<blink::mojom::PreviewsResourceLoadingHintsReceiver> loading_hints_agent; if (render_frame_host->GetRemoteAssociatedInterfaces()) { render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface( &loading_hints_agent); loading_hints_agent->SetCompressPublicImagesHints(std::move(images_hints)); } } // Invoked when the OptimizationGuideKeyedService has sufficient information // to make a decision for whether we can send resource loading image hints. // If |decision| is true, public image URLs contained in |metadata| will be // sent to the render frame host as specified by // |render_frame_host_routing_id| to later be compressed. void OnReadyToSendResourceLoadingImageHints( content::GlobalFrameRoutingId render_frame_host_routing_id, optimization_guide::OptimizationGuideDecision decision, const optimization_guide::OptimizationMetadata& optimization_metadata) { content::RenderFrameHost* current_render_frame_host = content::RenderFrameHost::FromID(render_frame_host_routing_id); // Check if the same render frame host is still valid. if (!current_render_frame_host) return; if (decision != optimization_guide::OptimizationGuideDecision::kTrue) return; if (!optimization_metadata.public_image_metadata()) return; std::vector<std::string> public_image_urls; const optimization_guide::proto::PublicImageMetadata public_image_metadata = optimization_metadata.public_image_metadata().value(); public_image_urls.reserve(public_image_metadata.url_size()); for (const auto& url : public_image_metadata.url()) public_image_urls.push_back(url); // Pass down the image URLs to renderer even if it could be empty. This acts // as a signal that the image hint fetch has finished, for coverage metrics // purposes. SetResourceLoadingImageHints( current_render_frame_host, blink::mojom::CompressPublicImagesHints::New(public_image_urls)); } } // namespace // static void SubresourceRedirectObserver::MaybeCreateForWebContents( content::WebContents* web_contents) { if (base::FeatureList::IsEnabled(blink::features::kSubresourceRedirect)) { SubresourceRedirectObserver::CreateForWebContents(web_contents); } } SubresourceRedirectObserver::SubresourceRedirectObserver( content::WebContents* web_contents) : content::WebContentsObserver(web_contents) { auto* optimization_guide_decider = GetOptimizationGuideDeciderFromWebContents(web_contents); if (optimization_guide_decider) { optimization_guide_decider->RegisterOptimizationTypesAndTargets( {optimization_guide::proto::COMPRESS_PUBLIC_IMAGES}, {}); } } SubresourceRedirectObserver::~SubresourceRedirectObserver() = default; void SubresourceRedirectObserver::DidFinishNavigation( content::NavigationHandle* navigation_handle) { DCHECK(navigation_handle); if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSameDocument()) { return; } auto* optimization_guide_decider = GetOptimizationGuideDeciderFromWebContents( navigation_handle->GetWebContents()); if (!optimization_guide_decider) return; content::RenderFrameHost* render_frame_host = navigation_handle->GetRenderFrameHost(); optimization_guide_decider->CanApplyOptimizationAsync( navigation_handle, optimization_guide::proto::COMPRESS_PUBLIC_IMAGES, base::BindOnce(&OnReadyToSendResourceLoadingImageHints, content::GlobalFrameRoutingId( render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()))); } WEB_CONTENTS_USER_DATA_KEY_IMPL(SubresourceRedirectObserver) } // namespace subresource_redirect
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
5e60ed3c70cc2cda57d3bbde17ea79fd6f3380d9
4f852af727fde026f34e03d800def8c328736855
/Classes/Script.cpp
d4bb92c09a118056a2a5984120603b6a40998c51
[ "MIT" ]
permissive
liusheng193/XXLZZ
c1cdadf68368c382313bb99f020994bb6bfba9da
0e40c1694f0622e03d9d911b4e40a15f252e1b01
refs/heads/master
2016-09-13T19:58:47.116380
2016-04-30T10:43:20
2016-04-30T10:43:20
57,314,575
1
0
null
null
null
null
GB18030
C++
false
false
18,417
cpp
#include "Script.h" #include "Scene_main.h" #include <string.h> #include "TH_log.h" //#include <assert.h> // // 构造函数 // CScriptAction::CScriptAction(CScene_main *win, CAction *oldAction, int mode) : CAction(win, oldAction),reader(0) { // 命令表格(command table)的初始化 cmd_table.insert(CmdTab("set", &CScriptAction::SetCmd)); cmd_table.insert(CmdTab("calc", &CScriptAction::SetCmd)); cmd_table.insert(CmdTab("text", &CScriptAction::TextCmd)); cmd_table.insert(CmdTab("goto", &CScriptAction::GotoCmd)); cmd_table.insert(CmdTab("if", &CScriptAction::IfCmd)); cmd_table.insert(CmdTab("menu", &CScriptAction::MenuCmd)); cmd_table.insert(CmdTab("click", &CScriptAction::ClickMenuCmd)); cmd_table.insert(CmdTab("exec", &CScriptAction::ExecCmd)); cmd_table.insert(CmdTab("load", &CScriptAction::LoadCmd)); cmd_table.insert(CmdTab("update", &CScriptAction::UpdateCmd)); cmd_table.insert(CmdTab("clear", &CScriptAction::ClearCmd)); cmd_table.insert(CmdTab("music", &CScriptAction::MusicCmd)); cmd_table.insert(CmdTab("stopm", &CScriptAction::StopmCmd)); cmd_table.insert(CmdTab("wait", &CScriptAction::WaitCmd)); cmd_table.insert(CmdTab("sound", &CScriptAction::SoundCmd)); cmd_table.insert(CmdTab("fadein", &CScriptAction::FadeInCmd)); cmd_table.insert(CmdTab("fadeout", &CScriptAction::FadeOutCmd)); cmd_table.insert(CmdTab("wipein", &CScriptAction::WipeInCmd)); cmd_table.insert(CmdTab("wipeout", &CScriptAction::WipeOutCmd)); cmd_table.insert(CmdTab("cutin", &CScriptAction::CutInCmd)); cmd_table.insert(CmdTab("cutout", &CScriptAction::CutOutCmd)); cmd_table.insert(CmdTab("whitein", &CScriptAction::WhiteInCmd)); cmd_table.insert(CmdTab("whiteout", &CScriptAction::WhiteOutCmd)); cmd_table.insert(CmdTab("flash", &CScriptAction::FlashCmd)); cmd_table.insert(CmdTab("shake", &CScriptAction::ShakeCmd)); cmd_table.insert(CmdTab("mode", &CScriptAction::ModeCmd)); cmd_table.insert(CmdTab("system", &CScriptAction::SystemCmd)); cmd_table.insert(CmdTab("battle", &CScriptAction::BattleCmd)); cmd_table.insert(CmdTab("end", &CScriptAction::EndCmd)); status = Continue; Pressed = false; MenuSelect = -1; PlayMode = mode; delete reader; reader = 0; } // // 析构函数 // CScriptAction::~CScriptAction() { delete reader; } // // 错误事件的格式 // char * CScriptAction::Format(const char *fmt, ...) { static char tmp[256]; //va_list args; //va_start(args, fmt); //_vsnprintf(tmp, sizeof(tmp), fmt, args); //va_end(args); return tmp; } // // 暂停 // void CScriptAction::Pause() { switch (status) { case WaitMenuDone: if (MenuSelect >= 0) { Parent->SelectMenu(MenuSelect, false); MenuSelect = -1; } break; default: break; } } // // 解除暂停 // void CScriptAction::Resume() { } // // 按下鼠标左键时的处理 // void CScriptAction::LButtonDown(UINT modKeys, Vec2 point) { switch (status) { case WaitKeyPressed: // 等待按键 Parent->HideWaitMark(); status = Continue; break; case WaitMenuDone: // 等待菜单 case WaitClickMenuDone: Pressed = true; break; } } // // 放开鼠标左键时的处理 // void CScriptAction::LButtonUp(UINT modKeys, Vec2 point) { switch (status) { case WaitKeyPressed: // 等待按键 //Parent->HideWaitMark(); status = Continue; break; case WaitMenuDone: // 等待菜单 if (Pressed) { Pressed = false; //MouseMove(modKeys, point); if (MenuSelect >= 0) { Parent->SetValue(MenuAnser, Parent->GetMenuAnser(MenuSelect)); Parent->HideMenuWindow(); status = Continue; } MenuSelect = -1; } break; case WaitClickMenuDone: if (Pressed) { Pressed = false; //int sel = Parent->GetClickMenuSelect(point); //if (sel >= 0) { // Parent->SetValue(MenuAnser, sel); // status = Continue; // } } break; } } // // 按下鼠标右键时的处理 // void CScriptAction::RButtonDown(UINT modKeys, Vec2 point) { } // // 移动鼠标时的处理 // void CScriptAction::MouseMove(UINT modKeys, Vec2 point) { //switch (status) { //case WaitMenuDone: // 等待菜单 //{ // int sel = Parent->GetMenuSelect(point); // if (sel != MenuSelect) { // Parent->SelectMenu(MenuSelect, false); // MenuSelect = sel; // Parent->SelectMenu(MenuSelect, true); // } //} // break; //} } // // 按下键盘时的处理 // void CScriptAction::KeyDown(UINT key) { } // // IDLE的处理 // bool CScriptAction::IdleAction() { if (status == Continue) { // 执行“继续” do { status = Step(); // 执行一步 } while (status == Continue); // 继续吗? if (status == BreakGame) { // 结束 Abort(); } else if (status == WaitNextIdle) { // 等待下个IDLE处理 status = Continue; // 继续 return true; } else if (status == WaitWipeDone) { // 等待特效结束 return true; // IDLE继续 } } return false; } // // 计时器的处理 // bool CScriptAction::TimedOut(int timerId) { return true; } // // Wipe特效结束时的处理 // void CScriptAction::WipeDone() { if (status == WaitWipeDone) // 等待特效结束 status = Continue; } // // Wave播放结束时的处理 // void CScriptAction::WaveDone() { if (status == WaitWaveDone) // 等待WAVE播放结束 status = Continue; } // // Script执行结束 // void CScriptAction::Abort() { } // // 读取Script档 // bool CScriptAction::LoadFile(const char *name) { char path[260]; sprintf(path, SCRIPTPATH "%s.txt", name); label_table.clear(); reader = new TextReader(path); return reader->IsOk(); } // // 读取Script档,并设定成员变量 // bool CScriptAction::Load(const char *name) { strncpy(Parent->GetParam().last_script, name, 16); if (!LoadFile(name)) { //读取script错误 return false; } return true; } // // 进行设定,让Script从储存位置中可以再度开启 // //bool CScriptAction::Setup(CParams &param) //{ // // return true; //} // // 错误事件的输出 // void CScriptAction::Error(const char *fmt, ...) { va_list args; char str[256]; int len = 0; THLog_Write(LOG_ID_GAME, true, fmt); //if (reader) // len = sprintf(str, "%s:%d ", reader->GetFileName(), reader->GetLineNo()); //va_start(args, fmt); //_vsnprintf(str + len, sizeof(str)-len, fmt, args); //va_end(args); //Parent->MessageBox(str); } // // 比对关键字 // bool CScriptAction::ChkKeyword(const char *str, const char *keyword) { while (*str) { if (tolower(*str++) != *keyword++) return false; } return true; } // // CG的指定位置设定成位置码 // int CScriptAction::GetPosition(const char *str) { if (ChkKeyword(str, "bg") || ChkKeyword(str, "back")) return POSITION_BACK; if (ChkKeyword(str, "bgo") || ChkKeyword(str, "backonly")) return POSITION_BACKONLY; if (ChkKeyword(str, "ov")) return POSITION_OVERLAP; if (ChkKeyword(str, "work")) return POSITION_WORK; Error("文法错误(position)"); return POSITION_BACK; } // // 依照命令来更新指定特效 // int CScriptAction::GetUpdateType(const char *str) { if (ChkKeyword(str, "cut") || ChkKeyword(str, "now")) return UPDATE_NOW; if (ChkKeyword(str, "overlap")) return UPDATE_OVERLAP; if (ChkKeyword(str, "wipe")) return UPDATE_WIPE; Error("文法错误(update type)"); return UPDATE_NOW; } // // 移到Script中指定的位置 // int CScriptAction::GotoCommand(const char *label) { labelmap::iterator p = label_table.find(label); if (p == label_table.end()) { // 找不到标签 const char *str; // 从Script档中搜寻标签 while ((str = reader->GetString()) != NULL) { Lexer lexer(str); if (lexer.NumToken() == 1 && lexer.GetType() == Lexer::IsLabel) { if (SetLabel(lexer) != Continue) // 登录标签 return BreakGame; const char *p = lexer.GetString(0) + 1; if (C_STRICMP(p, label) == 0) // 找到标签了! return Continue; } } Error("找不到标签[%s]", label); return BreakGame; } reader->SetPosition(p->second); return Continue; } // // 标签的登录指令 // int CScriptAction::SetLabel(Lexer &lexer) { if (lexer.NumToken() != 1) { cocos2d::log("参数太多了"); return BreakGame; } const char *label = lexer.GetString() + 1; labelmap::iterator p = label_table.find(label); if (p != label_table.end()) { // 标签已经存在 if (label_table[label] != reader->GetPosition()) { cocos2d::log("标签 [%s] 已经登录过了", label); return BreakGame; } } label_table[label] = reader->GetPosition(); return Continue; } // // set指令 // int CScriptAction::SetCmd(Lexer &lexer) { return Continue; } // // goto指令 // int CScriptAction::GotoCmd(Lexer &lexer) { const char *label = lexer.GetString(); if (label == 0 || lexer.GetString() != 0) { Error("文法错误(in goto command)"); return BreakGame; } return GotoCommand(label); } // // 取得变量或常数 // bool CScriptAction::GetValue(Lexer &lexer, int *value) { if (lexer.GetType() == Lexer::IsString) { // 字符串 const char *name = lexer.GetString(); *value = Parent->GetValue(name); return true; } return lexer.GetValue(value); // 当成数字读看看 } // // if 指令 // int CScriptAction::IfCmd(Lexer &lexer) { int value1, value2; bool b1 = GetValue(lexer, &value1); const char *op = lexer.GetString(); bool b2 = GetValue(lexer, &value2); const char *p = lexer.GetString(); const char *label = lexer.GetString(); if (!b1 || !b2 || op == 0 || label == 0 || lexer.GetString() != 0 && C_STRICMP(p, "goto") != 0) { Error("文法错误"); return BreakGame; } if (strcmp(op, "==") == 0) { if (value1 == value2) return GotoCommand(label); } else if (strcmp(op, "!=") == 0) { if (value1 != value2) return GotoCommand(label); } else if (strcmp(op, "<=") == 0) { if (value1 <= value2) return GotoCommand(label); } else if (strcmp(op, ">=") == 0) { if (value1 >= value2) return GotoCommand(label); } else if (strcmp(op, "<") == 0) { if (value1 < value2) return GotoCommand(label); } else if (strcmp(op, ">") == 0) { if (value1 > value2) return GotoCommand(label); } else { Error("文法错误"); return BreakGame; } return Continue; } // // menu 指令 // int CScriptAction::MenuCmd(Lexer &lexer) { const char *p = lexer.GetString(); if (p == 0 || lexer.GetString() != 0) { cocos2d::log("文法错误(in menu command)"); return BreakGame; } Parent->ClearMenuItemCount(); MenuAnser = p; const char *str; for (int no = 0; (str = reader->GetString()) != NULL; no++) { //#if defined(_WIN32) if (C_STRICMP(str, "end") == 0) break; Parent->SetMenuItem(str, no + 1); } MenuSelect = -1; Parent->OpenMenu(); return WaitMenuDone; } // // click命令 // int CScriptAction::ClickMenuCmd(Lexer &lexer) { const char *p = lexer.GetString(); return WaitClickMenuDone; } // // load 指令 // int CScriptAction::LoadCmd(Lexer &lexer) { const char *p1 = lexer.GetString(); const char *p2 = lexer.GetString(); if (p1 == 0 || p2 == 0 || lexer.GetString() != 0) { Error("文法错误(in load command)"); return BreakGame; } return LoadGraphic(p2, GetPosition(p1)); } // // update 指令 // int CScriptAction::UpdateCmd(Lexer &lexer) { const char *p = lexer.GetString(); if (p == 0 || lexer.GetString() != 0) { Error("文法错误(in update command)"); return BreakGame; } return UpdateImage(GetUpdateType(p)); } // // clear 指令 // int CScriptAction::ClearCmd(Lexer &lexer) { const char *p = lexer.GetString(); if (p == 0 || lexer.GetString() != 0) { Error("文法错误(in clear command)"); return BreakGame; } if (C_STRICMP(p, "text") == 0) { // clear text 个别处理 Parent->ClearMessage(); return WaitNextIdle; } return Clear(GetPosition(p)); } // // music 指令 // int CScriptAction::MusicCmd(Lexer &lexer) { return Continue; } // // sound 指令 // int CScriptAction::SoundCmd(Lexer &lexer) { return Continue; } // // exec 指令 // int CScriptAction::ExecCmd(Lexer &lexer) { const char *path = lexer.GetString(); if (path == 0 || lexer.GetString() != 0) { Error("文法错误(in exec command)"); return BreakGame; } if (!Load(path)) return BreakGame; PlayMode = MODE_SCENARIO; return Continue; } // // wait 指令 // int CScriptAction::WaitCmd(Lexer &lexer) { return WaitTimeOut; } // // Text的尾端确认 // bool CScriptAction::ChkTermination(const char *str) { if (*str++ != '.') return false; while (*str) { if (!isspace(*str)) return false; } return true; } // // text 指令 // int CScriptAction::TextCmd(Lexer &lexer) { if (lexer.GetString() != 0) { Error("文法错误(in text command)"); return BreakGame; } std::string work; for (int i = 0;; i++) { const char *str; if ((str = reader->GetString()) == nullptr) { Error("文法错误(text syntax)"); return BreakGame; } if (ChkTermination(str)) break; work += str; work += '\n'; if (i >= MessageLine) { Error("内容行数过多"); return BreakGame; } } Parent->WriteMessage(work.c_str()); return WaitKeyPressed; } // // mode 指令 // int CScriptAction::ModeCmd(Lexer &lexer) { const char *p = lexer.GetString(); if (p == 0 || lexer.GetString() != 0) { Error("文法错误"); return BreakGame; } //#if defined(_WIN32) if (C_STRICMP(p, "system") == 0){ PlayMode = MODE_SYSTEM; } else if (C_STRICMP(p, "scenario") == 0) { PlayMode = MODE_SCENARIO; } else { Error("文法错误"); return BreakGame; } return Continue; } // // system 指令 // int CScriptAction::SystemCmd(Lexer &lexer) { const char *p = lexer.GetString(); if (p == 0 || lexer.GetString() != 0) { Error("文法错误"); return BreakGame; } if (C_STRICMP(p, "load") == 0) { Parent->SetGameLoadAction(); return WaitNextIdle; } if (C_STRICMP(p, "exit") == 0) { Parent->SentNotyMessage(PS_CLOSE); return WaitNextIdle; } if (C_STRICMP(p, "clear") == 0) { Parent->ClearValue(); return Continue; } Error("文法错误"); return BreakGame; } // // battle 指令 // int CScriptAction::BattleCmd(Lexer &lexer) { const char *p = lexer.GetString(); if (p == 0 || lexer.GetString() != 0) { Error("文法错误"); return BreakGame; } Parent->Battle(p); return WaitNextIdle; } // // stopm 指令 // int CScriptAction::StopmCmd(Lexer &lexer) { return Continue; } // // fadein 指令 // int CScriptAction::FadeInCmd(Lexer &lexer) { Parent->GetParam().SetShowFlag(); Parent->FadeIn(); return WaitWipeDone; } // // fadeout 指令 // int CScriptAction::FadeOutCmd(Lexer &lexer) { Parent->GetParam().ResetShowFlag(); Parent->FadeOut(); return WaitWipeDone; } // // wipein 指令 // int CScriptAction::WipeInCmd(Lexer &lexer) { Parent->GetParam().SetShowFlag(); Parent->WipeIn(); return WaitWipeDone; } // // wipeout 指令 // int CScriptAction::WipeOutCmd(Lexer &lexer) { Parent->GetParam().SetShowFlag(); Parent->WipeOut(); return WaitWipeDone; } // // cutin 指令 // int CScriptAction::CutInCmd(Lexer &lexer) { return WaitNextIdle; } // // cutout 指令 // int CScriptAction::CutOutCmd(Lexer &lexer) { return WaitNextIdle; } // // whitein 指令 // int CScriptAction::WhiteInCmd(Lexer &lexer) { return WaitWipeDone; } // // whiteout 指令 // int CScriptAction::WhiteOutCmd(Lexer &lexer) { return WaitWipeDone; } // // flash 指令 // int CScriptAction::FlashCmd(Lexer &lexer) { return WaitWipeDone; } // // shake 指令 // int CScriptAction::ShakeCmd(Lexer &lexer) { return WaitWipeDone; } // // end 指令 // int CScriptAction::EndCmd(Lexer &lexer) { return BreakGame; } // // 指令判定 // CScriptAction::cmd_t CScriptAction::ParseCommand(Lexer &lexer) { const char *cmd = lexer.GetString(0); cmdmap::iterator p = cmd_table.find(cmd); if (p != cmd_table.end()) return p->second; // set, calc的省略型吗? if (lexer.NumToken() >= 3) { const char *p = lexer.GetString(1); lexer.GetType(0); // 回到最前面 if (strcmp(p, "+") == 0 || strcmp(p, "-") == 0 || strcmp(p, "=") == 0) { return &CScriptAction::SetCmd; } } Error("文法错误(command syntax)"); return NULL; } // // 解析一行 // int CScriptAction::ParserString(const char *str) { Lexer lexer(str); if (lexer.NumToken() == 0) return Continue; int type = lexer.GetType(); if (type == Lexer::IsLabel) { return SetLabel(lexer); } cmd_t cmd = ParseCommand(lexer); if (cmd == 0) return BreakGame; return (this->*cmd)(lexer); } // // 执行Script的一个步骤 // int CScriptAction::Step() { CC_ASSERT(reader); // 将现在的位置设定成SaveDate todo const char *str = reader->GetString(); if (str == 0) return BreakGame; return ParserString(str); } // // CG的载入 // int CScriptAction::LoadGraphic(const char *file, int pos) { bool result = false; switch (pos) { case POSITION_BACK: // 背景 Parent->GetParam().ClearOverlapCG(); Parent->ClearOverlap(); // no break case POSITION_BACKONLY: // 背景的部分 Parent->GetParam().SetBackCG(file); result = Parent->LoadImageBack(file); break; case POSITION_OVERLAP: // 重叠 Parent->GetParam().SetOverlapCG(file); result = Parent->LoadImageOverlap(file); break; case POSITION_WORK: // 作业使用 Parent->GetParam().SetWorkCG(file); result = Parent->LoadImageWork(file); break; } if (!result) { //Parent->MessageBox(Format("档案无法读出 [%s] 档案", file)); if (PlayMode == MODE_SYSTEM) { //离开游戏 //Parent->SendMessage(WM_CLOSE); } return BreakGame; } return Continue; } // // 删除CG // int CScriptAction::Clear(int pos) { switch (pos) { case POSITION_BACK: // 背景 Parent->GetParam().ClearOverlapCG(); Parent->ClearOverlap(); // no break case POSITION_BACKONLY: // 背景的部分 Parent->GetParam().ClearBackCG(); Parent->ClearBack(); break; case POSITION_OVERLAP: // 重叠 Parent->GetParam().ClearOverlapCG(); Parent->ClearOverlap(); break; case POSITION_WORK: // 作业使用 Parent->GetParam().ClearWorkCG(); break; } return Continue; } // // 画面更新 // int CScriptAction::UpdateImage(int flag) { Parent->GetParam().SetShowFlag(); auto rect = Parent->GetInvalidRect(); if (rect==0) return Continue; switch (flag) { case UPDATE_NOW: Parent->CutIn(rect); return WaitNextIdle; case UPDATE_OVERLAP: Parent->MixFade(rect); break; case UPDATE_WIPE: Parent->WipeIn(rect); break; } return WaitWipeDone; }
[ "liusheng193@163.com" ]
liusheng193@163.com
a52f4220dc1d29e39e704c0ecb0470fb2733aebf
33392bbfbc4abd42b0c67843c7c6ba9e0692f845
/codec/L2/demos/jxlEnc/third_partys/third_party/highway/hwy/cache_control.h
7020cc7b2e590f540e78b84334256d3ed405975d
[ "Apache-2.0" ]
permissive
Xilinx/Vitis_Libraries
bad9474bf099ed288418430f695572418c87bc29
2e6c66f83ee6ad21a7c4f20d6456754c8e522995
refs/heads/main
2023-07-20T09:01:16.129113
2023-06-08T08:18:19
2023-06-08T08:18:19
210,433,135
785
371
Apache-2.0
2023-07-06T21:35:46
2019-09-23T19:13:46
C++
UTF-8
C++
false
false
3,463
h
// Copyright 2020 Google LLC // // 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 HIGHWAY_HWY_CACHE_CONTROL_H_ #define HIGHWAY_HWY_CACHE_CONTROL_H_ #include <stddef.h> #include <stdint.h> #include "hwy/base.h" // Requires SSE2; fails to compile on 32-bit Clang 7 (see // https://github.com/gperftools/gperftools/issues/946). #if !defined(__SSE2__) || (HWY_COMPILER_CLANG && HWY_ARCH_X86_32) #undef HWY_DISABLE_CACHE_CONTROL #define HWY_DISABLE_CACHE_CONTROL #endif // intrin.h is sufficient on MSVC and already included by base.h. #if HWY_ARCH_X86 && !defined(HWY_DISABLE_CACHE_CONTROL) && !HWY_COMPILER_MSVC #include <emmintrin.h> // SSE2 #endif // Windows.h #defines these, which causes infinite recursion. Temporarily // undefine them in this header; these functions are anyway deprecated. // TODO(janwas): remove when these functions are removed. #pragma push_macro("LoadFence") #pragma push_macro("StoreFence") #undef LoadFence #undef StoreFence namespace hwy { // Even if N*sizeof(T) is smaller, Stream may write a multiple of this size. #define HWY_STREAM_MULTIPLE 16 // The following functions may also require an attribute. #if HWY_ARCH_X86 && !defined(HWY_DISABLE_CACHE_CONTROL) && !HWY_COMPILER_MSVC #define HWY_ATTR_CACHE __attribute__((target("sse2"))) #else #define HWY_ATTR_CACHE #endif // Delays subsequent loads until prior loads are visible. On Intel CPUs, also // serves as a full fence (waits for all prior instructions to complete). // No effect on non-x86. HWY_INLINE HWY_ATTR_CACHE void LoadFence() { #if HWY_ARCH_X86 && !defined(HWY_DISABLE_CACHE_CONTROL) _mm_lfence(); #endif } // Ensures previous weakly-ordered stores are visible. No effect on non-x86. HWY_INLINE HWY_ATTR_CACHE void StoreFence() { #if HWY_ARCH_X86 && !defined(HWY_DISABLE_CACHE_CONTROL) _mm_sfence(); #endif } // Begins loading the cache line containing "p". template <typename T> HWY_INLINE HWY_ATTR_CACHE void Prefetch(const T* p) { #if HWY_ARCH_X86 && !defined(HWY_DISABLE_CACHE_CONTROL) _mm_prefetch(reinterpret_cast<const char*>(p), _MM_HINT_T0); #elif HWY_COMPILER_GCC || HWY_COMPILER_CLANG // Hint=0 (NTA) behavior differs, but skipping outer caches is probably not // desirable, so use the default 3 (keep in caches). __builtin_prefetch(p, /*write=*/0, /*hint=*/3); #else (void)p; #endif } // Invalidates and flushes the cache line containing "p". No effect on non-x86. HWY_INLINE HWY_ATTR_CACHE void FlushCacheline(const void* p) { #if HWY_ARCH_X86 && !defined(HWY_DISABLE_CACHE_CONTROL) _mm_clflush(p); #else (void)p; #endif } // Reduces power consumption in spin-loops. No effect on non-x86. HWY_INLINE HWY_ATTR_CACHE void Pause() { #if HWY_ARCH_X86 && !defined(HWY_DISABLE_CACHE_CONTROL) _mm_pause(); #endif } } // namespace hwy // TODO(janwas): remove when these functions are removed. (See above.) #pragma pop_macro("StoreFence") #pragma pop_macro("LoadFence") #endif // HIGHWAY_HWY_CACHE_CONTROL_H_
[ "do-not-reply@gitenterprise.xilinx.com" ]
do-not-reply@gitenterprise.xilinx.com
0b282a10ee6619c006f2041e18579c3104fdc0e2
cd470ad61c4dbbd37ff004785fd6d75980987fe9
/AtCoder/agc036 AtCoder Grand Contest 036/F/std.cpp
1ef90b93081a90374197d963ce1128903cc14526
[]
no_license
AutumnKite/Codes
d67c3770687f3d68f17a06775c79285edc59a96d
31b7fc457bf8858424172bc3580389badab62269
refs/heads/master
2023-02-17T21:33:04.604104
2023-02-17T05:38:57
2023-02-17T05:38:57
202,944,952
3
1
null
null
null
null
UTF-8
C++
false
false
3,009
cpp
#include <bits/stdc++.h> #define debug(...) fprintf(stderr, __VA_ARGS__) #ifndef AT_HOME #define getchar() IO::myGetchar() #define putchar(x) IO::myPutchar(x) #endif namespace IO { static const int IN_BUF = 1 << 23, OUT_BUF = 1 << 23; inline char myGetchar() { static char buf[IN_BUF], *ps = buf, *pt = buf; if (ps == pt) { ps = buf, pt = buf + fread(buf, 1, IN_BUF, stdin); } return ps == pt ? EOF : *ps++; } template<typename T> inline bool read(T &x) { bool op = 0; char ch = getchar(); x = 0; for (; !isdigit(ch) && ch != EOF; ch = getchar()) { op ^= (ch == '-'); } if (ch == EOF) { return false; } for (; isdigit(ch); ch = getchar()) { x = x * 10 + (ch ^ '0'); } if (op) { x = -x; } return true; } inline int readStr(char *s) { int n = 0; char ch = getchar(); for (; isspace(ch) && ch != EOF; ch = getchar()) ; for (; !isspace(ch) && ch != EOF; ch = getchar()) { s[n++] = ch; } s[n] = '\0'; return n; } inline void myPutchar(char x) { static char pbuf[OUT_BUF], *pp = pbuf; struct _flusher { ~_flusher() { fwrite(pbuf, 1, pp - pbuf, stdout); } }; static _flusher outputFlusher; if (pp == pbuf + OUT_BUF) { fwrite(pbuf, 1, OUT_BUF, stdout); pp = pbuf; } *pp++ = x; } template<typename T> inline void print_(T x) { if (x == 0) { putchar('0'); return; } static int num[40]; if (x < 0) { putchar('-'); x = -x; } for (*num = 0; x; x /= 10) { num[++*num] = x % 10; } while (*num){ putchar(num[*num] ^ '0'); --*num; } } template<typename T> inline void print(T x, char ch = '\n') { print_(x); putchar(ch); } inline void printStr_(const char *s, int n = -1) { if (n == -1) { n = strlen(s); } for (int i = 0; i < n; ++i) { putchar(s[i]); } } inline void printStr(const char *s, int n = -1, char ch = '\n') { printStr_(s, n); putchar(ch); } } using namespace IO; const int N = 505; int n, P, r[N], l[N], f[N]; int main() { read(n), read(P); std::vector<std::pair<int, int>> a; for (int i = 0; i < n; ++i) { r[i] = sqrt(4 * n * n - i * i) + 1e-9 + 1; r[i] = std::min(r[i], 2 * n); l[i] = sqrt(n * n - i * i - 1) + 1e-9 + 1; a.push_back({l[i], -i}); } for (int i = n; i < 2 * n; ++i) { r[i] = sqrt(4 * n * n - i * i) + 1e-9 + 1; r[i] = std::min(r[i], 2 * n); a.push_back({r[i], -i}); } std::sort(a.begin(), a.end()); int dfcmd = 0; for (int k = 0; k <= n; ++k) { for (int i = 0; i <= n; ++i) { f[i] = 0; } f[0] = 1; int c0 = 0, c1 = 0; for (auto v : a) { int id = -v.second; if (id >= n) { for (int i = c0; ~i; --i) { f[i] = 1ll * f[i] * (r[id] - i - c1) % P; } ++c1; } else { for (int i = c0 + 1; ~i; --i) { f[i] = 1ll * f[i] * (r[id] - k - n - (c0 - i)) % P; if (i) { f[i] = (f[i] + 1ll * f[i - 1] * (l[id] - (i - 1) - c1)) % P; } } ++c0; } } dfcmd = (dfcmd + (k & 1 ? -1 : 1) * f[k]) % P; } print((dfcmd + P) % P); }
[ "1790397194@qq.com" ]
1790397194@qq.com
3d6299217910d9f037c456bd384db917456eb735
90047daeb462598a924d76ddf4288e832e86417c
/ui/gfx/buffer_format_util.cc
35003e1072d35d61bad2264967eb9cf4f1b17e1f
[ "BSD-3-Clause" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
7,367
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/buffer_format_util.h" #include "base/logging.h" #include "base/macros.h" #include "base/numerics/safe_math.h" namespace gfx { namespace { const BufferFormat kBufferFormats[] = { BufferFormat::ATC, BufferFormat::ATCIA, BufferFormat::DXT1, BufferFormat::DXT5, BufferFormat::ETC1, BufferFormat::R_8, BufferFormat::RG_88, BufferFormat::BGR_565, BufferFormat::RGBA_4444, BufferFormat::RGBX_8888, BufferFormat::RGBA_8888, BufferFormat::BGRX_8888, BufferFormat::BGRA_8888, BufferFormat::RGBA_F16, BufferFormat::UYVY_422, BufferFormat::YUV_420_BIPLANAR, BufferFormat::YVU_420}; static_assert(arraysize(kBufferFormats) == (static_cast<int>(BufferFormat::LAST) + 1), "BufferFormat::LAST must be last value of kBufferFormats"); bool RowSizeForBufferFormatChecked( size_t width, BufferFormat format, size_t plane, size_t* size_in_bytes) { base::CheckedNumeric<size_t> checked_size = width; switch (format) { case BufferFormat::ATCIA: case BufferFormat::DXT5: DCHECK_EQ(0u, plane); *size_in_bytes = width; return true; case BufferFormat::ATC: case BufferFormat::DXT1: case BufferFormat::ETC1: DCHECK_EQ(0u, plane); DCHECK_EQ(0u, width % 2); *size_in_bytes = width / 2; return true; case BufferFormat::R_8: checked_size += 3; if (!checked_size.IsValid()) return false; *size_in_bytes = (checked_size & ~0x3).ValueOrDie(); return true; case BufferFormat::RG_88: case BufferFormat::BGR_565: case BufferFormat::RGBA_4444: case BufferFormat::UYVY_422: checked_size *= 2; checked_size += 3; if (!checked_size.IsValid()) return false; *size_in_bytes = (checked_size & ~0x3).ValueOrDie(); return true; case BufferFormat::BGRX_8888: case BufferFormat::RGBX_8888: case BufferFormat::RGBA_8888: case BufferFormat::BGRA_8888: checked_size *= 4; if (!checked_size.IsValid()) return false; *size_in_bytes = checked_size.ValueOrDie(); return true; case BufferFormat::RGBA_F16: checked_size *= 8; if (!checked_size.IsValid()) return false; *size_in_bytes = checked_size.ValueOrDie(); return true; case BufferFormat::YVU_420: DCHECK_EQ(0u, width % 2); *size_in_bytes = width / SubsamplingFactorForBufferFormat(format, plane); return true; case BufferFormat::YUV_420_BIPLANAR: DCHECK_EQ(width % 2, 0u); *size_in_bytes = width; return true; } NOTREACHED(); return false; } } // namespace std::vector<BufferFormat> GetBufferFormatsForTesting() { return std::vector<BufferFormat>(kBufferFormats, kBufferFormats + arraysize(kBufferFormats)); } size_t NumberOfPlanesForBufferFormat(BufferFormat format) { switch (format) { case BufferFormat::ATC: case BufferFormat::ATCIA: case BufferFormat::DXT1: case BufferFormat::DXT5: case BufferFormat::ETC1: case BufferFormat::R_8: case BufferFormat::RG_88: case BufferFormat::BGR_565: case BufferFormat::RGBA_4444: case BufferFormat::RGBX_8888: case BufferFormat::RGBA_8888: case BufferFormat::BGRX_8888: case BufferFormat::BGRA_8888: case BufferFormat::RGBA_F16: case BufferFormat::UYVY_422: return 1; case BufferFormat::YUV_420_BIPLANAR: return 2; case BufferFormat::YVU_420: return 3; } NOTREACHED(); return 0; } size_t SubsamplingFactorForBufferFormat(BufferFormat format, size_t plane) { switch (format) { case BufferFormat::ATC: case BufferFormat::ATCIA: case BufferFormat::DXT1: case BufferFormat::DXT5: case BufferFormat::ETC1: case BufferFormat::R_8: case BufferFormat::RG_88: case BufferFormat::BGR_565: case BufferFormat::RGBA_4444: case BufferFormat::RGBX_8888: case BufferFormat::RGBA_8888: case BufferFormat::BGRX_8888: case BufferFormat::BGRA_8888: case BufferFormat::RGBA_F16: case BufferFormat::UYVY_422: return 1; case BufferFormat::YVU_420: { static size_t factor[] = {1, 2, 2}; DCHECK_LT(static_cast<size_t>(plane), arraysize(factor)); return factor[plane]; } case BufferFormat::YUV_420_BIPLANAR: { static size_t factor[] = {1, 2}; DCHECK_LT(static_cast<size_t>(plane), arraysize(factor)); return factor[plane]; } } NOTREACHED(); return 0; } size_t RowSizeForBufferFormat(size_t width, BufferFormat format, size_t plane) { size_t row_size = 0; bool valid = RowSizeForBufferFormatChecked(width, format, plane, &row_size); DCHECK(valid); return row_size; } size_t BufferSizeForBufferFormat(const Size& size, BufferFormat format) { size_t buffer_size = 0; bool valid = BufferSizeForBufferFormatChecked(size, format, &buffer_size); DCHECK(valid); return buffer_size; } bool BufferSizeForBufferFormatChecked(const Size& size, BufferFormat format, size_t* size_in_bytes) { base::CheckedNumeric<size_t> checked_size = 0; size_t num_planes = NumberOfPlanesForBufferFormat(format); for (size_t i = 0; i < num_planes; ++i) { size_t row_size = 0; if (!RowSizeForBufferFormatChecked(size.width(), format, i, &row_size)) return false; base::CheckedNumeric<size_t> checked_plane_size = row_size; checked_plane_size *= size.height() / SubsamplingFactorForBufferFormat(format, i); if (!checked_plane_size.IsValid()) return false; checked_size += checked_plane_size.ValueOrDie(); if (!checked_size.IsValid()) return false; } *size_in_bytes = checked_size.ValueOrDie(); return true; } size_t BufferOffsetForBufferFormat(const Size& size, BufferFormat format, size_t plane) { DCHECK_LT(plane, gfx::NumberOfPlanesForBufferFormat(format)); switch (format) { case BufferFormat::ATC: case BufferFormat::ATCIA: case BufferFormat::DXT1: case BufferFormat::DXT5: case BufferFormat::ETC1: case BufferFormat::R_8: case BufferFormat::RG_88: case BufferFormat::BGR_565: case BufferFormat::RGBA_4444: case BufferFormat::RGBX_8888: case BufferFormat::RGBA_8888: case BufferFormat::BGRX_8888: case BufferFormat::BGRA_8888: case BufferFormat::RGBA_F16: case BufferFormat::UYVY_422: return 0; case BufferFormat::YVU_420: { static size_t offset_in_2x2_sub_sampling_sizes[] = {0, 4, 5}; DCHECK_LT(plane, arraysize(offset_in_2x2_sub_sampling_sizes)); return offset_in_2x2_sub_sampling_sizes[plane] * (size.width() / 2 + size.height() / 2); } case gfx::BufferFormat::YUV_420_BIPLANAR: { static size_t offset_in_2x2_sub_sampling_sizes[] = {0, 4}; DCHECK_LT(plane, arraysize(offset_in_2x2_sub_sampling_sizes)); return offset_in_2x2_sub_sampling_sizes[plane] * (size.width() / 2 + size.height() / 2); } } NOTREACHED(); return 0; } } // namespace gfx
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
a4f8b4f3a169a84539cc77684572f9106dbfef96
19045b97354a33663911b309c6bf2e42f3d34ae2
/Classes/GameScene.cpp
a03ac3b612c2e252bb1df19358a124f05eb10ccf
[ "MIT" ]
permissive
MCB1074/Landlord_cpp
2faa194562daa070d31901969389cba0d054db1a
cca017961505f866c42e71ba01aa1b1b66bd1a57
refs/heads/master
2021-05-31T23:08:31.204656
2016-03-10T15:20:25
2016-03-10T15:20:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,460
cpp
#include "GameScene.h" GameScene::GameScene() { cardsNum = CARDS_NUM; startItem = nullptr; callLandItem = nullptr; netWorkItem = nullptr; noCallItem = nullptr; robLandItem = nullptr; noRobItem = nullptr; putItem = nullptr; noPutItem = nullptr; playerSelf = nullptr; playerLeft = nullptr; playerRight = nullptr; vecAllCardBacks.clear(); } GameScene::~GameScene() { } Scene* GameScene::createScene() { auto scene = Scene::create(); auto layer = GameScene::create(); scene->addChild(layer); return scene; } bool GameScene::init() { if (!Layer::init()) { return false; } visibleSize = Director::getInstance()->getVisibleSize(); //背景 auto sprBG = Sprite::create("image/bg_desktop.png"); sprBG->setPosition(visibleSize / 2); this->addChild(sprBG); playerSelf = Player::create(ERoleSide_Down); //playerSelf->setPutEnable(CC_CALLBACK_1(GameScene::setPutEnable, this)); this->addChild(playerSelf); //createButtons(); Card* card = Card::create(1); card->setPosition(visibleSize / 2); this->addChild(card); Card* card2 = Card::create(1); card2->setPosition(Vec2(visibleSize.width / 2 + 20.f, visibleSize.height / 2)); this->addChild(card2); return true; } void GameScene::onEnter() { Layer::onEnter(); //connServer(); } void GameScene::onExit() { //closeConn(); } void GameScene::createButtons() { //联网 netWorkItem = MenuItemImage::create("image/btn_i_know_1.png", "image/btn_i_know_2.png", CC_CALLBACK_1(GameScene::onNetwork, this)); netWorkItem->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 - netWorkItem->getContentSize().height)); netWorkItem->setVisible(false); //开始游戏 startItem = MenuItemImage::create("image/btn_start_app.png", "image/btn_start_app2.png", CC_CALLBACK_1(GameScene::onStartGame, this)); startItem->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 - startItem->getContentSize().height)); startItem->setVisible(false); //叫地主 callLandItem = MenuItemImage::create("image/btn_jiaodizhu_up.png", "image/btn_jiaodizhu_down.png", CC_CALLBACK_1(GameScene::onCallLand, this)); callLandItem->setPosition(Vec2(visibleSize.width / 2 - 150, visibleSize.height / 2 - callLandItem->getContentSize().height)); callLandItem->setVisible(false); //不叫 noCallItem = MenuItemImage::create("image/btn_bujiao.png", "image/btn_bujiao_down.png", CC_CALLBACK_1(GameScene::onNoCall, this)); noCallItem->setPosition(Vec2(visibleSize.width / 2 + 150, visibleSize.height / 2 - noCallItem->getContentSize().height)); noCallItem->setVisible(false); //抢地主 robLandItem = MenuItemImage::create("image/btn_qiangdizhu_up.png", "image/btn_qiangdizhu_down.png", CC_CALLBACK_1(GameScene::onRobLand, this)); robLandItem->setPosition(Vec2(visibleSize.width / 2 - 150, visibleSize.height / 2 - robLandItem->getContentSize().height)); robLandItem->setVisible(false); //不抢 noRobItem = MenuItemImage::create("image/btn_buqiang.png", "image/btn_buqiang_down.png", CC_CALLBACK_1(GameScene::onNoRob, this)); noRobItem->setPosition(Vec2(visibleSize.width / 2 + 150, visibleSize.height / 2 - noRobItem->getContentSize().height)); noRobItem->setVisible(false); //出牌 putItem = MenuItemImage::create("image/btn_chupai.png", "image/btn_chupai_down.png", "image/btn_chupai_hui.png", CC_CALLBACK_1(GameScene::onPut, this)); putItem->setPosition(Vec2(visibleSize.width / 2 - 150, visibleSize.height / 2 - putItem->getContentSize().height)); putItem->setVisible(false); //不出 noPutItem = MenuItemImage::create("image/btn_bujiao2.png", "image/btn_bujiao2_down.png", CC_CALLBACK_1(GameScene::onNoPut, this)); noPutItem->setPosition(Vec2(visibleSize.width / 2 + 150, visibleSize.height / 2 - noPutItem->getContentSize().height)); noPutItem->setVisible(false); auto menu = Menu::create(netWorkItem, startItem, callLandItem, noCallItem, robLandItem, noRobItem, putItem, noPutItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 100); } void GameScene::onNetwork(Ref* pSender) { std::thread recvThread(&GameScene::connThread, this); recvThread.detach(); } void GameScene::onStartGame(Ref* pSender) { startItem->setVisible(false); sendServer("StartGame:"); } void GameScene::onCallLand(Ref* pSender) { callLandItem->setVisible(false); noCallItem->setVisible(false); sendServer("CallLand:"); } void GameScene::onNoCall(Ref* pSender) { callLandItem->setVisible(false); noCallItem->setVisible(false); sendServer("NoCall:"); } void GameScene::onRobLand(Ref* pSender) { robLandItem->setVisible(false); noRobItem->setVisible(false); sendServer("RobLand:"); } void GameScene::onNoRob(Ref* pSender) { robLandItem->setVisible(false); noRobItem->setVisible(false); sendServer("NoRob:"); } void GameScene::onPut(Ref* pSender)//出牌 TODO { putItem->setVisible(false); noPutItem->setVisible(false); playerSelf->showSelfCards(); sendServer("Put:" + vectorTostring(playerSelf->getPutPoints())); } void GameScene::onNoPut(Ref* pSender) { putItem->setVisible(false); noPutItem->setVisible(false); sendServer("NoPut:"); } void GameScene::connServer() { //WinSock初始化 WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { CCLOG("WSAStartup fail"); return; } //确认WinSock DLL支持版本2.2 if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); CCLOG("WinSock DLL Version Invalid"); return; } //创建Socket,使用TCP协议 sockClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sockClient == INVALID_SOCKET) { closeConn(); CCLOG("socket fail"); return; } //服务器地址 addrClient.sin_family = AF_INET; addrClient.sin_port = htons(SERVER_PORT); inet_pton(AF_INET, "127.0.0.1", &addrClient.sin_addr.S_un.S_addr); //连接服务器 std::thread recvThread(&GameScene::connThread, this); recvThread.detach(); } void GameScene::connThread() { if (SOCKET_ERROR == connect(sockClient, (SOCKADDR*)&addrClient, sizeof(SOCKADDR))) { netWorkItem->setVisible(true); CCLOG("connect fail"); return; } netWorkItem->setVisible(false); startItem->setVisible(true); //连接消息 std::thread recvThread(&GameScene::recvThread, this); recvThread.detach(); } void GameScene::closeConn() { closesocket(sockClient); WSACleanup(); } void GameScene::recvThread() { char buff[100];//最大100 int pos; while (true) { recv(sockClient, buff, 100, 0); std::string strBuff = buff; CCLOG("%s", strBuff.c_str()); pos = 0; std::string strFront = strBuff.substr(pos, strBuff.find(":")); if (strFront == "SelfPlayID")//数据类型 SelfPlayID:0 { int playID = std::stoi(getStringByPos(strBuff, pos)); playerSelf->setPlayID(playID); mapPlayer[playID] = playerSelf; if (playID > 0) { playerLeft = Player::create(ERoleSide_Left); this->addChild(playerLeft); playerLeft->setPlayID((playID + 2) % 3); mapPlayer[playerLeft->getPlayID()] = playerLeft; } if (playID > 1) { playerRight = Player::create(ERoleSide_Right); this->addChild(playerRight); playerRight->setPlayID((playID + 1) % 3); mapPlayer[playerRight->getPlayID()] = playerRight; } } else if (strFront == "AddPlay")//数据类型 AddPlay: { if (playerRight) { playerLeft = Player::create(ERoleSide_Left); this->addChild(playerLeft); playerLeft->setPlayID((playerSelf->getPlayID() + 2) % 3); mapPlayer[playerLeft->getPlayID()] = playerLeft; } else { playerRight = Player::create(ERoleSide_Right); this->addChild(playerRight); playerRight->setPlayID((playerSelf->getPlayID() + 1) % 3); mapPlayer[playerRight->getPlayID()] = playerRight; } } else if (strFront == "SelfCards")//告诉你的牌 数据类型 SelfCards:1,2,3 { playerSelf->setPlayPoints(stringTovector(getStringByPos(strBuff, pos))); } else if (strFront == "DealCards")//发牌 数据类型 DealCards: { createAllCards(); dealCards(); } else if (strFront == "ChooseCallLand")//叫地主 数据类型 ChooseCallLand: { showChooseCallButtons(); } else if (strFront == "ChooseRobLand")//抢地主 数据类型 ChooseRobLand: { showChooseRobButtons(); } else if (strFront == "ReStart")//重新开始 现在不考虑 { } else if (strFront == "LandLordID")//地主是谁 数据类型 LandLordID:1 { int landLordID = std::stoi(getStringByPos(strBuff, pos)); for (int i = 0; i < mapPlayer.size(); i++) { if (i == landLordID) { mapPlayer[i]->setRole(ERoleStatu_Landlord); } else { mapPlayer[i]->setRole(ERoleStatu_Farmer); } } } else if (strFront == "LandCards")//地主牌 数据类型 LandCards:1,2,3 { std::vector<int> vecLandCards = stringTovector(getStringByPos(strBuff, pos)); //显示地主 for (int i = 0; i < vecLandCards.size(); i++) { Card* cardFront = Card::create(vecLandCards[i]); cardFront->setPosition(vecAllCardBacks[51 + i]->getPosition()); this->addChild(cardFront); } //添加地主 if (playerSelf->getRole() == ERoleStatu_Landlord) { playerSelf->addLandCards(vecLandCards); for (int i = 0; i < vecLandCards.size(); i++) { vecAllCardBacks.back()->removeFromParent(); vecAllCardBacks.pop_back(); } } else { Player* curPlay = playerLeft->getRole() == ERoleStatu_Landlord ? playerLeft : playerRight; for (int i = 0; i < vecLandCards.size(); i++) { curPlay->addCard(vecAllCardBacks[51 + i]); } } } else if (strFront == "ChoosePutCards")// 数据类型 ChoosePutCards:11,12,13 { std::string strCards = getStringByPos(strBuff, pos); if (strCards == "") { playerLeft->removeShowCards(); playerRight->removeShowCards(); } else { playerSelf->setComparePoints(stringTovector(strCards)); } playerSelf->removeShowCards(); showChoosePutButtons(); } else if (strFront == "ShowCards")//数据类型 ShowCards:1:1,2,3 { int playID = std::stoi(getStringByPos(strBuff, pos));//第一个:到第二个:之间的内容 std::string strPlayCards = getStringByPos(strBuff, pos); if (strPlayCards == "")//strPlayID 不要 { } //strPlayID 要 mapPlayer[playID]->showOtherCards(stringTovector(strPlayCards));//strPlayID号玩家 -- playerSelf } else if (strFront == "Win")//数据类型 Win:0::1:1,2,3 { int playID_1 = std::stoi(getStringByPos(strBuff, pos)); std::string strPlayCards_1 = getStringByPos(strBuff, pos); mapPlayer[playID_1]->showOtherCards(stringTovector(strPlayCards_1)); int playID_2 = std::stoi(getStringByPos(strBuff, pos)); std::string strPlayCards_2 = getStringByPos(strBuff, pos); mapPlayer[playID_2]->showOtherCards(stringTovector(strPlayCards_2)); //判断地主 if (strPlayCards_1 == "") { //地主 mapPlayer[playID_1] } else if (strPlayCards_2 == "") { //地主 mapPlayer[playID_2] } else { //地主 self } startItem->setVisible(true); } else if (strFront == "ARE YOU OK") { //sendServer("OK:"); } else//这是BUG 得治 { CCLOG("Undefined Message"); } } } void GameScene::sendServer(std::string strBuff) { const char* buff = strBuff.c_str(); send(sockClient, buff, strlen(buff) + 1, 0); } std::string GameScene::getStringByPos(std::string strBuff, int &pos) { pos = strBuff.find(":", pos) + 1; return strBuff.substr(pos, strBuff.find(":", pos) - pos); } std::vector<int> GameScene::stringTovector(std::string strCards)//比如12,15,13 { std::vector<int> vecCards; int nLength = strCards.length(); int nStart = 0; int nEnd = 0; while (nStart < nLength) { nEnd = strCards.find(",", nStart); if (nEnd == -1) { nEnd = nLength; } std::string nCard = strCards.substr(nStart, nEnd - nStart); vecCards.push_back(std::stoi(nCard)); nStart = nEnd + 1; } return vecCards; } std::string GameScene::vectorTostring(std::vector<int> vecCards)//比如12,15,13 { char cardsBuff[100]; char buff[4]; for (int i = 0, vecSize = vecCards.size() - 1; i < vecSize; i++) { sprintf_s(buff, "%d,", vecCards[i]); strcat_s(cardsBuff, buff); } sprintf_s(buff, "%d", vecCards[vecCards.size() - 1]); strcat_s(cardsBuff, buff); return cardsBuff; } //创建牌 void GameScene::createAllCards() { for (int i = 0; i < CARDS_NUM; i++) { Sprite* cardBack = Sprite::create("image/54.png"); cardBack->setPosition(Vec2(visibleSize.width / 2, visibleSize.height - cardBack->getContentSize().height / 2)); cardBack->setScale(0.5f); this->addChild(cardBack, 100); vecAllCardBacks.push_back(cardBack); } } //发牌 void GameScene::dealCards() { this->schedule(schedule_selector(GameScene::dealCard), 0.1f, 52, 0);//间隔,重复次数,延时 } void GameScene::dealCard(float dt) { cardsNum--; if (cardsNum > 2) { Player* curPlayer = nullptr; Vec2 player_pos = Vec2::ZERO; switch ((cardsNum + playerSelf->getPlayID()) % 3) { case 0: curPlayer = playerRight; player_pos = Vec2(visibleSize.width - 250, visibleSize.height - 90); break; case 1: curPlayer = playerLeft; player_pos = Vec2(250, visibleSize.height - 90); break; case 2: curPlayer = playerSelf; player_pos = Vec2(visibleSize.width / 2, 90); break; default: break; } Sprite* cardBack = vecAllCardBacks[cardsNum]; cardBack->runAction(Sequence::createWithTwoActions( MoveTo::create(0.1f, player_pos), CallFunc::create([this, curPlayer, cardBack]() { curPlayer->addCard(cardBack); }))); } else if (cardsNum == 2) { Sprite* cardBack = vecAllCardBacks[cardsNum]; Vec2 player_pos = Vec2(visibleSize.width / 2 - cardBack->getContentSize().width, visibleSize.height - cardBack->getContentSize().height / 2); cardBack->runAction(MoveTo::create(0.1f, player_pos)); } else { Sprite* cardBack = vecAllCardBacks[cardsNum]; Vec2 player_pos = Vec2(visibleSize.width / 2 + cardBack->getContentSize().width, visibleSize.height - cardBack->getContentSize().height / 2); cardBack->runAction(MoveTo::create(0.1f, player_pos)); } } void GameScene::showChooseCallButtons() { callLandItem->setVisible(true); noCallItem->setVisible(true); } void GameScene::showChooseRobButtons() { robLandItem->setVisible(true); noRobItem->setVisible(true); } void GameScene::showChoosePutButtons() { putItem->setVisible(true); putItem->setEnabled(false); noPutItem->setVisible(true); } void GameScene::setPutEnable(bool bEnable) { putItem->setEnabled(bEnable); }
[ "314725332@qq.com" ]
314725332@qq.com
f80ad63a4fc94f46a4c89abdef5a54525c363b30
05d0cdf14776f0ba714996d86ef92e4fef50516a
/libs/directag/freicore/BaseRunTimeConfig.cpp
88aa3c244a0b8653aeca3aa6128901bcb7cad294
[ "MIT" ]
permissive
buotex/BICEPS
5a10396374da2e70e262c9304cf9710a147da484
10ed3938af8b05e372758ebe01dcb012a671a16a
refs/heads/master
2020-05-30T20:20:55.378536
2014-01-06T21:31:56
2014-01-06T21:31:56
1,382,740
2
2
null
null
null
null
UTF-8
C++
false
false
3,003
cpp
#include "stdafx.h" #include "BaseRunTimeConfig.h" namespace freicore { BaseRunTimeConfig::BaseRunTimeConfig() { // Initialize variables to their default values // For each variable name: "VariableName = VariableDefaultValue;" //BOOST_PP_SEQ_FOR_EACH( RTCONFIG_INIT_DEFAULT_VAR, ~, BASE_RUNTIME_CONFIG ) } void BaseRunTimeConfig::initializeFromBuffer( string& cfgStr, const string& delim ) { size_t boolIdx; while( ( boolIdx = cfgStr.find( "true" ) ) != string::npos ) cfgStr = cfgStr.replace( boolIdx, 4, "1" ); while( ( boolIdx = cfgStr.find( "false" ) ) != string::npos ) cfgStr = cfgStr.replace( boolIdx, 5, "0" ); string strVal; // Find the variable name in the buffer of key-value pairs and read its corresponding value //BOOST_PP_SEQ_FOR_EACH( RTCONFIG_PARSE_BUFFER, ~, BASE_RUNTIME_CONFIG ) finalize(); } RunTimeVariableMap BaseRunTimeConfig::getVariables( bool hideDefaultValues ) { // Update the variable map // For each variable name: "m_variables[ "VariableName" ] = VariableName;" //BOOST_PP_SEQ_FOR_EACH( RTCONFIG_FILL_MAP, m_variables, BASE_RUNTIME_CONFIG ) return m_variables; } void BaseRunTimeConfig::setVariables( RunTimeVariableMap& vars ) { for( RunTimeVariableMap::iterator itr = vars.begin(); itr != vars.end(); ++itr ) { string value = UnquoteString( itr->second ); if( value == "true" ) itr->second = "\"1\""; else if( value == "false" ) itr->second = "\"0\""; } // Update the variable map // For each variable name: "m_variables[ "VariableName" ] = VariableName;" //BOOST_PP_SEQ_FOR_EACH( RTCONFIG_READ_MAP, vars, BASE_RUNTIME_CONFIG ) finalize(); } void BaseRunTimeConfig::dump() { getVariables(); string::size_type longestName = 0; for( RunTimeVariableMap::iterator itr = m_variables.begin(); itr != m_variables.end(); ++itr ) if( itr->first.length() > longestName ) longestName = itr->first.length(); for( RunTimeVariableMap::iterator itr = m_variables.begin(); itr != m_variables.end(); ++itr ) { cout.width( (streamsize) longestName + 2 ); stringstream s; s << right << itr->first << ": "; cout << s.str() << boolalpha << "\"" << itr->second << "\"" << endl; } } void BaseRunTimeConfig::finalize() { } int BaseRunTimeConfig::initializeFromFile( const string& rtConfigFilename, const string& delimiters ) { // Abort if( rtConfigFilename.empty() ) { finalize(); return 1; } // Read settings from file; abort if file does not exist else { ifstream rtConfigFile( rtConfigFilename.c_str(), ios::binary ); if( rtConfigFile.is_open() ) { //cout << GetHostname() << " is reading its configuration file \"" << rtConfigFilename << "\"" << endl; int cfgSize = (int) GetFileSize( rtConfigFilename ); cfgStr.resize( cfgSize ); rtConfigFile.read( &cfgStr[0], cfgSize ); initializeFromBuffer( cfgStr, delimiters ); rtConfigFile.close(); } else { finalize(); return 1; } } return 0; } }
[ "Buote.Xu@gmail.com" ]
Buote.Xu@gmail.com
340d2becb06d2ab701bdae8489a4a472886678a2
d528785c2562680b6fd66c2bed874eb1be074e1b
/JAN16/1.cpp
0186d47a66542deb65cd169f2bd700747b522f7c
[]
no_license
shivendra-it/Programming
5cfbd11fed83854606e5ac5918243d01fff7884f
ad0ed9bbace9c3707b4e6e6327c92fcac7078128
refs/heads/master
2021-01-12T02:46:10.433195
2017-08-04T05:23:57
2017-08-04T05:23:57
78,095,199
0
1
null
null
null
null
UTF-8
C++
false
false
744
cpp
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while (t--) { int c,d,l; cin>>c>>d>>l; int p = 0; if(l%4 != 0) { p=0; }else{ if(l==0 && (c!=0 && d!=0)){ p=0; }else{ int extleg = l-4*d; int catsonground = extleg/4; int catsondog = c - catsonground; if(catsondog < 2*d && catsondog >= 0){ p=1; }else{ p=0; } } } if(p == 1){ cout<<"yes"<<endl; }else{ cout<<"no"<<endl; } } return 0; }
[ "shivendraps15@gmail.com" ]
shivendraps15@gmail.com
0d9438048ece56cff2b209ea616d7258285623fe
799d52ae84811d9d12432a8aac191774152bfa03
/darknetUtility/src/DarknetUtility.cpp
38ad78e399fd43be09abd7338f388c833724e38f
[]
no_license
DimasVeliz/OpenCvDnnPythonAndBasicCpp
8c67acae9ed9a6751f265eb891dc3e483169ad6a
c1a33a8658f2bb0d195395844d3c866e6e686dc2
refs/heads/main
2023-03-07T10:26:53.169411
2021-02-24T02:40:14
2021-02-24T02:40:14
308,035,320
3
0
null
null
null
null
UTF-8
C++
false
false
11,161
cpp
#include "DarknetUtility.hpp" DarknetUtility::DarknetUtility(std::string configPath, std::string weightsPath, std::string labelsPath) { this->configFilePath = configPath; this->weightsFilePath = weightsPath; this->labelsFilePath = labelsPath; loadNetWork(); loadClasses(); generateRandomColors(); } DarknetUtility::~DarknetUtility() { } /*helper functions*/ void DarknetUtility::loadNetWork() { auto net = cv::dnn::readNetFromDarknet(this->configFilePath, this->weightsFilePath); this->net = net; this->isConfigured = true; } void DarknetUtility::loadClasses() { std::string fileGiven = this->labelsFilePath; std::vector<std::string> classes; std::ifstream file(fileGiven); std::string str; while (std::getline(file, str)) { classes.push_back(str); } this->classes = classes; } void DarknetUtility::generateRandomColors() { int amount = this->classes.size(); std::vector<cv::Scalar> colors; for (int i = 0; i < amount; i++) { int r, g, b; r = rand() % 255; g = rand() % 255; b = rand() % 255; cv::Scalar tmp(r, g, b); colors.push_back(tmp); } this->colors = colors; } /*Internal Functionality around OpenCv*/ std::vector<std::string> DarknetUtility::getOutputLayersName() { std::vector<std::string> outPutLayersN; auto layerNames = net.getLayerNames(); auto v = net.getUnconnectedOutLayers(); for (auto it = v.begin(); it != v.end(); ++it) { outPutLayersN.push_back(layerNames[it[0] - 1]); } return outPutLayersN; } void DarknetUtility::drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat &frame) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 255, 0)); std::string label = format("%.2f", conf); if (!classes.empty()) { CV_Assert(classId < (int)classes.size()); label = classes[classId] + ": " + label; } int baseLine; Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); top = max(top, labelSize.height); rectangle(frame, Point(left, top - labelSize.height), Point(left + labelSize.width, top + baseLine), Scalar::all(255), FILLED); putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.5, Scalar()); } void DarknetUtility::doPostProcessing(Mat &frame, const std::vector<Mat> &outs) { float confThreshold = 0.7; float nmsThreshold = 0.8; static std::vector<int> outLayers = net.getUnconnectedOutLayers(); static std::string outLayerType = net.getLayer(outLayers[0])->type; std::vector<int> classIds; std::vector<float> confidences; std::vector<Rect> boxes; if (outLayerType == "DetectionOutput") { // Network produces output blob with a shape 1x1xNx7 where N is a number of // detections and an every detection is a vector of values // [batchId, classId, confidence, left, top, right, bottom] CV_Assert(outs.size() > 0); for (size_t k = 0; k < outs.size(); k++) { float *data = (float *)outs[k].data; for (size_t i = 0; i < outs[k].total(); i += 7) //loop sets "i" to each batchId Index { float confidence = data[i + 2]; if (confidence > confThreshold) { int left = (int)data[i + 3]; int top = (int)data[i + 4]; int right = (int)data[i + 5]; int bottom = (int)data[i + 6]; int width = right - left + 1; int height = bottom - top + 1; if (width <= 2 || height <= 2) { left = (int)(data[i + 3] * frame.cols); top = (int)(data[i + 4] * frame.rows); right = (int)(data[i + 5] * frame.cols); bottom = (int)(data[i + 6] * frame.rows); width = right - left + 1; height = bottom - top + 1; } classIds.push_back((int)(data[i + 1]) - 1); // Skip 0th background class id. boxes.push_back(Rect(left, top, width, height)); confidences.push_back(confidence); } } } } else if (outLayerType == "Region") { for (size_t i = 0; i < outs.size(); ++i) { // Network produces output blob with a shape NxC where N is a number of // detected objects and C is a number of classes + 4 where the first 4 // numbers are [center_x, center_y, width, height] float *data = (float *)outs[i].data; for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols) { Mat scores = outs[i].row(j).colRange(5, outs[i].cols); Point classIdPoint; double confidence; minMaxLoc(scores, 0, &confidence, 0, &classIdPoint); if (confidence > confThreshold) { int centerX = (int)(data[0] * frame.cols); int centerY = (int)(data[1] * frame.rows); int width = (int)(data[2] * frame.cols); int height = (int)(data[3] * frame.rows); int left = centerX - width / 2; int top = centerY - height / 2; classIds.push_back(classIdPoint.x); confidences.push_back((float)confidence); boxes.push_back(Rect(left, top, width, height)); } } } } else CV_Error(Error::StsNotImplemented, "Unknown output layer type: " + outLayerType); // NMS is used inside Region layer only on DNN_BACKEND_OPENCV for another backends we need NMS in sample // or NMS is required if number of outputs > 1 if (outLayers.size() > 1 || (outLayerType == "Region")) { std::map<int, std::vector<size_t>> class2indices; for (size_t i = 0; i < classIds.size(); i++) { if (confidences[i] >= confThreshold) { class2indices[classIds[i]].push_back(i); } } std::vector<Rect> nmsBoxes; std::vector<float> nmsConfidences; std::vector<int> nmsClassIds; for (std::map<int, std::vector<size_t>>::iterator it = class2indices.begin(); it != class2indices.end(); ++it) { std::vector<Rect> localBoxes; std::vector<float> localConfidences; std::vector<size_t> classIndices = it->second; for (size_t i = 0; i < classIndices.size(); i++) { localBoxes.push_back(boxes[classIndices[i]]); localConfidences.push_back(confidences[classIndices[i]]); } std::vector<int> nmsIndices; cv::dnn::NMSBoxes(localBoxes, localConfidences, confThreshold, nmsThreshold, nmsIndices); for (size_t i = 0; i < nmsIndices.size(); i++) { size_t idx = nmsIndices[i]; nmsBoxes.push_back(localBoxes[idx]); nmsConfidences.push_back(localConfidences[idx]); nmsClassIds.push_back(it->first); } } boxes = nmsBoxes; classIds = nmsClassIds; confidences = nmsConfidences; } for (size_t idx = 0; idx < boxes.size(); ++idx) { Rect box = boxes[idx]; drawPred(classIds[idx], confidences[idx], box.x, box.y,box.x + box.width, box.y + box.height, frame); } } cv::Mat DarknetUtility::doInternalProcessing(cv::Mat image) { if (image.empty()) { std::cout << "The image didnt load properly" << std::endl; return image; } else { //working with the dnn functionalities and adding anotations to the image double scale = 0.00392; bool cropDecision = false; bool swapRBDecision = true; //works auto blob = cv::dnn::blobFromImage(image, scale, Size(416, 416), Scalar(0, 0, 0), swapRBDecision, cropDecision); //works net.setInput(blob); //works auto outputLayersName = getOutputLayersName(); //works //printVectorAux(outputLayersName); std::vector<cv::Mat> outs; net.forward(outs, outputLayersName); //testing the result size //std::cout<<outs.size()<<std::endl; std::vector<int> class_id; std::vector<double> confidences; std::vector<cv::Rect2d> boxes; doPostProcessing(image, outs); /*The image with the annotations is returned*/ return image; } } /*External Interface*/ int DarknetUtility::doImageProcessing(std::string imagePath) { if (!this->isConfigured) { return -1; } cv::Mat image = cv::imread(imagePath); cv::Mat annotatedPicture = doInternalProcessing(image); if (annotatedPicture.empty()) { std::cout << "The image didnt load properly" << std::endl; return -1; } cv::imshow("Predictions", annotatedPicture); cv::waitKey(0); cv::destroyAllWindows(); return 0; } int DarknetUtility::doVideoProcessing(cv::VideoCapture cap, bool doDetection) { // Check whether the camera opened properly or not if (!cap.isOpened()) { std::cout << "Error opening video stream or file" << std::endl; return -1; } while (true) { Mat frame; // Capturing frames continuously cap.read(frame); // stop if no frames are captured if (frame.empty()) { std::cout << "Empty Frame or video ended" << std::endl; return -1; } if (!doDetection) { // Displaying the frame imshow("Frame with no processing", frame); } else { cv::Mat annotatedPicture = doInternalProcessing(frame); if (annotatedPicture.empty()) { std::cout << "The processing failed" << std::endl; return -1; } cv::imshow("Predictions", annotatedPicture); } //stop if a key is pressed if (cv::waitKey(1) >= 0) { std::cout <<"stream manually stopped"<< std::endl; break; } } // releasing the video capture object cap.release(); // Closing up cv::destroyAllWindows(); return 0; } int DarknetUtility::capturingFromCamera(int camNumber, bool doDetection) { cv::VideoCapture cap(camNumber); if (!cap.isOpened()) { return -1; } return doVideoProcessing(cap, doDetection); } int DarknetUtility::capturingFromCamera(std::string streamerOrVideoFile, bool doDetection) { cv::VideoCapture cap(streamerOrVideoFile); if (!cap.isOpened()) { return -1; } return doVideoProcessing(cap, doDetection); } std::string DarknetUtility::sayHi() { return "Hola"; }
[ "trevor90094@yandex.com" ]
trevor90094@yandex.com
ca477b0f4c2d4b959ca4efd90c0638fa5de7841d
19194c2f2c07ab3537f994acfbf6b34ea9b55ae7
/android-28/android/media/MediaCodecInfo_AudioCapabilities.hpp
7762b8ffb89157ed9c13efdeda1d5bfdd0f477a9
[ "GPL-3.0-only" ]
permissive
YJBeetle/QtAndroidAPI
e372609e9db0f96602da31b8417c9f5972315cae
ace3f0ea2678967393b5eb8e4edba7fa2ca6a50c
refs/heads/Qt6
2023-08-05T03:14:11.842336
2023-07-24T08:35:31
2023-07-24T08:35:31
249,539,770
19
4
Apache-2.0
2022-03-14T12:15:32
2020-03-23T20:42:54
C++
UTF-8
C++
false
false
1,215
hpp
#pragma once #include "../../JIntArray.hpp" #include "../../JArray.hpp" #include "../util/Range.def.hpp" #include "./MediaCodecInfo_AudioCapabilities.def.hpp" namespace android::media { // Fields // Constructors // Methods inline android::util::Range MediaCodecInfo_AudioCapabilities::getBitrateRange() const { return callObjectMethod( "getBitrateRange", "()Landroid/util/Range;" ); } inline jint MediaCodecInfo_AudioCapabilities::getMaxInputChannelCount() const { return callMethod<jint>( "getMaxInputChannelCount", "()I" ); } inline JArray MediaCodecInfo_AudioCapabilities::getSupportedSampleRateRanges() const { return callObjectMethod( "getSupportedSampleRateRanges", "()[Landroid/util/Range;" ); } inline JIntArray MediaCodecInfo_AudioCapabilities::getSupportedSampleRates() const { return callObjectMethod( "getSupportedSampleRates", "()[I" ); } inline jboolean MediaCodecInfo_AudioCapabilities::isSampleRateSupported(jint arg0) const { return callMethod<jboolean>( "isSampleRateSupported", "(I)Z", arg0 ); } } // namespace android::media // Base class headers #ifdef QT_ANDROID_API_AUTOUSE using namespace android::media; #endif
[ "yjbeetle@gmail.com" ]
yjbeetle@gmail.com
c888a22c1cacd1022eb524058224fd2f97a2abde
505d530910f303be93919824d9e558ff31046522
/main.cc
7d96660e670a18f5c8774d7639f269c342923748
[]
no_license
nelhage/rules_fuzzer
a3316bfe5e086b38a4339814a90e045227d4bde7
35f458bde34ba10a6ee3177c6bab08ab09e7e20a
refs/heads/master
2021-08-10T19:25:35.628041
2017-11-12T22:44:44
2017-11-12T22:44:44
110,316,008
5
0
null
null
null
null
UTF-8
C++
false
false
130
cc
#include <iostream> using namespace std; int main(int argc, char **argv) { cout << "Hello, World!" << endl; return 0; }
[ "nelhage@nelhage.com" ]
nelhage@nelhage.com
0a828a8ffe02e24d45f9be4c93778c04fb97c7f5
977c82ec23f2f8f2b0da5c57984826e16a22787d
/src/IceRay/render/0scanner/_pure.cpp
5528f995a528a7e5d7d383deb317c95f374c074c
[ "MIT-0" ]
permissive
dmilos/IceRay
47ce08e2920171bc20dbcd6edcf9a6393461c33e
84fe8d90110c5190c7f58c4b2ec3cdae8c7d86ae
refs/heads/master
2023-04-27T10:14:04.743094
2023-04-20T14:33:45
2023-04-20T15:07:18
247,471,987
2
1
null
null
null
null
UTF-8
C++
false
false
763
cpp
#include "_pure.hpp" using namespace GS_DDMRM::S_IceRay::S_render::S_scanner; GC__pure::T2__base GC__pure::M2s_pixel; GC__pure::GC__pure() :GC__pure( nullptr ) { Fv_pixel( &M2s_pixel ); } GC__pure::GC__pure( T_pixel * P_pixel ) :M2_progress( T_scalar( 0 ) ) ,M2_work( false ) ,M2_pixel( P_pixel ) { Fv_pixel( &M2s_pixel ); } GC__pure::~GC__pure() { } GC__pure::T_report GC__pure::Fv_pixel( T_pixel * P_pixel ) { if( true == F_work() ) { return T_report( false ); } M2_pixel = P_pixel; return T_report( true ); } void GC__pure::Fv_render( T_picture & P_image ) { F1_work() = true; M2_pixel->F_resolution( P_image.F_size() ); F1v_render( P_image ); F1_work() = false; }
[ "dmilos@gmail.com" ]
dmilos@gmail.com
4ba1c4d4ca9d24cd02cf9b89f1c0261687408a6a
f03d1763fd7c65a6203e8e4c38f704c79a9b62b6
/OtE source/menus/ControlsMenu.cpp
aede082e22fdc2fbc3eeebc2c0598d6cff6bbe62
[ "MIT" ]
permissive
errantti/ontheedge
05be0a7ec00b150386233eb44c5df7b6ea2ab6cf
1dd5c630bdd6353183002e6f182847503efffc04
refs/heads/master
2023-02-22T13:32:37.456640
2021-01-23T19:23:02
2021-01-23T19:23:02
332,289,657
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,822
cpp
// On the Edge // // Copyright © 2004-2021 Jukka Tykkyläinen // // 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 "ControlsMenu.h" #include "..\\OnTheEdge.h" #include "PlayerControlsMenu.h" #include "GeneralControlsMenu.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CControlsMenu::CControlsMenu(IMenuManager *mgr) : CFlowMenu(MENU_ID_CONTROLS , mgr, MENU_ID_OPTIONS) { } CControlsMenu::~CControlsMenu() { } void CControlsMenu::CustomInit() { } bool CControlsMenu::OnEvent(SEvent event) { if(CFlowMenu::OnEvent(event)) return true; IGUIElement *e = (IGUIElement*)event.guiEvent.element; switch(event.type) { case EW_GUI_EVENT: switch(event.guiEvent.type) { case EWGUI_ELEMENT_PRESSED: switch(e->GetID()) { case CTR_CLOSE: CloseFlowMenu(); return true; case CTR_PLAYER1: CPlayerControlsMenu::SetPlayer(0); m_manager->OpenMenu(MENU_ID_PLAYER_CONTROLS, false); return true; case CTR_PLAYER2: CPlayerControlsMenu::SetPlayer(1); m_manager->OpenMenu(MENU_ID_PLAYER_CONTROLS, false); return true; case CTR_MOUSE: m_manager->OpenMenu(MENU_ID_MOUSE_CONFIGURATION, false); return true; case CTR_GENERAL_KEYBOARD: CGeneralControlsMenu::SetUseKeyboard(true); m_manager->OpenMenu(MENU_ID_GENERAL_CONTROLS, false); return true; case CTR_GENERAL_PAD: CGeneralControlsMenu::SetUseKeyboard(false); m_manager->OpenMenu(MENU_ID_GENERAL_CONTROLS, false); return true; case CTR_GADGET_HOTKEYS: m_manager->OpenMenu(MEDU_ID_GADGET_HOTKEYS, false); return true; } break; } } return false; } void CControlsMenu::OnClose() { }
[ "jukka.tykkylainen@gmail.com" ]
jukka.tykkylainen@gmail.com
b736baa9550579e5a90b758fe68619c1f5010ec3
0af5cf1f0331f389c42368b679db181ff4e007f1
/MEX-files/src/MEXs/mexBuildWarpedImages.cpp
0c6a98e8acabf461c35af69d2ed4c82222335a2f
[]
no_license
Heliot7/non-local-scene-flow
b0ed1b9cbd1e505b5a7f5fd8f5bd127e18e97497
97e56d0858f8d530e64f350416f919d303054ed1
refs/heads/master
2022-12-25T14:18:29.661105
2020-09-27T23:46:11
2020-09-27T23:46:11
299,140,175
0
0
null
null
null
null
UTF-8
C++
false
false
2,402
cpp
#include <iostream> #include <stdio.h> #include <math.h> #include <cstring> #include "mex.h" #include "libSceneFlow/nonLocalSceneFlow.hpp" using namespace std; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Macros for the input arguments */ #define t0Images_IN prhs[0] #define t1Images_IN prhs[1] #define t0ProjImgs_IN prhs[2] #define t1ProjImgs_IN prhs[3] #define t0occlusionMaps_IN prhs[4] #define t1occlusionMaps_IN prhs[5] /* Macros for the output arguments */ #define t0WarpedImgs_OUT plhs[0] #define t1WarpedImgs_OUT plhs[1] /* Check correctness of input/output arguments */ // Number of input/output arguments. if(nrhs < 6 || nrhs > 6) mexErrMsgTxt("Wrong number of input arguments."); else if(nlhs > 2) mexErrMsgTxt("Too many output arguments."); /* Get input data */ int imgRows = mxGetM(mxGetCell(t0Images_IN, 0)); int imgCols = mxGetN(mxGetCell(t0Images_IN, 0)); int numCameras = mxGetN(t0Images_IN); // Greyscale scheme int imgChannels = 1; // RGB scheme if(mxGetNumberOfDimensions(mxGetCell(t0Images_IN, 0)) > 2) { imgChannels = 3; imgCols /= 3; } double* t0ProjImgs = mxGetPr(t0ProjImgs_IN); double* t1ProjImgs = mxGetPr(t1ProjImgs_IN); bool* t0occlusionMaps = (bool*)mxGetData(t0occlusionMaps_IN); bool* t1occlusionMaps = (bool*)mxGetData(t1occlusionMaps_IN); unsigned char* t0Images[numCameras]; unsigned char* t1Images[numCameras]; for(int CAMi = 0; CAMi < numCameras; ++CAMi) { t0Images[CAMi] = (unsigned char*)mxGetData(mxGetCell(t0Images_IN, CAMi)); t1Images[CAMi] = (unsigned char*)mxGetData(mxGetCell(t1Images_IN, CAMi)); } const mwSize dims[4] = {numCameras, imgRows, imgCols, imgChannels}; t0WarpedImgs_OUT = mxCreateNumericArray(4, dims, mxDOUBLE_CLASS, mxREAL); double* t0WarpedImgs = mxGetPr(t0WarpedImgs_OUT); t1WarpedImgs_OUT = mxCreateNumericArray(4, dims, mxDOUBLE_CLASS, mxREAL); double* t1WarpedImgs = mxGetPr(t1WarpedImgs_OUT); /* Call method: buildWarpedImage */ buildWarpedImage(t0WarpedImgs, numCameras, imgRows, imgCols, imgChannels, t0Images, t0ProjImgs, t0occlusionMaps); buildWarpedImage(t1WarpedImgs, numCameras, imgRows, imgCols, imgChannels, t1Images, t1ProjImgs, t1occlusionMaps); return; }
[ "panareda@gmail.com" ]
panareda@gmail.com
4c78192d4d09de2eefaceffffc00580f20987ee5
d9d69f551991d64caeae3f5ab01c8b51dc0c4d5e
/tcp_server/tcp_client.cc
69ce143d01fcc6eda999baa5d5ae1b97a26d4b63
[]
no_license
Missingrakan/OS
b292e33999f8ae2d8bd14afa0b298c789f1264a0
57cc1c023fc0fa4176f93cd2d33b2409d300eed1
refs/heads/master
2023-06-02T19:00:42.651316
2021-05-31T13:39:01
2021-05-31T13:39:01
282,350,415
0
0
null
null
null
null
UTF-8
C++
false
false
371
cc
#include "tcp_client.hpp" void Usage(std::string proc) { std::cout << proc << " server_ip server_port" << std::endl; } int main(int argc,char *argv[]) { if(argc != 3){ Usage(argv[0]); exit(1); } std::string ip = argv[1]; int port = atoi(argv[2]); Client *cp = new Client(ip,port); cp->InitClient(); cp->Connect(); cp->Start(); return 0; }
[ "3047451493@qq.com" ]
3047451493@qq.com
91564708872c4748b1c9ec55ecdde523f90c9c09
6e3af4ff93f59ccd79725ee90d2f5ac74e6351d1
/cpp/addition_features/scopedPrr.cpp
2cc7ebc369a6da7faf7561089c1f7912337c22c7
[]
no_license
mikronavt/sometestcode
a834fde82f5d7498c640368801d012b159fce6c8
a80c9545edfb0366fb297017638e0277af774d0e
refs/heads/master
2020-12-24T09:53:23.519335
2016-11-09T07:51:24
2016-11-09T07:51:24
73,262,502
0
0
null
null
null
null
UTF-8
C++
false
false
831
cpp
struct Expression; struct Number; struct BinaryOperation; struct FunctionCall; struct Variable; struct ScopedPtr { // реализуйте следующие методы: // explicit ScopedPtr(Expression *ptr = 0){ this->ptr_ = ptr; } ~ScopedPtr(){ delete this->ptr_; } Expression* get() const{ return this->ptr_; } Expression* release(){ Expression *ptr = this->ptr_; ptr_=0; return ptr; } void reset(Expression *ptr = 0){ delete ptr_; this->ptr_ = ptr; } Expression& operator*() const{ return *ptr_; } Expression* operator->() const{ return this->ptr_; } private: // запрещаем копирование ScopedPtr ScopedPtr(const ScopedPtr&); ScopedPtr& operator=(const ScopedPtr&); Expression *ptr_; }; int main(){ return 0; }
[ "chgb-tol@ya.ru" ]
chgb-tol@ya.ru
b387dd6229260f3199a369be1bf8d8c8924b97f4
9c5bb4e9a4863cb5bd22db4012d6049678844668
/include/guilib/display_mode.h
51040a5686371402ff904f3b67e509df29482fc3
[]
no_license
MCMrARM/guilib
6ea18f324cf2008c5e90536da05835dea2d0e772
2b715368044641249cdf0ab90fa696201b3f300f
refs/heads/master
2021-03-27T10:12:50.090580
2017-03-28T16:28:55
2017-03-28T16:28:55
79,670,578
0
0
null
null
null
null
UTF-8
C++
false
false
109
h
#pragma once namespace guilib { enum class GuiDisplayMode { BLOCK, INLINE, INLINE_BLOCK }; }
[ "mcmrarm@gmail.com" ]
mcmrarm@gmail.com
8e517984c78b60a048bafa1eb5ed28791e62d61a
7033fb96dba84530911e99a51f6bd8c7e55a2956
/Lesson/Advanced Experiment/PantherTank_PS2/Servo.h
79d17461551915a60ade63758e93012947234c61
[]
no_license
1ya1ya/keywish-panther-tank
3350924a294d8a24678ed5c1a625d7f30bd6b1fa
796708d92f83960ec5d3cb3fad8c8a550fcf9667
refs/heads/master
2022-04-13T02:25:40.538778
2020-02-22T05:15:10
2020-02-22T05:15:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,472
h
/* Servo.h - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2 Copyright (c) 2009 Michael Margolis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method. The servos are pulsed in the background using the value most recently written using the write() method Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached. Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four. The sequence used to sieze timers is defined in timers.h The methods are: Servo - Class for manipulating servo motors connected to Arduino pins. attach(pin ) - Attaches a servo motor to an i/o pin. attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds default min is 544, max is 2400 write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds) writeMicroseconds() - Sets the servo pulse width in microseconds read() - Gets the last written servo pulse width as an angle between 0 and 180. readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release) attached() - Returns true if there is a servo attached. detach() - Stops an attached servos from pulsing its i/o pin. */ #ifndef Servo_h #define Servo_h #include <inttypes.h> /* * Defines for 16 bit timers used with Servo library * * If _useTimerX is defined then TimerX is a 16 bit timer on the curent board * timer16_Sequence_t enumerates the sequence that the timers should be allocated * _Nbr_16timers indicates how many 16 bit timers are available. * */ // Say which 16 bit timers can be used and in what order #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define _useTimer5 #define _useTimer1 #define _useTimer3 #define _useTimer4 typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers } timer16_Sequence_t; #elif defined(__AVR_ATmega32U4__) #define _useTimer3 #define _useTimer1 typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t; #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) #define _useTimer3 #define _useTimer1 typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t; #elif defined(__AVR_ATmega128__) ||defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__) #define _useTimer3 #define _useTimer1 typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t; #else // everything else #define _useTimer1 typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t; #endif #define Servo_VERSION 2 // software version of this library #define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo #define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo #define DEFAULT_PULSE_WIDTH 1500 // default pulse width when servo is attached #define REFRESH_INTERVAL 20000 // minumim time to refresh servos in microseconds #define SERVOS_PER_TIMER 12 // the maximum number of servos controlled by one timer #define MAX_SERVOS (_Nbr_16timers * SERVOS_PER_TIMER) #define INVALID_SERVO 255 // flag indicating an invalid servo index typedef struct { uint8_t nbr :6 ; // a pin number from 0 to 63 uint8_t isActive :1 ; // true if this channel is enabled, pin not pulsed if false } ServoPin_t; typedef struct { ServoPin_t Pin; unsigned int ticks; } servo_t; class Servo { public: Servo(); uint8_t attach(int pin); // attach the given pin to the next free channel, sets pinMode, returns channel number or 0 if failure uint8_t attach(int pin, int min, int max); // as above but also sets min and max values for writes. void detach(); void write(int value); // if value is < 200 its treated as an angle, otherwise as pulse width in microseconds void writeMicroseconds(int value); // Write pulse width in microseconds int read(); // returns current pulse width as an angle between 0 and 180 degrees int readMicroseconds(); // returns current pulse width in microseconds for this servo (was read_us() in first release) bool attached(); // return true if this servo is attached, otherwise false private: uint8_t servoIndex; // index into the channel data for this servo int8_t min; // minimum is this value times 4 added to MIN_PULSE_WIDTH int8_t max; // maximum is this value times 4 added to MAX_PULSE_WIDTH }; #endif
[ "ken@keywish-robot.com" ]
ken@keywish-robot.com
963e8de13e506abe053e12dfa85a59bb89681e8e
56946b97e766032e1964b49ad2a04a0a44f4e0f2
/Tree/1/11_Path_Sum_II/method1/solution.cc
65d236f9c2d5e736f47200d3f4a1458bdbd1b899
[ "MIT" ]
permissive
sheriby/DandAInLeetCode
d46473bfac3d4ea844104c014aa1431b9f2f610b
dd7f5029aa0c297ea82bb20f882b524789f35c96
refs/heads/master
2021-08-08T17:03:00.487364
2021-01-10T07:14:33
2021-01-10T07:14:33
238,877,494
1
0
null
null
null
null
UTF-8
C++
false
false
1,025
cc
#include <iostream> #include <vector> #include "treenode.h" using std::vector; class Solution { public: // 还是和之前一样,非常显而易见的递归题目 vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> results; vector<int> result; pathSum(root, sum, result, results); return results; } private: void pathSum(TreeNode* root, int sum, vector<int>& result, vector<vector<int>>& results) { if (!root) return; if (!root->left && !root->right && root->val == sum) { result.push_back(root->val); results.push_back(result); result.pop_back(); return; } result.push_back(root->val); int val = sum - root->val; if (root->left) { pathSum(root->left, val, result, results); } if (root->right) { pathSum(root->right, val, result, results); } result.pop_back(); } };
[ "hony_sher@foxmail.com" ]
hony_sher@foxmail.com
fd870c71e52fe35d1c5d09a80552a26fa78a4f9b
8cfdf40fa6f8d0b513ad2a766fdc0ac8985e6a2c
/nfc/halimpl/bcm2079x/adaptation/config.cpp
c8510b603851d3f2d4af2252fc5821a7fb54481d
[]
no_license
randomblame/android_device_motorola_clark
bdf9b652bf8fa13bfec0d36b6e396cc3823c534d
419928961a1e274df979a4dc7dfcb4b81aa4c791
refs/heads/lineage-16.0
2020-03-30T08:32:22.829311
2019-08-01T01:58:29
2019-08-01T01:58:29
151,022,922
9
9
null
2019-10-23T13:18:27
2018-10-01T01:23:40
C++
UTF-8
C++
false
false
19,468
cpp
/****************************************************************************** * * Copyright (C) 2011-2012 Broadcom Corporation * * 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. * ******************************************************************************/ #define LOG_TAG "NfcNciHal" #include "config.h" #include <stdio.h> #include <sys/stat.h> #include <list> #include <string> #include <vector> #include "_OverrideLog.h" const char* transport_config_paths[] = {"/odm/etc/", "/vendor/etc/", "/etc/"}; const int transport_config_path_size = (sizeof(transport_config_paths) / sizeof(transport_config_paths[0])); #define config_name "libnfc-nci.conf" #define extra_config_base "libnfc-nci-" #define extra_config_ext ".conf" #define IsStringValue 0x80000000 using namespace ::std; class CNfcParam : public string { public: CNfcParam(); CNfcParam(const char* name, const string& value); CNfcParam(const char* name, unsigned long value); virtual ~CNfcParam(); unsigned long numValue() const { return m_numValue; } const char* str_value() const { return m_str_value.c_str(); } size_t str_len() const { return m_str_value.length(); } private: string m_str_value; unsigned long m_numValue; }; class CNfcConfig : public vector<const CNfcParam*> { public: virtual ~CNfcConfig(); static CNfcConfig& GetInstance(); friend void readOptionalConfig(const char* optional); bool getValue(const char* name, char* pValue, size_t& len) const; bool getValue(const char* name, unsigned long& rValue) const; bool getValue(const char* name, unsigned short& rValue) const; const CNfcParam* find(const char* p_name) const; void clean(); private: CNfcConfig(); bool readConfig(const char* name, bool bResetContent); void moveFromList(); void moveToList(); void add(const CNfcParam* pParam); list<const CNfcParam*> m_list; bool mValidFile; unsigned long state; inline bool Is(unsigned long f) { return (state & f) == f; } inline void Set(unsigned long f) { state |= f; } inline void Reset(unsigned long f) { state &= ~f; } }; /******************************************************************************* ** ** Function: isPrintable() ** ** Description: detremine if a char is printable ** ** Returns: none ** *******************************************************************************/ inline bool isPrintable(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '/' || c == '_' || c == '-' || c == '.'; } /******************************************************************************* ** ** Function: isDigit() ** ** Description: detremine if a char is numeral digit ** ** Returns: none ** *******************************************************************************/ inline bool isDigit(char c, int base) { if ('0' <= c && c <= '9') return true; if (base == 16) { if (('A' <= c && c <= 'F') || ('a' <= c && c <= 'f')) return true; } return false; } /******************************************************************************* ** ** Function: getDigitValue() ** ** Description: return numercal value of a char ** ** Returns: none ** *******************************************************************************/ inline int getDigitValue(char c, int base) { if ('0' <= c && c <= '9') return c - '0'; if (base == 16) { if ('A' <= c && c <= 'F') return c - 'A' + 10; else if ('a' <= c && c <= 'f') return c - 'a' + 10; } return 0; } /******************************************************************************* ** ** Function: findConfigFilePathFromTransportConfigPaths() ** ** Description: find a config file path with a given config name from transport ** config paths ** ** Returns: none ** *******************************************************************************/ void findConfigFilePathFromTransportConfigPaths(const string& configName, string& filePath) { for (int i = 0; i < transport_config_path_size - 1; i++) { filePath.assign(transport_config_paths[i]); filePath += configName; struct stat file_stat; if (stat(filePath.c_str(), &file_stat) == 0 && S_ISREG(file_stat.st_mode)) { return; } } filePath.assign(transport_config_paths[transport_config_path_size - 1]); filePath += configName; } /******************************************************************************* ** ** Function: CNfcConfig::readConfig() ** ** Description: read Config settings and parse them into a linked list ** move the element from linked list to a array at the end ** ** Returns: none ** *******************************************************************************/ bool CNfcConfig::readConfig(const char* name, bool bResetContent) { enum { BEGIN_LINE = 1, TOKEN, STR_VALUE, NUM_VALUE, BEGIN_HEX, BEGIN_QUOTE, END_LINE }; FILE* fd = NULL; string token; string strValue; unsigned long numValue = 0; CNfcParam* pParam = NULL; int i = 0; int base = 0; char c = 0; state = BEGIN_LINE; /* open config file, read it into a buffer */ if ((fd = fopen(name, "rb")) == NULL) { ALOGD("%s Cannot open config file %s\n", __func__, name); if (bResetContent) { ALOGD("%s Using default value for all settings\n", __func__); mValidFile = false; } return false; } ALOGD("%s Opened %s config %s\n", __func__, (bResetContent ? "base" : "optional"), name); mValidFile = true; if (size() > 0) { if (bResetContent) clean(); else moveToList(); } while (!feof(fd) && fread(&c, 1, 1, fd) == 1) { switch (state & 0xff) { case BEGIN_LINE: if (c == '#') state = END_LINE; else if (isPrintable(c)) { i = 0; token.erase(); strValue.erase(); state = TOKEN; token.push_back(c); } break; case TOKEN: if (c == '=') { token.push_back('\0'); state = BEGIN_QUOTE; } else if (isPrintable(c)) token.push_back(c); else state = END_LINE; break; case BEGIN_QUOTE: if (c == '"') { state = STR_VALUE; base = 0; } else if (c == '0') state = BEGIN_HEX; else if (isDigit(c, 10)) { state = NUM_VALUE; base = 10; numValue = getDigitValue(c, base); i = 0; } else if (c == '{') { state = NUM_VALUE; base = 16; i = 0; Set(IsStringValue); } else state = END_LINE; break; case BEGIN_HEX: if (c == 'x' || c == 'X') { state = NUM_VALUE; base = 16; numValue = 0; i = 0; break; } else if (isDigit(c, 10)) { state = NUM_VALUE; base = 10; numValue = getDigitValue(c, base); break; } else if (c != '\n' && c != '\r') { state = END_LINE; break; } // fal through to numValue to handle numValue case NUM_VALUE: if (isDigit(c, base)) { numValue *= base; numValue += getDigitValue(c, base); ++i; } else if (base == 16 && (c == ':' || c == '-' || c == ' ' || c == '}')) { if (i > 0) { int n = (i + 1) / 2; while (n-- > 0) { unsigned char c = (numValue >> (n * 8)) & 0xFF; strValue.push_back(c); } } Set(IsStringValue); numValue = 0; i = 0; } else { if (c == '\n' || c == '\r') state = BEGIN_LINE; else state = END_LINE; if (Is(IsStringValue) && base == 16 && i > 0) { int n = (i + 1) / 2; while (n-- > 0) strValue.push_back(((numValue >> (n * 8)) & 0xFF)); } if (strValue.length() > 0) pParam = new CNfcParam(token.c_str(), strValue); else pParam = new CNfcParam(token.c_str(), numValue); add(pParam); strValue.erase(); numValue = 0; } break; case STR_VALUE: if (c == '"') { strValue.push_back('\0'); state = END_LINE; pParam = new CNfcParam(token.c_str(), strValue); add(pParam); } else if (isPrintable(c)) strValue.push_back(c); break; case END_LINE: if (c == '\n' || c == '\r') state = BEGIN_LINE; break; default: break; } } fclose(fd); moveFromList(); return size() > 0; } /******************************************************************************* ** ** Function: CNfcConfig::CNfcConfig() ** ** Description: class constructor ** ** Returns: none ** *******************************************************************************/ CNfcConfig::CNfcConfig() : mValidFile(true) {} /******************************************************************************* ** ** Function: CNfcConfig::~CNfcConfig() ** ** Description: class destructor ** ** Returns: none ** *******************************************************************************/ CNfcConfig::~CNfcConfig() {} /******************************************************************************* ** ** Function: CNfcConfig::GetInstance() ** ** Description: get class singleton object ** ** Returns: none ** *******************************************************************************/ CNfcConfig& CNfcConfig::GetInstance() { static CNfcConfig theInstance; if (theInstance.size() == 0 && theInstance.mValidFile) { string strPath; findConfigFilePathFromTransportConfigPaths(config_name, strPath); theInstance.readConfig(strPath.c_str(), true); } return theInstance; } /******************************************************************************* ** ** Function: CNfcConfig::getValue() ** ** Description: get a string value of a setting ** ** Returns: true if setting exists ** false if setting does not exist ** *******************************************************************************/ bool CNfcConfig::getValue(const char* name, char* pValue, size_t& len) const { const CNfcParam* pParam = find(name); if (pParam == NULL) return false; if (pParam->str_len() > 0) { memset(pValue, 0, len); if (len > pParam->str_len()) len = pParam->str_len(); memcpy(pValue, pParam->str_value(), len); return true; } return false; } /******************************************************************************* ** ** Function: CNfcConfig::getValue() ** ** Description: get a long numerical value of a setting ** ** Returns: true if setting exists ** false if setting does not exist ** *******************************************************************************/ bool CNfcConfig::getValue(const char* name, unsigned long& rValue) const { const CNfcParam* pParam = find(name); if (pParam == NULL) return false; if (pParam->str_len() == 0) { rValue = static_cast<unsigned long>(pParam->numValue()); return true; } return false; } /******************************************************************************* ** ** Function: CNfcConfig::getValue() ** ** Description: get a short numerical value of a setting ** ** Returns: true if setting exists ** false if setting does not exist ** *******************************************************************************/ bool CNfcConfig::getValue(const char* name, unsigned short& rValue) const { const CNfcParam* pParam = find(name); if (pParam == NULL) return false; if (pParam->str_len() == 0) { rValue = static_cast<unsigned short>(pParam->numValue()); return true; } return false; } /******************************************************************************* ** ** Function: CNfcConfig::find() ** ** Description: search if a setting exist in the setting array ** ** Returns: pointer to the setting object ** *******************************************************************************/ const CNfcParam* CNfcConfig::find(const char* p_name) const { if (size() == 0) return NULL; for (const_iterator it = begin(), itEnd = end(); it != itEnd; ++it) { if (**it < p_name) continue; else if (**it == p_name) { if ((*it)->str_len() > 0) ALOGD("%s found %s=%s\n", __func__, p_name, (*it)->str_value()); else ALOGD("%s found %s=(0x%lX)\n", __func__, p_name, (*it)->numValue()); return *it; } else break; } return NULL; } /******************************************************************************* ** ** Function: CNfcConfig::clean() ** ** Description: reset the setting array ** ** Returns: none ** *******************************************************************************/ void CNfcConfig::clean() { if (size() == 0) return; for (iterator it = begin(), itEnd = end(); it != itEnd; ++it) delete *it; clear(); } /******************************************************************************* ** ** Function: CNfcConfig::Add() ** ** Description: add a setting object to the list ** ** Returns: none ** *******************************************************************************/ void CNfcConfig::add(const CNfcParam* pParam) { if (m_list.size() == 0) { m_list.push_back(pParam); return; } for (list<const CNfcParam *>::iterator it = m_list.begin(), itEnd = m_list.end(); it != itEnd; ++it) { if (**it < pParam->c_str()) continue; m_list.insert(it, pParam); return; } m_list.push_back(pParam); } /******************************************************************************* ** ** Function: CNfcConfig::moveFromList() ** ** Description: move the setting object from list to array ** ** Returns: none ** *******************************************************************************/ void CNfcConfig::moveFromList() { if (m_list.size() == 0) return; for (list<const CNfcParam *>::iterator it = m_list.begin(), itEnd = m_list.end(); it != itEnd; ++it) push_back(*it); m_list.clear(); } /******************************************************************************* ** ** Function: CNfcConfig::moveToList() ** ** Description: move the setting object from array to list ** ** Returns: none ** *******************************************************************************/ void CNfcConfig::moveToList() { if (m_list.size() != 0) m_list.clear(); for (iterator it = begin(), itEnd = end(); it != itEnd; ++it) m_list.push_back(*it); clear(); } /******************************************************************************* ** ** Function: CNfcParam::CNfcParam() ** ** Description: class constructor ** ** Returns: none ** *******************************************************************************/ CNfcParam::CNfcParam() : m_numValue(0) {} /******************************************************************************* ** ** Function: CNfcParam::~CNfcParam() ** ** Description: class destructor ** ** Returns: none ** *******************************************************************************/ CNfcParam::~CNfcParam() {} /******************************************************************************* ** ** Function: CNfcParam::CNfcParam() ** ** Description: class copy constructor ** ** Returns: none ** *******************************************************************************/ CNfcParam::CNfcParam(const char* name, const string& value) : string(name), m_str_value(value), m_numValue(0) {} /******************************************************************************* ** ** Function: CNfcParam::CNfcParam() ** ** Description: class copy constructor ** ** Returns: none ** *******************************************************************************/ CNfcParam::CNfcParam(const char* name, unsigned long value) : string(name), m_numValue(value) {} /******************************************************************************* ** ** Function: GetStrValue ** ** Description: API function for getting a string value of a setting ** ** Returns: none ** *******************************************************************************/ extern "C" int GetStrValue(const char* name, char* pValue, unsigned long l) { size_t len = l; CNfcConfig& rConfig = CNfcConfig::GetInstance(); bool b = rConfig.getValue(name, pValue, len); return b ? len : 0; } /******************************************************************************* ** ** Function: GetNumValue ** ** Description: API function for getting a numerical value of a setting ** ** Returns: none ** *******************************************************************************/ extern "C" int GetNumValue(const char* name, void* pValue, unsigned long len) { if (!pValue) return false; CNfcConfig& rConfig = CNfcConfig::GetInstance(); const CNfcParam* pParam = rConfig.find(name); if (pParam == NULL) return false; unsigned long v = pParam->numValue(); if (v == 0 && pParam->str_len() > 0 && pParam->str_len() < 4) { const unsigned char* p = (const unsigned char*)pParam->str_value(); for (size_t i = 0; i < pParam->str_len(); ++i) { v *= 256; v += *p++; } } switch (len) { case sizeof(unsigned long): *(static_cast<unsigned long*>(pValue)) = (unsigned long)v; break; case sizeof(unsigned short): *(static_cast<unsigned short*>(pValue)) = (unsigned short)v; break; case sizeof(unsigned char): *(static_cast<unsigned char*>(pValue)) = (unsigned char)v; break; default: return false; } return true; } /******************************************************************************* ** ** Function: resetConfig ** ** Description: reset settings array ** ** Returns: none ** *******************************************************************************/ extern void resetConfig() { CNfcConfig& rConfig = CNfcConfig::GetInstance(); rConfig.clean(); } /******************************************************************************* ** ** Function: readOptionalConfig() ** ** Description: read Config settings from an optional conf file ** ** Returns: none ** *******************************************************************************/ void readOptionalConfig(const char* extra) { string strPath; string configName(extra_config_base); configName += extra; configName += extra_config_ext; findConfigFilePathFromTransportConfigPaths(configName, strPath); CNfcConfig::GetInstance().readConfig(strPath.c_str(), false); }
[ "dumbandroid@gmail.com" ]
dumbandroid@gmail.com
c27887fdcb1cd2a56d60da61003c90e3e6a1df8e
15c1b178f754e01170b55602e2fd3fb6fcfad5c6
/Plugins/VehiclePlugin/Code/Common/Components/LocalBikeComponent.cpp
64f0965aa1325806c36a65ade64cc6ad86f57722
[ "Apache-2.0" ]
permissive
CyberSys/Cry_SimpleBike
dab6c379de9e27ffd9f7b5daf1b668e106e1512a
55c93600bc34c964ec1f9fca8af1409a9e361f80
refs/heads/master
2022-02-16T22:57:50.144399
2019-05-18T07:37:47
2019-05-18T07:37:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,718
cpp
#include "StdAfx.h" #include "LocalBikeComponent.h" #include "SimpleVehiclePluginEnv.h" namespace SimpleVehicle { void LocalBikeComponent::Initialize() { m_BikeMovementPtr = std::make_shared<LocalBikeMovement>(); } uint64 LocalBikeComponent::GetEventMask() const { return ENTITY_EVENT_BIT(ENTITY_EVENT_START_GAME) | ENTITY_EVENT_BIT(ENTITY_EVENT_UPDATE) | ENTITY_EVENT_BIT(ENTITY_EVENT_DEACTIVATED) | ENTITY_EVENT_BIT(ENTITY_EVENT_PREPHYSICSUPDATE); } void LocalBikeComponent::ProcessEvent(const SEntityEvent& event) { switch (event.event) { case ENTITY_EVENT_START_GAME: { m_BikeMovementPtr->Init(m_pEntity); } break; case ENTITY_EVENT_PREPHYSICSUPDATE: { m_BikeMovementPtr->Physicalize(); } break; case ENTITY_EVENT_UPDATE: { SEntityUpdateContext* pCtx = (SEntityUpdateContext*)event.nParam[0]; float frameTime = pCtx->fFrameTime; m_BikeMovementPtr->Update(frameTime); } break; case ENTITY_EVENT_DEACTIVATED: { StopDrive(); } break; default: break; } } void LocalBikeComponent::OnShutDown() { //StopDrive(); } void LocalBikeComponent::StartDrive() { m_BikeMovementPtr->Start(); } void LocalBikeComponent::StopDrive() { m_BikeMovementPtr->Stop(); } void LocalBikeComponent::Turn(float angles) { m_BikeMovementPtr->Turn(angles); } void LocalBikeComponent::Move(float speed) { m_BikeMovementPtr->Move(speed); } const BikeTransfrom& LocalBikeComponent::GetBikeTransfrom() const { return m_BikeMovementPtr->GetBikeTransfrom(); } const BikeAnimation& LocalBikeComponent::GetBikeAnimation() const { return m_BikeMovementPtr->GetBikeAnimation(); } AUTO_REGISTER_COMPONENT(LocalBikeComponent) }
[ "jw463001558@outlook.com" ]
jw463001558@outlook.com