hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
37caa01c67b60d9dc807fc724d2a41b71d96f253
811
cpp
C++
SmallPetsHealthcare/AmbentController.cpp
mihotoyama/doingio-small-pets-healthcare
94f88e8ce10265a022cbc2c75554b9819f335cc6
[ "Apache-2.0" ]
6
2020-09-26T02:31:46.000Z
2022-03-17T07:20:08.000Z
SmallPetsHealthcare/AmbentController.cpp
mihotoyama/doingio-small-pets-healthcare
94f88e8ce10265a022cbc2c75554b9819f335cc6
[ "Apache-2.0" ]
1
2020-10-06T07:20:34.000Z
2020-10-06T07:20:34.000Z
SmallPetsHealthcare/AmbentController.cpp
mihotoyama/doingio-small-pets-healthcare
94f88e8ce10265a022cbc2c75554b9819f335cc6
[ "Apache-2.0" ]
3
2020-10-02T16:04:24.000Z
2021-12-11T00:16:53.000Z
#include "AmbentController.h" void AmbentController::setup(DayDataModel *_dayDataRef, int channelid, char *writekey, WiFiClient *wclient) { dayDataRef = _dayDataRef; if(channelid >= 0) { Serial.print("ambient setup"); const char* cwriteKey = writekey; int b = ambient.begin(channelid, cwriteKey, wclient); Serial.println(b); }else { isEnable = false; } } void AmbentController::send() { if(!isEnable) return; Serial.print("ambient send:"); ambient.set(1, dayDataRef->sensorsValue[0]); ambient.set(2, dayDataRef->sensorsValue[1]); ambient.set(3, dayDataRef->sensorsValue[2]); ambient.set(4, dayDataRef->sensorsValue[3]); ambient.set(5, dayDataRef->sensorsValue[4]); ambient.set(6, dayDataRef->sensorsValue[5]); bool b = ambient.send(); Serial.println(b); }
25.34375
107
0.694205
mihotoyama
37cae3a7a81edd4d93baa509512c37f826e930b0
2,414
cpp
C++
third_party/poco_1.5.3/Net/src/NTPEventArgs.cpp
0u812/roadrunner
f464c2649e388fa1f5a015592b0b29b65cc84b4b
[ "Apache-2.0" ]
1
2015-10-20T09:48:14.000Z
2015-10-20T09:48:14.000Z
third_party/poco_1.5.3/Net/src/NTPEventArgs.cpp
0u812/roadrunner
f464c2649e388fa1f5a015592b0b29b65cc84b4b
[ "Apache-2.0" ]
null
null
null
third_party/poco_1.5.3/Net/src/NTPEventArgs.cpp
0u812/roadrunner
f464c2649e388fa1f5a015592b0b29b65cc84b4b
[ "Apache-2.0" ]
3
2018-01-17T02:09:24.000Z
2019-11-16T23:55:53.000Z
// // NTPEventArgs.cpp // // $Id: //poco/1.4/Net/src/NTPEventArgs.cpp#1 $ // // Library: Net // Package: NTP // Module: NTPEventArgs // // Implementation of NTPEventArgs // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Net/NTPEventArgs.h" #include "Poco/Net/SocketAddress.h" #include "Poco/Net/DNS.h" #include "Poco/Exception.h" #include "Poco/Net/NetException.h" using Poco::IOException; using Poco::InvalidArgumentException; namespace Poco { namespace Net { NTPEventArgs::NTPEventArgs(const SocketAddress& address): _address(address), _packet() { } NTPEventArgs::~NTPEventArgs() { } std::string NTPEventArgs::hostName() const { try { return DNS::resolve(_address.host().toString()).name(); } catch (HostNotFoundException&) { } catch (NoAddressFoundException&) { } catch (DNSException&) { } catch (IOException&) { } return _address.host().toString(); } std::string NTPEventArgs::hostAddress() const { return _address.host().toString(); } } } // namespace Poco::Net
25.680851
78
0.738194
0u812
56cbd8c0aee4ca2b1a04dbfd6b30f6eda17af25b
323
cpp
C++
WBF/src/WBF_DATA/ModuleElement.cpp
heesok2/OpenGL
6ba159a77428635bf73eab9a0080203b248b015c
[ "MIT" ]
null
null
null
WBF/src/WBF_DATA/ModuleElement.cpp
heesok2/OpenGL
6ba159a77428635bf73eab9a0080203b248b015c
[ "MIT" ]
null
null
null
WBF/src/WBF_DATA/ModuleElement.cpp
heesok2/OpenGL
6ba159a77428635bf73eab9a0080203b248b015c
[ "MIT" ]
1
2019-11-25T02:03:08.000Z
2019-11-25T02:03:08.000Z
#include "stdafx.h" #include "ModuleElement.h" #include "EntityDefine.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CModuleElement::CModuleElement(CPackage * pPackage) : CModuleData<CEntityElement>(pPackage, E_TYPE_ELEMENT) { } CModuleElement::~CModuleElement() { }
17
56
0.770898
heesok2
56cd82760e635fa18e1fde799a2fc1debcb4ebe3
518
cpp
C++
CodeForces/Complete/800-899/831A-UnimodalArray.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/800-899/831A-UnimodalArray.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/800-899/831A-UnimodalArray.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> int main(){ long n; scanf("%ld", &n); long prev; scanf("%ld", &prev); int state(0); bool unimodal(true); for(long p = 1; p < n; p++){ long x; scanf("%ld", &x); if(x > prev && state > 0){unimodal = false; break;} else if(x == prev){ if(state == 0){state = 1;} else if(state > 1){unimodal = false; break;} } else if(x < prev){state = 2;} prev = x; } puts(unimodal ? "YES" : "NO"); return 0; }
20.72
59
0.451737
Ashwanigupta9125
56d0eb68f5cb6e620e2d79c9a5a1d67ce374978e
257
cpp
C++
c,c++ codes/letusc/ifelse.cpp
arpan-svci/c-cpp
5b1f9d9b3a90a846ea6b5fb437c9596293966089
[ "MIT" ]
null
null
null
c,c++ codes/letusc/ifelse.cpp
arpan-svci/c-cpp
5b1f9d9b3a90a846ea6b5fb437c9596293966089
[ "MIT" ]
null
null
null
c,c++ codes/letusc/ifelse.cpp
arpan-svci/c-cpp
5b1f9d9b3a90a846ea6b5fb437c9596293966089
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main() { int a,b,c; cout<<"enter the number"; cin>>a; if(a%2==0){ cout<<"\n the number is a even no."; } else{ cout<<"\n the number is a odd number"; } return 0; }
15.117647
46
0.513619
arpan-svci
56d10a34d66b25b5479d18e65432f0feb7d24c86
16,399
cxx
C++
main/sd/source/ui/framework/configuration/ResourceId.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sd/source/ui/framework/configuration/ResourceId.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sd/source/ui/framework/configuration/ResourceId.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include "precompiled_sd.hxx" #include "framework/ResourceId.hxx" #include "framework/FrameworkHelper.hxx" #include "tools/SdGlobalResourceContainer.hxx" #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <comphelper/processfactory.hxx> #include <rtl/ref.hxx> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::drawing::framework; using ::rtl::OUString; /** When the USE_OPTIMIZATIONS symbol is defined then at some optimizations are activated that work only together with XResourceId objects that are implemented by the ResourceId class. For other implementations of when the USE_OPTIMIZATIONS symbol is not defined then alternative code is used instead. */ #define USE_OPTIMIZATIONS namespace sd { namespace framework { Reference<XInterface> SAL_CALL ResourceId_createInstance ( const Reference<XComponentContext>& rxContext) { (void)rxContext; return Reference<XInterface>(static_cast<XWeak*>(new ::sd::framework::ResourceId())); } ::rtl::OUString ResourceId_getImplementationName (void) throw(RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.Draw.framework.ResourceId")); } Sequence<rtl::OUString> SAL_CALL ResourceId_getSupportedServiceNames (void) throw (RuntimeException) { static const ::rtl::OUString sServiceName( ::rtl::OUString::createFromAscii("com.sun.star.drawing.framework.ResourceId")); return Sequence<rtl::OUString>(&sServiceName, 1); } //===== ResourceId ============================================================ WeakReference<util::XURLTransformer> ResourceId::mxURLTransformerWeak; ResourceId::ResourceId (void) : ResourceIdInterfaceBase(), maResourceURLs(0), mpURL() { } ResourceId::ResourceId ( const std::vector<OUString>& rResourceURLs) : ResourceIdInterfaceBase(), maResourceURLs(rResourceURLs), mpURL() { ParseResourceURL(); } ResourceId::ResourceId ( const OUString& rsResourceURL) : ResourceIdInterfaceBase(), maResourceURLs(1, rsResourceURL), mpURL() { // Handle the special case of an empty resource URL. if (rsResourceURL.getLength() == 0) maResourceURLs.clear(); ParseResourceURL(); } ResourceId::ResourceId ( const OUString& rsResourceURL, const OUString& rsAnchorURL) : ResourceIdInterfaceBase(), maResourceURLs(2), mpURL() { maResourceURLs[0] = rsResourceURL; maResourceURLs[1] = rsAnchorURL; ParseResourceURL(); } ResourceId::ResourceId ( const OUString& rsResourceURL, const ::std::vector<OUString>& rAnchorURLs) : ResourceIdInterfaceBase(), maResourceURLs(1+rAnchorURLs.size()), mpURL() { maResourceURLs[0] = rsResourceURL; for (sal_uInt32 nIndex=0; nIndex<rAnchorURLs.size(); ++nIndex) maResourceURLs[nIndex+1] = rAnchorURLs[nIndex]; ParseResourceURL(); } ResourceId::ResourceId ( const OUString& rsResourceURL, const OUString& rsFirstAnchorURL, const Sequence<OUString>& rAnchorURLs) : ResourceIdInterfaceBase(), maResourceURLs(2+rAnchorURLs.getLength()), mpURL() { maResourceURLs[0] = rsResourceURL; maResourceURLs[1] = rsFirstAnchorURL; for (sal_Int32 nIndex=0; nIndex<rAnchorURLs.getLength(); ++nIndex) maResourceURLs[nIndex+2] = rAnchorURLs[nIndex]; ParseResourceURL(); } ResourceId::~ResourceId (void) { mpURL.reset(); } OUString SAL_CALL ResourceId::getResourceURL (void) throw(com::sun::star::uno::RuntimeException) { if (!maResourceURLs.empty()) return maResourceURLs[0]; else return OUString(); } util::URL SAL_CALL ResourceId::getFullResourceURL (void) throw(com::sun::star::uno::RuntimeException) { if (mpURL.get() != NULL) return *mpURL; Reference<util::XURLTransformer> xURLTransformer (mxURLTransformerWeak); if (xURLTransformer.is() && !maResourceURLs.empty() ) { mpURL.reset(new util::URL); mpURL->Complete = maResourceURLs[0]; xURLTransformer->parseStrict(*mpURL); return *mpURL; } util::URL aURL; if (!maResourceURLs.empty()) aURL.Complete = maResourceURLs[0]; return aURL; } sal_Bool SAL_CALL ResourceId::hasAnchor (void) throw (RuntimeException) { return maResourceURLs.size()>1; } Reference<XResourceId> SAL_CALL ResourceId::getAnchor (void) throw (RuntimeException) { ::rtl::Reference<ResourceId> rResourceId (new ResourceId()); const sal_Int32 nAnchorCount (maResourceURLs.size()-1); if (nAnchorCount > 0) { rResourceId->maResourceURLs.resize(nAnchorCount); for (sal_Int32 nIndex=0; nIndex<nAnchorCount; ++nIndex) rResourceId->maResourceURLs[nIndex] = maResourceURLs[nIndex+1]; } return Reference<XResourceId>(rResourceId.get()); } Sequence<OUString> SAL_CALL ResourceId::getAnchorURLs (void) throw (RuntimeException) { const sal_Int32 nAnchorCount (maResourceURLs.size() - 1); if (nAnchorCount > 0) { Sequence<OUString> aAnchorURLs (nAnchorCount); for (sal_Int32 nIndex=0; nIndex<nAnchorCount; ++nIndex) aAnchorURLs[nIndex] = maResourceURLs[nIndex+1]; return aAnchorURLs; } else return Sequence<OUString>(); } OUString SAL_CALL ResourceId::getResourceTypePrefix (void) throw (RuntimeException) { if (!maResourceURLs.empty() ) { // Return the "private:resource/<type>/" prefix. // Get the prefix that ends with the second "/". const OUString& rsResourceURL (maResourceURLs[0]); sal_Int32 nPrefixEnd (rsResourceURL.indexOf(sal_Unicode('/'), 0)); if (nPrefixEnd >= 0) nPrefixEnd = rsResourceURL.indexOf(sal_Unicode('/'), nPrefixEnd+1) + 1; else nPrefixEnd = 0; return rsResourceURL.copy(0,nPrefixEnd); } else return OUString(); } sal_Int16 SAL_CALL ResourceId::compareTo (const Reference<XResourceId>& rxResourceId) throw (RuntimeException) { sal_Int16 nResult (0); if ( ! rxResourceId.is()) { // The empty reference is interpreted as empty resource id object. if (!maResourceURLs.empty()) nResult = +1; else nResult = 0; } else { ResourceId* pId = NULL; #ifdef USE_OPTIMIZATIONS pId = dynamic_cast<ResourceId*>(rxResourceId.get()); #endif if (pId != NULL) { // We have direct access to the implementation of the given // resource id object. nResult = CompareToLocalImplementation(*pId); } else { // We have to do the comparison via the UNO interface of the // given resource id object. nResult = CompareToExternalImplementation(rxResourceId); } } return nResult; } sal_Int16 ResourceId::CompareToLocalImplementation (const ResourceId& rId) const { sal_Int16 nResult (0); const sal_uInt32 nLocalURLCount (maResourceURLs.size()); const sal_uInt32 nURLCount(rId.maResourceURLs.size()); // Start comparison with the top most anchors. for (sal_Int32 nIndex=nURLCount-1,nLocalIndex=nLocalURLCount-1; nIndex>=0 && nLocalIndex>=0; --nIndex,--nLocalIndex) { const OUString sLocalURL (maResourceURLs[nLocalIndex]); const OUString sURL (rId.maResourceURLs[nIndex]); const sal_Int32 nLocalResult (sURL.compareTo(sLocalURL)); if (nLocalResult != 0) { if (nLocalResult < 0) nResult = -1; else nResult = +1; break; } } if (nResult == 0) { // No difference found yet. When the lengths are the same then the // two resource ids are equivalent. Otherwise the shorter comes // first. if (nLocalURLCount != nURLCount) { if (nLocalURLCount < nURLCount) nResult = -1; else nResult = +1; } } return nResult; } sal_Int16 ResourceId::CompareToExternalImplementation (const Reference<XResourceId>& rxId) const { sal_Int16 nResult (0); const Sequence<OUString> aAnchorURLs (rxId->getAnchorURLs()); const sal_uInt32 nLocalURLCount (maResourceURLs.size()); const sal_uInt32 nURLCount(1+aAnchorURLs.getLength()); // Start comparison with the top most anchors. sal_Int32 nLocalResult (0); for (sal_Int32 nIndex=nURLCount-1,nLocalIndex=nLocalURLCount-1; nIndex>=0&&nLocalIndex>=0; --nIndex,--nLocalIndex) { if (nIndex == 0 ) nLocalResult = maResourceURLs[nIndex].compareTo(rxId->getResourceURL()); else nLocalResult = maResourceURLs[nIndex].compareTo(aAnchorURLs[nIndex-1]); if (nLocalResult != 0) { if (nLocalResult < 0) nResult = -1; else nResult = +1; break; } } if (nResult == 0) { // No difference found yet. When the lengths are the same then the // two resource ids are equivalent. Otherwise the shorter comes // first. if (nLocalURLCount != nURLCount) { if (nLocalURLCount < nURLCount) nResult = -1; else nResult = +1; } } return nResult; } sal_Bool SAL_CALL ResourceId::isBoundTo ( const Reference<XResourceId>& rxResourceId, AnchorBindingMode eMode) throw (RuntimeException) { if ( ! rxResourceId.is()) { // An empty reference is interpreted as empty resource id. return IsBoundToAnchor(NULL, NULL, eMode); } ResourceId* pId = NULL; #ifdef USE_OPTIMIZATIONS pId = dynamic_cast<ResourceId*>(rxResourceId.get()); #endif if (pId != NULL) { return IsBoundToAnchor(pId->maResourceURLs, eMode); } else { const OUString sResourceURL (rxResourceId->getResourceURL()); const Sequence<OUString> aAnchorURLs (rxResourceId->getAnchorURLs()); return IsBoundToAnchor(&sResourceURL, &aAnchorURLs, eMode); } } sal_Bool SAL_CALL ResourceId::isBoundToURL ( const OUString& rsAnchorURL, AnchorBindingMode eMode) throw (RuntimeException) { return IsBoundToAnchor(&rsAnchorURL, NULL, eMode); } Reference<XResourceId> SAL_CALL ResourceId::clone (void) throw(RuntimeException) { return new ResourceId(maResourceURLs); } //----- XInitialization ------------------------------------------------------- void SAL_CALL ResourceId::initialize (const Sequence<Any>& aArguments) throw (RuntimeException) { sal_uInt32 nCount (aArguments.getLength()); for (sal_uInt32 nIndex=0; nIndex<nCount; ++nIndex) { OUString sResourceURL; if (aArguments[nIndex] >>= sResourceURL) maResourceURLs.push_back(sResourceURL); else { Reference<XResourceId> xAnchor; if (aArguments[nIndex] >>= xAnchor) { if (xAnchor.is()) { maResourceURLs.push_back(xAnchor->getResourceURL()); Sequence<OUString> aAnchorURLs (xAnchor->getAnchorURLs()); for (sal_Int32 nURLIndex=0; nURLIndex<aAnchorURLs.getLength(); ++nURLIndex) { maResourceURLs.push_back(aAnchorURLs[nURLIndex]); } } } } } ParseResourceURL(); } //----------------------------------------------------------------------------- /** When eMode is DIRECTLY then the anchor of the called object and the anchor represented by the given sequence of anchor URLs have to be identical. When eMode is RECURSIVE then the anchor of the called object has to start with the given anchor URLs. */ bool ResourceId::IsBoundToAnchor ( const OUString* psFirstAnchorURL, const Sequence<OUString>* paAnchorURLs, AnchorBindingMode eMode) const { const sal_uInt32 nLocalAnchorURLCount (maResourceURLs.size() - 1); const bool bHasFirstAnchorURL (psFirstAnchorURL!=NULL); const sal_uInt32 nAnchorURLCount ((bHasFirstAnchorURL?1:0) + (paAnchorURLs!=NULL ? paAnchorURLs->getLength() : 0)); // Check the lengths. if (nLocalAnchorURLCount<nAnchorURLCount || (eMode==AnchorBindingMode_DIRECT && nLocalAnchorURLCount!=nAnchorURLCount)) { return false; } // Compare the nAnchorURLCount bottom-most anchor URLs of this resource // id and the given anchor. sal_uInt32 nOffset = 0; if (paAnchorURLs != NULL) { sal_uInt32 nCount = paAnchorURLs->getLength(); while (nOffset < nCount) { if ( ! maResourceURLs[nLocalAnchorURLCount - nOffset].equals( (*paAnchorURLs)[nCount - 1 - nOffset])) { return false; } ++nOffset; } } if (bHasFirstAnchorURL) { if ( ! psFirstAnchorURL->equals(maResourceURLs[nLocalAnchorURLCount - nOffset])) return false; } return true; } bool ResourceId::IsBoundToAnchor ( const ::std::vector<OUString>& rAnchorURLs, AnchorBindingMode eMode) const { const sal_uInt32 nLocalAnchorURLCount (maResourceURLs.size() - 1); const sal_uInt32 nAnchorURLCount (rAnchorURLs.size()); // Check the lengths. if (nLocalAnchorURLCount<nAnchorURLCount || (eMode==AnchorBindingMode_DIRECT && nLocalAnchorURLCount!=nAnchorURLCount)) { return false; } // Compare the nAnchorURLCount bottom-most anchor URLs of this resource // id and the given anchor. for (sal_uInt32 nOffset=0; nOffset<nAnchorURLCount; ++nOffset) { if ( ! maResourceURLs[nLocalAnchorURLCount - nOffset].equals( rAnchorURLs[nAnchorURLCount - 1 - nOffset])) { return false; } } return true; } void ResourceId::ParseResourceURL (void) { ::osl::Guard< ::osl::Mutex > aGuard (::osl::Mutex::getGlobalMutex()); Reference<util::XURLTransformer> xURLTransformer (mxURLTransformerWeak); if ( ! xURLTransformer.is()) { // Create the URL transformer. Reference<lang::XMultiServiceFactory> xServiceManager ( ::comphelper::getProcessServiceFactory()); xURLTransformer = Reference<util::XURLTransformer>( xServiceManager->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.util.URLTransformer"))), UNO_QUERY); mxURLTransformerWeak = xURLTransformer; SdGlobalResourceContainer::Instance().AddResource( Reference<XInterface>(xURLTransformer,UNO_QUERY)); } if (xURLTransformer.is() && !maResourceURLs.empty() ) { mpURL.reset(new util::URL); mpURL->Complete = maResourceURLs[0]; xURLTransformer->parseStrict(*mpURL); if (mpURL->Main == maResourceURLs[0]) mpURL.reset(); else maResourceURLs[0] = mpURL->Main; } } } } // end of namespace sd::framework
26.322632
96
0.631502
Grosskopf
56d6349b11bb21c869c0258aa3f8e3bc3572c2bf
1,486
hpp
C++
src/feata-gui/gui/wgt/basewidgetgeomsel.hpp
master-clown/ofeata
306cbc3a402551fb62b3925d23a2d4f63f60d525
[ "MIT" ]
1
2021-08-30T13:51:42.000Z
2021-08-30T13:51:42.000Z
src/feata-gui/gui/wgt/basewidgetgeomsel.hpp
master-clown/ofeata
306cbc3a402551fb62b3925d23a2d4f63f60d525
[ "MIT" ]
null
null
null
src/feata-gui/gui/wgt/basewidgetgeomsel.hpp
master-clown/ofeata
306cbc3a402551fb62b3925d23a2d4f63f60d525
[ "MIT" ]
1
2021-08-30T13:51:35.000Z
2021-08-30T13:51:35.000Z
#pragma once #include "gui/wgt/basewidget.hpp" #include "geom/geom_ent_type.hpp" namespace gui::wgt { class BaseWidgetGeomSel : public BaseWidget { public: BaseWidgetGeomSel(QWidget* parent = nullptr); virtual void SetGeomSelType(const geom::GeomEntityType geom_type); virtual bool GetSelectionState() const; virtual geom::GeomEntityType GetGeomSelType() const; public slots: virtual void SetSelectionState(const bool is_on); signals: /** * \brief SelectionToggled * Emit it every time the selection is toggled. */ void SelectionToggled(const bool is_on); protected: bool selection_state_ = false; geom::GeomEntityType geom_type_ = geom::GEOM_ENT_TYPE_INVALID; private: Q_OBJECT using Base = BaseWidget; }; } // impl namespace gui::wgt { inline BaseWidgetGeomSel::BaseWidgetGeomSel(QWidget* parent) : BaseWidget(parent) {} inline void BaseWidgetGeomSel::SetSelectionState(const bool is_on) { selection_state_ = is_on; } inline void BaseWidgetGeomSel::SetGeomSelType(const geom::GeomEntityType geom_type) { geom_type_ = geom_type; } inline bool BaseWidgetGeomSel::GetSelectionState() const { return selection_state_; } inline geom::GeomEntityType BaseWidgetGeomSel::GetGeomSelType() const { return geom_type_; } }
26.070175
101
0.653432
master-clown
56d93b499e9c428f2504811b1da595c4bb1f885b
2,910
cpp
C++
Real-Time Corruptor/BizHawk_RTC/lynx/rom.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
1,414
2015-06-28T09:57:51.000Z
2021-10-14T03:51:10.000Z
Real-Time Corruptor/BizHawk_RTC/lynx/rom.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
2,369
2015-06-25T01:45:44.000Z
2021-10-16T08:44:18.000Z
Real-Time Corruptor/BizHawk_RTC/lynx/rom.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
430
2015-06-29T04:28:58.000Z
2021-10-05T18:24:17.000Z
// // Copyright (c) 2004 K. Wilkins // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from // the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ////////////////////////////////////////////////////////////////////////////// // Handy - An Atari Lynx Emulator // // Copyright (c) 1996,1997 // // K. Wilkins // ////////////////////////////////////////////////////////////////////////////// // ROM emulation class // ////////////////////////////////////////////////////////////////////////////// // // // This class emulates the system ROM (512B), the interface is pretty // // simple: constructor, reset, peek, poke. // // // // K. Wilkins // // August 1997 // // // ////////////////////////////////////////////////////////////////////////////// // Revision History: // // ----------------- // // // // 01Aug1997 KW Document header added & class documented. // // // ////////////////////////////////////////////////////////////////////////////// #include "system.h" #include "rom.h" CRom::CRom(const uint8 *romfile, uint32 length) { //mWriteEnable = false; Reset(); std::memset(mRomData, DEFAULT_ROM_CONTENTS, ROM_SIZE); std::memcpy(mRomData, romfile, std::min<uint32>(ROM_SIZE, length)); } void CRom::Reset(void) { } SYNCFUNC(CRom) { //NSS(mWriteEnable); //NSS(mRomData); }
43.432836
78
0.390378
redscientistlabs
56daed38cdd38fa0f2c902776411b848bdc1e0fc
4,254
cpp
C++
SelectionDialog.cpp
Landgraf132/ScreenTranslator
fa894604666baaa5426057015cc181be93a62785
[ "MIT" ]
null
null
null
SelectionDialog.cpp
Landgraf132/ScreenTranslator
fa894604666baaa5426057015cc181be93a62785
[ "MIT" ]
null
null
null
SelectionDialog.cpp
Landgraf132/ScreenTranslator
fa894604666baaa5426057015cc181be93a62785
[ "MIT" ]
null
null
null
#include "SelectionDialog.h" #include "ui_SelectionDialog.h" #include "LanguageHelper.h" #include "StAssert.h" #include <QMouseEvent> #include <QPainter> #include <QDebug> #include <QMenu> SelectionDialog::SelectionDialog (const LanguageHelper &dictionary, QWidget *parent) : QDialog (parent), ui (new Ui::SelectionDialog), dictionary_ (dictionary), languageMenu_ (new QMenu), swapLanguagesAction_ (NULL) { ui->setupUi (this); setWindowFlags (Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint); ui->label->setAutoFillBackground (false); ui->label->installEventFilter (this); applySettings (); } SelectionDialog::~SelectionDialog () { delete languageMenu_; delete ui; } void SelectionDialog::applySettings () { dictionary_.updateMenu (languageMenu_, dictionary_.availableOcrLanguagesUi ()); if (!languageMenu_->isEmpty ()) { swapLanguagesAction_ = languageMenu_->addAction (tr ("Поменять язык текста и перевода")); } } bool SelectionDialog::eventFilter (QObject *object, QEvent *event) { if (object != ui->label) { return QDialog::eventFilter (object, event); } if (event->type () == QEvent::Show) { startSelectPos_ = currentSelectPos_ = QPoint (); } else if (event->type () == QEvent::MouseButtonPress) { QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event); if ((mouseEvent->button () == Qt::LeftButton || mouseEvent->button () == Qt::RightButton) && startSelectPos_.isNull ()) { startSelectPos_ = mouseEvent->pos (); } } else if (event->type () == QEvent::MouseMove) { QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event); if ((mouseEvent->buttons () & Qt::LeftButton || mouseEvent->buttons () & Qt::RightButton) && !startSelectPos_.isNull ()) { currentSelectPos_ = mouseEvent->pos (); ui->label->repaint (); } } else if (event->type () == QEvent::Paint) { QRect selection = QRect (startSelectPos_, currentSelectPos_).normalized (); if (selection.isValid ()) { QPainter painter (ui->label); painter.setPen (Qt::red); painter.drawRect (selection); } } else if (event->type () == QEvent::MouseButtonRelease) { QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event); if (mouseEvent->button () == Qt::LeftButton || mouseEvent->button () == Qt::RightButton) { if (startSelectPos_.isNull () || currentPixmap_.isNull ()) { return QDialog::eventFilter (object, event); } QPoint endPos = mouseEvent->pos (); QRect selection = QRect (startSelectPos_, endPos).normalized (); startSelectPos_ = currentSelectPos_ = QPoint (); QPixmap selectedPixmap = currentPixmap_.copy (selection); if (selectedPixmap.width () < 3 || selectedPixmap.height () < 3) { reject (); return QDialog::eventFilter (object, event); } ProcessingItem item; item.source = selectedPixmap; item.screenPos = pos () + selection.topLeft (); item.modifiers = mouseEvent->modifiers (); if (mouseEvent->button () == Qt::RightButton && !languageMenu_->children ().isEmpty ()) { QAction *action = languageMenu_->exec (QCursor::pos ()); if (action == NULL) { reject (); return QDialog::eventFilter (object, event); } if (action == swapLanguagesAction_) { item.swapLanguages_ = true; } else { item.ocrLanguage = dictionary_.ocrUiToCode (action->text ()); ST_ASSERT (!item.ocrLanguage.isEmpty ()); item.sourceLanguage = dictionary_.ocrToTranslateCodes (item.ocrLanguage); ST_ASSERT (!item.sourceLanguage.isEmpty ()); } } emit selected (item); } } return QDialog::eventFilter (object, event); } void SelectionDialog::setPixmap (QPixmap pixmap, const QRect &showGeometry) { ST_ASSERT (!pixmap.isNull ()); ST_ASSERT (!showGeometry.isEmpty ()); currentPixmap_ = pixmap; QPalette palette = this->palette (); palette.setBrush (this->backgroundRole (), pixmap); this->setPalette (palette); this->setGeometry (showGeometry); show (); activateWindow (); }
34.585366
93
0.649741
Landgraf132
56db3a1c74beb014fcad16326bd4f4948d3e7cac
14,809
cpp
C++
tarea-01/tests/half_edge/test_half_edge.cpp
ppizarror/tareas-CC7515
9f9bd00b33dcc20e60b549ffbee475e0ad4c9110
[ "MIT" ]
null
null
null
tarea-01/tests/half_edge/test_half_edge.cpp
ppizarror/tareas-CC7515
9f9bd00b33dcc20e60b549ffbee475e0ad4c9110
[ "MIT" ]
null
null
null
tarea-01/tests/half_edge/test_half_edge.cpp
ppizarror/tareas-CC7515
9f9bd00b33dcc20e60b549ffbee475e0ad4c9110
[ "MIT" ]
null
null
null
/** * Testea estructura Half-Edge. * * @package tests.half_edge * @author Pablo Pizarro * @date 01/10/2018 */ // Define parámetros compilación #pragma ide diagnostic ignored "performance-unnecessary-value-param" #pragma ide diagnostic ignored "modernize-use-auto" // Importa librerías #include <cassert> #include "../../half_edge/h_edge.h" template<class T> /** * Indica si dos números son parecidos. * * @tparam T Template * @param a Número a * @param b Número b * @return */ bool num_equal(T a, T b) { return fabs(a - b) < 1e15; } /** * Imprime el título del test * @param title Título del test */ void print_title(std::string title) { std::cout << "" << std::endl; std::cout << "----------------------------------------------------------" << std::endl; std::cout << title << std::endl; std::cout << "----------------------------------------------------------" << std::endl; } /** * Test básico, genera un cuadrado. */ void test_basic() { print_title("Test-basic"); /** * Crea algunos puntos, modificado por MOD * * p4 (0,1) -- p3 (1,1) * | | * | F | * | | * p1 (0,0) -- p2 (1,0) */ double MOD = 1.5; Face<double> f = Face<double>("F"); Point<double> p1 = Point<double>(0, 0) * MOD; Point<double> p2 = Point<double>(1, 0) * MOD; Point<double> p3 = Point<double>(1, 1) * MOD; Point<double> p4 = Point<double>(0, 1) * MOD; /** * Crea los Hedge */ H_Edge<double> he12 = H_Edge<double>(&p2, &f, "12"); H_Edge<double> he23 = H_Edge<double>(&p3, &f, "23"); H_Edge<double> he34 = H_Edge<double>(&p4, &f, "34"); H_Edge<double> he41 = H_Edge<double>(&p1, &f, "41"); // Realiza algunos prints std::cout << "Orden:" << std::endl; he12.print(); he23.print(); he34.print(); he41.print(); // Verifica que sea nulo assert(he12.get_next() == nullptr); assert(he12.get_name() == "12"); /** * Crea los siguiente/posterior */ he12.set_next(&he23); he23.set_next(&he34); he34.set_next(&he41); he41.set_next(&he12); // Verifica ciclo assert(he12.get_next() == &he23); assert(he23.get_prev() == &he12); assert(he12.get_next()->get_next()->get_next()->get_next() == &he12); assert(he12.get_prev()->get_prev()->get_prev()->get_prev() == &he12); // Verifica que el puntero de la cara sea el mismo assert(&f == he12.get_face() && &f == he23.get_face() && &f == he34.get_face()); // Verifica que ambos he estén dentro de la cara assert(f.in_face(&he12) && f.in_face(&he23) && f.in_face(&he34) && f.in_face(&he41)); // Verifica que punto sea el mismo assert(he12.get_point() == &p2); /** * Verifica propiedades geométricas */ assert(f.get_area() == MOD * MOD); assert(f.get_chain_length() == 4); assert(f.get_perimeter() == 4 * MOD); assert(f.is_ccw()); } /** * Testea dos caras, una en ccw, otra no. */ void test_he_ccw() { print_title("Test-ccw"); /** * Crea una cara en ccw y otra no, modificada por MOD * * p3 (0,1) * | \ * | T \ * | \ * p1 (0,0) -- p2 (1,0) */ double MOD = 1.5; Face<double> f = Face<double>("T-CCW"); Point<double> p1 = Point<double>(0, 0) * MOD; Point<double> p2 = Point<double>(1, 0) * MOD; Point<double> p3 = Point<double>(0, 1) * MOD; /** * Crea los Hedge */ H_Edge<double> he12 = H_Edge<double>(&p2, &f); H_Edge<double> he23 = H_Edge<double>(&p3, &f); H_Edge<double> he31 = H_Edge<double>(&p1, &f); // Verifica que sea nulo assert(he12.get_next() == nullptr); /** * Crea las relaciones topológicas */ he12.set_next(&he23); he23.set_next(&he31); he31.set_next(&he12); /** * Testea propiedades geométricas */ f.print_hedges(); assert(f.is_ccw()); assert(num_equal<double>(f.get_perimeter(), 2 * MOD + MOD * sqrt(2))); assert(f.get_area() == MOD * MOD / 2); /** * Ahora cambia la relación de orden */ he12.set_next(&he31); he23.set_next(&he12); he31.set_next(&he23); assert(!f.is_ccw()); } /** * Realiza un test básico con una figura compuesta por dos caras. */ void test_2face() { print_title("Test-2face"); /** * Crea una cara en ccw y otra no, modificada por MOD * * p4 (0,1) -- p3 (1,1) * | \ | * | F1 \ F2 | * | \ | * p1 (0,0) -- p2 (1,0) */ double MOD = 1; Face<double> f1 = Face<double>("F1"); Face<double> f2 = Face<double>("F2"); Point<double> p1 = Point<double>(0, 0) * MOD; Point<double> p2 = Point<double>(1, 0) * MOD; Point<double> p3 = Point<double>(1, 1) * MOD; Point<double> p4 = Point<double>(0, 1) * MOD; /** * Crea los Hedge */ H_Edge<double> he12 = H_Edge<double>(&p2, &f1, "12"); H_Edge<double> he24 = H_Edge<double>(&p4, &f1, "24"); H_Edge<double> he41 = H_Edge<double>(&p1, &f1, "41"); H_Edge<double> he23 = H_Edge<double>(&p3, &f2, "23"); H_Edge<double> he34 = H_Edge<double>(&p4, &f2, "34"); H_Edge<double> he42 = H_Edge<double>(&p2, &f2, "42"); /** * Crea las relaciones topológicas */ // F1 f1.set_hedge(&he12); he12.set_next(&he24); he24.set_next(&he41); he41.set_next(&he12); // F2 f2.set_hedge(&he34); he23.set_next(&he34); he34.set_next(&he42); he42.set_next(&he23); // Par he24.set_pair(&he42); /** * Verifica condiciones geométricas */ f1.print_hedges(); f2.print_hedges(); f1.print_points(); f2.print_points(); assert(num_equal<double>(f1.get_area(), f2.get_area())); assert(num_equal<double>(f1.get_perimeter(), f2.get_perimeter())); assert(f1.is_ccw() && f2.is_ccw()); assert(f1.get_chain_length() == f2.get_chain_length() && f1.get_chain_length() == 3); /** * Verifica condiciones link par */ H_Edge<double> *h = &he12; assert(he24.get_pair() == &he42 && he42.get_pair() == &he24); assert(h->get_next()->get_pair() == &he42); assert(h->get_next()->get_pair()->get_next()->get_next()->get_next()->get_pair()->get_next()->get_next() == &he12); } /** * Testea borrado simple. */ void test_deletion_simple() { print_title("Test-deletion-simple"); /** * Crea la estructura * p1 -> p2 -> p3 -> p4 * a b c */ Face<double> f = Face<double>("F1"); Point<double> p1 = Point<double>(0, 0); Point<double> p2 = Point<double>(1, 0); Point<double> p3 = Point<double>(2, 0); Point<double> p4 = Point<double>(3, 0); H_Edge<double> b = H_Edge<double>(&p3, &f, "b"); H_Edge<double> c = H_Edge<double>(&p4, &f, "c"); H_Edge<double> a = H_Edge<double>(&p2, &f, "a"); H_Edge<double> d; a.set_next(&b); b.set_next(&c); assert(a.get_next() == &b); assert(c.get_prev() == &b); b.destroy(); f.print_hedges(); assert(a.get_next() == &c); assert(c.get_prev() == &a); // Si borro a entonces el puntero de la cara debe cambiar a c a.destroy(); assert(a.get_next() == nullptr && c.get_prev() == nullptr); f.print_hedges(); c.destroy(); f.print_hedges(); // Testeo cara vacía assert(f.get_perimeter() == 0); assert(f.get_area() == 0); assert(f.get_chain_length() == 0); assert(f.get_hedge() == nullptr); /** * Crea la estructura * p1 -> p2 -> p3 -> p4 * a b c */ a = H_Edge<double>(&p2, &f, "a"); b = H_Edge<double>(&p3, &f, "b"); c = H_Edge<double>(&p4, &f, "c"); d = H_Edge<double>(&p1, &f, "d"); f.set_hedge(&a); a.set_next(&b); b.set_next(&c); c.set_next(&d); d.set_next(&a); assert(f.get_hedge() == &a); assert(a.get_next() == &b); assert(a.get_next()->get_next() == &c); assert(a.get_next()->get_next()->get_next() == &d); assert(d.get_next() == &a); assert(f.get_hedge()->get_next() == &b); assert(a.get_prev() == &d); f.print_hedges(); assert(a.get_next() == &b && b.get_next() == &c && c.get_next() == &d && d.get_next() == &a); assert(a.get_prev() == &d && d.get_prev() == &c && c.get_prev() == &b && b.get_prev() == &a); d.destroy(); f.print_hedges(); assert(a.get_next() == &b && b.get_next() == &c && c.get_next() == &a); assert(a.get_prev() == &c && c.get_prev() == &b && b.get_prev() == &a); b.destroy(); f.print_hedges(); assert(a.get_next() == &c && c.get_next() == &a); assert(a.get_prev() == &c && c.get_prev() == &a); c.destroy(); f.print_hedges(); assert(a.get_next() == nullptr); assert(a.get_prev() == nullptr); } /** * Testea eliminación de estructuras. * Crea una cara en ccw y otra no, modificada por MOD * * p3 (0,1) -- p4 (1,1) * | \ | * | T1 \ T2 | * | \ | * p1 (0,0) -- p2 (1,0) * */ void test_deletion_complex() { print_title("Test-deletion-complex"); /** * Crea la estructura */ double MOD = 1.5; Face<double> t1 = Face<double>("T1"); Face<double> t2 = Face<double>("T2"); Point<double> p1 = Point<double>(0, 0) * MOD; Point<double> p2 = Point<double>(1, 0) * MOD; Point<double> p3 = Point<double>(0, 1) * MOD; Point<double> p4 = Point<double>(1, 1) * MOD; H_Edge<double> he23 = H_Edge<double>(&p3, &t1, "23"); H_Edge<double> he31 = H_Edge<double>(&p1, &t1, "31"); H_Edge<double> he12 = H_Edge<double>(&p2, &t1, "12"); H_Edge<double> he24 = H_Edge<double>(&p4, &t2, "24"); H_Edge<double> he32 = H_Edge<double>(&p2, &t2, "32"); H_Edge<double> he43 = H_Edge<double>(&p3, &t2, "43"); he12.set_next(&he23); he23.set_next(&he31); he31.set_next(&he12); he24.set_next(&he43); he43.set_next(&he32); he32.set_next(&he24); he23.set_pair(&he32); t1.print_hedges(); t2.print_hedges(); /** * Borra un elemento */ std::cout << "HE23 DELETED" << std::endl; he23.destroy(); t1.print_hedges(); t2.print_hedges(); assert(he32.get_pair() == nullptr && he23.get_pair() == nullptr); std::cout << "HE12 DELETED" << std::endl; he12.destroy(); t1.print_hedges(); assert(!he31.is_conected()); assert(t1.get_chain_length() == 1); } /** * Testea las caras con largos infinitos. */ void test_infinite_loop() { print_title("Test-infinite-loop"); /** * Crea la estructura * x -> p2 -> p3 -> p4 * a b c */ Face<double> f = Face<double>("F1"); Point<double> p1 = Point<double>(0, 0); Point<double> p2 = Point<double>(1, 0); Point<double> p3 = Point<double>(2, 0); H_Edge<double> b = H_Edge<double>(&p2, &f, "b"); H_Edge<double> c = H_Edge<double>(&p3, &f, "c"); H_Edge<double> a = H_Edge<double>(&p1, &f, "a"); a.set_next(&b); b.set_next(&c); c.set_next(&b); // Acá hay un loop, salta de a>b>c>b>c... /** * Chequea que el largo de la cadena sea un error */ f.print_hedges(); f.print_points(); assert(f.get_chain_length() == -1); assert(f.get_area() == 0); assert(!f.is_ccw()); assert(!f.is_valid()); assert(!f.in_face(&a)); assert(!f.in_face(&b)); assert(!f.in_face(&c)); } /** * Testea que las caras estén conectadas de forma correcta. */ void test_connected_faces() { print_title("Test-connected-faces"); /** * Crea la siguiente figura de 4 caras * * 6 * / C \ * 4 -- 5 * / A\ D / B\ * 1 -- 2 -- 3 * */ Face<double> a = Face<double>("A"); Face<double> b = Face<double>("B"); Face<double> c = Face<double>("C"); Face<double> d = Face<double>("D"); Point<double> p1 = Point<double>(0, 0); Point<double> p2 = Point<double>(1, 0); Point<double> p3 = Point<double>(2, 0); Point<double> p4 = Point<double>(0.5, 1); Point<double> p5 = Point<double>(1.5, 1); Point<double> p6 = Point<double>(1, 2); H_Edge<double> he12 = H_Edge<double>(&p2, &a, "12"); H_Edge<double> he24 = H_Edge<double>(&p4, &a, "12"); H_Edge<double> he41 = H_Edge<double>(&p1, &a, "12"); H_Edge<double> he23 = H_Edge<double>(&p3, &b, "23"); H_Edge<double> he35 = H_Edge<double>(&p5, &b, "35"); H_Edge<double> he52 = H_Edge<double>(&p2, &b, "52"); H_Edge<double> he45 = H_Edge<double>(&p5, &c, "45"); H_Edge<double> he56 = H_Edge<double>(&p6, &c, "56"); H_Edge<double> he64 = H_Edge<double>(&p4, &c, "64"); H_Edge<double> he25 = H_Edge<double>(&p5, &d, "25"); H_Edge<double> he54 = H_Edge<double>(&p4, &d, "54"); H_Edge<double> he42 = H_Edge<double>(&p2, &d, "42"); // Establece primer Edge a.set_hedge(&he12); b.set_hedge(&he23); c.set_hedge(&he45); d.set_hedge(&he25); // Crea relaciones siguientes he12.set_next(&he24); // A he24.set_next(&he41); he41.set_next(&he12); he23.set_next(&he35); // B he35.set_next(&he52); he52.set_next(&he23); he45.set_next(&he56); // C he56.set_next(&he64); he64.set_next(&he45); he54.set_next(&he42); // D he42.set_next(&he25); he25.set_next(&he54); // Establece pares he24.set_pair(&he42); he25.set_pair(&he52); he54.set_pair(&he45); /** * Imprime topología */ a.print_hedges(); b.print_hedges(); c.print_hedges(); d.print_hedges(); /** * Verifica topología */ assert(a.is_ccw() && b.is_ccw() && c.is_ccw() && d.is_ccw()); assert(a.is_valid()); /** * Verifica que no se puedan establecer relaciones inválidas */ try { // Establecer un par de la misma cara he24.set_pair(&he12); assert(false); } catch (...) { static_assert(true, ""); } assert(he24.get_pair() == &he42); try { // Establecer un par de la misma cara he12.set_next(&he23); assert(false); } catch (...) { static_assert(true, ""); } assert(he12.get_next() == &he24); /** * Verifica caras que rodean */ assert(a.get_chain_length() == 3); assert(b.get_chain_length() == 3); assert(c.get_chain_length() == 3); assert(d.get_chain_length() == 3); assert(!a.is_surrounded()); assert(!b.is_surrounded()); assert(!c.is_surrounded()); assert(d.is_surrounded()); } /** * Corre los tests. */ int main() { // Mensaje en consola std::cout << "TEST HALF EDGE" << std::endl; // Corre los tests test_basic(); test_he_ccw(); test_2face(); test_deletion_simple(); test_deletion_complex(); test_infinite_loop(); test_connected_faces(); // Retorna return 0; }
26.118166
119
0.545817
ppizarror
56e12a0837e1348711900c9a2412157bf93bfd86
192
cpp
C++
codility/lesson-6/Distinct.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
codility/lesson-6/Distinct.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
codility/lesson-6/Distinct.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
#include <unordered_set> int solution(vector<int> &A) { unordered_set<int> st; int n = A.size(); for (int i=0; i<n; ++i) { st.insert(A[i]); } return st.size(); }
16
30
0.526042
juseongkr
56e1376d70867d0a2d08e92bea404630f986a9f5
4,894
cpp
C++
src/Drawing.cpp
karjonas/ld35
e6ea8334199bd636bde16412a642ba2f94756211
[ "MIT" ]
2
2021-09-03T12:33:58.000Z
2021-12-26T12:44:20.000Z
src/Drawing.cpp
karjonas/ld35
e6ea8334199bd636bde16412a642ba2f94756211
[ "MIT" ]
null
null
null
src/Drawing.cpp
karjonas/ld35
e6ea8334199bd636bde16412a642ba2f94756211
[ "MIT" ]
null
null
null
#include "Drawing.h" #include "GlobalState.h" #include "allegro5/allegro.h" #include <allegro5/allegro_primitives.h> #include <allegro5/allegro_font.h> #include <vector> #include <algorithm> struct ShapePoints { std::vector<Point> points; ALLEGRO_COLOR color; int mid_x; }; struct LineColor { LineColor(Point p0_in, Point p1_in, ALLEGRO_COLOR color_in) : p0(p0_in), p1(p1_in), color(color_in) {} Point p0; Point p1; ALLEGRO_COLOR color; }; void Drawing::draw_user(int w, int h, User& user) { std::vector<Point> points; if (user.user_shape == Shape::TRIANGLE) points = calc_user_triangle_points(user.user_x, h/2, false, user.rect_size); else points = calc_user_rectangle_points(user.user_x, h/2, false, user.rect_size); points.insert(points.begin(), Point(100,h/2)); points.push_back(Point(w-100,h/2)); const size_t num_pts = points.size(); for (int i = 0; i < num_pts - 1; i++) { auto fst = points[i]; auto snd = points[i+1]; al_draw_line(fst.x, fst.y, snd.x, snd.y, ColorScheme::color0(), 1.0f); } } void Drawing::draw_opponent(int /* w */, int h, Opponent& opponent) { std::vector<Point> points; if (opponent.shape == Shape::TRIANGLE) points = calc_user_triangle_points(opponent.x, h/2, false, opponent.rect_size); else points = calc_user_rectangle_points(opponent.x, h/2, false, opponent.rect_size); const size_t num_pts = points.size(); for (int i = 0; i < num_pts - 1; i++) { auto fst = points[i]; auto snd = points[i+1]; al_draw_line(fst.x, fst.y, snd.x, snd.y, opponent.is_shapeshifter ? ColorScheme::color0() : ColorScheme::color1(), 1.0f); } } void Drawing::draw_tutorial_texts(ALLEGRO_FONT* font, ALLEGRO_COLOR color, int x, int y, double time) { if (time < 2.0 && time < 3.5) al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Welcome!"); else if (time > 4.0 && time < 9.5) al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Move using arrow keys."); else if (time > 10.0 && time < 16.5) { al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Collide with a same color shape"); al_draw_text(font, color, x, y + 30, ALLEGRO_ALIGN_CENTRE, "to morph into it."); } else if (time > 17.0 && time < 23.5) { al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Collide with same shape to kill it."); } else if (time > 24.0 && time < 30) { al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Collide with another shape and "); al_draw_text(font, color, x, y + 30, ALLEGRO_ALIGN_CENTRE, "color and it kills you!"); } } void Drawing::draw_score_texts(ALLEGRO_FONT* font, ALLEGRO_COLOR color, int x, int y, int score) { al_draw_textf(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Score: %d", score); } void Drawing::draw_level_texts(ALLEGRO_FONT* font, ALLEGRO_COLOR color, int x, int y, int level, double time) { if (time < 3) al_draw_textf(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Level %d", level); } void Drawing::draw_credits(ALLEGRO_FONT* font, ALLEGRO_COLOR color, int x, int y) { al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Thanks for playing!"); } void Drawing::draw_all(int w, int h, User& user, const std::vector<Opponent>& opponents) { std::vector<ShapePoints> sps; { std::vector<Point> points = calc_shape_points(user.user_x, h/2, false, user.rect_size, user.user_shape); ShapePoints p; p.color = ColorScheme::color0(); p.mid_x = user.user_x; p.points = points; sps.push_back(p); } for (auto& opponent : opponents) { if (!opponent.active) continue; std::vector<Point> points = calc_shape_points(opponent.x, h/2, false, opponent.rect_size, opponent.shape); ShapePoints p; p.color = opponent.is_shapeshifter ? ColorScheme::color0() : ColorScheme::color1(); p.mid_x = opponent.x; p.points = points; sps.push_back(p); } std::sort(sps.begin(), sps.end(), [](const auto& sp0,const auto& sp1) { return sp0.mid_x < sp1.mid_x; }); std::vector<LineColor> lcs; auto last_pt = Point(100,h/2); for (auto& sp : sps) { lcs.emplace_back(last_pt, sp.points[0], ColorScheme::color0()); const int nums = static_cast<int>(sp.points.size()) - 1; for (int i = 0; i < nums; i++) { lcs.emplace_back(sp.points[i], sp.points[i+1], sp.color); } last_pt = sp.points.back(); } lcs.emplace_back(last_pt, Point(w-100, h/2), ColorScheme::color0()); for (auto& lc : lcs) { auto fst = lc.p0; auto snd = lc.p1; al_draw_line(fst.x, fst.y, snd.x, snd.y, lc.color, 1.0f); } }
29.305389
125
0.62076
karjonas
56e26e15b2781256469ba26b3a0551893914d35c
975
hpp
C++
include/gkom/ShaderLoader.hpp
akowalew/mill-opengl
91ef11e6cdbfe691e0073d9883e42c0a29d29b45
[ "MIT" ]
null
null
null
include/gkom/ShaderLoader.hpp
akowalew/mill-opengl
91ef11e6cdbfe691e0073d9883e42c0a29d29b45
[ "MIT" ]
null
null
null
include/gkom/ShaderLoader.hpp
akowalew/mill-opengl
91ef11e6cdbfe691e0073d9883e42c0a29d29b45
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <unordered_map> #include <vector> #include <string_view> namespace gkom { //! Forward declarations class GraphicsManager; class Logger; class ShaderLoader { public: ShaderLoader(GraphicsManager& graphicsManager); unsigned int loadShaderProgram(std::string_view vertexShaderName, std::string_view fragmentShaderName); private: unsigned int makeShaderProgram(std::string_view vertexShaderName, std::string_view fragmentShaderName); std::string loadShaderCode(std::string_view name); std::string getShaderPath(std::string_view name); unsigned int findShaderProgram(std::string_view vertexShaderName, std::string_view fragmentShaderName) const; std::unordered_map< std::string /*vertexShaderName*/, std::unordered_map< std::string /*fragmentShaderName*/, unsigned int /*shaderProgram*/ > > shaderPrograms_; GraphicsManager& graphicsManager_; Logger& logger_; }; } // gkom
21.195652
66
0.754872
akowalew
56e466326b75fbd4a90de96bbf77cb6ac88668c7
2,125
cpp
C++
test/basic4.cpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
54
2015-02-09T11:46:30.000Z
2021-08-13T14:08:52.000Z
test/basic4.cpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
null
null
null
test/basic4.cpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
17
2015-01-13T03:18:49.000Z
2022-03-23T02:20:57.000Z
/*! Tests whether the quorum will properly handle a dead node and it coming alive in a later stadium, including a proper catch up. */ #include <boost/date_time/posix_time/posix_time_duration.hpp> #include <paxos++/client.hpp> #include <paxos++/server.hpp> #include <paxos++/configuration.hpp> #include <paxos++/detail/util/debug.hpp> int main () { uint16_t calls = 0; uint16_t response_count = 0; paxos::server::callback_type callback = [& response_count](int64_t, std::string const &) -> std::string { ++response_count; return "bar"; }; paxos::server server1 ("127.0.0.1", 1337, callback); paxos::server server2 ("127.0.0.1", 1338, callback); paxos::client client; server1.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}}); server2.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}}); client.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}}); PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar"); PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar"); PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar"); PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar"); PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar"); PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar"); PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar"); PAXOS_DEBUG ("response_count = " << response_count); calls = 7; PAXOS_ASSERT_EQ (response_count, 2 * calls); paxos::server server3 ("127.0.0.1", 1339, callback); server3.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}}); /*! Let's wait a few seconds for 3 handshakes to occur */ boost::this_thread::sleep ( boost::posix_time::milliseconds ( paxos::configuration ().timeout ())); do { PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar"); ++calls; } while (response_count != 3 * calls && calls < 50); PAXOS_ASSERT_EQ (response_count, 3 * calls); PAXOS_INFO ("test succeeded"); }
31.25
100
0.585412
armos-db
56e6c51577d68c2427821b8aa06715c7acfb538f
18,164
cpp
C++
Backups/DxGuiFramework - 17.2.01/DGGraphics.cpp
Maultasche/SeniorProject
1bdb3c5e5d2298906f361af6fdda79438a56cb7c
[ "MIT" ]
null
null
null
Backups/DxGuiFramework - 17.2.01/DGGraphics.cpp
Maultasche/SeniorProject
1bdb3c5e5d2298906f361af6fdda79438a56cb7c
[ "MIT" ]
null
null
null
Backups/DxGuiFramework - 17.2.01/DGGraphics.cpp
Maultasche/SeniorProject
1bdb3c5e5d2298906f361af6fdda79438a56cb7c
[ "MIT" ]
null
null
null
/*------------------------------------------------------------------------ File Name: DGGraphics.h Description: This file contains the DGGraphics class implementation, which manages the DirectDraw surfaces and controls and what is drawn to the screen. Version: 1.0.0 10.02.2000 Created the file ------------------------------------------------------------------------*/ #include "DxGuiFramework.h" DGGraphics::DGGraphics() { OutputDebugString("DGGraphics constructor\n"); hWnd = DGGetApp()->GetWindowsHandle(); //Initialize DirectDraw object HRESULT result = DirectDrawCreateEx(NULL, (void**)&lpDD, IID_IDirectDraw7, NULL); if(result != DD_OK) HandleDDrawError(EC_DDINIT, result, __FILE__, __LINE__); //Set the cooperative level. result = lpDD->SetCooperativeLevel(hWnd, DDSCL_ALLOWREBOOT | DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN); if(result != DD_OK) HandleDDrawError(EC_DDINIT, result, __FILE__, __LINE__); //Get the hardware capabilities ddCaps.dwSize = sizeof(DDCAPS); result = lpDD->GetCaps(&ddCaps, NULL); SetGraphicsMode(DGPoint(640, 480), WS_WINDOWED, CD_16BIT, BT_SINGLE); } DGGraphics::~DGGraphics() { OutputDebugString("DGGraphics destructor\n"); lpDD->Release(); lpDD = NULL; } void DGGraphics::Initialize() { } void DGGraphics::SetGraphicsMode(DGPoint res, UINT winState, UINT clrDepth, UINT bufferMode) { screenRes.x = res.x; screenRes.y = res.y; windowedState = winState; HWND desktopWindow; int desktopClrDepth; //If we are switching to windowed mode, we need to question the desktop //about its color depth if(windowedState == WS_WINDOWED) { desktopWindow = GetDesktopWindow(); HDC desktopDC = GetDC(desktopWindow); desktopClrDepth = GetDeviceCaps(desktopDC, BITSPIXEL); ReleaseDC(desktopWindow, desktopDC); } if(clrDepth == CD_16BIT) { } else colorDepth = clrDepth; UINT appColorDepth = clrDepth; //UINT bufferingMode; } void DGGraphics::HandleDDrawError(UINT errorCode, HRESULT error, char* fileName, UINT lineNumber) { if(error == DD_OK) return; char errorText[512]; switch(error) { case DDERR_ALREADYINITIALIZED: strcpy(errorText, "DirectDraw object has already been initialized."); break; case DDERR_BLTFASTCANTCLIP: strcpy(errorText, "BltFast() cannot be used with a surface "\ "that has a DirectDrawClipper object attached."); break; case DDERR_CANNOTATTACHSURFACE: strcpy(errorText, "The surface cannot be attached."); break; case DDERR_CANNOTDETACHSURFACE: strcpy(errorText, "The surface cannot be detached."); break; case DDERR_CANTCREATEDC: strcpy(errorText, "The Windows device context could not be "\ "created."); break; case DDERR_CANTDUPLICATE: strcpy(errorText, "This surface cannot be duplicated."); break; case DDERR_CANTLOCKSURFACE: strcpy(errorText, "The surface cannot be locked."); break; case DDERR_CANTPAGELOCK: strcpy(errorText, "Page lock failed."); break; case DDERR_CANTPAGEUNLOCK: strcpy(errorText, "Page unlock failed."); break; case DDERR_CLIPPERISUSINGHWND: strcpy(errorText, "The clip list could not be added, as the "\ "DirectDrawClipper object is already monitoring a window "\ "handle."); break; case DDERR_COLORKEYNOTSET: strcpy(errorText, "No source color key has been set"); break; case DDERR_CURRENTLYNOTAVAIL: strcpy(errorText, "No support is currently available for this "\ "operation"); break; case DDERR_DDSCAPSCOMPLEXREQUIRED: strcpy(errorText, "This surface needs to be a complex surface"); break; case DDERR_DCALREADYCREATED: strcpy(errorText, "A device context has already been created for "\ "this surface"); break; case DDERR_DEVICEDOESNTOWNSURFACE: strcpy(errorText, "This surface is owned by another DirectDraw device "\ "and cannot be used"); break; case DDERR_DIRECTDRAWALREADYCREATED: strcpy(errorText, "A DirectDraw object representing this driver has "\ "already been created."); break; case DDERR_EXCEPTION: strcpy(errorText, "An exception was encountered while performing "\ "the requested operation."); break; case DDERR_EXCLUSIVEMODEALREADYSET: strcpy(errorText, "Exclusive mode has already been set."); break; case DDERR_EXPIRED: strcpy(errorText, "The data has expired and is invalid."); break; case DDERR_GENERIC: strcpy(errorText, "An undefined error condition has occurred."); break; case DDERR_HEIGHTALIGN: strcpy(errorText, "The height of the provided rectangle is not a "\ "multiple of the required alignment."); break; case DDERR_HWNDALREADYSET: strcpy(errorText, "The cooperative-level window handle has already been "\ "set."); break; case DDERR_HWNDSUBCLASSED: strcpy(errorText, "DirectDraw cannot restore because the DirectDraw "\ "cooperative-level window handle has been subclassed."); break; case DDERR_IMPLICITLYCREATED: strcpy(errorText, "Surface cannot be restored because it was implicitly "\ "created"); break; case DDERR_INCOMPATIBLEPRIMARY: strcpy(errorText, "The primary surface creation request does not match "\ "the existing primary surface."); break; case DDERR_INVALIDCAPS: strcpy(errorText, "One or more of the capability bits passed to the "\ "callback function are incorrect."); break; case DDERR_INVALIDCLIPLIST: strcpy(errorText, "DirectDraw does not support the provided clip list."); break; case DDERR_INVALIDDIRECTDRAWGUID: strcpy(errorText, "The provided GUID is an invalid DirectDraw GUID"); break; case DDERR_INVALIDMODE: strcpy(errorText, "DirectDraw does not support the requested mode."); break; case DDERR_INVALIDOBJECT: strcpy(errorText, "DirectDraw received a pointer to an invalid object."); break; case DDERR_INVALIDPARAMS: strcpy(errorText, "One or more parameters passed to this method are "\ "incorrect."); break; case DDERR_INVALIDPIXELFORMAT: strcpy(errorText, "The specified pixel format was invalid."); break; case DDERR_INVALIDPOSITION: strcpy(errorText, "The position of the overlay on the destination is "\ "no longer legal."); break; case DDERR_INVALIDRECT: strcpy(errorText, "The provided rectangle was invalid."); break; case DDERR_INVALIDSTREAM: strcpy(errorText, "The specified stream contains invalid data."); break; case DDERR_INVALIDSURFACETYPE: strcpy(errorText, "The surface was of the wrong type."); break; case DDERR_LOCKEDSURFACES: strcpy(errorText, "This operation failed due to a locked surface."); break; case DDERR_MOREDATA: strcpy(errorText, "There is more data available than the specified buffer "\ "can hold."); break; case DDERR_NO3D: strcpy(errorText, "No 3-D hardware or emulation is present."); break; case DDERR_NOALPHAHW: strcpy(errorText, "No alpha-acceleration hardware is present or available."); break; case DDERR_NOBLTHW: strcpy(errorText, "No blitter hardware is present."); break; case DDERR_NOCLIPLIST: strcpy(errorText, "No clip list is available."); break; case DDERR_NOCLIPPERATTACHED: strcpy(errorText, "No DirectDrawClipper is attached to the surface."); break; case DDERR_NOCOLORCONVHW: strcpy(errorText, "No color-conversion hardware is present or available."); break; case DDERR_NOCOLORKEY: strcpy(errorText, "The surface does not currently have a color key."); break; case DDERR_NOCOLORKEYHW: strcpy(errorText, "There is no hardware support for the destination color "\ "key."); break; case DDERR_NOCOOPERATIVELEVELSET: strcpy(errorText, "No cooperative level had been set."); break; case DDERR_NODC: strcpy(errorText, "No device context exists for this surface."); break; case DDERR_NODDROPSHW: strcpy(errorText, "No DirectDraw raster-operation (ROP) hardware is"\ "available."); break; case DDERR_NODIRECTDRAWHW: strcpy(errorText, "Hardware-only DirectDraw creation not possible."); break; case DDERR_NODIRECTDRAWSUPPORT: strcpy(errorText, "DirectDraw support is not possible with the current"\ "display driver."); break; case DDERR_NODRIVERSUPPORT: strcpy(errorText, "Testing cannot proceed due to no display driver support."); break; case DDERR_NOEMULATION: strcpy(errorText, "Software emulation not available."); break; case DDERR_NOEXCLUSIVEMODE: strcpy(errorText, "This operation requires the application to have "\ "exclusive mode."); break; case DDERR_NOFLIPHW: strcpy(errorText, "Flipping visible surfaces not supported."); break; case DDERR_NOFOCUSWINDOW: strcpy(errorText, "Cannot create or set a device window without having "\ "first set the focus window."); break; case DDERR_NOGDI: strcpy(errorText, "No GDI is present."); break; case DDERR_NOHWND: strcpy(errorText, "No cooperative-level window handle."); break; case DDERR_NOMIPMAPHW: strcpy(errorText, "No mipmap-capable texture mapping hardware is present "\ "or available."); break; case DDERR_NOMIRRORHW: strcpy(errorText, "No mirroring hardware is present of available."); break; case DDERR_NOMONITORINFORMATION: strcpy(errorText, "No monitor information exists."); break; case DDERR_NONONLOCALVIDMEM: strcpy(errorText, "No nonlocal video memory is available."); break; case DDERR_NOOPTIMIZEHW: strcpy(errorText, "Optimized surfaces not supported."); break; case DDERR_NOOVERLAYDEST: strcpy(errorText, "Overlay is not a destination."); break; case DDERR_NOOVERLAYHW: strcpy(errorText, "No overlay hardware present or available."); break; case DDERR_NOPALETTEATTACHED: strcpy(errorText, "No palette object is attached to the surface."); break; case DDERR_NOPALETTEHW: strcpy(errorText, "No hardware support for 16- or 256-color palettes."); break; case DDERR_NORASTEROPHW: strcpy(errorText, "No appropriate raster-operation hardware is present "\ " or available."); break; case DDERR_NOROTATIONHW: strcpy(errorText, "No rotation hardware is present or available."); break; case DDERR_NOSTEREOHARDWARE: strcpy(errorText, "No stereo hardware is present or available."); break; case DDERR_NOSTRETCHHW: strcpy(errorText, "No hardware support for stretching."); break; case DDERR_NOSURFACELEFT: strcpy(errorText, "No hardware that supports stereo surfaces."); break; case DDERR_NOT4BITCOLOR: strcpy(errorText, "This operation requires a 4-bit color palette."); break; case DDERR_NOT4BITCOLORINDEX: strcpy(errorText, "This operation requires a 4-bit color *index* palette."); break; case DDERR_NOT8BITCOLOR: strcpy(errorText, "This operation requires an 8-bit color palette."); break; case DDERR_NOTAOVERLAYSURFACE: strcpy(errorText, "Not an overlay surface."); break; case DDERR_NOTEXTUREHW: strcpy(errorText, "No texture-mapping hardware is present or available."); break; case DDERR_NOTFLIPPABLE: strcpy(errorText, "This surface cannot be flipped."); break; case DDERR_NOTFOUND: strcpy(errorText, "The requested item was not found."); break; case DDERR_NOTINITIALIZED: strcpy(errorText, "DirectDraw object has not been initialized."); break; case DDERR_NOTLOADED: strcpy(errorText, "Surface has not been allocated any memory."); break; case DDERR_NOTLOCKED: strcpy(errorText, "Surface was not locked."); break; case DDERR_NOTPAGELOCKED: strcpy(errorText, "Surface was not page-locked."); break; case DDERR_NOTPALETTIZED: strcpy(errorText, "Surface is not palette-based."); break; case DDERR_NOVSYNCHW: strcpy(errorText, "There is no hardware support for vertical blank or "\ "synchronized operations."); break; case DDERR_NOZBUFFERHW: strcpy(errorText, "There is no z-buffer hardware support."); break; case DDERR_NOZOVERLAYHW: strcpy(errorText, "Overlay surfaces cannot be z-layered: no hardware "\ "support."); break; case DDERR_OUTOFCAPS: strcpy(errorText, "The hardware needed for this operation has already "\ "been allocated."); break; case DDERR_OUTOFMEMORY: strcpy(errorText, "There is not enough memory to perform this operation."); break; case DDERR_OUTOFVIDEOMEMORY: strcpy(errorText, "There is not enough *display* memory to perform this "\ "operation."); break; case DDERR_OVERLAPPINGRECTS: strcpy(errorText, "Source and destination rectangles are on the same "\ "surface and overlap each other."); break; case DDERR_OVERLAYCANTCLIP: strcpy(errorText, "The hardware does not support clipped overlays."); break; case DDERR_OVERLAYCOLORKEYONLYONEACTIVE: strcpy(errorText, "Only one color key can be active on an overlay."); break; case DDERR_OVERLAYNOTVISIBLE : strcpy(errorText, "The specified overlay is hidden."); break; case DDERR_PALETTEBUSY: strcpy(errorText, "The palette is busy."); break; case DDERR_PRIMARYSURFACEALREADYEXISTS: strcpy(errorText, "A primary surface already exists."); break; case DDERR_REGIONTOOSMALL: strcpy(errorText, "The specified clip region is too small."); break; case DDERR_SURFACEALREADYATTACHED: strcpy(errorText, "The surface was already attached."); break; case DDERR_SURFACEALREADYDEPENDENT: strcpy(errorText, "The surface was already dependent."); break; case DDERR_SURFACEBUSY: strcpy(errorText, "The surface is busy."); break; case DDERR_SURFACEISOBSCURED: strcpy(errorText, "Access to surface denied: surface is obscured."); break; case DDERR_SURFACELOST: strcpy(errorText, "The surface had been lost: it must be restored."); break; case DDERR_SURFACENOTATTACHED: strcpy(errorText, "The requested surface is not attached."); break; case DDERR_TOOBIGHEIGHT: strcpy(errorText, "The requested height is too large."); break; case DDERR_TOOBIGSIZE: strcpy(errorText, "The requested size is too large."); break; case DDERR_TOOBIGWIDTH: strcpy(errorText, "The requested width is too large."); break; case DDERR_UNSUPPORTED: strcpy(errorText, "This operation is not supported."); break; case DDERR_UNSUPPORTEDFORMAT: strcpy(errorText, "The pixel format is not supported by DirectDraw."); break; case DDERR_UNSUPPORTEDMASK: strcpy(errorText, "The bitmask in the pixel format is not supported by "\ "DirectDraw."); break; case DDERR_UNSUPPORTEDMODE: strcpy(errorText, "The display is currently in an unsupported mode."); break; case DDERR_VERTICALBLANKINPROGRESS: strcpy(errorText, "A vertical blank is in progress."); break; case DDERR_VIDEONOTACTIVE: strcpy(errorText, "The video port is not active."); break; case DDERR_WASSTILLDRAWING: strcpy(errorText, "The operation was still drawing."); break; case DDERR_WRONGMODE: strcpy(errorText, "This surface cannot be restored: it was created in "\ "a different mode."); break; case DDERR_XALIGN: strcpy(errorText, "The rectangle was not horizontally aligned on a "\ "required boundary."); break; default: strcpy(errorText, "Unknown Error"); break; } throw(new DGException(errorText, errorCode, ET_DIRECTDRAW, fileName, lineNumber)); }
37.451546
88
0.609998
Maultasche
56ec4a59ede740735759a7b7a5e5195c78e13b84
1,960
cpp
C++
ToyRenderer/src/Audio/AudioEngine.cpp
IRCSS/ToyRenderer
39b919a99cae47f9da34229b427958ea720d98d0
[ "MIT" ]
40
2020-03-19T20:05:22.000Z
2022-03-27T07:52:38.000Z
ToyRenderer/src/Audio/AudioEngine.cpp
IRCSS/ToyRenderer
39b919a99cae47f9da34229b427958ea720d98d0
[ "MIT" ]
null
null
null
ToyRenderer/src/Audio/AudioEngine.cpp
IRCSS/ToyRenderer
39b919a99cae47f9da34229b427958ea720d98d0
[ "MIT" ]
5
2021-09-25T01:32:25.000Z
2021-11-18T13:42:18.000Z
#include "AudioEngine.h" #include "vendor/soloud/soloud.h" #include "Audio/AudioClip.h" #include "vendor/soloud/soloud_wav.h" #include "Components/Transform.h" #include "log/Log.h" namespace ToyRenderer { AudioEngine* AudioEngine::m_pSingelton = nullptr; AudioEngine::AudioEngine() : m_soLoudBackend(nullptr) { SoLoud::Soloud::FLAGS flags = static_cast<SoLoud::Soloud::FLAGS>(static_cast<int>(SoLoud::Soloud::FLAGS::CLIP_ROUNDOFF) | static_cast<int>(SoLoud::Soloud::FLAGS::LEFT_HANDED_3D)); m_soLoudBackend = new SoLoud::Soloud; // object created m_soLoudBackend->init(flags); // back-end initialization } AudioEngine::~AudioEngine() { m_soLoudBackend->deinit(); // Clean up! delete m_soLoudBackend; } void AudioEngine::OnUpdate(float deltaTime) { m_soLoudBackend->update3dAudio(); } int AudioEngine::Play(AudioClip* toPlay) { return m_soLoudBackend->play(toPlay->GetBackEndAudioSourceHandel()); } int AudioEngine::Play(AudioClip * toPlay, const Transform * transform) { int handel = m_soLoudBackend->play3d(toPlay->GetBackEndAudioSourceHandel(), transform->position.x, transform->position.y, transform->position.z); m_soLoudBackend->set3dSourceAttenuation(handel, 1, 1); return handel; } void AudioEngine::SetAudioListner(const Transform * listnerTransform) { m_soLoudBackend->set3dListenerPosition(listnerTransform->position.x , listnerTransform->position.y , listnerTransform->position.z ); m_soLoudBackend->set3dListenerAt (listnerTransform->Foward().x , listnerTransform->Foward().y , listnerTransform->Foward().z ); m_soLoudBackend->set3dListenerUp (listnerTransform->Up().x , listnerTransform->Up().y , listnerTransform->Up().z ); } AudioEngine & AudioEngine::Instance() { if (!m_pSingelton) m_pSingelton = new AudioEngine(); return *m_pSingelton; } void AudioEngine::Clear() { delete m_pSingelton; m_pSingelton = nullptr; } }
29.253731
181
0.729082
IRCSS
56efffeb98c7187150e4e1f289e9cf4291d7c4a7
777
cpp
C++
scripts/calc_recall_dis.cpp
PwzXxm/BBAnn
2dafce027599b3cdf84070248467294dca2a1042
[ "MIT" ]
11
2021-11-01T06:49:30.000Z
2022-02-25T08:09:21.000Z
scripts/calc_recall_dis.cpp
PwzXxm/BBAnn
2dafce027599b3cdf84070248467294dca2a1042
[ "MIT" ]
null
null
null
scripts/calc_recall_dis.cpp
PwzXxm/BBAnn
2dafce027599b3cdf84070248467294dca2a1042
[ "MIT" ]
5
2021-11-04T02:18:41.000Z
2022-03-17T04:13:07.000Z
#include <stdio.h> const char *flat = "bigann_flat.txt"; const char *index = "bigann_ivf_64.txt"; int nq = 1000; int topk = 1000; bool is_l2 = true; int main() { FILE *f1 = fopen(flat, "r"); FILE *f2 = fopen(index, "r"); if (!f1 || !f2) { return 0; } int truth = 0; double dis_base, dis_cnt; for (int i = 0; i < nq; i++) { for (int j = 1; j < topk; j++) fscanf(f1, "%*lf%*d"); fscanf(f1, "%lf%*d", &dis_base); for (int j = 0; j < topk; j++) { fscanf(f2, "%lf%*d", &dis_cnt); if (is_l2) { if (dis_cnt <= dis_base) { truth++; } } else { if (dis_cnt >= dis_base) { truth++; } } } } printf("recall rate %lf\n", double(truth) / (nq * topk)); return 0; }
18.95122
59
0.478764
PwzXxm
56f65353c1b604263049631bc31f9b911eef7970
1,608
cpp
C++
tests/api/evaluator/debug.cpp
SalusaSecondus/homomorphic-implementors-toolkit
b7775b77cb0ff4ff42a1b47bf958bb0e3c75fb9b
[ "Apache-2.0" ]
38
2020-12-02T12:43:16.000Z
2022-03-15T19:27:39.000Z
tests/api/evaluator/debug.cpp
SalusaSecondus/homomorphic-implementors-toolkit
b7775b77cb0ff4ff42a1b47bf958bb0e3c75fb9b
[ "Apache-2.0" ]
15
2020-12-03T05:04:12.000Z
2021-08-20T21:26:27.000Z
tests/api/evaluator/debug.cpp
SalusaSecondus/homomorphic-implementors-toolkit
b7775b77cb0ff4ff42a1b47bf958bb0e3c75fb9b
[ "Apache-2.0" ]
6
2021-01-06T18:37:00.000Z
2021-09-20T06:43:13.000Z
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #include <iostream> #include "../../testutil.h" #include "gtest/gtest.h" #include "hit/hit.h" using namespace std; using namespace hit; // Test variables. const int RANGE = 16; const int NUM_OF_SLOTS = 4096; const int ONE_MULTI_DEPTH = 1; const int LOG_SCALE = 30; TEST(DebugTest, Serialization) { DebugEval ckks_instance1 = DebugEval(NUM_OF_SLOTS, ONE_MULTI_DEPTH, LOG_SCALE); // serialize instance to files stringstream paramsStream(ios::in | ios::out | ios::binary); stringstream galoisKeyStream(ios::in | ios::out | ios::binary); stringstream relinKeyStream(ios::in | ios::out | ios::binary); stringstream secretKeyStream(ios::in | ios::out | ios::binary); ckks_instance1.save(paramsStream, galoisKeyStream, relinKeyStream, secretKeyStream); DebugEval ckks_instance2 = DebugEval(paramsStream, galoisKeyStream, relinKeyStream, secretKeyStream); vector<double> vector_input = random_vector(NUM_OF_SLOTS, RANGE); CKKSCiphertext ciphertext = ckks_instance2.encrypt(vector_input); ckks_instance2.square_inplace(ciphertext); ckks_instance2.relinearize_inplace(ciphertext); ckks_instance2.rescale_to_next_inplace(ciphertext); vector<double> vector_output = ckks_instance2.decrypt(ciphertext); vector<double> expected_output(NUM_OF_SLOTS); transform(vector_input.begin(), vector_input.end(), vector_input.begin(), expected_output.begin(), multiplies<>()); ASSERT_LE(relative_error(expected_output, vector_output), MAX_NORM); }
39.219512
119
0.758085
SalusaSecondus
56f95dbe031bdb94b5979686e8f30a4580d4cf92
4,261
cc
C++
RAVL2/Image/VideoIO/rawFormat.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Image/VideoIO/rawFormat.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Image/VideoIO/rawFormat.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2001, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here ////////////////////////////////////////////////// //! rcsid="$Id: rawFormat.cc 342 2001-08-28 13:33:14Z craftit $" //! lib=RavlVideoIO //! file="Ravl/Image/VideoIO/rawFormat.cc" #include "Ravl/Image/rawFormat.hh" #include "Ravl/Image/ImgIOrgb.hh" #include "Ravl/TypeName.hh" #include <ctype.h> #define DODEBUG 0 #if DODEBUG #define ONDEBUG(x) x #else #define ONDEBUG(x) #endif namespace RavlImageN { void InitRawIOFormat() {} // Raw //////////////////////////////////////////////////////////////// FileFormatRawBodyC::FileFormatRawBodyC() : FileFormatBodyC("raw",StringC("Format optimised for realtime IO")) { ONDEBUG(cerr << "Added format 'raw'. \n"); } //: Constructor. //: Is stream in std stream format ? // No way to tell !! // Just say no ?? const type_info & FileFormatRawBodyC::ProbeLoad(IStreamC &in,const type_info &obj_type) const { ONDEBUG(cerr << "FileFormatRawBodyC::ProbeLoad(IStreamC) Called. LoadType:'" << TypeName(obj_type) << "'\n"); return typeid(void); } const type_info & FileFormatRawBodyC::ProbeLoad(const StringC &nfilename,IStreamC &in,const type_info &obj_type) const { StringC suffix = Extension(nfilename); ONDEBUG(cerr << "FileFormatRawBodyC::ProbeLoad() Called. Filename:'"<<nfilename <<" Ext:'" << suffix << "' LoadType:'" << TypeName(obj_type) << "'\n"); if (suffix != "raw") return typeid(void); return typeid(ImageC<ByteRGBValueC>); } const type_info & FileFormatRawBodyC::ProbeSave(const StringC &nfilename,const type_info &obj_type,bool forceFormat) const { if(!forceFormat) { StringC suffix = Extension(nfilename); ONDEBUG(cerr << "FileFormatRawBodyC::ProbeSave() Called. Filename:'"<<nfilename <<" Ext:'" << suffix << "' LoadType:'" << TypeName(obj_type) << "'\n"); if (suffix != "raw") return typeid(void); } return typeid(ImageC<ByteRGBValueC>); } //: Create a input port for loading. // Will create an Invalid port if not supported. DPIPortBaseC FileFormatRawBodyC::CreateInput(IStreamC &in,const type_info &obj_type) const { ONDEBUG(cerr << "FileFormatRawBodyC::CreateInput(IStreamC &,const type_info &), Called. \n"); if(!in.good()) return DPIPortBaseC(); if(obj_type == typeid(ImageC<ByteRGBValueC>)) return DPIImageRGBC(in); return DPIPortBaseC(); } //: Create a output port for saving. // Will create an Invalid port if not supported. DPOPortBaseC FileFormatRawBodyC::CreateOutput(OStreamC &out,const type_info &obj_type) const { ONDEBUG(cerr << "FileFormatRawBodyC::CreateOutput(OStreamC &,const type_info &), Called. \n"); if(!out.good()) return DPOPortBaseC(); if(obj_type == typeid(ImageC<ByteRGBValueC>)) return DPOImageRGBC(out); return DPOPortBaseC(); } //: Create a input port for loading from file 'filename'. // Will create an Invalid port if not supported. <p> DPIPortBaseC FileFormatRawBodyC::CreateInput(const StringC &filename,const type_info &obj_type) const { ONDEBUG(cerr << "FileFormatRawBodyC::CreateInput(const StringC &,const type_info &), Called. \n"); if(obj_type != typeid(ImageC<ByteRGBValueC>)) return DPIPortBaseC(); return DPIImageRGBC(filename); } //: Create a output port for saving to file 'filename'.. // Will create an Invalid port if not supported. <p> DPOPortBaseC FileFormatRawBodyC::CreateOutput(const StringC &filename,const type_info &obj_type) const { ONDEBUG(cerr << "FileFormatRawBodyC::CreateOutput(const StringC &,const type_info &), Called. \n"); if(obj_type != typeid(ImageC<ByteRGBValueC>)) return DPOPortBaseC(); return DPOImageRGBC(filename); } //: Get prefered IO type. const type_info &FileFormatRawBodyC::DefaultType() const { return typeid(ImageC<ByteRGBValueC>); } FileFormatRawC RegisterFileFormatRaw(); }
35.214876
159
0.666041
isuhao
56fcf68c14a83e2d81bcf4fc60c0157e0e6f41ff
2,910
cpp
C++
liblumi/sources/Bmp.cpp
Rertsyd/LumiRT
d562fd786f769b385bc051e2ea8bcd26162a9dc6
[ "MIT" ]
null
null
null
liblumi/sources/Bmp.cpp
Rertsyd/LumiRT
d562fd786f769b385bc051e2ea8bcd26162a9dc6
[ "MIT" ]
null
null
null
liblumi/sources/Bmp.cpp
Rertsyd/LumiRT
d562fd786f769b385bc051e2ea8bcd26162a9dc6
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* ,, */ /* `7MMF' db `7MM"""Mq. MMP""MM""YMM */ /* MM MM `MM.P' MM `7 */ /* MM `7MM `7MM `7MMpMMMb.pMMMb. `7MM MM ,M9 MM */ /* MM MM MM MM MM MM MM MMmmdM9 MM */ /* MM , MM MM MM MM MM MM MM YM. MM */ /* MM ,M MM MM MM MM MM MM MM `Mb. MM */ /* .JMMmmmmMMM `Mbod"YML..JMML JMML JMML..JMML..JMML. .JMM. .JMML. */ /* */ /* ************************************************************************** */ #include <fstream> #include "Bmp.hpp" Bmp::Bmp() : FHeader(), IHeader(), Data(nullptr) { memset(&FHeader, 0u, sizeof(FHeader)); memset(&IHeader, 0u, sizeof(InfoHeader)); } void Bmp::InitHeader(const uint32_t width, const uint32_t height) { IHeader.Size = 40u; IHeader.Width = width; IHeader.Height = height; IHeader.Planes = 1u; IHeader.BitCount = 24u; IHeader.SizeImage = width * height * (IHeader.BitCount / 8u); Data.reset(new uint8_t[IHeader.SizeImage]); memset(Data.get(), 0x00u, IHeader.SizeImage); FHeader[0] = 'B'; FHeader[1] = 'M'; // OffBits FHeader[10] = static_cast<uint8_t>(54u); // Size const uint32_t sz = IHeader.SizeImage + FHeader[10]; FHeader[2] = sz & 0xFFu; FHeader[3] = (sz >> 8u) & 0xFFu; FHeader[4] = (sz >> 16u) & 0xFFu; FHeader[5] = (sz >> 24u) & 0xFFu; } void Bmp::Save(const char* path) { std::ofstream ofs(path, std::ios::binary); ofs.write(reinterpret_cast<char*>(FHeader), sizeof(FHeader)); ofs.write(reinterpret_cast<char*>(&IHeader), sizeof(InfoHeader)); const uint32_t bytesPerPixel = IHeader.BitCount / 8u; const uint32_t sizeLine = IHeader.Width * bytesPerPixel; const uint32_t padding = (4u - ((3u * IHeader.Width) % 4u)) % 4u; const char paddingData[4] = { 0x00, 0x00, 0x00, 0x00 }; for (uint32_t i = 0; i < IHeader.Height; ++i) { const uint8_t* ptr = &(Data.get()[(sizeLine * (IHeader.Height - i - 1u))]); ofs.write(reinterpret_cast<const char*>(ptr), sizeof(uint8_t) * sizeLine); ofs.write(paddingData, padding); } ofs.close(); } void Bmp::PutPixel(const uVec2 coord, const RGBColor clr) const { const uint32_t bytesPerPixel = IHeader.BitCount / 8u; const uint32_t sizeLine = IHeader.Width * bytesPerPixel; const uint32_t id = ((coord.y * sizeLine) + coord.x * bytesPerPixel); Data.get()[id + 2] = (clr.red >= 255.) ? 255u : static_cast<uint8_t>(clr.red); Data.get()[id + 1] = (clr.green >= 255.) ? 255u : static_cast<uint8_t>(clr.green); Data.get()[id] = (clr.blue >= 255.) ? 255u : static_cast<uint8_t>(clr.blue); }
35.060241
83
0.521993
Rertsyd
56fcfdbb0ae5310cd0986c36752dd5a390749e89
619
cpp
C++
MeetingCodes/Meeting3/Main.cpp
SubhoB/spectre-cpp-basics
0f581b879e83e88d1491b31e22aa447419d471a3
[ "MIT" ]
15
2020-06-01T19:48:57.000Z
2021-11-01T07:33:42.000Z
MeetingCodes/Meeting3/Main.cpp
SubhoB/spectre-cpp-basics
0f581b879e83e88d1491b31e22aa447419d471a3
[ "MIT" ]
1
2020-06-02T02:43:41.000Z
2020-06-02T03:55:50.000Z
MeetingCodes/Meeting3/Main.cpp
SubhoB/spectre-cpp-basics
0f581b879e83e88d1491b31e22aa447419d471a3
[ "MIT" ]
6
2020-06-23T22:36:56.000Z
2021-06-14T14:46:49.000Z
#include <iomanip> #include <iostream> #include "Rectangle.hpp" int main() { const Rectangle rect{4.0, 3.0}; Rectangle rect2{5.0, 6.0}; double x{4.0}; std::cout << std::setprecision(15) << std::fixed; std::cout << "Width of rect: " << rect.width() << "\n"; std::cout << "Width of height: " << rect.height() << "\n"; std::cout << "Perimeter of rect: " << rect.perimeter() << "\n"; std::cout << "Perimeter of rect2: " << rect2.evil_perimeter() << "\n"; std::cout << "Perimeter of rect2: " << rect2.evil_perimeter() << "\n"; std::cout << "Number of sides: " << rect.number_of_sides() << "\n"; }
26.913043
72
0.576737
SubhoB
56fdbfa78f19867040146caaace61c11befddabc
683
cpp
C++
Backdoor.Win32.Chode/modSettings.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
2
2021-02-04T06:47:45.000Z
2021-07-28T10:02:10.000Z
Backdoor.Win32.Chode/modSettings.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
Backdoor.Win32.Chode/modSettings.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
// modSettings.cpp : implementation file #include "stdafx.h" #include "modRewjgistry.h" //{{ChodeBot_Includes(CmodSettings) //}}ChodeBot_Includes #include "modSettings.h" bool GetSettingBool(CString& strName) { bool GetSettingBool = false; return GetSettingBool; } int GetSettingLong(CString& strName) { int GetSettingLong = 0; return GetSettingLong; } CString GetSetting(CString& strName) { CString GetSetting = "?"; return GetSetting; } void SaveSetting(CString& strName, CString strValue) { } short WriteINI(CString strSectionHeader, CString strVariableName, CString strValue, CString strFileName) { short WriteINI = 0; return WriteINI; } void GetSettings() { }
15.883721
104
0.758419
010001111
71013b7efd4b207eceb702a0be624e2ba7cf9f0c
15,904
cpp
C++
src/gpu_api/AmdgpuApi.cpp
DavHau/Riner
f9e9815b713572f03497f0e4e66c3f82a0241b66
[ "MIT" ]
4
2019-07-24T03:24:08.000Z
2022-03-04T07:41:08.000Z
src/gpu_api/AmdgpuApi.cpp
DavHau/Riner
f9e9815b713572f03497f0e4e66c3f82a0241b66
[ "MIT" ]
3
2019-07-30T22:10:39.000Z
2020-06-15T15:57:08.000Z
src/gpu_api/AmdgpuApi.cpp
DavHau/Riner
f9e9815b713572f03497f0e4e66c3f82a0241b66
[ "MIT" ]
6
2019-07-30T21:33:07.000Z
2022-03-21T20:53:11.000Z
#include "AmdgpuApi.h" #include <climits> #include <cstdio> #ifdef __linux__ #include <sys/types.h> #include <dirent.h> #endif namespace riner { static optional<int> getCurrentDpmFreq(std::fstream &file) { optional<int> freq = nullopt; if (file.is_open()) { file.clear(); file.seekg(0); std::string table(std::istreambuf_iterator<char>(file), {}); auto end_pos = table.find('*'); if (end_pos != std::string::npos) { auto start_pos = table.rfind('\n', end_pos); if (start_pos == std::string::npos) start_pos = 0; else start_pos++; int tmp; if (sscanf(table.data() + start_pos, "%*d: %dMHz", &tmp) == 1) freq = tmp; } } return freq; } template<typename T = int, typename Stream = std::ifstream> static optional<T> getIntFromFile(Stream &file) { optional<T> value = nullopt; if (file.is_open()) { file.clear(); file.seekg(0); T tmp; file >> tmp; if (!file.fail()) value = tmp; } return value; } static bool writeToFile(std::fstream &file, const std::string &str) { bool success = file.is_open(); if (success) { file.clear(); file.seekp(0); file << str << std::endl; success = file.good(); } return success; } bool AmdgpuApi::setPowerstateRange(AmdgpuApi::frequency_settings &settings, int begin, int end) { bool success = true; std::stringstream ss; end = std::min(end, (int) settings.table.size()); for (int state = begin; state < end; state++) ss << state << " "; std::string output = ss.str(); if (!output.empty()) { output.resize(output.size() - 1); success = writeToFile(settings.dpm, output); } return success; } bool AmdgpuApi::applyPowerplaySettings(AmdgpuApi::frequency_settings &settings, int *pMaxState) { bool isSet = !settings.freqTarget.has_value(); int maxState = settings.table.size(); if (readOnly || maxState == 0) return false; bool success = true; for (int state = 0; state < maxState; state++) { std::stringstream ss; const auto &entry = settings.table[state]; int newFreq = entry.freq; if (!isSet && (newFreq >= *settings.freqTarget || state == maxState - 1)) { isSet = true; maxState = state + 1; newFreq = *settings.freqTarget; } ss << settings.type << ' ' << state << " " << (newFreq - (state > 0)); if (entry.vddc.has_value()) { int voltage = std::min(*entry.vddc, vddcTarget.value_or(INT_MAX)); if (entry.measuredVddc.has_value() && *entry.measuredVddc < voltage) voltage = *entry.vddc; ss << " " << voltage; } success &= writeToFile(vddcTable, ss.str()); } if (pMaxState != nullptr) *pMaxState = maxState; else { success &= writeToFile(vddcTable, "c"); setPowerstateRange(settings, 0, maxState); } return success; } bool AmdgpuApi::setPowerProfile(const std::string &mode) { std::fstream file(pciePath + "power_dpm_force_performance_level"); return writeToFile(file, mode); } bool AmdgpuApi::setFanProfile(int profile) { std::fstream file(hwmonPath + "pwm1_enable"); return writeToFile(file, std::to_string(profile)); } optional<int> AmdgpuApi::getEngineClock() { optional<int> freqMhz; optional<uint32_t> freqHz = getIntFromFile<uint32_t>(sclk.currentFreq); if (freqHz) freqMhz = (*freqHz + 500000U) / 1000000U; else freqMhz = getCurrentDpmFreq(sclk.dpm); return freqMhz; } optional<int> AmdgpuApi::getMemoryClock() { optional<int> freqMhz; optional<uint32_t> freqHz = getIntFromFile<uint32_t>(mclk.currentFreq); if (freqHz) freqMhz = (*freqHz + 500000U) / 1000000U; else freqMhz = getCurrentDpmFreq(mclk.dpm); return freqMhz; } optional<int> AmdgpuApi::getVoltage() { return getIntFromFile(voltage); } optional<int> AmdgpuApi::getTemperature() { auto t = getIntFromFile(temp); if (t) t = (*t + 500) / 1000; return t; } optional<int> AmdgpuApi::getFanPercent() { auto pwm = getIntFromFile(fanPwm); if (pwm) pwm = (*pwm + 127) / 255; return pwm; } optional<int> AmdgpuApi::getFanRpm() { return getIntFromFile(fanRpm); } optional<int> AmdgpuApi::getPower() { auto p = getIntFromFile(power); if (p) p = (*p + 500000) / 1000000; return p; } optional<int> AmdgpuApi::getTdp() { auto tdp = getIntFromFile(powerCap); if (tdp) tdp = (*tdp + 500000) / 1000000; return tdp; } bool AmdgpuApi::setEngineClock(int freq) { VLOG(4) << "[AmdgpuApi] set core clock to " << freq << "MHz"; std::call_once(manualPowerProfile, &AmdgpuApi::setPowerProfile, this, "manual"); freq = std::min(std::max(sclk.range.first, freq), sclk.range.second); if (sclk.freqTarget.has_value() && *sclk.freqTarget == freq) return true; optional<int> oldFreq = sclk.freqTarget; setPowerstateRange(sclk, 0, 1); sclk.freqTarget = freq; bool success = applyPowerplaySettings(sclk); if (!success) sclk.freqTarget = oldFreq; return success; } bool AmdgpuApi::setMemoryClock(int freq) { VLOG(4) << "[AmdgpuApi] set memory clock to " << freq << "MHz"; std::call_once(manualPowerProfile, &AmdgpuApi::setPowerProfile, this, "manual"); freq = std::min(std::max(mclk.range.first, freq), mclk.range.second); if (mclk.freqTarget.has_value() && *mclk.freqTarget == freq) return true; optional<int> oldFreq = mclk.freqTarget; mclk.freqTarget = freq; bool success = applyPowerplaySettings(mclk); if (!success) mclk.freqTarget = oldFreq; return success; } bool AmdgpuApi::setVoltage(int voltage) { VLOG(4) << "[AmdgpuApi] set voltage to " << voltage << "mV"; std::call_once(manualPowerProfile, &AmdgpuApi::setPowerProfile, this, "manual"); voltage = std::min(std::max(vddcRange.first, voltage), vddcRange.second); if (vddcTarget.has_value() && *vddcTarget == voltage) return true; optional<int> oldVddc = vddcTarget; vddcTarget = voltage; setPowerstateRange(sclk, 0, 1); int maxMclkState = 0; bool success = applyPowerplaySettings(mclk, &maxMclkState) && applyPowerplaySettings(sclk); if (!success) vddcTarget = oldVddc; else setPowerstateRange(mclk, 0, maxMclkState); return success; } bool AmdgpuApi::setFanPercent(int percent) { VLOG(4) << "[AmdgpuApi] set fan to " << percent << "%"; std::call_once(manualFan, &AmdgpuApi::setFanProfile, this, 1); return writeToFile(fanPwm, std::to_string((255 * percent + 50) / 100)); } bool AmdgpuApi::setTdp(int tdp) { VLOG(4) << "[AmdgpuApi] set TDP to " << tdp << "W"; return writeToFile(powerCap, std::to_string(1000000 * tdp)); } AmdgpuApi::~AmdgpuApi() { if (pciePath.empty()) return; setFanProfile(2); // switch to automatic fan if (tdp) setTdp(*tdp); setPowerstateRange(sclk, 0, 1); setPowerstateRange(mclk, 0, 1); writeToFile(vddcTable, "r"); writeToFile(vddcTable, "c"); // reset PowerplayTable setPowerstateRange(sclk, 0); setPowerstateRange(mclk, 0); setPowerProfile("auto"); } std::unique_ptr<GpuApi> AmdgpuApi::tryMake(const GpuApiConstructionArgs &args) { #ifdef __linux__ auto api = std::unique_ptr<AmdgpuApi>(new AmdgpuApi()); if (auto optPciId = args.id.getIfPcieIndex()) { char path[128]{0}; const auto &pciId = *optPciId; std::snprintf(path, sizeof(path), "/sys/bus/pci/devices/%.4x:%.2x:%.2x.%.1x/", pciId.segment, pciId.bus, pciId.device, pciId.function); api->pciePath = path; std::memcpy(path + api->pciePath.size(), "hwmon", 6); DIR *hwmonDir = opendir(path); struct dirent *hwmonDirent; while (hwmonDir != nullptr && (hwmonDirent = readdir(hwmonDir)) != nullptr) { if (hwmonDirent->d_type == DT_DIR && !strncmp("hwmon", hwmonDirent->d_name, 5)) { api->hwmonPath = api->pciePath + "hwmon/" + hwmonDirent->d_name + "/"; break; } } if (hwmonDir != nullptr) closedir(hwmonDir); if (api->hwmonPath.empty()) return nullptr; std::ifstream nameFile(api->hwmonPath + "name"); std::string name; if (nameFile.good()) std::getline(nameFile, name); if (name != "amdgpu") return nullptr; api->fanRpm.open(api->hwmonPath + "fan1_input"); api->temp.open(api->hwmonPath + "temp1_input"); api->power.open(api->hwmonPath + "power1_average"); api->voltage.open(api->hwmonPath + "in0_input"); api->sclk.currentFreq.open(api->hwmonPath + "freq1_input"); api->mclk.currentFreq.open(api->hwmonPath + "freq2_input"); api->sclk.dpm.open(api->pciePath + "pp_dpm_sclk"); if (!api->sclk.dpm.is_open()) { api->sclk.dpm.open(api->pciePath + "pp_dpm_sclk", std::fstream::in); // read only api->readOnly |= api->sclk.dpm.is_open(); } api->mclk.dpm.open(api->pciePath + "pp_dpm_mclk"); if (!api->mclk.dpm.is_open()) { api->mclk.dpm.open(api->pciePath + "pp_dpm_mclk", std::fstream::in); // read only api->readOnly |= api->mclk.dpm.is_open(); } api->vddcTable.open(api->pciePath + "pp_od_clk_voltage"); api->fanPwm.open(api->hwmonPath + "pwm1"); if (!api->fanPwm.is_open()) { api->fanPwm.open(api->hwmonPath + "pwm1", std::fstream::in); // read only api->readOnly |= api->fanPwm.is_open(); } api->powerCap.open(api->hwmonPath + "power1_cap"); if (!api->powerCap.is_open()) { api->powerCap.open(api->hwmonPath + "power1_cap", std::fstream::in); // read only api->readOnly |= api->powerCap.is_open(); } std::string line; if (api->vddcTable.is_open()) { api->setPowerProfile("manual"); enum Stage { UNDEFINED, SCLK, MCLK, RANGE } stage = UNDEFINED; while (std::getline(api->vddcTable, line)) { int idx, freq, voltage; int min, max; optional<int> realVoltage; std::vector<table_entry> *table = nullptr; if (line == "OD_SCLK:") stage = SCLK; else if (line == "OD_MCLK:") stage = MCLK; else if (line == "OD_RANGE:") stage = RANGE; else { switch (stage) { case SCLK: table = &api->sclk.table; setPowerstateRange(api->sclk, table->size(), table->size() + 1); realVoltage = nullopt; // TODO: check whether api->getVoltage() to set optimized voltages if (realVoltage) realVoltage = *realVoltage + *realVoltage / 50; // add ~2 percent break; case MCLK: table = &api->mclk.table; break; case RANGE: if (sscanf(line.c_str(), "SCLK: %dMHz %dMHz", &min, &max) == 2) api->sclk.range = std::make_pair(min, max); else if (sscanf(line.c_str(), "MCLK: %dMHz %dMHz", &min, &max) == 2) api->mclk.range = std::make_pair(min, max); else if (sscanf(line.c_str(), "VDDC: %dmV %dmV", &min, &max) == 2) api->vddcRange = std::make_pair(min, max); else { LOG(WARNING) << "[AmdgpuApi] Error while parsing OD_RANGE in " << api->pciePath << "pp_od_clk_voltage"; stage = UNDEFINED; } break; default: break; } if (table != nullptr) { if (sscanf(line.c_str(), "%d: %dMHz %dmV", &idx, &freq, &voltage) == 3 && idx == table->size()) { table->emplace_back(table_entry{freq, voltage, realVoltage}); VLOG(4) << "[AmdgpuApi] " << (stage == SCLK ? "SCLK[" : "MCLK[") << idx << "]: " << voltage << "mV / " << realVoltage.value_or(-1) << "mV"; } else { LOG(WARNING) << "[AmdgpuApi] Error while parsing " << api->pciePath << "pp_od_clk_voltage"; stage = UNDEFINED; } } } } api->setPowerProfile("auto"); setPowerstateRange(api->sclk, 0); } else { while (std::getline(api->sclk.dpm, line)) { int idx, freq; if (sscanf(line.c_str(), "%d: %dMHz", &idx, &freq) == 2 && idx == api->sclk.table.size()) { api->sclk.table.emplace_back(table_entry{freq}); } else { LOG(WARNING) << "[AmdgpuApi] Error while parsing " << api->pciePath << "pp_dpm_sclk"; break; } } while (std::getline(api->mclk.dpm, line)) { int idx, freq; if (sscanf(line.c_str(), "%d: %dMHz", &idx, &freq) == 2 && idx == api->mclk.table.size()) { api->mclk.table.emplace_back(table_entry{freq}); } else { LOG(WARNING) << "[AmdgpuApi] Error while parsing " << api->pciePath << "pp_dpm_mclk"; break; } } } api->tdp = api->getTdp(); LOG(INFO) << "device " << api->pciePath.data() << " has sysfs API"; return api; } #endif VLOG(2) << "device has no sysfs API"; return nullptr; } }
39.859649
171
0.487676
DavHau
71045a5127c78b16379afa0ea5c27e8be27cafa8
4,913
cpp
C++
Source/WinWakerLib/codec.cpp
bingart/WinWaker
dc3f6c067a5f215c17aa2e0c3386f92f158ec941
[ "Apache-2.0" ]
null
null
null
Source/WinWakerLib/codec.cpp
bingart/WinWaker
dc3f6c067a5f215c17aa2e0c3386f92f158ec941
[ "Apache-2.0" ]
null
null
null
Source/WinWakerLib/codec.cpp
bingart/WinWaker
dc3f6c067a5f215c17aa2e0c3386f92f158ec941
[ "Apache-2.0" ]
null
null
null
#include <windows.h> #include <io.h> #include <string> #include "scrambler.h" #include "base64.h" #include "codec.h" #include "easylog.hpp" #include "libstr.h" #include "key.h" #define MAX_CODEC_LENGTH 20480000 #define MOD 13 BOOL Encode(const char* exe_file_path, const char* txt_file_path) { FILE* in = NULL; FILE* out = NULL; int rc = -1; do { in = fopen(exe_file_path, "rb"); if (in == NULL) { // "encode file fail, open exe file %s error\n" EasyLog::Format(GetLibStrById(401), exe_file_path); break; } out = fopen(txt_file_path, "w"); if (out == NULL) { // "encode file fail, open txt file %s error\n" EasyLog::Format(GetLibStrById(402), txt_file_path); break; } // Write KEY at fist line // "%d\n" fprintf(out, GetLibStrById(552), KEY); char ibuffer[BLOCK_SIZE]; char obuffer[2*BLOCK_SIZE]; rc = 0; while (!feof(in) && rc >= 0) { memset(ibuffer, 0, sizeof ibuffer); memset(obuffer, 0, sizeof obuffer); size_t len = fread(ibuffer, 1, BLOCK_SIZE, in); if (len > 0) { // encrypt for (size_t i = 0; i < len; i++) { ibuffer[i] = ibuffer[i] ^ (i % MOD) ^ KEY; } // convert to base64 rc = encode64(obuffer, sizeof obuffer, ibuffer, len); if (rc > 0) { // write into txt file // "%s\n" fprintf(out, GetLibStrById(403), obuffer); } else if (rc == 0) { // "encode file, encode64 rc %d\n" EasyLog::Format(GetLibStrById(404), rc); } else { // "encode file fails, encode64 rc %d < 0\n" EasyLog::Format(GetLibStrById(405), rc); break; } } } } while (FALSE); // close files if (in != NULL) fclose(in); if (out != NULL) { _commit(_fileno(out)); fclose(out); } return rc >= 0; } BOOL Decode(const char* txt_file_path, const char* exe_file_path) { FILE* in = NULL; FILE* out = NULL; char* cache = NULL; // cache int total_length = 0; int key = 0; do { in = fopen(txt_file_path, "r"); if (in == NULL) { // "decode file fail, open txt file %s error\n" EasyLog::Format(GetLibStrById(406), txt_file_path); break; } out = fopen(exe_file_path, "wb"); if (out == NULL) { // "decode file fail, open exe file %s error\n" EasyLog::Format(GetLibStrById(407), exe_file_path); break; } char ibuffer[2*BLOCK_SIZE]; char obuffer[2*BLOCK_SIZE]; cache = new char [MAX_CODEC_LENGTH]; // Read key from first line bool keyFound = false; if (!feof(in)) { memset(ibuffer, 0, sizeof ibuffer); char* str = fgets(ibuffer, sizeof ibuffer, in); if (str != NULL) { size_t len2 = strlen(ibuffer); // remove the line feed ibuffer[len2 - 1] = '\0'; key = atoi(ibuffer); } } if (key == 0) { // "decode fails, key not fould\n" EasyLog::Format(GetLibStrById(553)); } while (!feof(in) && total_length < MAX_CODEC_LENGTH) { memset(ibuffer, 0, sizeof ibuffer); memset(obuffer, 0, sizeof obuffer); char* str = fgets(ibuffer, sizeof ibuffer, in); if (str != NULL) { size_t len2 = strlen(ibuffer); // remove the line feed ibuffer[len2 - 1] = '\0'; // revert base64 int rc = decode64(obuffer, sizeof obuffer, ibuffer, strlen(ibuffer)); if (rc > 0) { memcpy(cache + total_length, obuffer, rc); total_length += rc; // Decrypt for (size_t i = 0; i < rc; i++) { obuffer[i] = obuffer[i] ^ (i % MOD) ^ (key & 0xff); } fwrite(obuffer, 1, rc, out); } else if (rc == 0) { // "decode file, decode64 rc %d\n" EasyLog::Format(GetLibStrById(408), rc); } else { // "decode file fails, decode64 rc %d < 0\n" EasyLog::Format(GetLibStrById(409), rc); break; } } } } while (FALSE); if (cache != NULL) { delete []cache; } // close files if (in != NULL) fclose(in); if (out != NULL) { fflush(out); _commit(_fileno(out)); fclose(out); } return total_length > 0 && total_length < MAX_CODEC_LENGTH; } BOOL DecodePHP(std::string szSrcLine, std::string& szDstLine) { char buffer[1024] = {0}; char buffer2[1024] = {0}; // Decode base64 memset(buffer, 0, sizeof buffer); int rc = decode64(buffer, sizeof buffer, szSrcLine.c_str(), szSrcLine.size()); if (rc <= 6) { // prefix + suffix return FALSE; } // Remove prefix and suffix memset(buffer2, 0, sizeof buffer2); memcpy(buffer2, buffer + 3, rc - 6); // Decode base64 memset(buffer, 0, sizeof buffer); rc = decode64(buffer, sizeof buffer, buffer2, rc - 6); if (rc <= 6) { // prefix + suffix return FALSE; } // Remove prefix and suffix memset(buffer2, 0, sizeof buffer2); memcpy(buffer2, buffer + 3, rc - 6); // Decode base64 memset(buffer, 0, sizeof buffer); rc = decode64(buffer, sizeof buffer, buffer2, rc - 6); if (rc <= 0) { // prefix + suffix return FALSE; } // Output szDstLine = buffer; return TRUE; }
19.34252
79
0.594342
bingart
7104938da106909fca42fe6914e1336cb08b4fb8
2,416
cpp
C++
solutions/course-schedule-ii/solution.cpp
locker/leetcode
bf34a697de47aaf32823224d054f9a45613ce180
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
solutions/course-schedule-ii/solution.cpp
locker/leetcode
bf34a697de47aaf32823224d054f9a45613ce180
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
solutions/course-schedule-ii/solution.cpp
locker/leetcode
bf34a697de47aaf32823224d054f9a45613ce180
[ "BSD-2-Clause-FreeBSD" ]
1
2019-08-30T06:53:23.000Z
2019-08-30T06:53:23.000Z
#include <iostream> #include <queue> #include <utility> #include <vector> using namespace std; template<typename T> ostream& operator<<(ostream& out, const vector<T>& v) { out << '['; for (auto it = v.begin(); it != v.end(); ++it) { if (it != v.begin()) out << ','; out << *it; } out << ']'; return out; } class Solution { public: vector<int> findOrder(int count, const vector<vector<int>>& prerequisites) { // // What we have is a graph in which vertexes represent courses // and edges represent dependencies: there's an edge coming // from vertex i to vertex j iff course i depends on course j. // The algorithm is trivial: // // 1. Take any vertex which doesn't any incoming edges // (a course that doesn't depend on any other course). // 2. Remove the vertex and all edges originating from it. // 3. Add the course corresponding to the vertex to the // resulting schedule. // 4. Unless the graph is empty, go to step 1. // // Map: vertex i => array of vertexes j such that there's // an edge coming from i to j. vector<vector<int>> edges(count); // Map: vertex i => number of incoming edges. vector<int> order(count); for (const auto& it: prerequisites) { edges[it[1]].push_back(it[0]); ++order[it[0]]; } queue<int> todo; for (int i = 0; i < count; ++i) { if (order[i] == 0) todo.push(i); } vector<int> schedule; schedule.reserve(count); while (!todo.empty()) { auto i = todo.front(); todo.pop(); for (auto j: edges[i]) { if (--order[j] == 0) todo.push(j); } schedule.push_back(i); } if (static_cast<int>(schedule.size()) < count) { // Looks like there's a cycle in the graph // hence there's no schedule such that all // courses are finished. schedule.clear(); } return schedule; } }; int main() { pair<int, vector<vector<int>>> input[] = { {1, {{0,0}}}, // [] {2, {{1,0}}}, // [0,1] {2, {{1,0},{0,1}}}, // [] {3, {{1,0},{2,0},{2,1}}}, // [0,1,2] {3, {{1,0},{0,2},{2,1}}}, // [] {4, {{1,0},{3,1},{3,2},{3,0}}}, // [0,2,1,3] {4, {{1,0},{2,1},{3,2},{1,3}}}, // [] }; Solution solution; for (const auto& p: input) { auto count = p.first; const auto& prerequisites = p.second; auto order = solution.findOrder(count, prerequisites); cout << "Input: " << count << ", " << prerequisites << endl << "Output: " << order << endl; } return 0; }
24.16
77
0.577815
locker
710508bb4cb3f037bb877de0dfb45bf0e516d871
439
cc
C++
fft/utils/Signals.cc
ddamiani/fft-tests
5f119271c12b4a8ae1caf3edb7c727d59d4f2170
[ "BSD-3-Clause" ]
null
null
null
fft/utils/Signals.cc
ddamiani/fft-tests
5f119271c12b4a8ae1caf3edb7c727d59d4f2170
[ "BSD-3-Clause" ]
null
null
null
fft/utils/Signals.cc
ddamiani/fft-tests
5f119271c12b4a8ae1caf3edb7c727d59d4f2170
[ "BSD-3-Clause" ]
null
null
null
#include "Signals.hh" #define _USE_MATH_DEFINES #include <cmath> void fft::math::signal(double& re, double& im, double frac) { double theta = frac * M_PI; re = 1.0 * std::cos(10.0 * theta) +0.5 * std::cos(25.0 * theta); im = 1.0 * std::sin(10.0 * theta) +0.5 * std::sin(25.0 * theta); }
54.875
308
0.412301
ddamiani
71051b2400d6e0116bd99945bfa47dd6f5794812
2,391
cpp
C++
Source/Pineapple/Engine/Graphics/TextureAtlas.cpp
JoshYaxley/Pineapple
490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec
[ "Zlib" ]
11
2017-04-15T14:44:19.000Z
2022-02-04T13:16:04.000Z
Source/Pineapple/Engine/Graphics/TextureAtlas.cpp
JoshYaxley/Pineapple
490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec
[ "Zlib" ]
25
2017-04-19T12:48:42.000Z
2020-05-09T05:28:29.000Z
Source/Pineapple/Engine/Graphics/TextureAtlas.cpp
JoshYaxley/Pineapple
490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec
[ "Zlib" ]
1
2019-04-21T21:14:04.000Z
2019-04-21T21:14:04.000Z
/*------------------------------------------------------------------------------ Pineapple Game Engine - Copyright (c) 2011-2017 Adam Yaxley This software is licensed under the Zlib license (see license.txt for details) ------------------------------------------------------------------------------*/ #include <Pineapple/Engine/Graphics/Texture.h> #include <Pineapple/Engine/Graphics/TextureAtlas.h> #include <Pineapple/Engine/Platform/Platform.h> #include <rapidjson/document.h> #include <rapidjson/rapidjson.h> struct pa::Document { rapidjson::Document json; }; pa::TextureAtlas::TextureAtlas(std::shared_ptr<pa::Texture> texture, const pa::FilePath& path) : m_texture(texture) , m_isLoaded(false) , m_path(path) { m_document = std::make_unique<pa::Document>(); } pa::TextureAtlas::~TextureAtlas() { } bool pa::TextureAtlas::load() { std::string contents; { pa::FileBuffer buffer; auto result = m_path.read(buffer); if (result != pa::FileResult::Success) { pa::Log::info("{}: {}", pa::FileSystem::getResultString(result), m_path.asString()); return false; } contents = buffer.createString(); } // Load json m_document->json.Parse<0>(contents.c_str()); if (m_document->json.HasParseError()) { pa::Log::info("Failed to parse {}, error was: {}", m_path.asString(), m_document->json.GetParseError()); m_isLoaded = false; } else { m_isLoaded = true; } return m_isLoaded; } std::shared_ptr<pa::Texture> pa::TextureAtlas::createTexture(const char* filename) { PA_ASSERTF(m_isLoaded, "You must load a texture atlas first."); if (m_document->json.IsObject()) { if (m_document->json.HasMember("frames")) { rapidjson::Value& frames = m_document->json["frames"]; if (frames.IsArray()) { // find path for (unsigned int i = 0; i < frames.Size(); i++) { rapidjson::Value& element = frames[i]; if (element.HasMember("filename")) { const char* elementFilename = element["filename"].GetString(); if (strcmp(elementFilename, filename) == 0) { // Same! Load this information rapidjson::Value& frame = element["frame"]; int x = frame["x"].GetInt(); int y = frame["y"].GetInt(); int w = frame["w"].GetInt(); int h = frame["h"].GetInt(); return m_texture->createTexture({ x, y }, { w, h }); } } } } } } return nullptr; }
24.397959
106
0.60435
JoshYaxley
7106db184bf174c54734760b9d196b1e6e9221ef
1,121
cpp
C++
C-PhotoDeal_level2_APP/C-PhotoDeal_level2/main.cpp
numberwolf/iOSDealFace
5a109690d143ac125a4b679a8ea6ef28a9f147e3
[ "Apache-2.0" ]
8
2016-03-12T08:39:56.000Z
2021-07-12T01:48:20.000Z
C-PhotoDeal_level2_APP/C-PhotoDeal_level2/main.cpp
numberwolf/iOSDealFace
5a109690d143ac125a4b679a8ea6ef28a9f147e3
[ "Apache-2.0" ]
null
null
null
C-PhotoDeal_level2_APP/C-PhotoDeal_level2/main.cpp
numberwolf/iOSDealFace
5a109690d143ac125a4b679a8ea6ef28a9f147e3
[ "Apache-2.0" ]
2
2016-03-15T09:48:38.000Z
2017-02-04T23:53:32.000Z
// // main.cpp // C-PhotoDeal_level2 // // Created by numberwolf on 2016/10/12. // Copyright © 2016年 numberwolf. All rights reserved. // #include <iostream> #include "canny_door.hpp" #include "numberPhoto.hpp" #include "tess_ocr.hpp" using namespace cv; using namespace std; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; char *path = "/Users/numberwolf/Documents/XCode&C++/C-PhotoDeal/C-PhotoDeal_level2_APP/img/cro.jpg"; // canny_door *CannyDoor = new canny_door(path); IplImage *ColorImage = cvLoadImage(path); int height = ColorImage->height; int width = ColorImage->width; // numberPhoto::sobelCanny(ColorImage, width, height); // numberPhoto::otsuBinary(ColorImage, width, height, false, 80, 80); // numberPhoto::method_two(ColorImage, width, height, false, 800, 800, 1); char *ocr_filename = "/Users/numberwolf/Documents/XCode&C++/C-PhotoDeal/C-PhotoDeal_level2_APP/img/testocr.png"; // tess_orc *ocr = new tess_orc(); // ocr->scan_eng_string_by_img(ocr_filename); return 0; }
28.74359
116
0.676182
numberwolf
7107d8b6fc0612ab31329ef5ffb946698aa3226f
2,332
cpp
C++
tests/cxx/isce3/focus/presum.cpp
isce3-testing/isce3-circleci-poc
ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3
[ "Apache-2.0" ]
64
2019-08-06T19:22:22.000Z
2022-03-20T17:11:46.000Z
tests/cxx/isce3/focus/presum.cpp
isce-framework/isce3
59cdd2c659a4879367db5537604b0ca93d26b372
[ "Apache-2.0" ]
8
2020-09-01T22:46:53.000Z
2021-11-04T00:05:28.000Z
tests/cxx/isce3/focus/presum.cpp
isce-framework/isce3
59cdd2c659a4879367db5537604b0ca93d26b372
[ "Apache-2.0" ]
29
2019-08-05T21:40:55.000Z
2022-03-23T00:17:03.000Z
#include <gtest/gtest.h> #include <isce3/core/Kernels.h> #include <isce3/focus/Presum.h> TEST(Presum, Domain) { // Check that coefficients cover the expected domain. long n = 10, offset = 0; // set up a time vector--uniformly sampled. std::vector<double> t(n); for (long i = 0; i < n; ++i) { t[i] = i; } // Use a dummy autocorrelation function, with width = 3. isce3::core::BartlettKernel<double> acorr(3.0); // Compute weights. { // Expect three coefficents at i = {4, 5, 6} auto coeff = isce3::focus::getPresumWeights(acorr, t, 5.0, &offset); EXPECT_EQ(coeff.size(), 3); EXPECT_EQ(offset, 4); } { // Ask for an output exactly between two points. // Expect an extra coeff (four) at i = {4, 5, 6, 7} auto coeff = isce3::focus::getPresumWeights(acorr, t, 5.5, &offset); EXPECT_EQ(coeff.size(), 4); EXPECT_EQ(offset, 4); } } TEST(Presum, Values) { // Check that coefficients have the expected values. long n = 10, offset = 0; // set up a time vector--uniformly sampled. Eigen::VectorXd t(n); for (long i = 0; i < n; ++i) { t[i] = i; } // Use a dummy autocorrelation function, with width = 3. isce3::core::BartlettKernel<double> acorr(3.0); // Compute weights. { // Expect three coefficents at i = {4, 5, 6} // with values {0, 1, 0} auto coeff = isce3::focus::getPresumWeights(acorr, t, 5.0, &offset); EXPECT_DOUBLE_EQ(coeff(0), 0.0); EXPECT_DOUBLE_EQ(coeff(1), 1.0); EXPECT_DOUBLE_EQ(coeff(2), 0.0); EXPECT_EQ(coeff.size(), 3); EXPECT_EQ(offset, 4); } // TODO more general example? } TEST(Presum, NoData) { // Check behavior for a gap too large. // Data correlated on interval [-L,L] const double L = 1.0; isce3::core::AzimuthKernel<double> acorr(L); // Only have two data points, separated by more than that. std::vector<double> t {0.0, 10 * L}; long offset = -1; auto coeffs = isce3::focus::getPresumWeights(acorr, t, 5 * L, &offset); EXPECT_EQ(coeffs.size(), 0); EXPECT_GE(offset, 0); EXPECT_LT(offset, t.size()); } int main(int argc, char * argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
27.761905
76
0.588336
isce3-testing
7108d320e449735ac0586fe26b0123887828fa19
3,425
cpp
C++
test/variant.cpp
jmairboeck/PTL
fed731de5cf73219fad1f2006e2978d981c02535
[ "BSL-1.0" ]
null
null
null
test/variant.cpp
jmairboeck/PTL
fed731de5cf73219fad1f2006e2978d981c02535
[ "BSL-1.0" ]
null
null
null
test/variant.cpp
jmairboeck/PTL
fed731de5cf73219fad1f2006e2978d981c02535
[ "BSL-1.0" ]
null
null
null
// Copyright Michael Florian Hava. // 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) #include <boost/test/unit_test.hpp> #include "ptl/variant.hpp" #include "moveable.hpp" BOOST_AUTO_TEST_SUITE(variant) BOOST_AUTO_TEST_CASE(ctor) { ptl::variant<int, double> var1; BOOST_TEST(!var1.valueless_by_exception()); BOOST_TEST(ptl::get<int>(var1) == 0); var1 = 10.; BOOST_TEST(ptl::holds_alternative<double>(var1)); BOOST_TEST(ptl::get<double>(var1) == 10.); var1 = 10; BOOST_TEST(ptl::holds_alternative<int>(var1)); BOOST_TEST(ptl::get<int>(var1) == 10); struct X { X() {} X(int, int) {} }; struct Y { Y() {} Y(int, int, int) {} }; ptl::variant<int, double, X, Y> var2{std::in_place_type<X>, 4, 5}; BOOST_TEST(ptl::holds_alternative<X>(var2)); var2.emplace<Y>(1, 2, 3); BOOST_TEST(ptl::holds_alternative<Y>(var2)); } BOOST_AUTO_TEST_CASE(copy) { ptl::variant<double, int> var{1000}; BOOST_TEST(!var.valueless_by_exception()); BOOST_TEST(!ptl::holds_alternative<double>(var)); auto copy1 = var; BOOST_TEST(!copy1.valueless_by_exception()); BOOST_TEST(!ptl::holds_alternative<double>(copy1)); BOOST_TEST(ptl::get<int>(var) == ptl::get<int>(copy1)); decltype(var) copy2; copy2 = copy1; BOOST_TEST(!copy2.valueless_by_exception()); BOOST_TEST(!ptl::holds_alternative<double>(copy2)); BOOST_TEST(ptl::get<int>(var) == ptl::get<int>(copy2)); } BOOST_AUTO_TEST_CASE(move) { using ptl::test::moveable; ptl::variant<moveable> var1; decltype(var1) var2{std::move(var1)}; BOOST_TEST( ptl::get<moveable>(var1).moved); BOOST_TEST(!ptl::get<moveable>(var2).moved); var1 = std::move(var2); BOOST_TEST(!ptl::get<moveable>(var1).moved); BOOST_TEST( ptl::get<moveable>(var2).moved); } BOOST_AUTO_TEST_CASE(visit) { ptl::variant<int, double> var; var.visit( [](int) { BOOST_TEST(true); }, [](double) { BOOST_TEST(false); } ); var = 1.5; var.visit( [](int) { BOOST_TEST(false); }, [](double) { BOOST_TEST(true); } ); BOOST_TEST(var.visit([](const auto & value) -> double { return value; }) == 1.5); var = 1; var.visit( [](int) { BOOST_TEST(true); }, [](double) { BOOST_TEST(false); } ); BOOST_TEST(var.visit([](const auto & value) -> double { return value; }) == 1.0); } BOOST_AUTO_TEST_CASE(swapping) { ptl::variant<int, double> var1{10}, var2{20.2}; BOOST_TEST(ptl::holds_alternative<int>(var1)); BOOST_TEST(ptl::holds_alternative<double>(var2)); swap(var1, var2); BOOST_TEST(ptl::holds_alternative<double>(var1)); BOOST_TEST(ptl::get<double>(var1) == 20.2); BOOST_TEST(ptl::holds_alternative<int>(var2)); BOOST_TEST(ptl::get<int>(var2) == 10); decltype(var1) var3{20}; swap(var2, var3); BOOST_TEST(ptl::holds_alternative<int>(var2)); BOOST_TEST(ptl::get<int>(var2) == 20); BOOST_TEST(ptl::holds_alternative<int>(var3)); BOOST_TEST(ptl::get<int>(var3) == 10); } BOOST_AUTO_TEST_CASE(comparison) { const ptl::variant<int, double> var1{10}, var2{10.}; BOOST_TEST(!(var1 == var2)); BOOST_TEST( var1 != var2); const auto var3{var1}; BOOST_TEST( var1 == var3); BOOST_TEST(!(var1 != var3)); BOOST_TEST( var1 < var2); BOOST_TEST(!(var1 > var2)); BOOST_TEST( var2 > var1); BOOST_TEST(!(var2 < var1)); decltype(var1) var4{1}; BOOST_TEST(var1 > var4); BOOST_TEST(var4 < var1); } BOOST_AUTO_TEST_SUITE_END()
25.94697
82
0.675912
jmairboeck
710bee79fdae07c6b845edc2546744ffc7b6daad
1,903
cpp
C++
src/examples/cpp/example-perlin.cpp
Overdrivr/ZNoise
9d3727cadb671bd4e5998e679721381812dbf007
[ "MIT" ]
27
2015-09-16T10:04:31.000Z
2021-11-12T02:46:16.000Z
src/examples/cpp/example-perlin.cpp
Overdrivr/ZNoise
9d3727cadb671bd4e5998e679721381812dbf007
[ "MIT" ]
7
2015-08-07T15:35:12.000Z
2016-12-16T03:55:17.000Z
src/examples/cpp/example-perlin.cpp
Overdrivr/ZNoise
9d3727cadb671bd4e5998e679721381812dbf007
[ "MIT" ]
4
2016-08-05T15:49:19.000Z
2017-08-03T10:53:16.000Z
#include <iostream> #include "Perlin.hpp" #include "include_all.hpp" void generate_perlin(cimg_library::CImg<unsigned char> & image) { /* Generate Perlin 2D */ Perlin perlin; perlin.Shuffle(10); for(int x = 0 ; x < image.width() ; x++) for(int y = 0 ; y < image.height() ; y++) { float value = perlin.Get({x , y},0.01f); unsigned int greyscale = static_cast<unsigned int>((value + 1.f) / 2.f * 255.f); image(x,y,0) = greyscale; image(x,y,1) = greyscale; image(x,y,2) = greyscale; } image.save("perlin2d.bmp"); std::cout<<"Saved perlin2d.bmp"<<std::endl; } void generate_perlin_3dslice(cimg_library::CImg<unsigned char> & image) { /* Generate Perlin 3D */ Perlin perlin; perlin.Shuffle(10); for(int x = 0 ; x < image.width() ; x++) for(int y = 0 ; y < image.height() ; y++) { float value = perlin.Get({x , y, 0.f},0.01f); unsigned int greyscale = static_cast<unsigned int>((value + 1.f) / 2.f * 255.f); image(x,y,0) = greyscale; image(x,y,1) = greyscale; image(x,y,2) = greyscale; } image.save("perlin3d.bmp"); std::cout<<"Saved perlin3d.bmp"<<std::endl; } void generate_perlin_4dslice(cimg_library::CImg<unsigned char> & image) { /* Generate Perlin 4D */ Perlin perlin; perlin.Shuffle(10); for(int x = 0 ; x < image.width() ; x++) for(int y = 0 ; y < image.height() ; y++) { float value = perlin.Get({x , y, 0.f, 1.f},0.01f); unsigned int greyscale = static_cast<unsigned int>((value + 1.f) / 2.f * 255.f); image(x,y,0) = greyscale; image(x,y,1) = greyscale; image(x,y,2) = greyscale; } image.save("perlin4d.bmp"); std::cout<<"Saved perlin4d.bmp"<<std::endl; }
27.185714
92
0.538623
Overdrivr
711340b5d95cde832fd8f7900d9a3eb017149ef3
845
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR/File GetAttributes/CPP/file getattributes.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_CLR/File GetAttributes/CPP/file getattributes.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_CLR/File GetAttributes/CPP/file getattributes.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// <Snippet1> using namespace System; using namespace System::IO; using namespace System::Text; int main() { String^ path = "c:\\temp\\MyTest.txt"; // Create the file if it does not exist. if ( !File::Exists( path ) ) { File::Create( path ); } if ( (File::GetAttributes( path ) & FileAttributes::Hidden) == FileAttributes::Hidden ) { // Show the file. File::SetAttributes(path, File::GetAttributes( path ) & ~FileAttributes::Hidden); Console::WriteLine( "The {0} file is no longer hidden.", path ); } else { // Hide the file. File::SetAttributes( path, static_cast<FileAttributes>(File::GetAttributes( path ) | FileAttributes::Hidden) ); Console::WriteLine( "The {0} file is now hidden.", path ); } } // </Snippet1>
25.606061
118
0.583432
hamarb123
7115ab51860209c3f30e6ca6e06bb72e15cfe21a
712
hpp
C++
include/complex.hpp
BURNINGTIGER/Complex
c87aa365aa123a89608aa176342dc4ee9db019fb
[ "MIT" ]
null
null
null
include/complex.hpp
BURNINGTIGER/Complex
c87aa365aa123a89608aa176342dc4ee9db019fb
[ "MIT" ]
null
null
null
include/complex.hpp
BURNINGTIGER/Complex
c87aa365aa123a89608aa176342dc4ee9db019fb
[ "MIT" ]
null
null
null
#include <iostream> #include <conio.h> #include <locale> using namespace std; class Complex { double rel, img; public: Complex(); Complex(double real, double imag); Complex add(const Complex) const; Complex sub(const Complex) const; Complex mult(const int) const; Complex divd(const int) const; Complex(const Complex&); Complex operator*(Complex&); Complex operator/(Complex&); bool operator==(Complex&); Complex operator=(Complex&); Complex operator+=(Complex&); Complex operator-=(Complex&); Complex operator*=(Complex&); Complex operator/=(Complex&); friend ostream& operator<<(ostream&, Complex&); friend istream& operator>>(istream&, Complex &); double real(); double imag(); };
21.575758
49
0.710674
BURNINGTIGER
7122261a541cb87857a672832aedfaf08f6dd602
13,620
hpp
C++
src/mlpack/methods/ann/cnn.hpp
vj-ug/Contribution-to-mlpack
0ddb5ed463861f459ff2829712bdc59ba9d810b0
[ "BSD-3-Clause" ]
null
null
null
src/mlpack/methods/ann/cnn.hpp
vj-ug/Contribution-to-mlpack
0ddb5ed463861f459ff2829712bdc59ba9d810b0
[ "BSD-3-Clause" ]
null
null
null
src/mlpack/methods/ann/cnn.hpp
vj-ug/Contribution-to-mlpack
0ddb5ed463861f459ff2829712bdc59ba9d810b0
[ "BSD-3-Clause" ]
null
null
null
/** * @file cnn.hpp * @author Shangtong Zhang * @author Marcus Edel * * Definition of the CNN class, which implements convolutional neural networks. */ #ifndef __MLPACK_METHODS_ANN_CNN_HPP #define __MLPACK_METHODS_ANN_CNN_HPP #include <mlpack/core.hpp> #include <mlpack/methods/ann/network_traits.hpp> #include <mlpack/methods/ann/layer/layer_traits.hpp> #include <mlpack/methods/ann/performance_functions/cee_function.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * An implementation of a standard convolutional network. * * @tparam LayerTypes Contains all layer modules used to construct the network. * @tparam OutputLayerType The outputlayer type used to evaluate the network. * @tparam PerformanceFunction Performance strategy used to claculate the error. */ template < typename LayerTypes, typename OutputLayerType, class PerformanceFunction = CrossEntropyErrorFunction<> > class CNN { public: /** * Construct the CNN object, which will construct a feed forward neural * network with the specified layers. * * @param network The network modules used to construct the network. * @param outputLayer The outputlayer used to evaluate the network. */ CNN(const LayerTypes& network, OutputLayerType& outputLayer) : network(network), outputLayer(outputLayer), trainError(0) { // Nothing to do here. } /** * Run a single iteration of the feed forward algorithm, using the given * input and target vector, store the calculated error into the error * parameter. * * @param input Input data used to evaluate the network. * @param target Target data used to calculate the network error. * @param error The calulated error of the output layer. */ template <typename InputType, typename TargetType, typename ErrorType> void FeedForward(const InputType& input, const TargetType& target, ErrorType& error) { deterministic = false; trainError += Evaluate(input, target, error); } /** * Run a single iteration of the feed backward algorithm, using the given * error of the output layer. * * @param error The calulated error of the output layer. */ template <typename InputType, typename ErrorType> void FeedBackward(const InputType& /* unused */, const ErrorType& error) { Backward(error, network); UpdateGradients(network); } /** * Update the weights using the layer defined optimizer. */ void ApplyGradients() { ApplyGradients(network); // Reset the overall error. trainError = 0; } /** * Evaluate the network using the given input. The output activation is * stored into the output parameter. * * @param input Input data used to evaluate the network. * @param output Output data used to store the output activation */ template <typename InputDataType, typename OutputDataType> void Predict(const InputDataType& input, OutputDataType& output) { deterministic = true; ResetParameter(network); Forward(input, network); OutputPrediction(output, network); } /** * Evaluate the trained network using the given input and compare the output * with the given target vector. * * @param input Input data used to evaluate the trained network. * @param target Target data used to calculate the network error. * @param error The calulated error of the output layer. */ template <typename InputType, typename TargetType, typename ErrorType> double Evaluate(const InputType& input, const TargetType& target, ErrorType& error) { deterministic = false; ResetParameter(network); Forward(input, network); return OutputError(target, error, network); } //! Get the error of the network. double Error() const { return trainError; } private: /** * Reset the network by setting the layer status. * * enable_if (SFINAE) is used to iterate through the network. The general * case peels off the first type and recurses, as usual with * variadic function templates. */ template<size_t I = 0, typename... Tp> typename std::enable_if<I == sizeof...(Tp), void>::type ResetParameter(std::tuple<Tp...>& /* unused */) { /* Nothing to do here */ } template<size_t I = 0, typename... Tp> typename std::enable_if<I < sizeof...(Tp), void>::type ResetParameter(std::tuple<Tp...>& t) { ResetDeterministic(std::get<I>(t)); ResetParameter<I + 1, Tp...>(t); } /** * Reset the layer status by setting the current deterministic parameter * through all layer that implement the Deterministic function. * * enable_if (SFINAE) is used to iterate through the network. The general * case peels off the first type and recurses, as usual with * variadic function templates. */ template<typename T> typename std::enable_if< HasDeterministicCheck<T, bool&(T::*)(void)>::value, void>::type ResetDeterministic(T& t) { t.Deterministic() = deterministic; } template<typename T> typename std::enable_if< not HasDeterministicCheck<T, bool&(T::*)(void)>::value, void>::type ResetDeterministic(T& /* unused */) { /* Nothing to do here */ } /** * Run a single iteration of the feed forward algorithm, using the given * input and target vector, store the calculated error into the error * vector. * * enable_if (SFINAE) is used to select between two template overloads of * the get function - one for when I is equal the size of the tuple of * layer, and one for the general case which peels off the first type * and recurses, as usual with variadic function templates. */ template<size_t I = 0, typename DataType, typename... Tp> void Forward(const DataType& input, std::tuple<Tp...>& t) { std::get<I>(t).InputParameter() = input; std::get<I>(t).Forward(std::get<I>(t).InputParameter(), std::get<I>(t).OutputParameter()); ForwardTail<I + 1, Tp...>(t); } template<size_t I = 1, typename... Tp> typename std::enable_if<I == sizeof...(Tp), void>::type ForwardTail(std::tuple<Tp...>& /* unused */) { LinkParameter(network); } template<size_t I = 1, typename... Tp> typename std::enable_if<I < sizeof...(Tp), void>::type ForwardTail(std::tuple<Tp...>& t) { std::get<I>(t).Forward(std::get<I - 1>(t).OutputParameter(), std::get<I>(t).OutputParameter()); ForwardTail<I + 1, Tp...>(t); } /** * Link the calculated activation with the connection layer. * * enable_if (SFINAE) is used to iterate through the network. The general * case peels off the first type and recurses, as usual with * variadic function templates. */ template<size_t I = 1, typename... Tp> typename std::enable_if<I == sizeof...(Tp), void>::type LinkParameter(std::tuple<Tp...>& /* unused */) { /* Nothing to do here */ } template<size_t I = 1, typename... Tp> typename std::enable_if<I < sizeof...(Tp), void>::type LinkParameter(std::tuple<Tp...>& t) { if (!LayerTraits<typename std::remove_reference< decltype(std::get<I>(t))>::type>::IsBiasLayer) { std::get<I>(t).InputParameter() = std::get<I - 1>(t).OutputParameter(); } LinkParameter<I + 1, Tp...>(t); } /* * Calculate the output error and update the overall error. */ template<typename DataType, typename ErrorType, typename... Tp> double OutputError(const DataType& target, ErrorType& error, const std::tuple<Tp...>& t) { // Calculate and store the output error. outputLayer.CalculateError( std::get<sizeof...(Tp) - 1>(t).OutputParameter(), target, error); // Masures the network's performance with the specified performance // function. return PerformanceFunction::Error( std::get<sizeof...(Tp) - 1>(t).OutputParameter(), target); } /** * Run a single iteration of the feed backward algorithm, using the given * error of the output layer. Note that we iterate backward through the * layer modules. * * enable_if (SFINAE) is used to select between two template overloads of * the get function - one for when I is equal the size of the tuple of * layer, and one for the general case which peels off the first type * and recurses, as usual with variadic function templates. */ template<size_t I = 1, typename DataType, typename... Tp> typename std::enable_if<I < (sizeof...(Tp) - 1), void>::type Backward(const DataType& error, std::tuple<Tp...>& t) { std::get<sizeof...(Tp) - I>(t).Backward( std::get<sizeof...(Tp) - I>(t).OutputParameter(), error, std::get<sizeof...(Tp) - I>(t).Delta()); BackwardTail<I + 1, DataType, Tp...>(error, t); } template<size_t I = 1, typename DataType, typename... Tp> typename std::enable_if<I == (sizeof...(Tp)), void>::type BackwardTail(const DataType& /* unused */, std::tuple<Tp...>& /* unused */) { } template<size_t I = 1, typename DataType, typename... Tp> typename std::enable_if<I < (sizeof...(Tp)), void>::type BackwardTail(const DataType& error, std::tuple<Tp...>& t) { std::get<sizeof...(Tp) - I>(t).Backward( std::get<sizeof...(Tp) - I>(t).OutputParameter(), std::get<sizeof...(Tp) - I + 1>(t).Delta(), std::get<sizeof...(Tp) - I>(t).Delta()); BackwardTail<I + 1, DataType, Tp...>(error, t); } /** * Iterate through all layer modules and update the the gradient using the * layer defined optimizer. * * enable_if (SFINAE) is used to iterate through the network layer. * The general case peels off the first type and recurses, as usual with * variadic function templates. */ template<size_t I = 0, typename... Tp> typename std::enable_if<I == (sizeof...(Tp) - 1), void>::type UpdateGradients(std::tuple<Tp...>& /* unused */) { } template<size_t I = 0, typename... Tp> typename std::enable_if<I < (sizeof...(Tp) - 1), void>::type UpdateGradients(std::tuple<Tp...>& t) { Update(std::get<I>(t), std::get<I>(t).OutputParameter(), std::get<I + 1>(t).Delta()); UpdateGradients<I + 1, Tp...>(t); } template<typename T, typename P, typename D> typename std::enable_if< HasGradientCheck<T, void(T::*)(const D&, P&)>::value, void>::type Update(T& t, P& /* unused */, D& delta) { t.Gradient(delta, t.Gradient()); t.Optimizer().Update(); } template<typename T, typename P, typename D> typename std::enable_if< not HasGradientCheck<T, void(T::*)(const P&, D&)>::value, void>::type Update(T& /* unused */, P& /* unused */, D& /* unused */) { /* Nothing to do here */ } /** * Update the weights using the calulated gradients. * * enable_if (SFINAE) is used to iterate through the network connections. * The general case peels off the first type and recurses, as usual with * variadic function templates. */ template<size_t I = 0, typename... Tp> typename std::enable_if<I == (sizeof...(Tp) - 1), void>::type ApplyGradients(std::tuple<Tp...>& /* unused */) { /* Nothing to do here */ } template<size_t I = 0, typename... Tp> typename std::enable_if<I < (sizeof...(Tp) - 1), void>::type ApplyGradients(std::tuple<Tp...>& t) { Apply(std::get<I>(t), std::get<I>(t).OutputParameter(), std::get<I + 1>(t).Delta()); ApplyGradients<I + 1, Tp...>(t); } template<typename T, typename P, typename D> typename std::enable_if< HasGradientCheck<T, void(T::*)(const D&, P&)>::value, void>::type Apply(T& t, P& /* unused */, D& /* unused */) { t.Optimizer().Optimize(); t.Optimizer().Reset(); } template<typename T, typename P, typename D> typename std::enable_if< not HasGradientCheck<T, void(T::*)(const P&, D&)>::value, void>::type Apply(T& /* unused */, P& /* unused */, D& /* unused */) { /* Nothing to do here */ } /* * Calculate and store the output activation. */ template<typename DataType, typename... Tp> void OutputPrediction(DataType& output, std::tuple<Tp...>& t) { // Calculate and store the output prediction. outputLayer.OutputClass(std::get<sizeof...(Tp) - 1>(t).OutputParameter(), output); } //! The layer modules used to build the network. LayerTypes network; //! The outputlayer used to evaluate the network OutputLayerType& outputLayer; //! The current training error of the network. double trainError; //! The current evaluation mode (training or testing). bool deterministic; }; // class CNN //! Network traits for the CNN network. template < typename LayerTypes, typename OutputLayerType, class PerformanceFunction > class NetworkTraits< CNN<LayerTypes, OutputLayerType, PerformanceFunction> > { public: static const bool IsFNN = false; static const bool IsRNN = false; static const bool IsCNN = true; }; }; // namespace ann }; // namespace mlpack #endif
33.058252
80
0.624156
vj-ug
7123259643cb93a1b3dda4dd1b15381b22bc0887
1,765
cc
C++
cpp/server/debug_server.cc
propaganda-gold/deeprev
0c6ccf83131a879ed858acdb0675e75ebf2f2d3d
[ "BSD-3-Clause" ]
null
null
null
cpp/server/debug_server.cc
propaganda-gold/deeprev
0c6ccf83131a879ed858acdb0675e75ebf2f2d3d
[ "BSD-3-Clause" ]
2
2021-05-11T16:29:38.000Z
2022-01-22T12:28:49.000Z
cpp/server/debug_server.cc
propaganda-gold/deeprev
0c6ccf83131a879ed858acdb0675e75ebf2f2d3d
[ "BSD-3-Clause" ]
null
null
null
#include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "api/router.h" #include "data/connection.h" #include "data/globals.h" #include "data/vectorbook.pb.h" #include "handlers/api.h" #include "handlers/delegating_handler.h" #include "handlers/requests.h" #include "network/init.h" #include "server/http_server.h" #include "server/options.h" #include "server/server_https.hpp" #include "util/includes.h" #include "util/mongo_adapter.h" #include <boost/filesystem.hpp> #include <memory> ABSL_FLAG(std::string, rest_options, "", ""); ABSL_FLAG(std::string, secrets, "", "Path to a pbtxt of type 'Secrets'."); ABSL_FLAG(std::string, model_spec, "", ""); ABSL_FLAG(int, port, 8090, "The port number for the server."); using SimpleHttpServer = SimpleWeb::Server<SimpleWeb::HTTP>; using namespace std; using namespace vectorbook; Void Main() { auto rest_options = absl::GetFlag(FLAGS_rest_options); ASSERT(!rest_options.empty()); auto secrets = absl::GetFlag(FLAGS_secrets); ASSERT(!secrets.empty()); ASSERT_SUCCEEDS(curl::Initialize()); ASSERT_SUCCEEDS(statics::LoadRestOptions(rest_options)); ASSERT_SUCCEEDS(statics::LoadSecrets(secrets)); ASSERT_SUCCEEDS(CreateRedisConnection()); ASSERT_SUCCEEDS(mongodb::Initialize(statics::secrets().mongodb_uri())); HttpServerConfig config; config.address = "0.0.0.0"; config.port = absl::GetFlag(FLAGS_port); auto handler = RestRouter(); ASSERT_OK(handler); auto server = CreateHttpServer(config, handler.get()); // ASSERT(server != nullptr); Output_() << "Starting server: http://" << config.address << ":" << config.port << "\n"; auto start = server->Start(); ASSERT_OK(start); ASSERT_SUCCEEDS(curl::CleanUp()); return Ok(); } #include "util/main_incl.h"
28.934426
74
0.717847
propaganda-gold
712631463cd05be873393e3f95c1e72b548a884f
2,759
cpp
C++
OpenTESArena/src/Media/Font.cpp
Digital-Monk/OpenTESArena
95f0bdaa642ff090b94081795a53b00f10dc4b03
[ "MIT" ]
null
null
null
OpenTESArena/src/Media/Font.cpp
Digital-Monk/OpenTESArena
95f0bdaa642ff090b94081795a53b00f10dc4b03
[ "MIT" ]
null
null
null
OpenTESArena/src/Media/Font.cpp
Digital-Monk/OpenTESArena
95f0bdaa642ff090b94081795a53b00f10dc4b03
[ "MIT" ]
null
null
null
#include <unordered_map> #include "SDL.h" #include "Font.h" #include "FontName.h" #include "../Assets/FontFile.h" #include "../Rendering/Renderer.h" #include "../Rendering/Surface.h" #include "components/debug/Debug.h" namespace { const std::unordered_map<FontName, std::string> FontFilenames = { { FontName::A, "FONT_A.DAT" }, { FontName::Arena, "ARENAFNT.DAT" }, { FontName::B, "FONT_B.DAT" }, { FontName::C, "FONT_C.DAT" }, { FontName::Char, "CHARFNT.DAT" }, { FontName::D, "FONT_D.DAT" }, { FontName::Four, "FONT4.DAT" }, { FontName::S, "FONT_S.DAT" }, { FontName::Teeny, "TEENYFNT.DAT" } }; } Font::Font(FontName fontName) { this->fontName = fontName; // Load the font file for this font name. const std::string &filename = FontFilenames.at(fontName); FontFile fontFile; if (!fontFile.init(filename.c_str())) { DebugCrash("Could not init font file \"" + filename + "\"."); } const int elementHeight = fontFile.getHeight(); this->characterHeight = elementHeight; // There are 95 characters, plus space. this->characters.resize(96); // Create an SDL surface for each character image. Start with space (ASCII 32), // and end with delete (ASCII 127). for (int i = 0; i < 96; i++) { const char c = i + 32; const int elementWidth = fontFile.getWidth(c); const uint32_t *elementPixels = fontFile.getPixels(c); Surface surface = Surface::createWithFormat(elementWidth, elementHeight, Renderer::DEFAULT_BPP, Renderer::DEFAULT_PIXELFORMAT); uint32_t *pixels = static_cast<uint32_t*>(surface.get()->pixels); const int pixelCount = surface.getWidth() * surface.getHeight(); for (int index = 0; index < pixelCount; index++) { pixels[index] = elementPixels[index]; } this->characters.at(i) = std::move(surface); } } Font::Font(Font &&font) { this->characters = std::move(font.characters); this->characterHeight = font.characterHeight; this->fontName = font.fontName; } const std::string &Font::fromName(FontName fontName) { const std::string &filename = FontFilenames.at(fontName); return filename; } int Font::getCharacterHeight() const { return this->characterHeight; } FontName Font::getFontName() const { return this->fontName; } SDL_Surface *Font::getSurface(char c) const { // If an invalid character is requested, print a warning and return // a default character. if ((c < 32) || (c > 127)) { DebugLogWarning("Character value \"" + std::to_string(c) + "\" out of range (must be ASCII 32-127)."); return this->characters.at(0).get(); } // Space (ASCII 32) is at index 0. SDL_Surface *surface = this->characters.at(c - 32).get(); return surface; }
25.546296
82
0.654223
Digital-Monk
7128adf5c1f9d10dd50b9ce20fc49699b7eb1eb1
513
cpp
C++
compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp
rohinikumar4073/CppMicroServices
f8ce77814c65eb8273823c7ca5df256ec9768956
[ "Apache-2.0" ]
1
2020-12-08T16:21:45.000Z
2020-12-08T16:21:45.000Z
compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp
iHouLei/CppMicroServices
aa9cc47dde75ba9ead18df399ce08269c15e3aa1
[ "Apache-2.0" ]
null
null
null
compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp
iHouLei/CppMicroServices
aa9cc47dde75ba9ead18df399ce08269c15e3aa1
[ "Apache-2.0" ]
null
null
null
#include "ManagedServiceFactoryServiceImpl.hpp" namespace cppmicroservices { namespace service { namespace cm { namespace test { TestManagedServiceFactoryServiceImpl::TestManagedServiceFactoryServiceImpl(int initialValue) : value{initialValue} {} TestManagedServiceFactoryServiceImpl::~TestManagedServiceFactoryServiceImpl() = default; int TestManagedServiceFactoryServiceImpl::getValue() { return value; } } // namespace test } // namespace cm } // namespace service } // namespace cppmicroservices
24.428571
92
0.805068
rohinikumar4073
71297894429bf2299c8e6b641c7a3a9cf26b29c1
981
cpp
C++
cloud_processing/cpp/ground_removal.cpp
MinesNicaicai/large-scale-pointcloud-matching
cfe140f2be1110ed75b6edd27538021e513a31c9
[ "MIT" ]
1
2020-11-21T16:39:51.000Z
2020-11-21T16:39:51.000Z
cloud_processing/cpp/ground_removal.cpp
MinesNicaicai/large-scale-pointcloud-matching
cfe140f2be1110ed75b6edd27538021e513a31c9
[ "MIT" ]
null
null
null
cloud_processing/cpp/ground_removal.cpp
MinesNicaicai/large-scale-pointcloud-matching
cfe140f2be1110ed75b6edd27538021e513a31c9
[ "MIT" ]
1
2020-12-13T14:51:44.000Z
2020-12-13T14:51:44.000Z
#include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <string> using PointT = pcl::PointXYZ; int main(int argc, char **argv) { if (argc != 2) { std::cout << "usage: ./ground_removal pcd-file\n"; return 0; } // Read in the cloud data pcl::PCDReader reader; pcl::PointCloud<PointT>::Ptr in_cloud(new pcl::PointCloud<PointT>()); pcl::PointCloud<PointT>::Ptr out_cloud(new pcl::PointCloud<PointT>()); reader.read(argv[1], *in_cloud); for (const auto& point : in_cloud->points) { if (point.z > 0) { out_cloud->points.emplace_back(point); } } out_cloud->width = out_cloud->points.size(); out_cloud->height = 1; out_cloud->is_dense = true; pcl::PCDWriter writer; std::string out_file_name(argv[1]); out_file_name = out_file_name.substr(0, out_file_name.size()-4) + "_wo_ground.pcd"; writer.write<PointT>(out_file_name, *out_cloud, false); return (0); }
25.815789
87
0.623853
MinesNicaicai
712ab680f4ba1b33a33efb844bc787502179d0a0
363
hpp
C++
libmsr145/headers/libmsr145_structs.hpp
StefanRvO/libmsr145
f9e49c1b116cdb8bb991084e9de11d5df8cd3b37
[ "Beerware" ]
null
null
null
libmsr145/headers/libmsr145_structs.hpp
StefanRvO/libmsr145
f9e49c1b116cdb8bb991084e9de11d5df8cd3b37
[ "Beerware" ]
null
null
null
libmsr145/headers/libmsr145_structs.hpp
StefanRvO/libmsr145
f9e49c1b116cdb8bb991084e9de11d5df8cd3b37
[ "Beerware" ]
null
null
null
#pragma once #include <cstdint> #include "libmsr145_enums.hpp" struct rec_entry { uint16_t address; struct tm time; uint16_t length; bool isRecording; }; struct sample { sampletype type; int16_t value; uint64_t timestamp; //this is the time since the start of the recording in 1/512 seconds uint32_t rawsample; //for debugging };
19.105263
92
0.707989
StefanRvO
712f7037a3aac3be92d9bb0bff838fa72dffa626
5,364
cc
C++
components/safe_browsing_db/database_manager.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
components/safe_browsing_db/database_manager.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
components/safe_browsing_db/database_manager.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
// 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/safe_browsing_db/database_manager.h" #include "components/safe_browsing_db/v4_get_hash_protocol_manager.h" #include "content/public/browser/browser_thread.h" #include "net/url_request/url_request_context_getter.h" #include "url/gurl.h" using content::BrowserThread; namespace safe_browsing { SafeBrowsingDatabaseManager::SafeBrowsingDatabaseManager() : v4_get_hash_protocol_manager_(NULL) { } SafeBrowsingDatabaseManager::~SafeBrowsingDatabaseManager() { DCHECK(v4_get_hash_protocol_manager_ == NULL); } void SafeBrowsingDatabaseManager::StartOnIOThread( net::URLRequestContextGetter* request_context_getter, const V4ProtocolConfig& config) { DCHECK_CURRENTLY_ON(BrowserThread::IO); v4_get_hash_protocol_manager_ = V4GetHashProtocolManager::Create( request_context_getter, config); } // |shutdown| not used. Destroys the v4 protocol managers. This may be called // multiple times during the life of the DatabaseManager. // Must be called on IO thread. void SafeBrowsingDatabaseManager::StopOnIOThread(bool shutdown) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // This cancels all in-flight GetHash requests. if (v4_get_hash_protocol_manager_) { delete v4_get_hash_protocol_manager_; v4_get_hash_protocol_manager_ = NULL; } // Delete pending checks, calling back any clients with empty metadata. for (auto check : api_checks_) { if (check->client()) { check->client()-> OnCheckApiBlacklistUrlResult(check->url(), ThreatMetadata()); } } STLDeleteElements(&api_checks_); } SafeBrowsingDatabaseManager::CurrentApiChecks::iterator SafeBrowsingDatabaseManager::FindClientApiCheck(Client* client) { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (CurrentApiChecks::iterator it = api_checks_.begin(); it != api_checks_.end(); ++it) { if ((*it)->client() == client) { return it; } } return api_checks_.end(); } bool SafeBrowsingDatabaseManager::CancelApiCheck(Client* client) { DCHECK_CURRENTLY_ON(BrowserThread::IO); CurrentApiChecks::iterator it = FindClientApiCheck(client); if (it != api_checks_.end()) { delete *it; api_checks_.erase(it); return true; } NOTREACHED(); return false; } bool SafeBrowsingDatabaseManager::CheckApiBlacklistUrl(const GURL& url, Client* client) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(v4_get_hash_protocol_manager_); // Make sure we can check this url. if (!(url.SchemeIs(url::kHttpScheme) || url.SchemeIs(url::kHttpsScheme))) { return true; } // There can only be one in-progress check for the same client at a time. DCHECK(FindClientApiCheck(client) == api_checks_.end()); // Compute a list of hashes for this url. std::vector<SBFullHash> full_hashes; UrlToFullHashes(url, false, &full_hashes); if (full_hashes.empty()) return true; // Copy to prefixes. std::vector<SBPrefix> prefixes; for (const SBFullHash& full_hash : full_hashes) { prefixes.push_back(full_hash.prefix); } // Multiple full hashes could share a prefix, remove duplicates. std::sort(prefixes.begin(), prefixes.end()); prefixes.erase(std::unique(prefixes.begin(), prefixes.end()), prefixes.end()); DCHECK(!prefixes.empty()); SafeBrowsingApiCheck* check = new SafeBrowsingApiCheck(url, full_hashes, client); api_checks_.insert(check); // TODO(kcarattini): Implement cache compliance. v4_get_hash_protocol_manager_->GetFullHashesWithApis(prefixes, base::Bind(&SafeBrowsingDatabaseManager::HandleGetHashesWithApisResults, base::Unretained(this), check)); return false; } void SafeBrowsingDatabaseManager::HandleGetHashesWithApisResults( SafeBrowsingApiCheck* check, const std::vector<SBFullHashResult>& full_hash_results, const base::Time& negative_cache_expire) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(check); // If the check is not in |api_checks_| then the request was cancelled by the // client. CurrentApiChecks::iterator it = api_checks_.find(check); if (it == api_checks_.end()) return; ThreatMetadata md; // Merge the metadata from all matching results. // TODO(kcarattini): This is O(N^2). Look at improving performance by // using a map, sorting or doing binary search etc.. for (const SBFullHashResult& result : full_hash_results) { for (const SBFullHash& full_hash : check->full_hashes()) { if (SBFullHashEqual(full_hash, result.hash)) { md.api_permissions.insert(md.api_permissions.end(), result.metadata.api_permissions.begin(), result.metadata.api_permissions.end()); break; } } } check->client()->OnCheckApiBlacklistUrlResult(check->url(), md); api_checks_.erase(it); delete check; } SafeBrowsingDatabaseManager::SafeBrowsingApiCheck::SafeBrowsingApiCheck( const GURL& url, const std::vector<SBFullHash>& full_hashes, Client* client) : url_(url), full_hashes_(full_hashes), client_(client) { } SafeBrowsingDatabaseManager::SafeBrowsingApiCheck::~SafeBrowsingApiCheck() { } } // namespace safe_browsing
33.31677
80
0.7239
maidiHaitai
71311f1d13a7e8e83939ef6b87d92c0f10fbb72c
224
cpp
C++
2521/1683225_AC_0MS_68K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
2521/1683225_AC_0MS_68K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
2521/1683225_AC_0MS_68K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#include<iostream.h> void main() { int iCost,iSell,iFake,iBack; while(1) { cin>>iCost>>iSell>>iFake>>iBack; if(iCost==0 && iSell==0 && iFake==0 && iBack==0) break; cout<<iCost-iSell+iFake<<endl; } }
17.230769
51
0.580357
vandreas19
71376ccf83770aa04107f163ca946c1244c462a5
2,147
cpp
C++
progpar/test/progpar-test.cpp
dmitigr/cefeika
6189843d4244f7334558708e57e952584561b1e0
[ "Zlib" ]
19
2019-07-21T15:38:12.000Z
2022-01-06T05:24:48.000Z
progpar/test/progpar-test.cpp
dmitigr/cefeika
6189843d4244f7334558708e57e952584561b1e0
[ "Zlib" ]
6
2019-12-07T22:12:37.000Z
2022-01-10T22:31:48.000Z
progpar/test/progpar-test.cpp
dmitigr/cefeika
6189843d4244f7334558708e57e952584561b1e0
[ "Zlib" ]
1
2019-08-15T14:49:00.000Z
2019-08-15T14:49:00.000Z
// -*- C++ -*- // Copyright (C) 2021 Dmitry Igrishin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // Dmitry Igrishin // dmitigr@gmail.com #include "../../progpar.hpp" #include "../../testo.hpp" #include <iostream> int main(int argc, char* argv[]) { namespace progpar = dmitigr::progpar; using namespace dmitigr::testo; try { const progpar::Program_parameters po{argc, argv}; const auto epath = po.path(); ASSERT(!epath.empty()); std::cout << "Executable path: " << epath << std::endl; const auto& opts = po.options(); std::cout << opts.size() << " options specified"; if (!opts.empty()) { std::cout << ":" << std::endl; for (const auto& o : opts) { std::cout << " " << o.first; if (o.second) std::cout << " = " << *o.second; std::cout << std::endl; } } else std::cout << "." << std::endl; const auto& args = po.arguments(); std::cout << args.size() << " arguments specified"; if (!args.empty()) { std::cout << ":" << std::endl; for (const auto& a : args) std::cout << " " << a << std::endl; } else std::cout << "." << std::endl; } catch (const std::exception& e) { report_failure(argv[0], e); return 1; } catch (...) { report_failure(argv[0]); return 2; } }
32.044776
77
0.616209
dmitigr
7143ac46680ebf63717201570aae8b1099c84a9e
6,537
cpp
C++
gddm/netlib_server.cpp
asm128/nwol
a28d6df356bec817393adcd2e6573a65841832e2
[ "MIT" ]
3
2017-06-05T13:49:43.000Z
2017-06-19T22:31:58.000Z
gddm/netlib_server.cpp
asm128/nwol
a28d6df356bec817393adcd2e6573a65841832e2
[ "MIT" ]
1
2017-06-19T12:36:46.000Z
2017-06-30T22:34:06.000Z
gddm/netlib_server.cpp
asm128/nwol
a28d6df356bec817393adcd2e6573a65841832e2
[ "MIT" ]
null
null
null
#include "netlib_server.h" #include "nwol_sleep.h" #include "gref_definition.h" #include <time.h> #if defined(__WINDOWS__) #include <process.h> #include <WinSock2.h> #endif void gdnet::disconnectClient (SServer& serverInstance, int32_t clientId) { ::nwol::CMutexGuard lockClients (serverInstance.ConnectionsMutex); for(uint32_t i = 0; i < serverInstance.ClientConnections.size(); ++i) { ::gdnet::SNetworkNode * client = serverInstance.ClientConnections[i]; if(client && client->Id == clientId) { GPNCO(::gdnet, SNetworkNode) endClient = 0; error_if(0 > serverInstance.ClientConnections.pop(&endClient), "This is broken! No elements to pop?") else re_if(errored(serverInstance.ClientConnections.set(endClient, i)), "Failed to set client! Out of memory?"); } } } int32_t gdnet::SServer::InitServer (uint16_t listeningPort, ::gdnet::TRANSPORT_PROTOCOL mode) { ::gethostname(HostName, sizeof(HostName)); // Get host name of this computer QueuedConnectionCount = 0; GPNCO(::gdnet, IEndpoint) endpointListener = nullptr; // Information about the client nwol_necall(::gdnet::endpointCreate(HostName, (uint16_t)listeningPort, 0, mode, &endpointListener) , "Failed to initialize listening endpoint on %u:.%s." , (uint32_t)listeningPort, ::nwol::get_value_label(mode).begin()); nwol_necall(::gdnet::endpointInit(endpointListener) , "Failed to initialize listening endpoint on %u:.%s." , (uint32_t)listeningPort, ::nwol::get_value_label(mode).begin()); nwol_necall(::gdnet::endpointBind(endpointListener) , "Failed to bind listening endpoint on %u:.%s." , (uint32_t)listeningPort, ::nwol::get_value_label(mode).begin()); EndpointListener = endpointListener; bListening = true; return 0; } int32_t gdnet::SServer::Listen () { if(!bListening) return 1; ::gdnet::SCommand command = ::gdnet::INVALID_COMMAND; GPNCO(::gdnet, IEndpoint) endpointToAccept = nullptr; // Information about the client int32_t bytes_received = 0; { ::gdnet::SIPv4 addressListener = {}; ::gdnet::endpointAddress(EndpointListener, addressListener); info_printf("Server listening on %u.%u.%u.%u:%u.", NWOL_EXPAND_IPV4_UINT32(addressListener)); // -- Receive bytes from client ::nwol::error_t errMy = ::gdnet::endpointReceive( EndpointListener.get_address(), (byte_t*)&command, sizeof(::gdnet::SCommand), &bytes_received, ::gdnet::RECEIVE_FLAG_REMOVE, &endpointToAccept ); ree_if(bytes_received < 0, "Could not receive datagram. 0x%x.", errMy); rww_if(bytes_received == 0, "Server listener may have been closed. 0x%x.", errMy); } { ::gdnet::SIPv4 addressToAccept = {}; error_if(errored(::gdnet::endpointAddress(endpointToAccept, addressToAccept)), "I have no idea why this would ever fail."); info_printf("Received %u bytes from %u.%u.%u.%u:%u. Command: %s:%s.", (uint32_t)bytes_received, NWOL_EXPAND_IPV4_UINT32(addressToAccept) , ::nwol::get_value_label(command.Type ).c_str() , ::nwol::get_value_label(command.Command ).c_str() ); if(bListening && command.Command == ::gdnet::NWON_COMMAND_CONNECT && QueuedConnectionCount < (int64_t)::nwol::size(QueuedConnectionList)) QueuedConnectionList[sync_increment(QueuedConnectionCount) - 1] = endpointToAccept; } return 0; } int32_t gdnet::SServer::Accept () { if( 0 == QueuedConnectionCount ) return 1; static int32_t connectionsAccepted = 0; ::gdnet::SConnectionAddress address = {}; GPNCO(::gdnet, IEndpoint) endpointListener = 0; GPNCO(::gdnet, IEndpoint) endpointRemote = QueuedConnectionList[sync_decrement(QueuedConnectionCount)]; nwol_necall(::gdnet::endpointAddress (EndpointListener, address.Local) , "Failed to resolve local address."); nwol_necall(::gdnet::endpointAddress (endpointRemote, address.Remote) , "Failed to resolve remote address."); address.Local.Port = 0; // Let the system pick the port number. nwol_necall(::gdnet::endpointCreate (address.Local, TRANSPORT_PROTOCOL_UDP, &endpointListener) , "%s", "Failed to create client listener."); nwol_necall(::gdnet::endpointInit (endpointListener) , "%s", "Failed to initialize client listener connection."); nwol_necall(::gdnet::endpointBind (endpointListener) , "%s", "Failed to bind client listener connection."); GPObj(::gdnet, SNetworkNode) newClient; uint32_t indexFound = (uint32_t)-1; { ::nwol::CMutexGuard lockClients (ConnectionsMutex); for(uint32_t iClient = 0, clientCount = ClientConnections.size(); iClient<clientCount; ++iClient) { ::gdnet::GREF(SNetworkNode) * refClient = ClientConnections.begin()[iClient]; if(0 == refClient) { indexFound = iClient; break; } else if(refClient->get()->Endpoints.Local == 0 || refClient->get()->Endpoints.Remote == 0) { newClient = ::nwol::acquire(refClient); break; } } if(0 == newClient) { newClient.create(); if(indexFound != (uint32_t)-1) nwol_necall(ClientConnections.set(newClient, indexFound), "Failed to set client to connection list! Why would this ever happen?"); else nwol_necall(ClientConnections.push_back(newClient), "Failed to push client connection. Out of memory?"); } uint64_t newClientId = connectionsAccepted++; nwol_necall(::gdnet::nodeInit(newClient, {endpointListener, endpointRemote}, newClientId), "Failed to initialize node. This may be due to the socket being closed before fully initializing."); } Sleep(10); return 0; }; ::nwol::error_t gdnet::SServer::ShutdownServer () { bListening = false; EndpointListener = {}; ::nwol::sleep(100); while(QueuedConnectionCount > 0) QueuedConnectionList[sync_decrement(QueuedConnectionCount)] = 0; { ::nwol::CMutexGuard lockClients (ConnectionsMutex); for(uint32_t iClient = 0, clientCount = ClientConnections.size(); iClient < clientCount; ++iClient) { ::gdnet::SNetworkNode * nodeToDisconnect = ClientConnections[iClient]; if (nodeToDisconnect) nodeToDisconnect->Endpoints = {}; } ::nwol::sleep(100); } return 0; }
50.284615
221
0.659936
asm128
714a23b2269a75ab0a6137842ce74562b0f9f337
1,895
cpp
C++
Beeftext/Snippet/ShortcutSnippetFragment.cpp
sharpsteve/Beeftext
9f4c7abfe6f33914cd49956f9c576ab5b10ff660
[ "MIT" ]
546
2017-12-19T15:44:56.000Z
2022-03-29T20:38:01.000Z
Beeftext/Snippet/ShortcutSnippetFragment.cpp
sharpsteve/Beeftext
9f4c7abfe6f33914cd49956f9c576ab5b10ff660
[ "MIT" ]
455
2017-12-30T07:47:49.000Z
2022-03-24T15:53:14.000Z
Beeftext/Snippet/ShortcutSnippetFragment.cpp
sharpsteve/Beeftext
9f4c7abfe6f33914cd49956f9c576ab5b10ff660
[ "MIT" ]
45
2018-03-04T15:07:22.000Z
2022-03-16T22:13:58.000Z
/// \file /// \author /// /// \brief Implementation of shortcut snippet fragment class. /// /// Copyright (c) . All rights reserved. /// Licensed under the MIT License. See LICENSE file in the project root for full license information. #include "stdafx.h" #include "ShortcutSnippetFragment.h" #include "BeeftextUtils.h" //********************************************************************************************************************** /// \param[in] shortcut The shortcut. //********************************************************************************************************************** ShortcutSnippetFragment::ShortcutSnippetFragment(SpShortcut const& shortcut) : shortcut_(shortcut) { } //********************************************************************************************************************** /// \return The type of snippet fragment. //********************************************************************************************************************** SnippetFragment::EType ShortcutSnippetFragment::type() const { return EType::Shortcut; } //********************************************************************************************************************** /// \return A string describing the shortcut snippet fragment //********************************************************************************************************************** QString ShortcutSnippetFragment::toString() const { return QString("Shortcut fragment : %1").arg(shortcut_ ? shortcut_->toString() : "null"); } //********************************************************************************************************************** // //********************************************************************************************************************** void ShortcutSnippetFragment::render() const { if (shortcut_) renderShortcut(shortcut_); }
37.9
120
0.355145
sharpsteve
714d2195d6ab17af6170977fd9ef4dee662ea17f
571
cpp
C++
src/platform/web/worker.cpp
reubenscratton/oaknut
03b37965ad84745bd5c077a27d8b53d58a173662
[ "MIT" ]
5
2019-10-04T05:10:06.000Z
2021-02-03T23:29:10.000Z
src/platform/web/worker.cpp
reubenscratton/oaknut
03b37965ad84745bd5c077a27d8b53d58a173662
[ "MIT" ]
null
null
null
src/platform/web/worker.cpp
reubenscratton/oaknut
03b37965ad84745bd5c077a27d8b53d58a173662
[ "MIT" ]
2
2019-09-27T00:34:36.000Z
2020-10-27T09:44:26.000Z
// // Copyright © 2018 Sandcastle Software Ltd. All rights reserved. // // This file is part of 'Oaknut' which is released under the MIT License. // See the LICENSE file in the root of this installation for details. // #if PLATFORM_WEB #include <oaknut.h> #if BUILD_AS_WORKER emscripten_worker_respond(0, 0); #else void Worker::start(const variant& config) { ByteBufferStream bb; bb.writeVariant(config); auto configData = bb._data; emscripten_call_worker(_worker, "ww_start", (char*)configData.data, configData.cb, NULL, 0); } #endif #endif
17.30303
96
0.718039
reubenscratton
7150dc8663ec4dddc2f9528a8cdb214f9023ad50
1,264
cpp
C++
leetcode/128_Longest_Consecutive_Sequence.cpp
wllvcxz/leetcode
82358a0946084ba935ca1870b5e3f7c29c03fac3
[ "MIT" ]
null
null
null
leetcode/128_Longest_Consecutive_Sequence.cpp
wllvcxz/leetcode
82358a0946084ba935ca1870b5e3f7c29c03fac3
[ "MIT" ]
null
null
null
leetcode/128_Longest_Consecutive_Sequence.cpp
wllvcxz/leetcode
82358a0946084ba935ca1870b5e3f7c29c03fac3
[ "MIT" ]
null
null
null
#include <unordered_map> #include <vector> using namespace std; class Solution { public: int longestConsecutive(const vector<int> &nums) { unordered_map<int, bool> used; used.find(123); for(auto i : nums) used[i] = false; int maxlen = 0; for(auto i: nums){ if(used[i] == false){ used[i] = true; int len = 1; len += find_left(i, used); len += find_right(i, used); maxlen = maxlen < len? len: maxlen; } } return maxlen; } int find_left(int i, unordered_map<int, bool>& used){ int count = 0; while(true){ i = i + 1; if(used.find(i) == used.end() || used[i] == true){ return count; }else{ count++; used[i] = true; } } } int find_right(int i, unordered_map<int, bool>& used){ int count = 0; while(true){ i = i - 1; if(used.find(i) == used.end() || used[i] == true){ return count; }else{ count++; used[i] = true; } } } };
25.28
62
0.412184
wllvcxz
715ef9818033fa5e738ed84fdd366620ae9afdc4
657
cpp
C++
src/servo/ServoPublisher.cpp
CatixBot/KinematicsNode
451d109a472807029de8dc7392dd851f3039c3db
[ "MIT" ]
null
null
null
src/servo/ServoPublisher.cpp
CatixBot/KinematicsNode
451d109a472807029de8dc7392dd851f3039c3db
[ "MIT" ]
null
null
null
src/servo/ServoPublisher.cpp
CatixBot/KinematicsNode
451d109a472807029de8dc7392dd851f3039c3db
[ "MIT" ]
null
null
null
#include "servo/ServoPublisher.h" #include <catix_messages/ServoState.h> servo::ServoPublisher::ServoPublisher(size_t servoIndex, ros::NodeHandle& node) : servoIndex(servoIndex) , publisherServoState(node.advertise<catix_messages::ServoState>("Catix/Servo", 1)) { } bool servo::ServoPublisher::setAngle(double servoAngle) { catix_messages::ServoState servoStateMessage; servoStateMessage.servo_index = static_cast<uint8_t>(this->servoIndex); servoStateMessage.rotate_angle = servoAngle; this->publisherServoState.publish(servoStateMessage); ROS_INFO("Joint %d: [%frad]", this->servoIndex, servoAngle); return true; }
31.285714
87
0.757991
CatixBot
715f98468a0e18a07ffcd8d1d964dc29da804d66
4,380
cpp
C++
qt-gui/siditemmodel.cpp
jgilje/reveller
19529bcf63811146e605d3fe7c16dd73bdd7814d
[ "Apache-2.0" ]
5
2015-05-23T14:44:08.000Z
2020-03-23T20:17:36.000Z
qt-gui/siditemmodel.cpp
jgilje/reveller
19529bcf63811146e605d3fe7c16dd73bdd7814d
[ "Apache-2.0" ]
7
2015-05-23T09:30:05.000Z
2021-07-06T07:24:41.000Z
qt-gui/siditemmodel.cpp
jgilje/reveller
19529bcf63811146e605d3fe7c16dd73bdd7814d
[ "Apache-2.0" ]
null
null
null
#include "siditemmodel.h" #include "siditem.h" #include <QDebug> #include <QFileIconProvider> SidItemModel::SidItemModel(QObject *parent) : QAbstractItemModel(parent) { rootItem = new SidItem("ROOT", SidItem::DIRECTORY); } SidItemModel::~SidItemModel() { } QModelIndex SidItemModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) { return QModelIndex(); } SidItem *parentItem = itemFromModelIndex(parent); SidItem *childItem = parentItem->child(row); if (childItem) { return createIndex(row, column, childItem); } else { return QModelIndex(); } } QModelIndex SidItemModel::parent(const QModelIndex &index) const { if (!index.isValid()) return QModelIndex(); SidItem *childItem = static_cast<SidItem*>(index.internalPointer()); SidItem *parentItem = childItem->parent(); if (parentItem == rootItem) return QModelIndex(); return createIndex(parentItem->row(), 0, parentItem); } int SidItemModel::rowCount(const QModelIndex &parent) const { if (parent.column() > 0) { return 0; } SidItem *parentItem = itemFromModelIndex(parent); return parentItem->childCount(); } int SidItemModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return 1; } QVariant SidItemModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); SidItem *item = static_cast<SidItem*>(index.internalPointer()); QFileIconProvider iconprovider; switch (role) { case Qt::DisplayRole: return item->name(); case Qt::DecorationRole: switch (item->type()) { case SidItem::DIRECTORY: return iconprovider.icon(QFileIconProvider::Folder); case SidItem::SIDFILE: return iconprovider.icon(QFileIconProvider::File); } break; default: // qDebug() << role; return QVariant(); } return QVariant(); } Qt::ItemFlags SidItemModel::flags(const QModelIndex &index) const { if (!index.isValid()) return 0; return QAbstractItemModel::flags(index); } QVariant SidItemModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(role) return QVariant(QString("HeaderData %1, %2").arg(section).arg(orientation)); } void SidItemModel::directoryData(const QString& path, const QStringList &directories, const QStringList &sidfiles) { QModelIndex modelIndex = fromPath(path); beginInsertRows(modelIndex, 0, directories.size() + sidfiles.size()); SidItem *parentItem = itemFromModelIndex(modelIndex); foreach (const QString& dir, directories) { parentItem->appendDirectory(dir); } foreach (const QString& sidfile, sidfiles) { parentItem->appendSidFile(sidfile); } parentItem->setLoaded(); endInsertRows(); } SidItem* SidItemModel::itemFromModelIndex(const QModelIndex &modelIndex) const { SidItem *item; if (!modelIndex.isValid()) item = rootItem; else item = static_cast<SidItem*>(modelIndex.internalPointer()); return item; } bool SidItemModel::canFetchMore(const QModelIndex &parent) const { SidItem *item = itemFromModelIndex(parent); return !item->isLoading() && !item->hasLoaded(); } void SidItemModel::fetchMore(const QModelIndex &parent) { SidItem *item = itemFromModelIndex(parent); item->setLoading(); emit fetchItem(item); } bool SidItemModel::hasChildren(const QModelIndex &parent) const { SidItem *item = itemFromModelIndex(parent); if (item->type() == SidItem::DIRECTORY) { return true; } return false; } SidItem* SidItemModel::root() { return rootItem; } QModelIndex SidItemModel::fromPath(const QString &path) { if (path.isEmpty()) { return QModelIndex(); } int pathIndex = 0; QStringList pathItems = path.split("/"); QModelIndex parent; SidItem* item = rootItem; for (int i = 0; i < pathItems.size(); i++) { item = item->child(pathItems[pathIndex]); if (item == NULL) { return QModelIndex(); } parent = index(item->row(), 0, parent); if (! parent.isValid()) { return QModelIndex(); } pathIndex++; } return parent; }
25.172414
116
0.652283
jgilje
716067b7af884a37fd3019909351f61da829093b
11,760
cpp
C++
source/lexical.cpp
Facenapalm/interpreter
4bb8906098e5eb9fee6d9782c51d855013fea548
[ "MIT" ]
2
2019-09-10T18:13:34.000Z
2020-09-27T11:42:14.000Z
source/lexical.cpp
Facenapalm/interpreter
4bb8906098e5eb9fee6d9782c51d855013fea548
[ "MIT" ]
null
null
null
source/lexical.cpp
Facenapalm/interpreter
4bb8906098e5eb9fee6d9782c51d855013fea548
[ "MIT" ]
null
null
null
#include <sstream> #include "exceptions.h" #include "lexical.h" LexicalAnalyzer::LexicalAnalyzer(bool case_insensetive, bool alternative_names): case_insensetive(case_insensetive), alternative_names(alternative_names), ready(false), state(NULL), lexeme_line(0), lexeme_column(0), input(NULL), cur_char('\0'), line(0), column(0) { buff.reserve(256); } void LexicalAnalyzer::get_next_char() { if (!(*input >> std::noskipws >> cur_char)) { cur_char = '\0'; } if (case_insensetive && state != &LexicalAnalyzer::state_string && state != &LexicalAnalyzer::state_escape && cur_char >= 'A' && cur_char <= 'Z') { cur_char -= 'A'; cur_char += 'a'; } if (cur_char == '\n') { line += 1; column = 0; } else { column += 1; } } void LexicalAnalyzer::buff_char() { if (buff == "") { lexeme_line = line; lexeme_column = column; } buff += cur_char; } void LexicalAnalyzer::push_lexeme(LexemeType type) { result.push_back(Lexeme(type, buff, lexeme_line, lexeme_column)); buff = ""; } void LexicalAnalyzer::transition(AnalyzerState new_state) { state = new_state; get_next_char(); } void LexicalAnalyzer::transition_buff(AnalyzerState new_state) { buff_char(); state = new_state; get_next_char(); } void LexicalAnalyzer::transition_push(AnalyzerState new_state, LexemeType type) { buff_char(); push_lexeme(type); state = new_state; get_next_char(); } void LexicalAnalyzer::transition_eps(AnalyzerState new_state) { state = new_state; } void LexicalAnalyzer::transition_push_eps(AnalyzerState new_state, LexemeType type) { push_lexeme(type); state = new_state; } void LexicalAnalyzer::transition_error(const std::string &message) { std::stringstream stream; stream << "Lexical error: " << message << " (line " << line << ", column " << column << ")"; throw LexicalError(stream.str()); } static inline bool is_space(char ch) { return ch == ' ' || ch == '\n' || ch == '\t' || ch == '\v' || ch == '\r'; } static inline bool is_letter(char ch) { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_'; } static inline bool is_digit(char ch) { return ch >= '0' && ch <= '9'; } inline LexemeType LexicalAnalyzer::get_separator_type() { switch (cur_char) { case ',': return ltComma; case '{': return ltBlockOpen; case '}': return ltBlockClose; case '(': return ltBracketOpen; case ')': return ltBracketClose; default: return ltSemicolon; } } inline LexemeType LexicalAnalyzer::get_keyword_type() { if (alternative_names) { if (buff == "print") { return ltWrite; } else if (buff == "str") { return ltString; } else if (buff == "bool") { return ltBoolean; } } if (buff == "program") { return ltProgram; } else if (buff == "if") { return ltIf; } else if (buff == "else") { return ltElse; } else if (buff == "while") { return ltWhile; } else if (buff == "read") { return ltRead; } else if (buff == "write") { return ltWrite; } else if (buff == "do") { return ltDo; } else if (buff == "break") { return ltBreak; } else if (buff == "continue") { return ltContinue; } else if (buff == "int") { return ltInt; } else if (buff == "string") { return ltString; } else if (buff == "boolean") { return ltBoolean; } else if (buff == "real") { return ltReal; } else if (buff == "true" || buff == "false") { return ltConstBoolean; } else if (buff == "not") { return ltNot; } else if (buff == "and") { return ltAnd; } else if (buff == "or") { return ltOr; } else { return ltIdentificator; } } void LexicalAnalyzer::state_start() { if (cur_char == '\0') { transition_eps(NULL); } else if (is_space(cur_char)) { transition(&LexicalAnalyzer::state_start); } else if (is_digit(cur_char)) { transition_buff(&LexicalAnalyzer::state_int); } else if (is_letter(cur_char)) { transition_buff(&LexicalAnalyzer::state_identificator); } else if (cur_char == '"') { transition(&LexicalAnalyzer::state_string); } else if (cur_char == '{' || cur_char == '}' || cur_char == '(' || cur_char == ',' || cur_char == ';') { transition_push(&LexicalAnalyzer::state_start, get_separator_type()); } else if (cur_char == ')') { transition_push(&LexicalAnalyzer::state_after_operand, ltBracketClose); } else if (cur_char == '+' || cur_char == '-') { transition_buff(&LexicalAnalyzer::state_sign); } else if (cur_char == '*') { transition_push(&LexicalAnalyzer::state_start, ltMul); } else if (cur_char == '%') { transition_push(&LexicalAnalyzer::state_start, ltMod); } else if (cur_char == '/') { transition_buff(&LexicalAnalyzer::state_comment_start); } else if (cur_char == '=' || cur_char == '!' || cur_char == '<' || cur_char == '>') { transition_buff(&LexicalAnalyzer::state_comparison); } else { transition_error(std::string() + "unexpected symbol '" + cur_char + "'"); } } void LexicalAnalyzer::state_after_operand() { if (is_space(cur_char)) { transition(&LexicalAnalyzer::state_after_operand); } else if (cur_char == '+') { transition_push(&LexicalAnalyzer::state_start, ltPlus); } else if (cur_char == '-') { transition_push(&LexicalAnalyzer::state_start, ltMinus); } else if (cur_char == '/') { transition_buff(&LexicalAnalyzer::state_comment_start_AO); } else { transition_eps(&LexicalAnalyzer::state_start); } } void LexicalAnalyzer::state_identificator() { if (is_letter(cur_char) || is_digit(cur_char)) { transition_buff(&LexicalAnalyzer::state_identificator); } else { LexemeType type = get_keyword_type(); transition_push_eps(type == ltIdentificator ? &LexicalAnalyzer::state_after_operand : &LexicalAnalyzer::state_start, type); } } void LexicalAnalyzer::state_sign() { if (is_digit(cur_char)) { transition_buff(&LexicalAnalyzer::state_int); } else { transition_push_eps(&LexicalAnalyzer::state_start, buff == "+" ? ltPlusUn : ltMinusUn); } } void LexicalAnalyzer::state_int() { if (is_digit(cur_char)) { transition_buff(&LexicalAnalyzer::state_int); } else if (cur_char == '.') { transition_buff(&LexicalAnalyzer::state_dot); } else if (is_letter(cur_char)) { transition_error(std::string() + "unexpected symbol '" + cur_char + "' after number"); } else { transition_push_eps(&LexicalAnalyzer::state_after_operand, ltConstInt); } } void LexicalAnalyzer::state_dot() { if (is_digit(cur_char)) { transition_buff(&LexicalAnalyzer::state_real); } else { transition_error(std::string() + "expected fractional part of number, got '" + cur_char + "'"); } } void LexicalAnalyzer::state_real() { if (is_digit(cur_char)) { transition_buff(&LexicalAnalyzer::state_real); } else if (is_letter(cur_char) || cur_char == '.') { transition_error(std::string() + "unexpected symbol '" + cur_char + "' after number"); } else { transition_push_eps(&LexicalAnalyzer::state_after_operand, ltConstReal); } } void LexicalAnalyzer::state_comparison() { if (cur_char == '=') { switch (buff[0]) { case '=': transition_push(&LexicalAnalyzer::state_start, ltEq); break; case '<': transition_push(&LexicalAnalyzer::state_start, ltSmEq); break; case '>': transition_push(&LexicalAnalyzer::state_start, ltGrEq); break; case '!': transition_push(&LexicalAnalyzer::state_start, ltNotEq); break; default: throw std::runtime_error("StateReadComparison fail"); } } else { switch (buff[0]) { case '=': transition_push_eps(&LexicalAnalyzer::state_start, ltAssign); break; case '<': transition_push_eps(&LexicalAnalyzer::state_start, ltSm); break; case '>': transition_push_eps(&LexicalAnalyzer::state_start, ltGr); break; case '!': transition_error("unexpected symbol '!'"); default: throw std::runtime_error("StateReadComparison fail"); } } } void LexicalAnalyzer::state_string() { if (cur_char == '\\') { transition(&LexicalAnalyzer::state_escape); } else if (cur_char == '"') { push_lexeme(ltConstString); transition(&LexicalAnalyzer::state_after_operand); } else if (cur_char == '\0' || cur_char == '\n') { transition_error("unclosed string"); } else { transition_buff(&LexicalAnalyzer::state_string); } } void LexicalAnalyzer::state_escape() { if (cur_char == 'n') { buff += '\n'; transition(&LexicalAnalyzer::state_string); } else if (cur_char == '\0') { transition_error("unclosed string"); } else { transition_buff(&LexicalAnalyzer::state_string); } } void LexicalAnalyzer::state_comment_start() { if (cur_char == '*') { buff = ""; transition(&LexicalAnalyzer::state_comment); } else { push_lexeme(ltDiv); transition_eps(&LexicalAnalyzer::state_start); } } void LexicalAnalyzer::state_comment_start_AO() { if (cur_char == '*') { buff = ""; transition(&LexicalAnalyzer::state_comment_AO); } else { push_lexeme(ltDiv); transition_eps(&LexicalAnalyzer::state_start); } } void LexicalAnalyzer::state_comment() { if (cur_char == '\0') { transition_error("unclosed comment"); } else if (cur_char == '*') { transition(&LexicalAnalyzer::state_comment_end); } else { transition(&LexicalAnalyzer::state_comment); } } void LexicalAnalyzer::state_comment_AO() { if (cur_char == '\0') { transition_error("unclosed comment"); } else if (cur_char == '*') { transition(&LexicalAnalyzer::state_comment_end_AO); } else { transition(&LexicalAnalyzer::state_comment_AO); } } void LexicalAnalyzer::state_comment_end() { if (cur_char == '/') { transition(&LexicalAnalyzer::state_start); } else { transition_eps(&LexicalAnalyzer::state_comment); } } void LexicalAnalyzer::state_comment_end_AO() { if (cur_char == '/') { transition(&LexicalAnalyzer::state_after_operand); } else { transition_eps(&LexicalAnalyzer::state_comment_AO); } } void LexicalAnalyzer::process() { ready = false; result.clear(); buff = ""; line = 1; column = 0; transition(&LexicalAnalyzer::state_start); while (state) { (this->*state)(); } ready = true; } void LexicalAnalyzer::parse_stream(std::istream &stream) { input = &stream; process(); input = NULL; } void LexicalAnalyzer::parse_string(const std::string &str) { std::istringstream stream(str); parse_stream(stream); } const LexemeArray &LexicalAnalyzer::get_lexemes() const { if (!ready) { throw std::runtime_error("Attempt to get lexems from analyzer in error state"); } return result; }
26.910755
95
0.591582
Facenapalm
716251e358fe5dc5609abe7111749217d9607cab
1,084
cpp
C++
GPcode00_Timer/StopWatch.cpp
dknife/Lectures
cc00046bebd0d38c07a6442cd4d7af6c06624c1d
[ "Unlicense" ]
1
2016-04-20T13:00:29.000Z
2016-04-20T13:00:29.000Z
GPcode00_Timer/StopWatch.cpp
dknife/Lectures
cc00046bebd0d38c07a6442cd4d7af6c06624c1d
[ "Unlicense" ]
null
null
null
GPcode00_Timer/StopWatch.cpp
dknife/Lectures
cc00046bebd0d38c07a6442cd4d7af6c06624c1d
[ "Unlicense" ]
null
null
null
/* * StopWatch.cpp * Young-Min Kang * Tongmyong University * */ #include "StopWatch.h" StopWatch::StopWatch() { #ifdef WIN32 QueryPerformanceFrequency(&frequency); startCount.QuadPart = 0; endCount.QuadPart = 0; #else startCount.tv_sec = startCount.tv_usec = 0; endCount.tv_sec = endCount.tv_usec = 0; #endif startTimeInMicroSec = endTimeInMicroSec = 0.0; } void StopWatch::start() { #ifdef WIN32 QueryPerformanceCounter(&startCount); #else gettimeofday(&startCount, NULL); #endif } void StopWatch::stop() { #ifdef WIN32 QueryPerformanceCounter(&endCount); #else gettimeofday(&endCount, NULL); #endif } double StopWatch::getElapsedTime(){ #ifdef WIN32 startTimeInMicroSec = startCount.QuadPart * (1000000.0 / frequency.QuadPart); endTimeInMicroSec = endCount.QuadPart * (1000000.0 / frequency.QuadPart); #else startTimeInMicroSec = (startCount.tv_sec * 1000000.0) + startCount.tv_usec; endTimeInMicroSec = (endCount.tv_sec * 1000000.0) + endCount.tv_usec; #endif return endTimeInMicroSec - startTimeInMicroSec; }
23.06383
81
0.719557
dknife
7162b04f9ca9821d3b0be771e612a4a6c51f6d42
1,829
cpp
C++
foo_spider_monkey_panel/ui/ui_slow_script.cpp
kbuffington/foo_spider_monkey_panel
ce39bb098a9ea150baf78d18c60f7ee6617598f7
[ "MIT" ]
189
2018-09-28T19:02:41.000Z
2022-03-30T06:43:36.000Z
foo_spider_monkey_panel/ui/ui_slow_script.cpp
kbuffington/foo_spider_monkey_panel
ce39bb098a9ea150baf78d18c60f7ee6617598f7
[ "MIT" ]
145
2018-09-20T01:09:55.000Z
2022-03-03T16:50:40.000Z
foo_spider_monkey_panel/ui/ui_slow_script.cpp
kbuffington/foo_spider_monkey_panel
ce39bb098a9ea150baf78d18c60f7ee6617598f7
[ "MIT" ]
34
2018-09-20T12:44:01.000Z
2022-03-13T22:24:21.000Z
#include <stdafx.h> #include "ui_slow_script.h" namespace smp::ui { // TODO: add question icon like here - https://www.google.com/search?q=firefox+slow+script+warning&tbm=isch CDialogSlowScript::CDialogSlowScript( const qwr::u8string& panelName, const qwr::u8string& scriptInfo, CDialogSlowScript::Data& data ) : panelName_( panelName ) , scriptInfo_( scriptInfo ) , data_( data ) { } LRESULT CDialogSlowScript::OnInitDialog( HWND, LPARAM ) { (void)CenterWindow(); const auto text = [&panelName = panelName_, &scriptInfo = scriptInfo_] { qwr::u8string tmp; if ( !panelName.empty() ) { tmp += fmt::format( "Panel: {}", panelName ); } if ( !scriptInfo.empty() ) { if ( !tmp.empty() ) { tmp += "\n"; } tmp += fmt::format( "Script: {}", scriptInfo ); } if ( tmp.empty() ) { tmp = "<Unable to fetch panel info>"; } return tmp; }(); (void)uSetWindowText( GetDlgItem( IDC_SLOWSCRIPT_SCRIPT_NAME ), text.c_str() ); return FALSE; // set focus to default control } LRESULT CDialogSlowScript::OnContinueScript( WORD, WORD, HWND ) { data_.stop = false; EndDialog( IDOK ); return 0; } LRESULT CDialogSlowScript::OnStopScript( WORD, WORD, HWND ) { data_.stop = true; data_.askAgain = true; EndDialog( IDOK ); return 0; } LRESULT CDialogSlowScript::OnDontAskClick( WORD, WORD wID, HWND hWndCtl ) { data_.askAgain = uButton_GetCheck( hWndCtl, wID ); return 0; } LRESULT CDialogSlowScript::OnCloseCmd( WORD, WORD wID, HWND ) { if ( wID == IDCANCEL ) { data_.stop = false; data_.askAgain = true; } EndDialog( wID ); return 0; } } // namespace smp::ui
22.036145
134
0.58994
kbuffington
7165747917d856a2da08088c2d11eda94f7106e7
1,545
cpp
C++
dot_prod/dot_prod.cpp
drreynolds/Math6370-codes
5fbc413204c64dabf9a262f308314da3d372f98e
[ "CC0-1.0" ]
1
2021-09-05T01:11:31.000Z
2021-09-05T01:11:31.000Z
dot_prod/dot_prod.cpp
drreynolds/Math6370-codes
5fbc413204c64dabf9a262f308314da3d372f98e
[ "CC0-1.0" ]
null
null
null
dot_prod/dot_prod.cpp
drreynolds/Math6370-codes
5fbc413204c64dabf9a262f308314da3d372f98e
[ "CC0-1.0" ]
null
null
null
/* Daniel R. Reynolds SMU Mathematics Math 4370/6370 7 February 2015 */ // Inclusions #include <stdlib.h> #include <stdio.h> #include "get_time.h" // Example routine to compute the dot-product of two vectors int main(int argc, char* argv[]) { // declarations int i, n; double *a, *b, sum, alloctime, inittime, runtime; double stime, ftime; // ensure that an argument was passed in if (argc < 2) { printf("Error: function requires one argument (vector length)\n"); return 1; } // set n as the input argument, and ensure it's positive n = atoi(argv[1]); if (n < 1) { printf("Error: vector length %i must be greater than 0\n", n); return 1; } // allocate the vectors stime = get_time(); a = new double[n]; b = new double[n]; ftime = get_time(); alloctime = ftime-stime; // initialize the vector values stime = get_time(); for (i=0; i<n; i++) a[i] = (0.001 * (i + 1.0)) / n; for (i=0; i<n; i++) b[i] = (0.001 * (n - i - 1.0)) / n; ftime = get_time(); inittime = ftime-stime; // compute dot-product stime = get_time(); sum = 0.0; for (i=0; i<n; i++) sum += a[i]*b[i]; ftime = get_time(); runtime = ftime - stime; // output computed value and runtime printf(" vector length = %i\n",n); printf(" dot-product = %.16e\n",sum); printf(" alloc time = %.2e\n",alloctime); printf(" init time = %.2e\n",inittime); printf(" run time = %.2e\n",runtime); // delete vectors delete[] a; delete[] b; return 0; } // end main
22.391304
70
0.587702
drreynolds
7169274d62bcd4f4613351eedba1f4725c0af843
13,558
cpp
C++
src/phyx-1.01/src/main_bpseq.cpp
jlanga/smsk_selection
08070c6d4a6fbd9320265e1e698c95ba80f81123
[ "MIT" ]
4
2021-07-18T05:20:20.000Z
2022-01-03T10:22:33.000Z
src/phyx-1.01/src/main_bpseq.cpp
jlanga/smsk_selection
08070c6d4a6fbd9320265e1e698c95ba80f81123
[ "MIT" ]
1
2017-08-21T07:26:13.000Z
2018-11-08T13:59:48.000Z
src/phyx-1.01/src/main_bpseq.cpp
jlanga/smsk_orthofinder
08070c6d4a6fbd9320265e1e698c95ba80f81123
[ "MIT" ]
2
2021-07-18T05:20:26.000Z
2022-03-31T18:23:31.000Z
#include <iostream> #include <fstream> #include <string> #include <vector> #include <cstring> #include <getopt.h> #include <algorithm> #include <set> using namespace std; #include "tree.h" #include "tree_reader.h" #include "sequence.h" #include "seq_reader.h" #include "utils.h" #include "log.h" void print_help() { cout << "This will print out partitions found in seqfile." << endl; cout << "Can read from stdin or file." << endl; cout << endl; cout << "Usage: pxbpsq [OPTION]... [FILE]..." << endl; cout << endl; cout << " -s, --seqf=FILE input sequence file, stdin otherwise" << endl; cout << " -t, --treef=FILE input tree file, stdin otherwise" << endl; cout << " -o, --outf=FILE output file, stout otherwise" << endl; cout << " -h, --help display this help and exit" << endl; cout << " -V, --version display version and exit" << endl; cout << endl; cout << "Report bugs to: <https://github.com/FePhyFoFum/phyx/issues>" << endl; cout << "phyx home page: <https://github.com/FePhyFoFum/phyx>" << endl; } /* * add you name if you contribute (probably add another line) */ string versionline("pxbpsq 0.1\nCopyright (C) 2014 FePhyFoFum\nLicense GPLv3\nwritten by Stephen A. Smith (blackrim)"); static struct option const long_options[] = { {"seqf", required_argument, NULL, 's'}, {"treef", required_argument, NULL, 't'}, {"outf", required_argument, NULL, 'o'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'V'}, {NULL, 0, NULL, 0} }; int main(int argc, char * argv[]) { log_call(argc, argv); bool fileset = false; bool tfileset = false; bool outfileset = false; bool conditional = false; // not used char * seqf = NULL; char * treef = NULL; char * outf = NULL; while (1) { int oi = -1; int c = getopt_long(argc, argv, "s:t:o:hV", long_options, &oi); if (c == -1) { break; } switch(c) { case 's': fileset = true; seqf = strdup(optarg); check_file_exists(seqf); break; case 't': tfileset = true; conditional = true; treef = strdup(optarg); check_file_exists(treef); break; case 'o': outfileset = true; outf = strdup(optarg); break; case 'h': print_help(); exit(0); case 'V': cout << versionline << endl; exit(0); default: print_error(argv[0], (char)c); exit(0); } } istream * pios = NULL; istream * piost = NULL; ostream * poos = NULL; ifstream * fstr = NULL; ofstream * ofstr = NULL; ifstream * tfstr = NULL; if (fileset == true) { fstr = new ifstream(seqf); pios = fstr; } else { pios = &cin; if (check_for_input_to_stream() == false) { print_help(); exit(1); } } if (outfileset == true) { ofstr = new ofstream(outf); poos = ofstr; } else { poos = &cout; } // if treefile there, read the trees // then we will calculate the conditional biparts as well vector<Tree *> trees; if (tfileset == true) { tfstr = new ifstream(treef); piost = tfstr; TreeReader tr; string retstring; while (getline(*piost,retstring)) { trees.push_back(tr.readTree(retstring)); } int numtrees = trees.size(); if (numtrees == 0) { cout << "there are no trees;" << endl; } } // read the sequences vector<Sequence> seqs; Sequence seq; string retstring; int ft = test_seq_filetype_stream(*pios,retstring); while (read_next_seq_from_stream(*pios,ft,retstring,seq)) { seqs.push_back(seq); } // fasta has a trailing one if (ft == 2) { seqs.push_back(seq); } // get the biparts for the trees vector<string> names; map<string,int> name_index; map<int,string> name_st_index; for (unsigned int i=0; i < seqs.size(); i++) { string tname = seqs[i].get_id(); name_index[tname] = i; (*poos) << tname << " " << i << endl; names.push_back(tname); name_st_index[i] = tname; } int numseqs = seqs.size(); int numcols = seqs[0].get_sequence().size(); // hardcoded for DNA // can try to get more elegant later vector<vector<vector<int> > > all_bp; vector<double> bp_count; vector<int> seq_bipart_map; // for each column for (int i=0; i < numcols; i++) { vector<int> tbpa; vector<int> tbpc; vector<int> tbpg; vector<int> tbpt; int skip = 0; for (int j=0; j < numseqs; j++) { if (seqs[j].get_sequence()[i] == 'A') { tbpa.push_back(j); } else if (seqs[j].get_sequence()[i] == 'C') { tbpc.push_back(j); } else if (seqs[j].get_sequence()[i] == 'G') { tbpg.push_back(j); } else if (seqs[j].get_sequence()[i] == 'T') { tbpt.push_back(j); } else { cout << "don't recognize character " << seqs[j].get_sequence()[i] << endl; skip += 1; } } if (skip == numseqs) { continue; } sort(tbpa.begin(),tbpa.end()); sort(tbpc.begin(),tbpc.end()); sort(tbpg.begin(),tbpg.end()); sort(tbpt.begin(),tbpt.end()); vector<vector<int> > tallbp; tallbp.push_back(tbpa); tallbp.push_back(tbpc); tallbp.push_back(tbpg); tallbp.push_back(tbpt); // check to see if the bipart is new bool add = true; for (unsigned int j=0; j < all_bp.size(); j++) { // for each bipart set bool got = true; for (unsigned int k=0; k < tallbp.size(); k++) { // or each nucleotide set //bool tm = true; not used if ((int)count(all_bp[j].begin(),all_bp[j].end(),tallbp[k]) == 0) { // no match //tm = false; got = false; break; } } if (got == true) { // we have a match bp_count[j] += 1; seq_bipart_map.push_back(j); add = false; break; } } if (add == true) { all_bp.push_back(tallbp); bp_count.push_back(1); seq_bipart_map.push_back(bp_count.size()-1); } } (*poos) << numseqs << " sequences with " << numcols << " cols" << endl; (*poos) << all_bp.size() << " unique parts found" << endl; // calculate the ICA // get the parts that are not compatible // this would be an intersection of each of the parts and if one is null then it is compatible double ACA = 0; vector<double> bp_ica(bp_count.size()); for (unsigned int i=0; i < all_bp.size(); i++) { double totalcount = bp_count[i]; vector<double> conflict_nums; conflict_nums.push_back(bp_count[i]); vector<int> conflicts; for (unsigned int j=0; j < all_bp.size(); j++) { if (i == j) { continue; } bool good = true; int compcount = 0; for (unsigned int m=0; m < all_bp[i].size(); m++) { if (all_bp[i][m].size() <= 1) { continue; } else { compcount += 1; } int badcount = 0; int compcount2 = 0; for (unsigned int n=0; n < all_bp[i].size(); n++) { if (all_bp[j][n].size() <= 1) { continue; } compcount2 += 1; // intersection of [i][m] and [j][n] vector<int> v3; set_intersection(all_bp[i][m].begin(),all_bp[i][m].end(),all_bp[j][n].begin(),all_bp[j][n].end(),back_inserter(v3)); if (v3.size() > 0 && v3.size() < all_bp[j][n].size() && v3.size() < all_bp[i][m].size()) { badcount += 1; } } if (badcount >= 2 && compcount > 1 && compcount2 > 1) { good = false; break; } } if (good == false) { conflicts.push_back(j); conflict_nums.push_back(bp_count[j]); totalcount += bp_count[j]; // cout << i << " ("<<bp_count[i] << ") and " << j << " (" <<bp_count[j] << " )" << endl; // cout << "\t" << get_string_vector(all_bp[i][0]) << " | " << get_string_vector(all_bp[i][1]) << " | " << get_string_vector(all_bp[i][2]) << " | " << get_string_vector(all_bp[i][3]) << endl; // cout << "\t" << get_string_vector(all_bp[j][0]) << " | " << get_string_vector(all_bp[j][1]) << " | " << get_string_vector(all_bp[j][2]) << " | " << get_string_vector(all_bp[j][3]) << endl; } } if (conflict_nums.size() == 1) { (*poos) << i << " ("<<bp_count[i] << ") no conflict " << get_string_vector(all_bp[i][0]) << " | " << get_string_vector(all_bp[i][1]) << " | " << get_string_vector(all_bp[i][2]) << " | " << get_string_vector(all_bp[i][3]) << endl; bp_ica[i] = 1; continue; } // calculate ICA double sign = 1; for (unsigned int j=0; j < conflict_nums.size(); j++) { conflict_nums[j]/=totalcount; if (conflict_nums[j] > conflict_nums[0]) { sign = -1; } } double ICA = 1; // same as logn(conflict_nums.size(),conflict_nums.size()); for (unsigned int j=0; j < conflict_nums.size(); j++) { ICA += (conflict_nums[j]*logn(conflict_nums[j],conflict_nums.size())); } ACA += ICA; ICA *= sign; bp_ica[i] = ICA; (*poos) << i <<" (" << bp_count[i] << ")\t" << ICA << " " << get_string_vector(all_bp[i][0]) << " | " << get_string_vector(all_bp[i][1]) << " | " << get_string_vector(all_bp[i][2]) << " | " << get_string_vector(all_bp[i][3]) << endl; } (*poos) << " " << ACA << endl; //cout << get_string_vector(seq_bipart_map) << endl; // tree processing if (tfileset) { for (unsigned int t=0; t < trees.size(); t++) { vector<string> rt_nms = trees[t]->getRoot()->get_leave_names(); set<string> rt_nms_set; copy(rt_nms.begin(),rt_nms.end(),inserter(rt_nms_set,rt_nms_set.begin())); for (int j=0; j < trees[t]->getInternalNodeCount(); j++) { vector<string> nms = trees[t]->getInternalNode(j)->get_leave_names(); (*poos) << get_string_vector(nms) << endl; vector<int> nms_i; set<string> nms_s; copy(nms.begin(),nms.end(),inserter(nms_s,nms_s.begin())); for (unsigned int k=0; k < nms.size(); k++) { nms_i.push_back(name_index[nms[k]]); } sort(nms_i.begin(),nms_i.end()); // get the other side of the bipart vector<int> nms_i2; vector<string> nms_s2(rt_nms.size()); vector<string>::iterator it; it = set_difference(rt_nms_set.begin(),rt_nms_set.end(),nms_s.begin(),nms_s.end(),nms_s2.begin()); nms_s2.resize(it-nms_s2.begin()); for (unsigned int k=0; k < nms_s2.size(); k++) { nms_i2.push_back(name_index[nms_s2[k]]); } // find the biparts that are the same vector<int> matches; for (unsigned int i=0; i < all_bp.size(); i++) { for (unsigned int m=0; m < all_bp[i].size(); m++) { if (all_bp[i][m].size() <= 1 || (all_bp[i][m].size() != nms_i.size() && all_bp[i][m].size() != nms_i2.size() ) ) { continue; } vector<int> v3; set_intersection(all_bp[i][m].begin(),all_bp[i][m].end(),nms_i.begin(),nms_i.end(),back_inserter(v3)); if (v3.size() == nms_i.size()) { (*poos) << i << " (" << bp_ica[i] << ") "; break; } vector<int> v4; set_intersection(all_bp[i][m].begin(),all_bp[i][m].end(),nms_i2.begin(),nms_i2.end(),back_inserter(v4)); if (v4.size() == nms_i2.size()) { (*poos) << i << " (" << bp_ica[i] << ") "; break; } }//each part of the bipart }//each bipart (*poos) << endl; }//each internal node }//each tree tfstr->close(); delete piost; } //shut things down if (fileset) { fstr->close(); delete pios; } if (outfileset) { ofstr->close(); delete poos; } return EXIT_SUCCESS; }
36.643243
243
0.474923
jlanga
716a14b13f23ea4982ea9db24a3910515a5adea9
4,503
cpp
C++
nucleus/library/tests_timely/test_earth_time.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
2
2019-01-22T23:34:37.000Z
2021-10-31T15:44:15.000Z
nucleus/library/tests_timely/test_earth_time.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
2
2020-06-01T16:35:46.000Z
2021-10-05T21:02:09.000Z
nucleus/library/tests_timely/test_earth_time.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
null
null
null
/* * Name : test_earth_time * * Author : Chris Koeritz * ** * Copyright (c) 2007-$now By Author. 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 is online at: * * http://www.fsf.org/copyleft/gpl.html * * Please send any updates to: fred@gruntose.com * */ #define DEBUG_EARTH_TIME // set this to enable debugging features of the string class. #include <application/hoople_main.h> #include <basis/functions.h> #include <basis/guards.h> #include <basis/astring.h> #include <loggers/file_logger.h> #include <mathematics/chaos.h> #include <structures/static_memory_gremlin.h> #include <timely/earth_time.h> #include <timely/time_stamp.h> #include <unit_test/unit_base.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace application; using namespace basis; using namespace mathematics; using namespace filesystem; using namespace loggers; using namespace structures; using namespace textual; using namespace timely; using namespace unit_test; #undef LOG #define LOG(s) CLASS_EMERGENCY_LOG(program_wide_logger::get(), s) #undef BASE_LOG #define BASE_LOG(s) STAMPED_EMERGENCY_LOG(program_wide_logger::get(), s) const int TIME_FORMAT = clock_time::MERIDIAN | clock_time::SECONDS | clock_time::MILLISECONDS; // the way we like to see our seconds get printed out. ////////////// class test_earth_time : virtual public unit_base, virtual public application_shell { public: test_earth_time() {} DEFINE_CLASS_NAME("test_earth_time"); virtual int execute(); void run_test_01(); void run_test_02(); }; ////////////// void test_earth_time::run_test_01() { FUNCDEF("run_test_01"); // this test makes sure that clock_time's normalize is working as expected. time_locus checker_1(clock_time(12, 0, 60), day_in_year(), 2007); clock_time::normalize(checker_1); time_locus compare_1(clock_time(12, 1, 0), day_in_year(), 2007); //BASE_LOG(astring("a=") + checker_1.text_form(TIME_FORMAT)); //BASE_LOG(astring("b=") + compare_1.text_form(TIME_FORMAT)); ASSERT_EQUAL(checker_1, compare_1, "normalize should not fail test 1"); time_locus checker_2(clock_time(12, 0, -1), day_in_year(), 2007); clock_time::normalize(checker_2); time_locus compare_2(clock_time(11, 59, 59), day_in_year(), 2007); ASSERT_EQUAL(checker_2, compare_2, "normalize should not fail test 2"); time_locus checker_3(clock_time(11, 59, 61), day_in_year(), 2007); clock_time::normalize(checker_3); time_locus compare_3(clock_time(12, 00, 01), day_in_year(), 2007); ASSERT_EQUAL(checker_3, compare_3, "normalize should not fail test 3"); time_locus checker_4(clock_time(12, 54, -61), day_in_year(), 2007); clock_time::normalize(checker_4); time_locus compare_4(clock_time(12, 52, 59), day_in_year(), 2007); ASSERT_EQUAL(checker_4, compare_4, "normalize should not fail test 4"); time_locus checker_5(clock_time(12, -32, -62), day_in_year(), 2007); clock_time::normalize(checker_5); time_locus compare_5(clock_time(11, 26, 58), day_in_year(), 2007); ASSERT_EQUAL(checker_5, compare_5, "normalize should not fail test 5"); } void test_earth_time::run_test_02() { FUNCDEF("run_test_02"); // this test makes sure that day_in_year's normalize is working as expected. time_locus checker_1(clock_time(0, 0, -1), day_in_year(JANUARY, 1), 2007); time_locus::normalize(checker_1); time_locus compare_1(clock_time(23, 59, 59), day_in_year(DECEMBER, 31), 2006); //BASE_LOG(astring("a=") + checker_1.text_form(TIME_FORMAT)); //BASE_LOG(astring("b=") + compare_1.text_form(TIME_FORMAT)); ASSERT_EQUAL(checker_1, compare_1, "normalize should not fail test 1"); time_locus checker_2(clock_time(23, 59, 60), day_in_year(DECEMBER, 31), 2007); time_locus::normalize(checker_2); time_locus compare_2(clock_time(0, 0, 0), day_in_year(JANUARY, 1), 2008); ASSERT_EQUAL(checker_2, compare_2, "normalize should not fail test 2"); //add more cases! // test leap years // test lotso things. } int test_earth_time::execute() { FUNCDEF("execute"); run_test_01(); run_test_02(); return final_report(); } ////////////// HOOPLE_MAIN(test_earth_time, )
32.868613
82
0.70664
fredhamster
716a4f48a8db46c8577cc5bb2b5ef1ef5f698de7
28,586
cpp
C++
src/ofxRemoteUI.cpp
bensnell/ofxRemoteUI
748c2da201d7568370610212efef4e4ea9710265
[ "MIT" ]
74
2015-01-06T05:08:42.000Z
2022-01-09T03:29:14.000Z
src/ofxRemoteUI.cpp
bensnell/ofxRemoteUI
748c2da201d7568370610212efef4e4ea9710265
[ "MIT" ]
15
2015-01-22T20:37:32.000Z
2020-02-06T12:25:58.000Z
src/ofxRemoteUI.cpp
bensnell/ofxRemoteUI
748c2da201d7568370610212efef4e4ea9710265
[ "MIT" ]
12
2015-02-22T16:52:14.000Z
2020-06-30T04:19:10.000Z
// // ofxRemoteUI.cpp // emptyExample // // Created by Oriol Ferrer Mesià on 09/01/13. // // #include "ofxRemoteUI.h" #include <iostream> #include <stdlib.h> #include "uriencode.h" #include <sstream> #ifdef _WIN32 #include <windows.h> #include <iphlpapi.h> #include <WinSock2.h> #pragma comment(lib, "iphlpapi.lib") #endif using namespace std; void split(vector<std::string> &tokens, const std::string &text, char separator) { std::size_t start = 0, end = 0; while ((end = text.find(separator, start)) != std::string::npos) { tokens.emplace_back(text.substr(start, end - start)); start = end + 1; } tokens.emplace_back(text.substr(start)); } bool ofxRemoteUI::ready(){ return readyToSend; } void ofxRemoteUI::setVerbose(bool b){ verbose_ = b; } float ofxRemoteUI::connectionLag(){ return avgTimeSinceLastReply; } vector<std::string> ofxRemoteUI::getPresetsList(){ return presetNames; } void ofxRemoteUI::printAllParamsDebug(){ if(orderedKeys.size() == 0) return; dataMutex.lock(); cout << "#### FULL PARAM LIST ################################" << endl; for(size_t i = 0; i < orderedKeys.size(); i++){ string key = orderedKeys[i]; RemoteUIParam thisP = params[key]; cout << " index: " << i << " list: " << key << " > "; thisP.print(); } dataMutex.unlock(); cout << "####################################################" << endl; } bool ofxRemoteUI::addParamToDB(const RemoteUIParam & p, const std::string & thisParamName){ //see if we already had it, if we didnt, set its add order # dataMutex.lock(); bool ok; auto it = params.find(thisParamName); if ( it == params.end() ){ //not found! params[thisParamName] = p; orderedKeys[ (int)orderedKeys.size() ] = thisParamName; paramsFromCode[thisParamName] = p; //cos this didnt exist before, we store it as "from code" ok = true; }else{ RLOG_ERROR << "already have a Param with that name on the DB : '" << thisParamName << "'. Ignoring it!"; ok = false; } dataMutex.unlock(); return ok; } void ofxRemoteUI::setParamDescription(const std::string & paramName, const std::string & description){ dataMutex.lock(); auto it = params.find(paramName); if ( it != params.end() ){ //not found! it->second.description = description; } dataMutex.unlock(); } void ofxRemoteUI::clearOscReceiverMsgQueue(){ ofxOscMessage tempM; //int c = 0; //delete all pending messages while (oscReceiver.getNextMessage(tempM)) { //cout << "clearOscReceiverMsgQueue " << c << endl; //c++; } } vector<std::string> ofxRemoteUI::getChangedParamsList(){ std::vector<std::string> result (paramsChangedSinceLastCheck.begin(), paramsChangedSinceLastCheck.end()); paramsChangedSinceLastCheck.clear(); return result; } DecodedMessage ofxRemoteUI::decode(const ofxOscMessage & m) const{ std::string msgAddress = m.getAddress(); if((int)msgAddress.size() > 0){ if(msgAddress[0] == '/'){ //if address starts with "/", drop it to match the fucked up remoteUI protocol msgAddress = msgAddress.substr(1, msgAddress.size() - 1); } //allow address to use the standard style /SEND/FLT/paramName instead of the legacy "SEND FLT paramName" //allow /bbb/jjj/ syntax, but convert to space-based to avoid changing all the internal logic for(int i = 0; i < (int)msgAddress.size(); i++){ if(msgAddress[i] == '/') msgAddress[i] = ' '; } } std::string action = msgAddress.substr(0, 4); //cout <<"Decode: "<< msgAddress << " action >> " << action << endl; DecodedMessage dm; //this is the lazynes maximus! if (msgAddress.length() >= 3) { if (action == "HELO") dm.action = HELO_ACTION; else if (action == "REQU") dm.action = REQUEST_ACTION; else if (action == "SEND") dm.action = SEND_PARAM_ACTION; else if (action == "CIAO") dm.action = CIAO_ACTION; else if (action == "TEST") dm.action = TEST_ACTION; else if (action == "PREL") dm.action = PRESET_LIST_ACTION; else if (action == "DELP") dm.action = DELETE_PRESET_ACTION; else if (action == "SAVP") dm.action = SAVE_PRESET_ACTION; else if (action == "SETP") dm.action = SET_PRESET_ACTION; else if (action == "RESX") dm.action = RESET_TO_XML_ACTION; else if (action == "RESD") dm.action = RESET_TO_DEFAULTS_ACTION; else if (action == "SAVE") dm.action = SAVE_CURRENT_STATE_ACTION; else if (action == "MISP") dm.action = GET_MISSING_PARAMS_IN_PRESET; //groups (note lower case p, l) else if (action == "DELp") dm.action = DELETE_GROUP_PRESET_ACTION; else if (action == "SAVp") dm.action = SAVE_GROUP_PRESET_ACTION; else if (action == "SETp") dm.action = SET_GROUP_PRESET_ACTION; //log else if (action == "LOG_") dm.action = SEND_LOG_LINE_ACTION; //remove params else if (action == "REMp") { dm.action = REMOVE_PARAM; dm.paramName = m.getArgAsString(0); } } if (msgAddress.length() >= 8) { std::string arg1 = msgAddress.substr(5, 3); //cout << "Decode" << msgAddress << " arg1 >> " << arg1 << endl; dm.argument = NULL_ARG; if (arg1 == "FLT") dm.argument = FLT_ARG; else if (arg1 == "INT") dm.argument = INT_ARG; else if (arg1 == "BOL") dm.argument = BOL_ARG; else if (arg1 == "STR") dm.argument = STR_ARG; else if (arg1 == "ENU") dm.argument = ENUM_ARG; else if (arg1 == "COL") dm.argument = COLOR_ARG; else if (arg1 == "SPA") dm.argument = SPACER_ARG; }else{ //must be a LOG_ action } if (msgAddress.length() >= 9) { std::string paramName = msgAddress.substr(9, msgAddress.length() - 9); dm.paramName = paramName; }else{ //must be a LOG_ action } return dm; } std::string ofxRemoteUI::getMyIP(std::string userChosenInteface, std::string & subnetMask){ //from https://github.com/jvcleave/LocalAddressGrabber/blob/master/src/LocalAddressGrabber.h //and http://stackoverflow.com/questions/17288908/get-network-interface-name-from-ipv4-address std::string output = RUI_LOCAL_IP_ADDRESS; #if defined(__APPLE__) || defined(__linux__) struct ifaddrs *myaddrs; struct ifaddrs *ifa; struct sockaddr_in *s4; int status; char buf[64]; status = getifaddrs(&myaddrs); if (status != 0){ RLOG_ERROR << "getifaddrs failed! errno: " << errno; }else{ for (ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next){ if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET){ s4 = (struct sockaddr_in *)(ifa->ifa_addr); if (inet_ntop(ifa->ifa_addr->sa_family, (void *)&(s4->sin_addr), buf, sizeof(buf)) == NULL){ RLOG_ERROR <<ifa->ifa_name << ": inet_ntop failed!"; } void * tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr; char SnAddressBuffer[INET_ADDRSTRLEN]; if(inet_ntop(AF_INET, tmpAddrPtr, SnAddressBuffer, INET_ADDRSTRLEN) == NULL){ RLOG_ERROR <<ifa->ifa_name << ": inet_ntop for subnet failed!"; } if(inet_ntop(ifa->ifa_addr->sa_family, (void *)&(s4->sin_addr), buf, sizeof(buf)) == NULL){ RLOG_ERROR <<ifa->ifa_name << ": inet_ntop for address failed!"; }else{ std::string interface = std::string(ifa->ifa_name); if(verbose_) RLOG_VERBOSE << "found interface: " << interface ; if( interface.length() > 2 || interface == userSuppliedNetInterface ){ if (userSuppliedNetInterface.length() > 0){ if (interface == userSuppliedNetInterface){ output = std::string(buf); subnetMask = std::string(SnAddressBuffer); RLOG_VERBOSE << "using user chosen interface: " << interface; break; } }else{ if ((interface[0] == 'e' && interface[1] == 'n') || (interface[0] == 'e' && interface[1] == 't')){ if(strlen(buf) > 2){ bool is169 = buf[0] == '1' && buf[1] == '6' && buf[2] == '9'; if(!is169){ //avoid 169.x.x.x addresses output = std::string(buf); subnetMask = std::string(SnAddressBuffer); RLOG_NOTICE << "Using interface: " << interface << " IP: " << output << " SubnetMask: " << subnetMask; break; } } } } } } } } freeifaddrs(myaddrs); } #endif #ifdef _WIN32 ULONG buflen = sizeof(IP_ADAPTER_INFO); IP_ADAPTER_INFO *pAdapterInfo = (IP_ADAPTER_INFO *)malloc(buflen); if (GetAdaptersInfo(pAdapterInfo, &buflen) == ERROR_BUFFER_OVERFLOW) { free(pAdapterInfo); pAdapterInfo = (IP_ADAPTER_INFO *)malloc(buflen); } if (GetAdaptersInfo(pAdapterInfo, &buflen) == NO_ERROR) { //FIXME: this is crappy, we get the first non 0.0.0.0 interface (no idea which order they come in) for (IP_ADAPTER_INFO *pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) { //printf("%s (%s)\n", pAdapter->IpAddressList.IpAddress.String, pAdapter->Description); std::string ip = pAdapter->IpAddressList.IpAddress.String; if (ip != "0.0.0.0"){ output = ip; subnetMask = pAdapter->IpAddressList.IpMask.String; break; } } } if (pAdapterInfo) free(pAdapterInfo); #endif if (userSuppliedNetInterface.length() > 0){ if (output == RUI_LOCAL_IP_ADDRESS){ RLOG_ERROR << "could not find the user supplied net interface: " << userSuppliedNetInterface; RLOG_ERROR << "automatic advertising will not work! "; } } return output; } #ifdef _WIN32 void GetHostName(std::string& host_name){ WSAData wsa_data; int ret_code; char buf[MAX_PATH]; WSAStartup(MAKEWORD(1, 1), &wsa_data); ret_code = gethostname(buf, MAX_PATH); if (ret_code == SOCKET_ERROR) host_name = RUI_LOCAL_IP_ADDRESS; else host_name = buf; WSACleanup(); } #endif void ofxRemoteUI::updateParamFromDecodedMessage(const ofxOscMessage & m, DecodedMessage dm){ std::string paramName = dm.paramName; RemoteUIParam original; bool newParam = true; auto it = params.find(paramName); if ( it != params.end() ){ //found the param, we already had it original = params[paramName]; newParam = false; } RemoteUIParam p = original; size_t arg = 0; switch (dm.argument) { case FLT_ARG: p.type = REMOTEUI_PARAM_FLOAT; p.floatVal = m.getArgAsFloat(arg); arg++; if(m.getNumArgs() > 1){ p.minFloat = m.getArgAsFloat(arg); arg++; p.maxFloat = m.getArgAsFloat(arg); arg++; } if (p.floatValAddr){ *p.floatValAddr = p.floatVal; }break; case INT_ARG: p.type = REMOTEUI_PARAM_INT; p.intVal = m.getArgAsInt32(arg); arg++; if(m.getNumArgs() > 1){ p.minInt = m.getArgAsInt32(arg); arg++; p.maxInt = m.getArgAsInt32(arg); arg++; } if (p.intValAddr){ *p.intValAddr = p.intVal; }break; case COLOR_ARG: p.type = REMOTEUI_PARAM_COLOR; if(m.getNumArgs() == 1){ //hex rgba encoded in one single int - vezér style #ifdef OF_AVAILABLE std::uint32_t rgba = m.getArgAsRgbaColor(arg); arg++; #else std::uint32_t rgba = m.getArgAsInt32(arg); arg++; #endif p.redVal = (rgba & 0xFF000000) >> 24; p.greenVal = (rgba & 0x00FF0000) >> 16; p.blueVal = (rgba & 0x0000FF00) >> 8; p.alphaVal = (rgba & 0x000000FF); }else{ //legacy ofxRemoteUI p.redVal = (int)m.getArgAsInt32(arg); arg++; p.greenVal = (int)m.getArgAsInt32(arg); arg++; p.blueVal = (int)m.getArgAsInt32(arg); arg++; p.alphaVal = (int)m.getArgAsInt32(arg); arg++; } if (p.redValAddr){ *p.redValAddr = p.redVal; *(p.redValAddr+1) = p.greenVal; *(p.redValAddr+2) = p.blueVal; *(p.redValAddr+3) = p.alphaVal; }break; case ENUM_ARG:{ p.type = REMOTEUI_PARAM_ENUM; p.intVal = m.getArgAsInt32(arg); arg++; if (p.intValAddr){ *p.intValAddr = p.intVal; } if(m.getNumArgs() > 1){ //for standard RUI client p.minInt = m.getArgAsInt32(arg); arg++; p.maxInt = m.getArgAsInt32(arg); arg++; int n = p.maxInt - p.minInt + 1; int i = 0; p.enumList.clear(); for (i = 0; i < n; i++) { p.enumList.emplace_back( m.getArgAsString(arg + i) ); } arg = arg + i; }else{ //for basic enum suppport, where only the enum int value is sent (ie vezer) arg ++; //only one param was used } }break; case BOL_ARG: p.type = REMOTEUI_PARAM_BOOL; p.boolVal = m.getArgAsInt32(arg) == 0 ? false : true; arg++; if (p.boolValAddr){ *p.boolValAddr = p.boolVal; }break; case STR_ARG: p.type = REMOTEUI_PARAM_STRING; p.stringVal = m.getArgAsString(arg); arg++; if (p.stringValAddr){ *p.stringValAddr = p.stringVal; }break; case SPACER_ARG: p.type = REMOTEUI_PARAM_SPACER; p.stringVal = m.getArgAsString(arg); arg++; break; case NULL_ARG: RLOG_ERROR << "updateParamFromDecodedMessage NULL type!"; break; default: RLOG_ERROR << "updateParamFromDecodedMessage unknown type!"; break; } if(m.getNumArgs() > arg){ //if msg contains bg color, parse it p.r = m.getArgAsInt32(arg); arg++; p.g = m.getArgAsInt32(arg); arg++; p.b = m.getArgAsInt32(arg); arg++; p.a = m.getArgAsInt32(arg); arg++; p.group = m.getArgAsString(arg); arg++; if(m.getNumArgs() > arg){ //if it provides a description, read it p.description = m.getArgAsString(arg); arg++; } } if ( !p.isEqualTo(original) || newParam ){ // if the udpdate changed the param, keep track of it if(std::find(paramsChangedSinceLastCheck.begin(), paramsChangedSinceLastCheck.end(), paramName) == paramsChangedSinceLastCheck.end()){ paramsChangedSinceLastCheck.emplace_back(paramName); } } //here we update our param db //params[paramName] = p; if(newParam) addParamToDB(p, paramName); else params[paramName] = p; } vector<std::string> ofxRemoteUI::getAllParamNamesList(){ vector<std::string>paramsList; //get list of params in add order dataMutex.lock(); for( auto ii = orderedKeys.begin(); ii != orderedKeys.end(); ++ii ){ const std::string & paramName = (*ii).second; paramsList.emplace_back(paramName); } dataMutex.unlock(); return paramsList; } vector<std::string> ofxRemoteUI::scanForUpdatedParamsAndSync(){ vector<std::string>paramsPendingUpdate; dataMutex.lock(); for( auto ii = params.begin(); ii != params.end(); ++ii ){ RemoteUIParam p = (*ii).second; if ( hasParamChanged(p) ){ paramsPendingUpdate.emplace_back( (*ii).first ); syncParamToPointer((*ii).first); } } dataMutex.unlock(); return paramsPendingUpdate; } void ofxRemoteUI::sendUpdateForParamsInList(vector<std::string>list){ dataMutex.lock(); for(size_t i = 0; i < list.size(); i++){ std::string name = list[i]; auto it = params.find(name); if(it!=params.end()){ const RemoteUIParam & p = params[list[i]]; //cout << "ofxRemoteUIServer: sending updated param " + list[i]; p.print(); sendParam(list[i], p); }else{ RLOG_ERROR << "param not found?!"; } } dataMutex.unlock(); } void ofxRemoteUI::syncAllParamsToPointers(){ dataMutex.lock(); for( auto ii = params.begin(); ii != params.end(); ++ii ){ syncParamToPointer( (*ii).first ); } dataMutex.unlock(); } void ofxRemoteUI::syncAllPointersToParams(){ dataMutex.lock(); for( auto ii = params.begin(); ii != params.end(); ++ii ){ syncPointerToParam( (*ii).first ); } dataMutex.unlock(); } void ofxRemoteUI::syncPointerToParam(const std::string & paramName){ RemoteUIParam &p = params[paramName]; switch (p.type) { case REMOTEUI_PARAM_FLOAT: if (p.floatValAddr){ *p.floatValAddr = p.floatVal; }break; case REMOTEUI_PARAM_ENUM: case REMOTEUI_PARAM_INT: if (p.intValAddr){ *p.intValAddr = p.intVal; }break; case REMOTEUI_PARAM_COLOR: if (p.redValAddr){ *p.redValAddr = p.redVal ; *(p.redValAddr+1) = p.greenVal; *(p.redValAddr+2) = p.blueVal; *(p.redValAddr+3) = p.alphaVal; }break; case REMOTEUI_PARAM_BOOL: if (p.boolValAddr){ *p.boolValAddr = p.boolVal; }break; case REMOTEUI_PARAM_SPACER: case REMOTEUI_PARAM_STRING: if (p.stringValAddr){ *p.stringValAddr = p.stringVal; }break; default: break; } } void ofxRemoteUI::syncParamToPointer(const std::string & paramName){ RemoteUIParam & p = params[paramName]; switch (p.type) { case REMOTEUI_PARAM_FLOAT: if (p.floatValAddr){ p.floatVal = *p.floatValAddr; }break; case REMOTEUI_PARAM_ENUM: case REMOTEUI_PARAM_INT: if (p.intValAddr){ p.intVal = *p.intValAddr; }break; case REMOTEUI_PARAM_COLOR: if (p.redValAddr){ p.redVal = *p.redValAddr; p.greenVal = *(p.redValAddr+1); p.blueVal = *(p.redValAddr+2); p.alphaVal = *(p.redValAddr+3); }break; case REMOTEUI_PARAM_BOOL: if (p.boolValAddr){ p.boolVal = *p.boolValAddr; }break; case REMOTEUI_PARAM_SPACER: case REMOTEUI_PARAM_STRING: if (p.stringValAddr){ p.stringVal = *p.stringValAddr; }break; default: break; } } bool ofxRemoteUI::hasParamChanged(const RemoteUIParam & p){ switch (p.type) { case REMOTEUI_PARAM_FLOAT: if (p.floatValAddr){ if (*p.floatValAddr != p.floatVal) return true; else return false; } return false; case REMOTEUI_PARAM_ENUM: case REMOTEUI_PARAM_INT: if (p.intValAddr){ if (*p.intValAddr != p.intVal) return true; else return false; } return false; case REMOTEUI_PARAM_COLOR: if (p.redValAddr){ if (*p.redValAddr != p.redVal || *(p.redValAddr+1) != p.greenVal || *(p.redValAddr+2) != p.blueVal || *(p.redValAddr+3) != p.alphaVal ) return true; else return false; } return false; case REMOTEUI_PARAM_BOOL: if (p.boolValAddr){ if (*p.boolValAddr != p.boolVal) return true; else return false; } return false; case REMOTEUI_PARAM_STRING: if (p.stringValAddr){ if (*p.stringValAddr != p.stringVal) return true; else return false; } return false; case REMOTEUI_PARAM_SPACER: return false; default: break; } RLOG_ERROR << "hasParamChanged >> something went wrong, unknown param type"; return false; } std::string ofxRemoteUI::stringForParamType(RemoteUIParamType t){ switch (t) { case REMOTEUI_PARAM_FLOAT: return "FLT"; case REMOTEUI_PARAM_INT: return "INT"; case REMOTEUI_PARAM_COLOR: return "COL"; case REMOTEUI_PARAM_ENUM: return "ENU"; case REMOTEUI_PARAM_BOOL: return "BOL"; case REMOTEUI_PARAM_STRING: return "STR"; case REMOTEUI_PARAM_SPACER: return "SPA"; default: break; } RLOG_ERROR << "stringForParamType >> UNKNOWN TYPE!"; return "ERR"; } bool ofxRemoteUI::paramExistsForName(const std::string & paramName){ dataMutex.lock(); auto it = params.find(paramName); dataMutex.unlock(); return it != params.end(); } RemoteUIParam ofxRemoteUI::getParamForName(const std::string & paramName){ RemoteUIParam p; dataMutex.lock(); auto it = params.find(paramName); if ( it != params.end() ){ // found! p = params[paramName]; }else{ RLOG_ERROR << "getParamForName >> param " + paramName + " not found!"; } dataMutex.unlock(); return p; } RemoteUIParam& ofxRemoteUI::getParamRefForName(const std::string & paramName){ auto it = params.find(paramName); if ( it != params.end() ){ // found! return params[paramName]; }else{ RLOG_ERROR << "getParamForName >> param " + paramName + " not found!"; } return nullParam; } std::string ofxRemoteUI::getValuesAsString(const vector<std::string> & paramList){ std::stringstream out; auto it = orderedKeys.begin(); while( it != orderedKeys.end() ){ std::string pname = it->second; if(paramList.size() == 0 || find(paramList.begin(), paramList.end(), pname) != paramList.end()){ RemoteUIParam param = params[it->second]; if(param.type != REMOTEUI_PARAM_SPACER){ out << UriEncode(it->second) << "="; } switch (param.type) { case REMOTEUI_PARAM_FLOAT: out << param.floatVal << endl; break; case REMOTEUI_PARAM_INT: out << param.intVal << endl; break; case REMOTEUI_PARAM_COLOR: out << (int)param.redVal << " " << (int)param.greenVal << " " << (int)param.blueVal << " " << (int)param.alphaVal << " " << endl; break; case REMOTEUI_PARAM_ENUM: out << param.intVal << endl; break; case REMOTEUI_PARAM_BOOL: out << (param.boolVal?"1":"0") << endl; break; case REMOTEUI_PARAM_STRING: out << UriEncode(param.stringVal) << endl; break; case REMOTEUI_PARAM_SPACER: break; default: break; } } ++it; } return out.str(); } void ofxRemoteUI::setValuesFromString( const std::string & values ){ stringstream in(values); std::string name, value; vector<std::string>changedParam; while( !in.eof() ){ getline( in, name, '=' ); getline( in, value, '\n' ); dataMutex.lock(); if( params.find( name ) != params.end() ){ RemoteUIParam param = params[name]; RemoteUIParam original = params[name]; changedParam.emplace_back(name); stringstream valstr( UriDecode(value) ); switch (param.type) { case REMOTEUI_PARAM_FLOAT: valstr >> param.floatVal; break; case REMOTEUI_PARAM_INT: valstr >> param.intVal; break; case REMOTEUI_PARAM_COLOR: { std::istringstream ss(UriDecode(value)); std::string token; std::getline(ss, token, ' '); param.redVal = atoi(token.c_str()); std::getline(ss, token, ' '); param.greenVal = atoi(token.c_str()); std::getline(ss, token, ' '); param.blueVal = atoi(token.c_str()); std::getline(ss, token, ' '); param.alphaVal = atoi(token.c_str()); } case REMOTEUI_PARAM_ENUM: valstr >> param.intVal; break; case REMOTEUI_PARAM_BOOL: valstr >> param.boolVal; break; case REMOTEUI_PARAM_STRING: param.stringVal = valstr.str(); break; case REMOTEUI_PARAM_SPACER: break; default: break; } if ( !param.isEqualTo(original) ){ // if the udpdate changed the param, keep track of it params[name] = param; syncPointerToParam(name); if(std::find(paramsChangedSinceLastCheck.begin(), paramsChangedSinceLastCheck.end(), name) == paramsChangedSinceLastCheck.end()){ paramsChangedSinceLastCheck.emplace_back(name); } } dataMutex.unlock(); }else{ if(name.size()){ RLOG_NOTICE << "unknown param name; ignoring (" << name << ")"; } } } vector<std::string>::iterator it = changedParam.begin(); while( it != changedParam.end() ){ dataMutex.lock(); if ( params.find( *it ) != params.end()){ RemoteUIParam param = params[*it]; sendUntrackedParamUpdate(param, *it); RLOG_VERBOSE << "sending update for " << *it ; ScreenNotifArg arg; arg.paramName = *it; arg.p = param; arg.bgColor = (param.type == REMOTEUI_PARAM_COLOR) ? param.getColor() : ofColor(0,0,0,0); #ifdef OF_AVAILABLE ofNotifyEvent(eventShowParamUpdateNotification, arg, this); #endif } dataMutex.unlock(); it++; } } void ofxRemoteUI::sendParam(std::string paramName, const RemoteUIParam & p){ ofxOscMessage m; //if(verbose_){ ofLogVerbose("sending >> %s ", paramName.c_str()); p.print(); } m.setAddress("/SEND " + stringForParamType(p.type) + " " + paramName); switch (p.type) { case REMOTEUI_PARAM_FLOAT: m.addFloatArg(p.floatVal); m.addFloatArg(p.minFloat); m.addFloatArg(p.maxFloat); break; case REMOTEUI_PARAM_INT: m.addIntArg(p.intVal); m.addIntArg(p.minInt); m.addIntArg(p.maxInt); break; case REMOTEUI_PARAM_COLOR: m.addIntArg(p.redVal); m.addIntArg(p.greenVal); m.addIntArg(p.blueVal); m.addIntArg(p.alphaVal); break; case REMOTEUI_PARAM_BOOL: m.addIntArg(p.boolVal ? 1 : 0); break; case REMOTEUI_PARAM_STRING: m.addStringArg(p.stringVal); break; case REMOTEUI_PARAM_ENUM:{ m.addIntArg(p.intVal); m.addIntArg(p.minInt); m.addIntArg(p.maxInt); for (size_t i = 0; i < p.enumList.size(); i++) { m.addStringArg(p.enumList[i]); } }break; case REMOTEUI_PARAM_SPACER: m.addStringArg(p.stringVal); break; default: break; } m.addIntArg(p.r); m.addIntArg(p.g); m.addIntArg(p.b); m.addIntArg(p.a); // set bg color! m.addStringArg(p.group); m.addStringArg(p.description); try{ sendMessage(m); if(verbose_) RLOG_VERBOSE << "sendParam(" << paramName << ")"; paramsSentOverOsc.insert(paramName); }catch(std::exception & e){ RLOG_ERROR << "exception sendParam " << paramName; } } //if used by server, confirmation == YES //else, NO void ofxRemoteUI::sendREQU(bool confirmation){ if(verbose_) RLOG_VERBOSE << "sendREQU()"; ofxOscMessage m; m.setAddress("/REQU"); if (confirmation) m.addStringArg("OK"); sendMessage(m); } void ofxRemoteUI::sendRESX(bool confirm){ if(verbose_) RLOG_VERBOSE << "sendRESX()"; ofxOscMessage m; m.setAddress("/RESX"); if (confirm) m.addStringArg("OK"); sendMessage(m); } void ofxRemoteUI::sendRESD(bool confirm){ if(verbose_) RLOG_VERBOSE << "sendRESD()"; ofxOscMessage m; m.setAddress("/RESD"); if (confirm) m.addStringArg("OK"); sendMessage(m); } void ofxRemoteUI::sendSAVE(bool confirm){ if(verbose_) RLOG_VERBOSE << "sendSAVE()"; ofxOscMessage m; m.setAddress("/SAVE"); if (confirm) m.addStringArg("OK"); sendMessage(m); } void ofxRemoteUI::sendTEST(){ //if(verbose_) RLOG_VERBOSE << "sendTEST()"; waitingForReply = true; timeSinceLastReply = 0.0f; ofxOscMessage m; m.setAddress("/TEST"); sendMessage(m); } //on client call, presetNames should be empty vector (request ing the list) //on server call, presetNames should have all the presetNames void ofxRemoteUI::sendPREL( vector<std::string> presetNames_ ){ if(verbose_) RLOG_VERBOSE << "sendPREL()"; ofxOscMessage m; m.setAddress("/PREL"); if (presetNames_.size() == 0){ // if we are the client requesting a preset list, delete our current list presetNames.clear(); m.addStringArg("OK"); } for(size_t i = 0; i < presetNames_.size(); i++){ m.addStringArg(presetNames_[i]); } sendMessage(m); } //on client call, presetName should be the new preset name //on server call, presetName should be empty string (so it will send "OK" void ofxRemoteUI::sendSAVP(std::string presetName, bool confirm){ if(verbose_) RLOG_VERBOSE << "sendSAVP()"; ofxOscMessage m; m.setAddress("/SAVP"); m.addStringArg(presetName); if (confirm){ m.addStringArg("OK"); } sendMessage(m); } //on client call, presetName should be the new preset name //on server call, presetName should be empty string (so it will send "OK" void ofxRemoteUI::sendSETP(std::string presetName, bool confirm){ if(verbose_) RLOG_VERBOSE << "sendSETP()"; ofxOscMessage m; m.setAddress("/SETP"); m.addStringArg(presetName); if (confirm){ m.addStringArg("OK"); } sendMessage(m); } void ofxRemoteUI::sendMISP(vector<std::string> missingParamsInPreset){ if (missingParamsInPreset.size() == 0) return; //do nothing if no params are missing if(verbose_) RLOG_VERBOSE << "sendMISP()"; ofxOscMessage m; m.setAddress("/MISP"); for(size_t i = 0; i < missingParamsInPreset.size(); i++){ m.addStringArg(missingParamsInPreset[i]); } sendMessage(m); } void ofxRemoteUI::sendREMp(const string & paramName){ if(verbose_) RLOG_VERBOSE << "sendREMp() " << paramName ; if(readyToSend){ ofxOscMessage m; m.setAddress("/REMp"); m.addStringArg(paramName); try{ sendMessage(m); }catch(std::exception & e){ RLOG_ERROR << "Exception sendREMp " << e.what() ; } } } void ofxRemoteUI::sendDELP(std::string presetName, bool confirm){ if(verbose_) RLOG_VERBOSE << "sendDELP()"; ofxOscMessage m; m.setAddress("/DELP"); m.addStringArg(presetName); if (confirm){ m.addStringArg("OK"); } sendMessage(m); } void ofxRemoteUI::sendHELLO(){ ofxOscMessage m; m.setAddress("/HELO"); sendMessage(m); } void ofxRemoteUI::sendCIAO(){ ofxOscMessage m; m.setAddress("/CIAO"); sendMessage(m); } //on client call, presetName should be the new preset name //on server call, presetName should be empty string (so it will send "OK" void ofxRemoteUI::sendSETp(std::string presetName, std::string group, bool confirm){ if(verbose_) RLOG_VERBOSE << "sendSETp()"; ofxOscMessage m; m.setAddress("/SETp"); m.addStringArg(presetName); m.addStringArg(group); if (confirm){ m.addStringArg("OK"); } sendMessage(m); } //on client call, presetName should be the new preset name //on server call, presetName should be empty string (so it will send "OK" void ofxRemoteUI::sendSAVp(std::string presetName, std::string group, bool confirm){ if(verbose_) RLOG_VERBOSE << "sendSAVp()"; ofxOscMessage m; m.setAddress("/SAVp"); m.addStringArg(presetName); m.addStringArg(group); if (confirm){ m.addStringArg("OK"); } sendMessage(m); } //on client call, presetName should be the new preset name //on server call, presetName should be empty string (so it will send "OK" void ofxRemoteUI::sendDELp(std::string presetName, std::string group, bool confirm){ if(verbose_) RLOG_VERBOSE << "sendDELp()"; ofxOscMessage m; m.setAddress("/DELp"); m.addStringArg(presetName); m.addStringArg(group); if (confirm){ m.addStringArg("OK"); } sendMessage(m); } const char *get_filename_ext(const char *filename) { const char *dot = strrchr(filename, '.'); if(!dot || dot == filename) return ""; return dot + 1; }
29.050813
167
0.669489
bensnell
716d6ff89efec8bad608f89174518f0b59c56ae0
2,783
cpp
C++
src/Components/ConcaveCollider.cpp
charlieSewell/YOKAI
4fb39975e58e9a49bc984bc6e844721a7ad9462e
[ "MIT" ]
null
null
null
src/Components/ConcaveCollider.cpp
charlieSewell/YOKAI
4fb39975e58e9a49bc984bc6e844721a7ad9462e
[ "MIT" ]
null
null
null
src/Components/ConcaveCollider.cpp
charlieSewell/YOKAI
4fb39975e58e9a49bc984bc6e844721a7ad9462e
[ "MIT" ]
null
null
null
#include "ConcaveCollider.hpp" ConcaveCollider::ConcaveCollider(GameObject* parent) : Component(parent){} void ConcaveCollider::Start() { if(m_parent->GetComponent<Transform>() == nullptr) { m_parent->AddComponent<Transform>(); } modelID = m_parent->GetComponent<DrawableEntity>()->GetModelID(); m_colliderID = PhysicsSystem::getInstance().AddConcaveShape(3,m_parent->GetComponent<Transform>().get(),m_parent->GetComponent<DrawableEntity>()->GetModelID()); } void ConcaveCollider::Update(float deltaTime) { } void ConcaveCollider::setMass(double m) { PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetMass(m); } double ConcaveCollider::getMass() { return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetMass(); } double ConcaveCollider::getInverseMass() { return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetInverseMass(); } void ConcaveCollider::setCentreOfMass(glm::dvec3 com) { PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetCentreOfMass(com); } glm::dvec3 ConcaveCollider::getCentreOfMass() { return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetCentreOfMass(); } void ConcaveCollider::setInertiaTensor(glm::dmat3x3 it) { PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetInertiaTensor(it); } glm::dmat3x3 ConcaveCollider::getInertiaTensor() { return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetInertiaTensor(); } glm::dmat3x3 ConcaveCollider::getInverseInertiaTensor() { return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetInverseInertiaTensor(); } void ConcaveCollider::setLinearVelocity(glm::dvec3 lv) { PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetLinearVelocity(lv); } glm::dvec3 ConcaveCollider::getLinearVelocity() { return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetLinearVelocity(); } void ConcaveCollider::setAngularVelocity(glm::dvec3 av) { PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetAngularVelocity(av); } glm::dvec3 ConcaveCollider::getAngularVelocity() { return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetAngularVelocity(); } void ConcaveCollider::setIsStaticObject(bool s) { PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetIsStaticObject(s); } bool ConcaveCollider::getIsStaticObject() { return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetIsStaticObject(); } void ConcaveCollider::setGravityAffected(bool g) { PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetGravityAffected(g); } bool ConcaveCollider::getGravityAffected() { return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetGravityAffected(); }
33.939024
161
0.775782
charlieSewell
716f342aa6b588f4e376ac4f8618ba577645342c
1,928
cpp
C++
C++/Timer.cpp
juliafeingold/My-Cpp-programs
cbc7095082da25ce2a4f66d711d77af8d794206c
[ "Apache-2.0" ]
null
null
null
C++/Timer.cpp
juliafeingold/My-Cpp-programs
cbc7095082da25ce2a4f66d711d77af8d794206c
[ "Apache-2.0" ]
null
null
null
C++/Timer.cpp
juliafeingold/My-Cpp-programs
cbc7095082da25ce2a4f66d711d77af8d794206c
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; class Timer { protected: int setting; int current; public: Timer(int s){ setting = s; current = s; } virtual void OneTick(){ current--; } virtual bool Done() const{ return (current == 0); } virtual void Reset(){ current = setting; } virtual void Go() { while (this->Done() == false) { cout << current << "*"; this->OneTick(); } cout << "ding!\n"; } }; class UpwardCounter : public Timer { public: UpwardCounter(int s) : Timer(s){ current = 0; } virtual void OneTick(){ current++; } virtual bool Done() const{ return (current >= setting); } virtual void Reset() { current = 0; } }; class MultCounter : public UpwardCounter { protected: int mult; public: MultCounter(int s, int m) : UpwardCounter(s){ mult = m; current = 1; } virtual void OneTick() { current = current * mult; } virtual void Reset() { current = 1; } }; class ExpoCounter : public MultCounter { public: ExpoCounter(int s, int m = 1) : MultCounter(s, m) { current = 1; } void OneTick() { mult++; current = mult * mult; } void Reset() { mult = 1; current = 1; } }; int main() { cout << "Part 1" << endl; Timer timerA(4); timerA.Go(); cout << endl << endl; cout << "Part 2" << endl; UpwardCounter upB(4); upB.Go(); cout << endl << endl; cout << "Part 3" << endl; MultCounter multC(8, 2); multC.Go(); cout << endl << endl; cout << "Part 4" << endl; MultCounter multD(20, 3); multD.Go(); cout << endl << endl; cout << "Part 5" << endl; timerA.Reset(); timerA.Go(); cout << endl << endl; cout << "Part 6" << endl; upB.Reset(); upB.Go(); cout << endl << endl; cout << "Part 7" << endl; multD.Reset(); multD.Go(); cout << endl << endl; cout << "Part 8" << endl; ExpoCounter ecE(100); ecE.Go(); cout << endl << endl; return 0; }
14.176471
53
0.560685
juliafeingold
716fcb49daa264f7a86e37db02e53c3b1ac79a24
670
cpp
C++
src/hatchetfish_stopwatch.cpp
microwerx/hatchetfish
923b951fc0ef578773fe88edaad9754d8a43ff77
[ "MIT" ]
null
null
null
src/hatchetfish_stopwatch.cpp
microwerx/hatchetfish
923b951fc0ef578773fe88edaad9754d8a43ff77
[ "MIT" ]
null
null
null
src/hatchetfish_stopwatch.cpp
microwerx/hatchetfish
923b951fc0ef578773fe88edaad9754d8a43ff77
[ "MIT" ]
null
null
null
#include <hatchetfish_stopwatch.hpp> namespace Hf { StopWatch::StopWatch() { start_timepoint = std::chrono::system_clock::now(); } StopWatch::~StopWatch() {} void StopWatch::Start() { start_timepoint = std::chrono::system_clock::now(); } void StopWatch::Stop() { end_timepoint = std::chrono::system_clock::now(); } double StopWatch::GetSecondsElapsed() { auto diff = end_timepoint - start_timepoint; return std::chrono::duration<double>(diff).count(); } double StopWatch::GetMillisecondsElapsed() { auto diff = end_timepoint - start_timepoint; return std::chrono::duration<double, std::milli>(diff).count(); } }
23.928571
66
0.676119
microwerx
7172b98808cb8022c7da883aeb8c5bd3eadaa54b
739
cpp
C++
atcoder/abc/abc162/b.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
atcoder/abc/abc162/b.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
atcoder/abc/abc162/b.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using pll = pair<ll, ll>; #define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i) #define all(x) (x).begin(),(x).end() #define m0(x) memset(x,0,sizeof(x)) int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1}; int main() { ll n,ans=0; cin>>n; ans=(n+1)*n/2; ll m3=n-(n%3); ll m5=n-(n%5); ll m15=n-(n%15); ll kou3=(m3-0)/3; ll sum3=kou3*(3+m3)/2; ll kou5=(m5-0)/5; ll sum5=kou5*(5+m5)/2; ll kou15=(m15-0)/15; ll sum15=kou15*(15+m15)/2; ans=ans-sum3-sum5+sum15; //cout<<ans<<" "<<sum3<<" "<<sum5<<" "<<sum15<<endl; cout<<ans<<endl; return 0; }
18.02439
58
0.516915
yu3mars
71744100fa3dcbba7d3dc1c420e6aaccd574fa6b
2,808
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/os/CMessenger.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/os/CMessenger.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/os/CMessenger.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "Elastos.Droid.Content.h" #include "elastos/droid/ext/frameworkext.h" #include "elastos/droid/os/CMessenger.h" namespace Elastos { namespace Droid { namespace Os { CAR_INTERFACE_IMPL_2(CMessenger, Object, IMessenger, IParcelable) CAR_OBJECT_IMPL(CMessenger) ECode CMessenger::constructor() { return NOERROR; } ECode CMessenger::constructor( /* [in] */ IHandler* handler) { return handler->GetIMessenger((IIMessenger**)&mTarget); } ECode CMessenger::constructor( /* [in] */ IIMessenger* target) { mTarget = target; return NOERROR; } ECode CMessenger::Send( /* [in] */ IMessage* message) { return mTarget->Send(message); } ECode CMessenger::ReadFromParcel( /* [in] */ IParcel* source) { AutoPtr<IInterface> obj; source->ReadInterfacePtr((Handle32*)&obj); mTarget = IIMessenger::Probe(obj); return NOERROR; } ECode CMessenger::WriteToParcel( /* [in] */ IParcel* dest) { return dest->WriteInterfacePtr(mTarget.Get()); } ECode CMessenger::GetIMessenger( /* [in] */ IIMessenger** mgr) { VALIDATE_NOT_NULL(mgr); *mgr = mTarget; REFCOUNT_ADD(*mgr); return NOERROR; } ECode CMessenger::GetBinder( /* [in] */ IBinder** mgr) { VALIDATE_NOT_NULL(mgr); *mgr = IBinder::Probe(mTarget); REFCOUNT_ADD(*mgr); return NOERROR; } ECode CMessenger::GetHashCode( /* [out] */ Int32* hashcode) { VALIDATE_NOT_NULL(hashcode); *hashcode = (Int32)mTarget.Get(); return NOERROR; } ECode CMessenger::Equals( /* [in] */ IMessenger* other, /* [out] */ Boolean* equals) { VALIDATE_NOT_NULL(equals); *equals = FALSE; if (other != NULL) { AutoPtr<IIMessenger> msgr; other->GetIMessenger((IIMessenger**)&msgr); *equals = (mTarget.Get() == msgr.Get()); } return NOERROR; } ECode CMessenger::Equals( /* [in] */ IInterface* other, /* [out] */ Boolean* equals) { return Equals(IMessenger::Probe(other), equals); } } // namespace Os } // namespace Droid } // namespace Elastos
23.596639
75
0.633547
jingcao80
71794cdb6a0874ede23cb71158bf445c76abbe89
1,476
cpp
C++
audio/linux/AudioEngine-linux.cpp
yangosoft/cocos2d-x-arm-opengles
af33a880b3f375ea31f0eacf4ffab769424ceba6
[ "MIT" ]
1
2020-12-26T19:47:41.000Z
2020-12-26T19:47:41.000Z
audio/linux/AudioEngine-linux.cpp
yangosoft/cocos2d-x-arm-opengles
af33a880b3f375ea31f0eacf4ffab769424ceba6
[ "MIT" ]
1
2018-05-09T08:39:17.000Z
2018-06-13T05:44:43.000Z
audio/linux/AudioEngine-linux.cpp
yangosoft/cocos2d-x-arm-opengles
af33a880b3f375ea31f0eacf4ffab769424ceba6
[ "MIT" ]
null
null
null
/** * @author cesarpachon */ #include <cstring> #include "audio/linux/AudioEngine-linux.h" #include "cocos2d.h" using namespace cocos2d; using namespace cocos2d::experimental; AudioEngineImpl * g_AudioEngineImpl = nullptr; typedef int FMOD_RESULT; AudioEngineImpl::AudioEngineImpl(){ }; AudioEngineImpl::~AudioEngineImpl(){ }; bool AudioEngineImpl::init(){ return true; }; int AudioEngineImpl::play2d(const std::string &fileFullPath ,bool loop ,float volume){ return 0; }; void AudioEngineImpl::setVolume(int audioID,float volume){ }; void AudioEngineImpl::setLoop(int audioID, bool loop){ }; bool AudioEngineImpl::pause(int audioID){ return true; }; bool AudioEngineImpl::resume(int audioID){ return true; }; bool AudioEngineImpl::stop(int audioID){ return true; }; void AudioEngineImpl::stopAll(){ }; float AudioEngineImpl::getDuration(int audioID){ return 0.0f; }; float AudioEngineImpl::getCurrentTime(int audioID){ return 0; }; bool AudioEngineImpl::setCurrentTime(int audioID, float time){ return true; }; void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback){ }; void AudioEngineImpl::uncache(const std::string& path){ }; void AudioEngineImpl::uncacheAll(){ }; int AudioEngineImpl::preload(const std::string& filePath, std::function<void(bool isSuccess)> callback){ return 0; }; void AudioEngineImpl::update(float dt){ };
15.216495
117
0.72019
yangosoft
717957c21cf925811f7f560c87d312e025a0ac71
367
cpp
C++
Algorithms/strReverseInP.cpp
Alex0Blackwell/c-projects
eb5a4507603b8510abc18223fd99c454e8effc38
[ "MIT" ]
1
2020-12-07T03:00:52.000Z
2020-12-07T03:00:52.000Z
Algorithms/strReverseInP.cpp
Alex0Blackwell/c-projects
eb5a4507603b8510abc18223fd99c454e8effc38
[ "MIT" ]
1
2020-10-02T06:27:48.000Z
2020-10-02T06:27:48.000Z
Algorithms/strReverseInP.cpp
Alex0Blackwell/c-projects
eb5a4507603b8510abc18223fd99c454e8effc38
[ "MIT" ]
2
2020-10-02T06:16:11.000Z
2020-10-27T15:05:25.000Z
#include <iostream> using namespace std; void str_reverse(char * str) { int len = 0; while (str[len] != '\0') len++; for (int i = 0; i < len / 2; i++) { char _tmp = str[i]; str[i] = str[len - 1 - i]; str[len - 1 - i] = _tmp; } return; } int main(void) { char str[] = "testing"; str_reverse(str); cout << str << endl; return 0; }
15.291667
37
0.514986
Alex0Blackwell
717a9cc799efd9644639ab0d1289a8b34e6f68e8
332
cpp
C++
code/uva/Q494.cpp
as535364/Judge-WriteupCode
e3e439a8c01d473e84422558593f7c992d0e9f8d
[ "MIT" ]
null
null
null
code/uva/Q494.cpp
as535364/Judge-WriteupCode
e3e439a8c01d473e84422558593f7c992d0e9f8d
[ "MIT" ]
null
null
null
code/uva/Q494.cpp
as535364/Judge-WriteupCode
e3e439a8c01d473e84422558593f7c992d0e9f8d
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { string s; while(getline (cin,s) ){ bool flag = 0; int ans = 0; for(int i=0;i<s.size();i++){ if( ('A'<=s[i]&&s[i]<='Z')||('a'<=s[i]&&s[i]<='z') ) flag = 1; else if(flag==1){ ans++; flag = 0; } } cout<<ans<<'\n'; } return 0; }
15.809524
55
0.478916
as535364
717e672f38fe33083e75f97b54301e9deae62407
1,057
cpp
C++
src/engine/Log.cpp
KrokodileGlue/blueshock
0e082556015562ec8fd847b9fb2f0ec62bdd9bd9
[ "MIT" ]
null
null
null
src/engine/Log.cpp
KrokodileGlue/blueshock
0e082556015562ec8fd847b9fb2f0ec62bdd9bd9
[ "MIT" ]
1
2019-06-09T14:16:34.000Z
2019-06-18T20:10:42.000Z
src/engine/Log.cpp
KrokodileGlue/blueshock
0e082556015562ec8fd847b9fb2f0ec62bdd9bd9
[ "MIT" ]
null
null
null
#include "Log.h" #include <algorithm> #include <fstream> #include <chrono> #include <ctime> std::ostringstream oss; std::ostringstream null_stream; LogLevel max_log_level = LogLevel::DEBUG3; std::ostringstream& log(LogLevel level) { if (level > max_log_level) { null_stream.str(""), null_stream.clear(); return null_stream; } oss << std::endl; std::chrono::time_point<std::chrono::system_clock> time; time = std::chrono::system_clock::now(); std::time_t end_time = std::chrono::system_clock::to_time_t(time); std::string time_str = std::ctime(&end_time); time_str.erase(std::remove(time_str.begin(), time_str.end(), '\n'), time_str.end()); oss << time_str; switch (level) { case LogLevel::ERROR: oss << " [ERROR] "; break; case LogLevel::WARNING: oss << " [WARNING] "; break; case LogLevel::INFO: oss << " [INFO] "; break; case LogLevel::DEBUG1: case LogLevel::DEBUG2: case LogLevel::DEBUG3: oss << " [DEBUG] "; break; } return oss; } void dump_log() { std::ofstream out("blueshock.log"); out << oss.str(); out.close(); }
22.020833
85
0.676443
KrokodileGlue
7180d4551c55f2a4edf3579c055c57094047cc56
34,226
cpp
C++
external/GTEngine/Source/Imagics/GteMarchingCubesTable.cpp
yushuiqiang/geometry3cpp
2727986b89da2d40ffbd0dddb6947183c8bf68b0
[ "BSL-1.0" ]
1
2021-02-18T10:25:42.000Z
2021-02-18T10:25:42.000Z
external/GTEngine/Source/Imagics/GteMarchingCubesTable.cpp
yushuiqiang/geometry3cpp
2727986b89da2d40ffbd0dddb6947183c8bf68b0
[ "BSL-1.0" ]
null
null
null
external/GTEngine/Source/Imagics/GteMarchingCubesTable.cpp
yushuiqiang/geometry3cpp
2727986b89da2d40ffbd0dddb6947183c8bf68b0
[ "BSL-1.0" ]
null
null
null
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2018 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) #include <GTEnginePCH.h> #include <Imagics/GteMarchingCubesTable.h> namespace gte { int const gMarchingCubesTable[256][41] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 0, 1, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 1, 3, 1, 5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 4, 2, 0, 4, 0, 2, 1, 3, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; }
125.369963
134
0.315754
yushuiqiang
71830e78e2b8897dfc1f04b796deb1f4a414220c
81
cpp
C++
Source/FSDEngine/Private/SDFSphereComponent.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
8
2021-07-10T20:06:05.000Z
2022-03-04T19:03:50.000Z
Source/FSDEngine/Private/SDFSphereComponent.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
9
2022-01-13T20:49:44.000Z
2022-03-27T22:56:48.000Z
Source/FSDEngine/Private/SDFSphereComponent.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
2
2021-07-10T20:05:42.000Z
2022-03-14T17:05:35.000Z
#include "SDFSphereComponent.h" USDFSphereComponent::USDFSphereComponent() { }
13.5
44
0.790123
trumank
7184fc1cd21606c535d6a2867dd72c3ebf651762
229
hpp
C++
src/lib/utils/null_streambuf.hpp
nilsthamm/hyrise
75a701f281bb7dc1636832012c43005ec3c66384
[ "MIT" ]
2
2019-01-22T19:44:32.000Z
2019-01-22T19:52:33.000Z
src/lib/utils/null_streambuf.hpp
nilsthamm/hyrise
75a701f281bb7dc1636832012c43005ec3c66384
[ "MIT" ]
69
2019-05-24T10:01:32.000Z
2019-12-13T19:09:05.000Z
src/lib/utils/null_streambuf.hpp
nilsthamm/hyrise
75a701f281bb7dc1636832012c43005ec3c66384
[ "MIT" ]
null
null
null
#pragma once #include <iosfwd> namespace opossum { // Create no-op stream that just swallows everything streamed into it // See https://stackoverflow.com/a/11826666 std::ostream& get_null_streambuf(); } // namespace opossum
19.083333
69
0.751092
nilsthamm
71852aa19c76eef464ec2e50994909b5d2afb0ff
6,257
cpp
C++
WildMagic4/LibFoundation/ComputationalGeometry/Wm4Query.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
23
2015-08-13T07:36:00.000Z
2022-01-24T19:00:04.000Z
WildMagic4/LibFoundation/ComputationalGeometry/Wm4Query.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
null
null
null
WildMagic4/LibFoundation/ComputationalGeometry/Wm4Query.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
6
2015-07-06T21:37:31.000Z
2020-07-01T04:07:50.000Z
// Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 4.10.0 (2009/11/18) #include "Wm4FoundationPCH.h" #include "Wm4Query.h" using namespace Wm4; //---------------------------------------------------------------------------- Query::Query () { } //---------------------------------------------------------------------------- Query::~Query () { } //---------------------------------------------------------------------------- bool Query::Sort (int& iV0, int& iV1) { int j0, j1; bool bPositive; if (iV0 < iV1) { j0 = 0; j1 = 1; bPositive = true; } else { j0 = 1; j1 = 0; bPositive = false; } int aiValue[2] = { iV0, iV1 }; iV0 = aiValue[j0]; iV1 = aiValue[j1]; return bPositive; } //---------------------------------------------------------------------------- bool Query::Sort (int& iV0, int& iV1, int& iV2) { int j0, j1, j2; bool bPositive; if (iV0 < iV1) { if (iV2 < iV0) { j0 = 2; j1 = 0; j2 = 1; bPositive = true; } else if (iV2 < iV1) { j0 = 0; j1 = 2; j2 = 1; bPositive = false; } else { j0 = 0; j1 = 1; j2 = 2; bPositive = true; } } else { if (iV2 < iV1) { j0 = 2; j1 = 1; j2 = 0; bPositive = false; } else if (iV2 < iV0) { j0 = 1; j1 = 2; j2 = 0; bPositive = true; } else { j0 = 1; j1 = 0; j2 = 2; bPositive = false; } } int aiValue[3] = { iV0, iV1, iV2 }; iV0 = aiValue[j0]; iV1 = aiValue[j1]; iV2 = aiValue[j2]; return bPositive; } //---------------------------------------------------------------------------- bool Query::Sort (int& iV0, int& iV1, int& iV2, int& iV3) { int j0, j1, j2, j3; bool bPositive; if (iV0 < iV1) { if (iV2 < iV3) { if (iV1 < iV2) { j0 = 0; j1 = 1; j2 = 2; j3 = 3; bPositive = true; } else if (iV3 < iV0) { j0 = 2; j1 = 3; j2 = 0; j3 = 1; bPositive = true; } else if (iV2 < iV0) { if (iV3 < iV1) { j0 = 2; j1 = 0; j2 = 3; j3 = 1; bPositive = false; } else { j0 = 2; j1 = 0; j2 = 1; j3 = 3; bPositive = true; } } else { if (iV3 < iV1) { j0 = 0; j1 = 2; j2 = 3; j3 = 1; bPositive = true; } else { j0 = 0; j1 = 2; j2 = 1; j3 = 3; bPositive = false; } } } else { if (iV1 < iV3) { j0 = 0; j1 = 1; j2 = 3; j3 = 2; bPositive = false; } else if (iV2 < iV0) { j0 = 3; j1 = 2; j2 = 0; j3 = 1; bPositive = false; } else if (iV3 < iV0) { if (iV2 < iV1) { j0 = 3; j1 = 0; j2 = 2; j3 = 1; bPositive = true; } else { j0 = 3; j1 = 0; j2 = 1; j3 = 2; bPositive = false; } } else { if (iV2 < iV1) { j0 = 0; j1 = 3; j2 = 2; j3 = 1; bPositive = false; } else { j0 = 0; j1 = 3; j2 = 1; j3 = 2; bPositive = true; } } } } else { if (iV2 < iV3) { if (iV0 < iV2) { j0 = 1; j1 = 0; j2 = 2; j3 = 3; bPositive = false; } else if (iV3 < iV1) { j0 = 2; j1 = 3; j2 = 1; j3 = 0; bPositive = false; } else if (iV2 < iV1) { if (iV3 < iV0) { j0 = 2; j1 = 1; j2 = 3; j3 = 0; bPositive = true; } else { j0 = 2; j1 = 1; j2 = 0; j3 = 3; bPositive = false; } } else { if (iV3 < iV0) { j0 = 1; j1 = 2; j2 = 3; j3 = 0; bPositive = false; } else { j0 = 1; j1 = 2; j2 = 0; j3 = 3; bPositive = true; } } } else { if (iV0 < iV3) { j0 = 1; j1 = 0; j2 = 3; j3 = 2; bPositive = true; } else if (iV2 < iV1) { j0 = 3; j1 = 2; j2 = 1; j3 = 0; bPositive = true; } else if (iV3 < iV1) { if (iV2 < iV0) { j0 = 3; j1 = 1; j2 = 2; j3 = 0; bPositive = false; } else { j0 = 3; j1 = 1; j2 = 0; j3 = 2; bPositive = true; } } else { if (iV2 < iV0) { j0 = 1; j1 = 3; j2 = 2; j3 = 0; bPositive = true; } else { j0 = 1; j1 = 3; j2 = 0; j3 = 2; bPositive = false; } } } } int aiValue[4] = { iV0, iV1, iV2, iV3 }; iV0 = aiValue[j0]; iV1 = aiValue[j1]; iV2 = aiValue[j2]; iV3 = aiValue[j3]; return bPositive; } //----------------------------------------------------------------------------
26.400844
79
0.282564
rms80
718d79499f119a3f97eeee29a7b7b42a0ac73e6c
3,843
hpp
C++
RobWorkStudio/src/rwslibs/luaeditor/LuaEditorWindow.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWorkStudio/src/rwslibs/luaeditor/LuaEditorWindow.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWorkStudio/src/rwslibs/luaeditor/LuaEditorWindow.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 LUAEDITORWINDOW_HPP_ #define LUAEDITORWINDOW_HPP_ #include <rw/core/PropertyMap.hpp> #include <rw/core/Ptr.hpp> #include <QMainWindow> #include <map> namespace rw { namespace core { class Log; }} // namespace rw::core namespace rwlibs { namespace swig { class LuaState; }} // namespace rwlibs::swig class CodeEditor; class LuaHighlighter; namespace Ui { class LuaEditorWindow; } class TreeModelCompleter; class QAbstractItemModel; namespace rws { class RobWorkStudio; class LuaExecutionThread; /** * @brief A lua editor and programming pad designed to resemble a teach pendent * for devices in RobWorkStudio. * * This editor will enable lua scripting and execution from within RobWorkStudio. */ class LuaEditorWindow : public QMainWindow { Q_OBJECT public: /** * @brief Constructor * @param lua [in] the lua state on which to operate * @param output [in] the log on which to stream print functionality and errors * @param rwstudio [in] instance of RobWorkStudio * @param parent [in] the Qt parent widget */ LuaEditorWindow (rw::core::Ptr< rwlibs::swig::LuaState > lua, rw::core::Ptr< rw::core::Log > output, rws::RobWorkStudio* rwstudio, QWidget* parent); //! @brief destructor virtual ~LuaEditorWindow (); /** * @brief change the lua state * @param lua [in] the new lua state which is to be used. */ void setLuaState (rw::core::Ptr< rwlibs::swig::LuaState > lua) { _lua = lua; } public Q_SLOTS: void on_actionNew_triggered (bool); void on_actionOpen_triggered (bool); void on_actionSave_triggered (bool); void on_actionSave_As_triggered (bool); void on_actionRun_triggered (bool); void on_actionStop_triggered (bool); void on_actionReset_triggered (bool); void on_actionReload_triggered (bool); void on_actionClose_triggered (bool); void textChanged (); void runFinished (); void ShowContextMenu (const QPoint& p); void setCheckAction (QAction*); private: QAbstractItemModel* modelFromFile (const QString& fileName, TreeModelCompleter* completer); struct EditorTab { typedef rw::core::Ptr< EditorTab > Ptr; std::string _id; CodeEditor* _editor; LuaHighlighter* _highlighter; TreeModelCompleter* _completer; std::string _filename; }; EditorTab::Ptr makeEditor (); bool save (); bool saveAs (); bool save (const std::string& filename); EditorTab::Ptr getCurrentTab (); private: //! hold std::map< QWidget*, EditorTab::Ptr > _editors; class Ui::LuaEditorWindow* _ui; rw::core::Ptr< rwlibs::swig::LuaState > _lua; rw::core::Ptr< rw::core::Log > _output; rw::core::PropertyMap _pmap; bool _isRunning; QTabWidget* _tabPane; LuaExecutionThread* _luaRunner; rws::RobWorkStudio* _rws; }; } // namespace rws #endif /* LUAEDITORWINDOW_HPP_ */
28.894737
95
0.659901
ZLW07
718d9f01288ac2f7d4dbbb76e6f7c3fad456603b
7,808
cpp
C++
dlc/src/v20210125/model/TableInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
dlc/src/v20210125/model/TableInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
dlc/src/v20210125/model/TableInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/dlc/v20210125/model/TableInfo.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Dlc::V20210125::Model; using namespace std; TableInfo::TableInfo() : m_tableBaseInfoHasBeenSet(false), m_dataFormatHasBeenSet(false), m_columnsHasBeenSet(false), m_partitionsHasBeenSet(false), m_locationHasBeenSet(false) { } CoreInternalOutcome TableInfo::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("TableBaseInfo") && !value["TableBaseInfo"].IsNull()) { if (!value["TableBaseInfo"].IsObject()) { return CoreInternalOutcome(Core::Error("response `TableInfo.TableBaseInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_tableBaseInfo.Deserialize(value["TableBaseInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_tableBaseInfoHasBeenSet = true; } if (value.HasMember("DataFormat") && !value["DataFormat"].IsNull()) { if (!value["DataFormat"].IsObject()) { return CoreInternalOutcome(Core::Error("response `TableInfo.DataFormat` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_dataFormat.Deserialize(value["DataFormat"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_dataFormatHasBeenSet = true; } if (value.HasMember("Columns") && !value["Columns"].IsNull()) { if (!value["Columns"].IsArray()) return CoreInternalOutcome(Core::Error("response `TableInfo.Columns` is not array type")); const rapidjson::Value &tmpValue = value["Columns"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { Column item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_columns.push_back(item); } m_columnsHasBeenSet = true; } if (value.HasMember("Partitions") && !value["Partitions"].IsNull()) { if (!value["Partitions"].IsArray()) return CoreInternalOutcome(Core::Error("response `TableInfo.Partitions` is not array type")); const rapidjson::Value &tmpValue = value["Partitions"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { Partition item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_partitions.push_back(item); } m_partitionsHasBeenSet = true; } if (value.HasMember("Location") && !value["Location"].IsNull()) { if (!value["Location"].IsString()) { return CoreInternalOutcome(Core::Error("response `TableInfo.Location` IsString=false incorrectly").SetRequestId(requestId)); } m_location = string(value["Location"].GetString()); m_locationHasBeenSet = true; } return CoreInternalOutcome(true); } void TableInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_tableBaseInfoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TableBaseInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_tableBaseInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_dataFormatHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DataFormat"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_dataFormat.ToJsonObject(value[key.c_str()], allocator); } if (m_columnsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Columns"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_columns.begin(); itr != m_columns.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } if (m_partitionsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Partitions"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_partitions.begin(); itr != m_partitions.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } if (m_locationHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Location"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_location.c_str(), allocator).Move(), allocator); } } TableBaseInfo TableInfo::GetTableBaseInfo() const { return m_tableBaseInfo; } void TableInfo::SetTableBaseInfo(const TableBaseInfo& _tableBaseInfo) { m_tableBaseInfo = _tableBaseInfo; m_tableBaseInfoHasBeenSet = true; } bool TableInfo::TableBaseInfoHasBeenSet() const { return m_tableBaseInfoHasBeenSet; } DataFormat TableInfo::GetDataFormat() const { return m_dataFormat; } void TableInfo::SetDataFormat(const DataFormat& _dataFormat) { m_dataFormat = _dataFormat; m_dataFormatHasBeenSet = true; } bool TableInfo::DataFormatHasBeenSet() const { return m_dataFormatHasBeenSet; } vector<Column> TableInfo::GetColumns() const { return m_columns; } void TableInfo::SetColumns(const vector<Column>& _columns) { m_columns = _columns; m_columnsHasBeenSet = true; } bool TableInfo::ColumnsHasBeenSet() const { return m_columnsHasBeenSet; } vector<Partition> TableInfo::GetPartitions() const { return m_partitions; } void TableInfo::SetPartitions(const vector<Partition>& _partitions) { m_partitions = _partitions; m_partitionsHasBeenSet = true; } bool TableInfo::PartitionsHasBeenSet() const { return m_partitionsHasBeenSet; } string TableInfo::GetLocation() const { return m_location; } void TableInfo::SetLocation(const string& _location) { m_location = _location; m_locationHasBeenSet = true; } bool TableInfo::LocationHasBeenSet() const { return m_locationHasBeenSet; }
29.243446
136
0.653304
suluner
718f2915857eb78572ee3087ff8964cb0a6cb89e
3,848
cpp
C++
PressureEngineCore/Src/Graphics/Skybox/SkyboxRenderer.cpp
Playturbo/PressureEngine
6b023165fcaecb267e13cf5532ea26a8da3f1450
[ "MIT" ]
1
2017-09-13T13:29:27.000Z
2017-09-13T13:29:27.000Z
PressureEngineCore/Src/Graphics/Skybox/SkyboxRenderer.cpp
Playturbo/PressureEngine
6b023165fcaecb267e13cf5532ea26a8da3f1450
[ "MIT" ]
null
null
null
PressureEngineCore/Src/Graphics/Skybox/SkyboxRenderer.cpp
Playturbo/PressureEngine
6b023165fcaecb267e13cf5532ea26a8da3f1450
[ "MIT" ]
1
2019-01-18T07:16:59.000Z
2019-01-18T07:16:59.000Z
#include "SkyboxRenderer.h" #include "../Textures/TextureManager.h" namespace Pressure { const std::vector<float> SkyboxRenderer::VERTICES = { -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE }; SkyboxRenderer::SkyboxRenderer(Loader& loader, GLFWwindow* window) : m_Window(window), m_Cube(loader.loadToVao(VERTICES, 3)) { m_Texture = loader.loadCubeMap(PRESSURE_SKYBOX_FILE); updateProjectionMatrix(); } void SkyboxRenderer::updateProjectionMatrix() { m_Shader.start(); m_Shader.loadProjectionMatrix(Matrix4f().createProjectionMatrix(m_Window)); m_Shader.stop(); } void SkyboxRenderer::render(Camera& camera) { m_Shader.start(); m_Shader.loadViewMatrix(camera); m_Cube.getVertexArray().bind(); glEnableVertexAttribArray(0); glActiveTexture(GL_TEXTURE0); TextureManager::Inst()->BindTexture(m_Texture, GL_TEXTURE_CUBE_MAP); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glDrawArrays(GL_TRIANGLES, 0, m_Cube.getVertexCount()); glDisableVertexAttribArray(0); m_Cube.getVertexArray().unbind(); m_Shader.stop(); } }
48.1
77
0.836798
Playturbo
71901b35a1e9482e7ee7a427b6ceec6f61d50b0b
525
cc
C++
media/base/win/mf_feature_checks.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-16T13:10:29.000Z
2021-11-16T13:10:29.000Z
media/base/win/mf_feature_checks.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/base/win/mf_feature_checks.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2021 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 "media/base/win/mf_feature_checks.h" #include "base/win/windows_version.h" #include "media/base/media_switches.h" namespace media { bool SupportMediaFoundationClearPlayback() { return base::win::GetVersion() >= base::win::Version::WIN10_RS3 && base::FeatureList::IsEnabled(media::kMediaFoundationClearPlayback); } } // namespace media
30.882353
76
0.750476
zealoussnow
7192f64980fdd3af0c267a589655e31114203a1e
142
cpp
C++
tournaments/metroCard/metroCard.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
5
2020-02-06T09:51:22.000Z
2021-03-19T00:18:44.000Z
tournaments/metroCard/metroCard.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
null
null
null
tournaments/metroCard/metroCard.cpp
gurfinkel/codeSignal
114817947ac6311bd53a48f0f0e17c0614bf7911
[ "MIT" ]
3
2019-09-27T13:06:21.000Z
2021-04-20T23:13:17.000Z
std::vector<int> metroCard(int lastNumberOfDays) { if (lastNumberOfDays == 31) { return {28, 30, 31}; } else { return {31}; } }
17.75
50
0.591549
gurfinkel
71932e8b4bcf143e427c8f8bc21a1315ba681d1a
10,837
cc
C++
chrome/browser/cookies_tree_model.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
chrome/browser/cookies_tree_model.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/cookies_tree_model.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009 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/cookies_tree_model.h" #include <algorithm> #include <functional> #include <vector> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "app/table_model_observer.h" #include "app/tree_node_model.h" #include "base/linked_ptr.h" #include "base/string_util.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "chrome/browser/profile.h" #include "grit/app_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/cookie_monster.h" #include "net/base/registry_controlled_domain.h" #include "net/url_request/url_request_context.h" #include "third_party/skia/include/core/SkBitmap.h" /////////////////////////////////////////////////////////////////////////////// // CookieTreeNode, public: void CookieTreeNode::DeleteStoredObjects() { std::for_each(children().begin(), children().end(), std::mem_fun(&CookieTreeNode::DeleteStoredObjects)); } CookiesTreeModel* CookieTreeNode::GetModel() const { if (GetParent()) return GetParent()->GetModel(); else return NULL; } /////////////////////////////////////////////////////////////////////////////// // CookieTreeCookieNode, public: CookieTreeCookieNode::CookieTreeCookieNode( net::CookieMonster::CookieListPair* cookie) : CookieTreeNode(UTF8ToWide(cookie->second.Name())), cookie_(cookie) { } void CookieTreeCookieNode::DeleteStoredObjects() { GetModel()->DeleteCookie(*cookie_); } namespace { // comparison functor, for use in CookieTreeRootNode class OriginNodeComparator { public: bool operator() (const CookieTreeNode* lhs, const CookieTreeNode* rhs) { // We want to order by registry controlled domain, so we would get // google.com, ad.google.com, www.google.com, // microsoft.com, ad.microsoft.com. CanonicalizeHost transforms the origins // into a form like google.com.www so that string comparisons work. return (CanonicalizeHost(lhs->GetTitle()) < CanonicalizeHost(rhs->GetTitle())); } private: static std::string CanonicalizeHost(const std::wstring& host_w) { // The canonicalized representation makes the registry controlled domain // come first, and then adds subdomains in reverse order, e.g. // 1.mail.google.com would become google.com.mail.1, and then a standard // string comparison works to order hosts by registry controlled domain // first. Leading dots are ignored, ".google.com" is the same as // "google.com". std::string host = WideToUTF8(host_w); std::string retval = net::RegistryControlledDomainService:: GetDomainAndRegistry(host); if (!retval.length()) // Is an IP address or other special origin. return host; std::string::size_type position = host.rfind(retval); // The host may be the registry controlled domain, in which case fail fast. if (position == 0 || position == std::string::npos) return host; // If host is www.google.com, retval will contain google.com at this point. // Start operating to the left of the registry controlled domain, e.g. in // the www.google.com example, start at index 3. --position; // If position == 0, that means it's a dot; this will be ignored to treat // ".google.com" the same as "google.com". while (position > 0) { retval += std::string("."); // Copy up to the next dot. host[position] is a dot so start after it. std::string::size_type next_dot = host.rfind(".", position - 1); if (next_dot == std::string::npos) { retval += host.substr(0, position); break; } retval += host.substr(next_dot + 1, position - (next_dot + 1)); position = next_dot; } return retval; } }; } // namespace /////////////////////////////////////////////////////////////////////////////// // CookieTreeRootNode, public: CookieTreeOriginNode* CookieTreeRootNode::GetOrCreateOriginNode( const std::wstring& origin) { // Strip the trailing dot if it exists. std::wstring rewritten_origin = origin; if (origin.length() >= 1 && origin[0] == '.') rewritten_origin = origin.substr(1); CookieTreeOriginNode rewritten_origin_node(rewritten_origin); // First see if there is an existing match. std::vector<CookieTreeNode*>::iterator origin_node_iterator = lower_bound(children().begin(), children().end(), &rewritten_origin_node, OriginNodeComparator()); if (origin_node_iterator != children().end() && rewritten_origin == (*origin_node_iterator)->GetTitle()) return static_cast<CookieTreeOriginNode*>(*origin_node_iterator); // Node doesn't exist, create a new one and insert it into the (ordered) // children. CookieTreeOriginNode* retval = new CookieTreeOriginNode(rewritten_origin); DCHECK(model_); model_->Add(this, (origin_node_iterator - children().begin()), retval); return retval; } /////////////////////////////////////////////////////////////////////////////// // CookieTreeOriginNode, public: CookieTreeCookiesNode* CookieTreeOriginNode::GetOrCreateCookiesNode() { if (cookies_child_) return cookies_child_; // need to make a Cookies node, add it to the tree, and return it CookieTreeCookiesNode* retval = new CookieTreeCookiesNode; GetModel()->Add(this, 0, retval); cookies_child_ = retval; return retval; } /////////////////////////////////////////////////////////////////////////////// // CookieTreeCookiesNode, public: CookieTreeCookiesNode::CookieTreeCookiesNode() : CookieTreeNode(l10n_util::GetString(IDS_COOKIES_COOKIES)) {} void CookieTreeCookiesNode::AddCookieNode( CookieTreeCookieNode* new_child) { std::vector<CookieTreeNode*>::iterator cookie_iterator = lower_bound(children().begin(), children().end(), new_child, CookieTreeCookieNode::CookieNodeComparator()); GetModel()->Add(this, (cookie_iterator - children().begin()), new_child); } /////////////////////////////////////////////////////////////////////////////// // CookieTreeCookieNode, private bool CookieTreeCookieNode::CookieNodeComparator::operator() ( const CookieTreeNode* lhs, const CookieTreeNode* rhs) { return (static_cast<const CookieTreeCookieNode*>(lhs)-> cookie_->second.Name() < static_cast<const CookieTreeCookieNode*>(rhs)-> cookie_->second.Name()); } /////////////////////////////////////////////////////////////////////////////// // CookiesTreeModel, public: CookiesTreeModel::CookiesTreeModel(Profile* profile) : ALLOW_THIS_IN_INITIALIZER_LIST(TreeNodeModel<CookieTreeNode>( new CookieTreeRootNode(this))), profile_(profile) { LoadCookies(); } /////////////////////////////////////////////////////////////////////////////// // CookiesTreeModel, TreeModel methods (public): // TreeModel methods: // Returns the set of icons for the nodes in the tree. You only need override // this if you don't want to use the default folder icons. void CookiesTreeModel::GetIcons(std::vector<SkBitmap>* icons) { icons->push_back(*ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_DEFAULT_FAVICON)); icons->push_back(*ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_COOKIE_ICON)); } // Returns the index of the icon to use for |node|. Return -1 to use the // default icon. The index is relative to the list of icons returned from // GetIcons. int CookiesTreeModel::GetIconIndex(TreeModelNode* node) { CookieTreeNode* ct_node = static_cast<CookieTreeNode*>(node); switch (ct_node->GetDetailedInfo().node_type) { case CookieTreeNode::DetailedInfo::TYPE_ORIGIN: return ORIGIN; break; case CookieTreeNode::DetailedInfo::TYPE_COOKIE: return COOKIE; break; default: return -1; } } void CookiesTreeModel::LoadCookies() { LoadCookiesWithFilter(L""); } void CookiesTreeModel::LoadCookiesWithFilter(const std::wstring& filter) { // mmargh mmargh mmargh! // Since we are running on the UI thread don't call GetURLRequestContext(). net::CookieMonster* cookie_monster = profile_->GetRequestContext()->GetCookieStore()->GetCookieMonster(); all_cookies_ = cookie_monster->GetAllCookies(); CookieTreeRootNode* root = static_cast<CookieTreeRootNode*>(GetRoot()); for (CookieList::iterator it = all_cookies_.begin(); it != all_cookies_.end(); ++it) { // Get the origin cookie if (!filter.size() || (UTF8ToWide(it->first).find(filter) != std::wstring::npos)) { CookieTreeOriginNode* origin = root->GetOrCreateOriginNode(UTF8ToWide(it->first)); CookieTreeCookiesNode* cookies_node = origin->GetOrCreateCookiesNode(); CookieTreeCookieNode* new_cookie = new CookieTreeCookieNode(&*it); cookies_node->AddCookieNode(new_cookie); } } } void CookiesTreeModel::DeleteCookie( const net::CookieMonster::CookieListPair& cookie) { // notify CookieMonster that we should delete this cookie // Since we are running on the UI thread don't call GetURLRequestContext(). net::CookieMonster* monster = profile_->GetRequestContext()->GetCookieStore()->GetCookieMonster(); // We have stored a copy of all the cookies in the model, and our model is // never re-calculated. Thus, we just need to delete the nodes from our // model, and tell CookieMonster to delete the cookies. We can keep the // vector storing the cookies in-tact and not delete from there (that would // invalidate our pointers), and the fact that it contains semi out-of-date // data is not problematic as we don't re-build the model based on that. monster->DeleteCookie(cookie.first, cookie.second, true); } void CookiesTreeModel::DeleteAllCookies() { CookieTreeNode* root = GetRoot(); root->DeleteStoredObjects(); int num_children = root->GetChildCount(); for (int i = num_children - 1; i >= 0; --i) delete Remove(root, i); NotifyObserverTreeNodeChanged(root); } void CookiesTreeModel::DeleteCookieNode(CookieTreeNode* cookie_node) { cookie_node->DeleteStoredObjects(); // find the parent and index CookieTreeNode* parent_node = cookie_node->GetParent(); int cookie_node_index = parent_node->IndexOfChild(cookie_node); delete Remove(parent_node, cookie_node_index); } void CookiesTreeModel::UpdateSearchResults(const std::wstring& filter) { CookieTreeNode* root = GetRoot(); int num_children = root->GetChildCount(); for (int i = num_children - 1; i >= 0; --i) delete Remove(root, i); LoadCookiesWithFilter(filter); NotifyObserverTreeNodeChanged(root); }
36.860544
79
0.667251
rwatson
719cd1668f97259fd6054860c45f9deeac2c3834
2,765
cpp
C++
project-euler/229/euler_229_v1.cpp
zoffixznet/project-euler
39921379385ae2521354c7266a541c46785e85a2
[ "MIT" ]
null
null
null
project-euler/229/euler_229_v1.cpp
zoffixznet/project-euler
39921379385ae2521354c7266a541c46785e85a2
[ "MIT" ]
null
null
null
project-euler/229/euler_229_v1.cpp
zoffixznet/project-euler
39921379385ae2521354c7266a541c46785e85a2
[ "MIT" ]
null
null
null
// The Expat License // // Copyright (c) 2017, Shlomi Fish // // 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 <string.h> #include <stdio.h> typedef long long ll; #if 0 const int L = 10000000-1; #else const ll L = 2000000000-1; #endif unsigned char v[(L >> 3) + 1]; unsigned char v2[(L >> 3) + 1]; int main(int argc, char * argv[]) { memset(v, '\0', sizeof(v)); ll dx = 1; for (ll xs = 1; xs < L; xs += (dx += 2)) { printf("Reached xs=%lld\n", xs); ll dy = dx; for (ll xys=(xs<<1); xys <= L; xys += (dy += 2)) { v[xys >> 3] |= (1 << (xys & 0x7)); } } unsigned char * o = v; unsigned char * t = v2; memset(t, '\0', sizeof(v)); const ll f_s[4] = {2,3,7,0}; for (ll f_idx=0;f_idx<3;f_idx++) { const ll f = f_s[f_idx]; const ll ddy = (f<<1); ll dx = 1; for (ll xs = 1; xs < L; xs += (dx += 2)) { printf("Reached f=%lld xs=%lld\n", f, xs); ll dy = f; for (ll xys=xs+dy; xys <= L; xys += (dy += ddy)) { const ll byte = xys >> 3; const ll bit = (1 << (xys & 0x7)); if (o[byte] & bit) { t[byte] |= bit; } } } if (o == v) { o = v2; t = v; } else { o = v; t = v2; } memset(t, '\0', sizeof(v)); } { ll c = 0; for (ll n = 2 ; n <= L ; n++) { if (o[n >> 3] & (1 << (n&0x7))) { printf( "Found %lld\n", (++c)); } } } return 0; }
26.84466
80
0.515009
zoffixznet
719f720be5fbe75c0f3c5fe4a2b09b9b8d09eaac
20,394
cpp
C++
src/funcs_cpp/BACKUP/BKU_lib_integrals_electron.cpp
Jussmith01/HFSCFCISProgram
957d92229905c06fb97fba4ca3c2765ae8f700bb
[ "MIT" ]
null
null
null
src/funcs_cpp/BACKUP/BKU_lib_integrals_electron.cpp
Jussmith01/HFSCFCISProgram
957d92229905c06fb97fba4ca3c2765ae8f700bb
[ "MIT" ]
null
null
null
src/funcs_cpp/BACKUP/BKU_lib_integrals_electron.cpp
Jussmith01/HFSCFCISProgram
957d92229905c06fb97fba4ca3c2765ae8f700bb
[ "MIT" ]
null
null
null
#define _USE_MATH_DEFINES #include <stdio.h> #include <stdlib.h> #include <sstream> #include <string.h> #include <string> #include <cmath> #include <math.h> #include <fstream> #include <time.h> #include <iostream> #include "../utils_cpp/lib_includes.h" #include "../classes/classes.h" #include "../scf_main/scf_classes.h" #include "func_classes.h" #include "lib_integrals.h" using namespace std; //________________________________________________________________________// // ************************************************************* // // Calculate P0 portion of the Electron Integrals // // ************************************************************* // /* ----Author: Justin Smith ---- ----Date Modified: 10/27/2014 ---- ----Modified By: ---- */ double J0_func(int axI,int axJ,double an1,double an2) { double rtnval; rtnval = pow(-1,axI + axJ) * fact(axI) * fact(axJ) / (double)(pow(an1 + an2,axI + axJ)); return rtnval; } //________________________________________________________________________// // ************************************************************* // // Calculate J1 portion of the Electron Integrals // // ************************************************************* // /* ----Author: Justin Smith ---- ----Date Modified: 10/27/2014 ---- ----Modified By: ---- */ double J1_func(int i1,int i2,int o1,int o2,int r1,int aA,int aB,int aC,int aD,double an1,double an2,double an3,double an4,double Axyz,double Bxyz) { double rtnval; rtnval = (pow(-1, o2 + r1) * fact(o1 + o2) / (double)(pow(4,i1 + i2 + r1) * fact(i1) * fact(i2) * fact(o1) * fact(o2) * fact(r1))) * ((pow(an1,o2 - i1 - r1) * pow(an2,o1 - i2 - r1) * pow(an1 + an2,2 * (i1 + i2) + r1) * pow(Axyz - Bxyz,o1 + o2 - 2 * r1)) / (double)(fact(aA - 2 * i1 - o1) * fact(aB - 2 * i2 - o2) * fact(o1 + o2 - 2 * r1))) * ((fact(aC) * fact(aD)) / (double)(pow(an3 + an4,aC + aD))); return rtnval; } //________________________________________________________________________// // ************************************************************* // // Calculate J2 portion of the Electron Integrals // // ************************************************************* // /* ----Author: Justin Smith ---- ----Date Modified: 10/27/2014 ---- ----Modified By: ---- */ double J2_func(int i3,int i4,int o3,int o4,int r2,int aC,int aD,double an3,double an4,double Cxyz,double Dxyz) { double rtnval; rtnval = ((pow(-1,o3 + r2) * fact(o3 + o4)) / (double)(pow(4,i3 + i4 + r2) * fact(i3) * fact(i4) * fact(o3) * fact(o4) * fact(r2))) * ((pow(an3,o4 - i3 - r2) * pow(an4,o3 - i4 - r2) * pow(an3 + an4,2 * (i3 + i4) + r2) * pow(Cxyz - Dxyz,o3 + o4 - 2 * r2)) / (double)(fact(aC - 2 * i3 - o3) * fact(aD - 2 * i4 - o4) * fact(o3 + o4 - 2 * r2))); //rtnval = 1; return rtnval; } //________________________________________________________________________// // ************************************************************* // // Calculate J3 portion of the Electron Integrals // // ************************************************************* // /* ----Author: Justin Smith ---- ----Date Modified: 10/27/2014 ---- ----Modified By: ---- */ double J3_func(int u,int mu,double n,double Pxyz,double Qxyz) { double rtnval; rtnval = ((pow(-1,u) * fact(mu) * pow(n,mu - u) * pow(Pxyz - Qxyz,mu - 2 * u)) / (double)(pow(4,u) * fact(u) * fact(mu - 2 * u))); //rtnval = 1; return rtnval; } //________________________________________________________________________// // ************************************************************* // // Calc_sum_J Terms // // ************************************************************* // /* ----Author: Justin Smith ---- ----Date Modified: 10/27/2014 ---- ----Modified By: ---- */ double calc_sum_J(int test,int axA,int ayA,int azA,int axB,int ayB,int azB,int axC,int ayC,int azC,int axD,int ayD,int azD,double Ax,double Ay,double Az,double Bx,double By,double Bz,double Cx,double Cy,double Cz,double Dx,double Dy,double Dz,double an1,double an2,double an3,double an4) { double tol = 1.0E-13; double rtnval = 0; double pos = 0; double neg = 0; double Px = (an1 * Ax + an2 * Bx) / (double)(an1 + an2); double Py = (an1 * Ay + an2 * By) / (double)(an1 + an2); double Pz = (an1 * Az + an2 * Bz) / (double)(an1 + an2); double Qx = (an3 * Cx + an4 * Dx) / (double)(an3 + an4); double Qy = (an3 * Cy + an4 * Dy) / (double)(an3 + an4); double Qz = (an3 * Cz + an4 * Dz) / (double)(an3 + an4); double PmQ = (Px - Qx) * (Px - Qx) + (Py - Qy) * (Py - Qy) + (Pz - Qz) * (Pz - Qz); //double PmQ = ((an1 * pow(pow(Ax,2.0) + pow(Ay,2.0) + pow(Az,2.0),0.5) - (an2 * pow(pow(Bx,2.0) + pow(By,2.0) + pow(Bz,2.0),0.5)) / (double)(an1 + an2))) - ((an3 * pow(pow(Cx,2.0) + pow(Cy,2.0) + pow(Cz,2.0),0.5) - (an4 * pow(pow(Dx,2.0) + pow(Dy,2.0) + pow(Dz,2.0),0.5)) / (double)(an3 + an4))); //cout << "CmP: " << CmP << " an: " << an << " bm:" << bm << "\n"; //cout << "Cx: " << Cx << " Cy: " << Cy << " Cz: " << Cz << " Px: " << Px << " Py: " << Py << " Pz: " << Pz << "\n"; cout << "axA: " << axA << " ayA: " << ayA << " azA: " << azA << " | " ; cout << " axB: " << axB << " ayB: " << ayB << " azB: " << azB << " | " ; cout << " axC: " << axC << " ayC: " << ayC << " azC: " << azC << " | " ; cout << " axD: " << axD << " ayD: " << ayD << " azD: " << azD << " | " << " PmQ: " << PmQ << "\n"; double nFACT = ((an1 + an2) * (an3 + an4)) / (double)((an1 + an2) + (an3 + an4)); //Indicies for X calculations //double J0x = J0_func(axA,axB,an1,an2) * J0_func(axC,axD,an3,an4); //double J0y = J0_func(ayA,ayB,an1,an2) * J0_func(ayC,ayD,an3,an4); //double J0z = J0_func(azA,azB,an1,an2) * J0_func(azC,azD,an3,an4); double J0x = J0_func(axA,axB,an1,an2); double J0y = J0_func(ayA,ayB,an1,an2); double J0z = J0_func(azA,azB,an1,an2); for (int ix1 = 0; ix1 <= floor(axA / (double)2.0); ++ix1) { for (int ix2 = 0; ix2 <= floor(axB / (double)2.0); ++ix2) { for (int ox1 = 0; ox1 <= axA - 2.0 * ix1; ++ox1) { for (int ox2 = 0; ox2 <= axB - 2.0 * ix2; ++ox2) { for (int rx1 = 0; rx1 <= floor((ox1 + ox2) / (double)2.0); ++rx1) { double J1x = J1_func(ix1,ix2,ox2,ox2,rx1,axA,axB,axC,axD,an1,an2,an3,an4,Ax,Bx); for (int ix3 = 0; ix3 <= floor(axC / (double)2.0); ++ix3) { for (int ix4 = 0; ix4 <= floor(axD / (double)2.0); ++ix4) { for (int ox3 = 0; ox3 <= axC - 2.0 * ix3; ++ox3) { for (int ox4 = 0; ox4 <= axD - 2.0 * ix4; ++ox4) { for (int rx2 = 0; rx2 <= floor((ox3 + ox4) / (double)2.0); ++rx2) { double J2x = J2_func(ix3,ix4,ox3,ox4,rx2,axC,axD,an3,an4,Cx,Dx); int mux = axA + axB + axC + axD - 2.0 * (ix1 + ix2 + ix3 + ix4) - (ox1 + ox2 + ox3 + ox4); for (int ux = 0; ux <= floor(mux / (double)2.0); ++ux) { double J3x = J3_func(ux,mux,nFACT,Px,Qx); //Indicies for Y calculations //double J0y = J0_func(ayA,ayB,an1,an2); for (int iy1 = 0; iy1 <= floor(ayA / (double)2.0); ++iy1) { for (int iy2 = 0; iy2 <= floor(ayB / (double)2.0); ++iy2) { for (int oy1 = 0; oy1 <= ayA - 2.0 * iy1; ++oy1) { for (int oy2 = 0; oy2 <= ayB - 2.0 * iy2; ++oy2) { for (int ry1 = 0; ry1 <= floor((oy1 + oy2) / (double)2.0); ++ry1) { double J1y = J1_func(iy1,iy2,oy2,oy2,ry1,ayA,ayB,ayC,ayD,an1,an2,an3,an4,Ay,By); for (int iy3 = 0; iy3 <= floor(ayC / (double)2.0); ++iy3) { for (int iy4 = 0; iy4 <= floor(ayD / (double)2.0); ++iy4) { for (int oy3 = 0; oy3 <= ayC - 2.0 * iy3; ++oy3) { for (int oy4 = 0; oy4 <= ayD - 2.0 * iy4; ++oy4) { for (int ry2 = 0; ry2 <= floor((oy3 + oy4) / (double)2.0); ++ry2) { double J2y = J2_func(iy3,iy4,oy3,oy4,ry2,ayC,ayD,an3,an4,Cy,Dy); int muy = ayA + ayB + ayC + ayD - 2.0 * (iy1 + iy2 + iy3 + iy4) - (oy1 + oy2 + oy3 + oy4); for (int uy = 0; uy <= floor(muy / (double)2.0); ++uy) { double J3y = J3_func(uy,muy,nFACT,Py,Qy); //Indicies for Z calculations //double J0z = J0_func(azA,azB,an1,an2); for (int iz1 = 0; iz1 <= floor(azA / (double)2.0); ++iz1) { for (int iz2 = 0; iz2 <= floor(azB / (double)2.0); ++iz2) { for (int oz1 = 0; oz1 <= azA - 2.0 * iz1; ++oz1) { for (int oz2 = 0; oz2 <= azB - 2.0 * iz2; ++oz2) { for (int rz1 = 0; rz1 <= floor((oz1 + oz2) / (double)2.0); ++rz1) { double J1z = J1_func(iz1,iz2,oz2,oz2,rz1,azA,azB,azC,azD,an1,an2,an3,an4,Az,Bz); for (int iz3 = 0; iz3 <= floor(azC / (double)2.0); ++iz3) { for (int iz4 = 0; iz4 <= floor(azD / (double)2.0); ++iz4) { for (int oz3 = 0; oz3 <= azC - 2.0 * iz3; ++oz3) { for (int oz4 = 0; oz4 <= azD - 2.0 * iz4; ++oz4) { for (int rz2 = 0; rz2 <= floor((oz3 + oz4) / (double)2.0); ++rz2) { double J2z = J2_func(iz3,iz4,oz3,oz4,rz2,azC,azD,an3,an4,Cz,Dz); int muz = azA + azB + azC + azD - 2.0 * (iz1 + iz2 + iz3 + iz4) - (oz1 + oz2 + oz3 + oz4); for (int uz = 0; uz <= floor(muz / (double)2.0); ++uz) { double J3z = J3_func(uz,muz,nFACT,Pz,Qz); double nu = mux + muy + muz - (ux + uy + uz); //Putting it all together double val = J3x * J2x * J1x * J0x * J3y * J2y * J1y * J0y * J3z * J2z * J1z * J0z * 2.0 * Fnu(nu,PmQ * nFACT); if (val > 0 && val > tol) {pos += val;} else if (val < 0 && abs(val) > tol) {neg += abs(val);} cout.setf( std::ios::fixed, std::ios::floatfield ); cout << " J3x: " << J3x << " J2x: " << J2x << " J1x: " << J1x << " J0x: " << J0x << " J3y: " << J3y << " J2y: " << J2y << " J1y: " << J1y << " J0y: " << J0y << " J3z: " << J3z << " J2z: " << J2z << " J1z: " << J1z << " J0z: " << J0z << " Fnu: " << Fnu(nu,PmQ * nFACT) << "\n"; }}}}}}}}}}} }}}}}}}}}}} }}}}}}}}}}} rtnval = pos - neg; cout << " RTNVAL: " << rtnval << "\n"; return rtnval; } //________________________________________________________________________// // ************************************************************* // // Calculate the Nuclear Attraction Integrals // Function that calculates the kinetic contribution to the fock // matrix. // ************************************************************* // /* ----Author: Justin Smith ---- ----Date Modified: 10/27/2014 ---- ----Modified By: ---- Math functions nCk(), fact(), d_fact() */ double calculate_electron_repulsion(int basisA,int basisB, int basisC,int basisD,MemHandler *data_mem,scf_data *scf,STOnG_handler *STO,int assu,int test) { double rtnval = 0; int N = STO->N; //Orbital Index int basis_A = data_mem->orb_idx[basisA]; //orbital type 1,2,3,4,5 ... int basis_B = data_mem->orb_idx[basisB]; int basis_C = data_mem->orb_idx[basisC]; int basis_D = data_mem->orb_idx[basisD]; //Atmoic Index int atomic_data_A = data_mem->atom_idx[basisA]; //Gives index of the atom in question int atomic_data_B = data_mem->atom_idx[basisB]; int atomic_data_C = data_mem->atom_idx[basisC]; int atomic_data_D = data_mem->atom_idx[basisD]; //Atomic Number int Anum = data_mem->atom_data[atomic_data_A].atomic_num; int Bnum = data_mem->atom_data[atomic_data_B].atomic_num; int Cnum = data_mem->atom_data[atomic_data_C].atomic_num; int Dnum = data_mem->atom_data[atomic_data_D].atomic_num; //A Position double Ax = data_mem->atom_data[atomic_data_A].pos_xyz[0]; double Ay = data_mem->atom_data[atomic_data_A].pos_xyz[1]; double Az = data_mem->atom_data[atomic_data_A].pos_xyz[2]; //B Position double Bx = data_mem->atom_data[atomic_data_B].pos_xyz[0]; double By = data_mem->atom_data[atomic_data_B].pos_xyz[1]; double Bz = data_mem->atom_data[atomic_data_B].pos_xyz[2]; //C Position double Cx = data_mem->atom_data[atomic_data_C].pos_xyz[0]; double Cy = data_mem->atom_data[atomic_data_C].pos_xyz[1]; double Cz = data_mem->atom_data[atomic_data_C].pos_xyz[2]; //D Position double Dx = data_mem->atom_data[atomic_data_D].pos_xyz[0]; double Dy = data_mem->atom_data[atomic_data_D].pos_xyz[1]; double Dz = data_mem->atom_data[atomic_data_D].pos_xyz[2]; //|A-B|^2 double AmB = (Ax - Bx) * (Ax - Bx) + (Ay - By) * (Ay - By) + (Az - Bz) * (Az - Bz); //|C-D|^2 double CmD = (Cx - Dx) * (Cx - Dx) + (Cy - Dy) * (Cy - Dy) + (Cz - Dz) * (Cz - Dz); //Used for indexing the constants array and obtaining the correct constants int basis_idx_A = STO[Anum].rtn_bas_idx(basis_A); int basis_idx_B = STO[Bnum].rtn_bas_idx(basis_B); int basis_idx_C = STO[Bnum].rtn_bas_idx(basis_C); int basis_idx_D = STO[Bnum].rtn_bas_idx(basis_D); //The following sets the angular numbers for the given orbital int axA,ayA,azA; int axB,ayB,azB; int axC,ayC,azC; int axD,ayD,azD; switch (basis_A) { case 1:{axA=0;ayA=0;azA=0;break;} case 2:{axA=0;ayA=0;azA=0;break;} case 3:{axA=1;ayA=0;azA=0;break;} case 4:{axA=0;ayA=1;azA=0;break;} case 5:{axA=0;ayA=0;azA=1;break;} } switch (basis_B) { case 1:{axB=0;ayB=0;azB=0;break;} case 2:{axB=0;ayB=0;azB=0;break;} case 3:{axB=1;ayB=0;azB=0;break;} case 4:{axB=0;ayB=1;azB=0;break;} case 5:{axB=0;ayB=0;azB=1;break;} } switch (basis_C) { case 1:{axC=0;ayC=0;azC=0;break;} case 2:{axC=0;ayC=0;azC=0;break;} case 3:{axC=1;ayC=0;azC=0;break;} case 4:{axC=0;ayC=1;azC=0;break;} case 5:{axC=0;ayC=0;azC=1;break;} } switch (basis_D) { case 1:{axD=0;ayD=0;azD=0;break;} case 2:{axD=0;ayD=0;azD=0;break;} case 3:{axD=1;ayD=0;azD=0;break;} case 4:{axD=0;ayD=1;azD=0;break;} case 5:{axD=0;ayD=0;azD=1;break;} } //This statement decides if the basis functions are orthogonal P functions, if they are set rtnval to 0. if ((basis_A >= 3 && basis_B >= 3 && basis_A != basis_B) || (basis_C >= 3 && basis_D >= 3 && basis_C != basis_D) && assu == 0) { rtnval = 0.00; //The following else statement calculates the rest of the integrals which are not orthogonal P functions. } else { for (int n1 = 0; n1 < N ;++n1) { for (int n2 = 0; n2 < N ;++n2) { for (int n3 = 0; n3 < N ;++n3) { for (int n4 = 0; n4 < N ;++n4) { //Load primitive gaussian exponent constant double an1 = STO[Anum - 1].a[n1 + (N * basis_idx_A - N)]; double an2 = STO[Bnum - 1].a[n2 + (N * basis_idx_B - N)]; double an3 = STO[Cnum - 1].a[n3 + (N * basis_idx_C - N)]; double an4 = STO[Dnum - 1].a[n4 + (N * basis_idx_D - N)]; //Load primitive gaussian contraction coefficient double dn1 = STO[Anum - 1].d[n1 + (N * basis_idx_A - N)]; double dn2 = STO[Bnum - 1].d[n2 + (N * basis_idx_B - N)]; double dn3 = STO[Cnum - 1].d[n3 + (N * basis_idx_C - N)]; double dn4 = STO[Dnum - 1].d[n4 + (N * basis_idx_D - N)]; //Define GammaP and GammaQ double gammaP = an1 + an2; double gammaQ = an3 + an4; //Define constant factor double NRI_fact = pow(M_PI,5 / (double)2) / (double)(gammaP * gammaQ * sqrt(gammaP + gammaQ)); cout << " n1: " << n1 << " n2: " << n2 << " n3: " << n3 << " n4: " << n4 << "\n"; double Ifact = calc_sum_J(test,axA,ayA,azA,axB,ayB,azB,axC,ayC,azC,axD,ayD,azD,Ax,Ay,Az,Bx,By,Bz,Cx,Cy,Cz,Dx,Dy,Dz,an1,an2,an3,an4); rtnval += norm(axA,ayA,azA,an1) * norm(axB,ayB,azB,an2) * norm(axC,ayC,azC,an3) * norm(axD,ayD,azD,an4) * dn1 * dn2 * dn3 * dn4 * NRI_fact * Ifact * E_factor(an1,an2,AmB) * E_factor(an3,an4,CmD); //cout << "NORMA: " << norm(axA,ayA,azA,an1) << " NORMB: " << norm(axB,ayB,azB,an2) << " NORMC: " << norm(axC,ayC,azC,an3) << " NORMD: " << norm(axD,ayD,azD,an4) << " dn1: " << dn1 << " dn2: " << dn2 << " dn3: " << dn3 << " dn4: " << dn4 << " NRI_fact: " << NRI_fact << " IFACT: " << Ifact << " E_factor1: " << E_factor(an1,an2,AmB) << " E_factor2: " << E_factor(an3,an4,CmD) << "\n"; }}}} } return rtnval; } //________________________________________________________________________// // ************************************************************* // // Electron Repulsion Main Function // Create initial index and calculate the integrals for all // degenerate electron repulsion integrals. // ************************************************************* // /* ----Author: Justin Smith ---- ----Date Modified: 10/22/2014 ---- ----Modified By: ---- */ extern void electron_repulsion_main(MemHandler *data_mem,scf_data *scf,dataOutput *optfile,STOnG_handler *STO) { //Set some variables timer int_timer; optfile->ofile << "\nBeginning Electron Repulsion Calculations...\n"; int_timer.set_timer(); //************************************** //Start Nuclear Attraction Computations //************************************** int count = 0; scf->num_deg = 0; int tot1 = scf->orbitals * (scf->orbitals + 1) / 2; int total_calcs = tot1 * (tot1 + 1) / 2; int check = 0; int strider; for (int i = 0; i < scf->orbitals; ++i) { for (int j = i; j < scf->orbitals; ++j) { for (int k = i; k < scf->orbitals; ++k) { for (int l = k; l < scf->orbitals; ++l) { if ((long int)scf->FEI.produce_unique_ident(i,j,k,l) == (long int)scf->FEI.produce_ident(i,j,k,l)) { //int testval = scf->FEI.produce_ident(i,j,k,l); //ofstream myfile; //myfile.open ("edata.bin", ios::app); //myfile << "TEST: " << i << "-" << j << "|" << k << "-" << l << "\n"; //myfile.close(); //scf->ERI_idx[scf->num_deg] = uint_val; double ERIij; //ERIij = calculate_electron_repulsion(i,j,k,l,data_mem,scf,STO,1,0); ERIij = 0.0; //scf->ERI[scf->num_deg] = ERIij; scf->FEI.set_val(ERIij,i,j,k,l); //if (abs(ERIij - ERIij2) > 1.0E-10) //{ //cout << i << "," << j << "|" << k << "," << l << " = " << ERIij << " = " << ERIij2 << "\n"; //} //cout << scf->FEI.get_val(i,j,k,l) << "\n"; double perc = (scf->num_deg / (double)total_calcs) * 100; if (perc >= check) { //cout << perc << "\%\n"; check += 10; } ++scf->num_deg; } ++count; }}}} cout << "|---------------------------------FIRST: \n\n"; double Ifact1 = calculate_electron_repulsion(2,5,5,5,data_mem,scf,STO,1,0); cout << "|---------------------------------SECOND: \n\n"; double Ifact2 = calculate_electron_repulsion(5,2,5,5,data_mem,scf,STO,1,0); cout.setf( std::ios::fixed, std::ios::floatfield ); cout << "IFACT1: " << Ifact1 << " IFACT2: " << "" << Ifact2 << "\n"; /*cout.setf( std::ios::fixed, std::ios::floatfield ); for (int n = 0;n < scf->num_deg;++n) {cout << scf->ERI_idx[n] << " = " << scf->ERI[n] << " | ";if (n % 6 == 0) {cout << "\n";}} */ //cout << "\n"; cout << " count: " << count << "\n"; cout << "FINISHED ARRAY: CALC_SIZE(" << scf->FEI.num_val << ")\n"; //************************************ //End Nuclear Attraction Computations //************************************ //Some ending functions int_timer.end_timer(); string message = "Electron Repulsion Calculationi Clock Time: "; int_timer.print_clock_time(message,optfile->ofile); optfile->ofile << "\n"; }
43.484009
409
0.500539
Jussmith01
71a35a92fec1bf1815c9967598ef40051242e149
3,416
cpp
C++
frameworks/util/socket/test/uds_session_test.cpp
openharmony-gitee-mirror/multimodalinput_input
17303b7662d0382f27c972ad7d149bee61a14f23
[ "Apache-2.0" ]
1
2021-12-03T13:56:40.000Z
2021-12-03T13:56:40.000Z
frameworks/util/socket/test/uds_session_test.cpp
openharmony-gitee-mirror/multimodalinput_input
17303b7662d0382f27c972ad7d149bee61a14f23
[ "Apache-2.0" ]
null
null
null
frameworks/util/socket/test/uds_session_test.cpp
openharmony-gitee-mirror/multimodalinput_input
17303b7662d0382f27c972ad7d149bee61a14f23
[ "Apache-2.0" ]
1
2021-09-13T11:18:23.000Z
2021-09-13T11:18:23.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include "proto.h" #include "uds_session.h" namespace { using namespace testing::ext; using namespace OHOS::MMI; class UDSSessionTest : public testing::Test { public: static void SetUpTestCase(void) {} static void TearDownTestCase(void) {} int fd_ = -1; static constexpr char programName_[] = "uds_sesion_test"; const int moduleType_ = 3; // 3 CONNECT_MODULE_TYPE_ST_TEST void SetUp() override; void TearDown() override; }; void UDSSessionTest::SetUp() { fd_ = STDOUT_FILENO; } void UDSSessionTest::TearDown() { // do nothing } HWTEST_F(UDSSessionTest, Construct, TestSize.Level1) { UDSSession udsSession(programName_, moduleType_, fd_); udsSession.Close(); } HWTEST_F(UDSSessionTest, SendMsg_type1_001, TestSize.Level1) { const char *buf = "1234"; size_t size = 4; UDSSession sesObj(programName_, moduleType_, fd_); bool retResult = sesObj.SendMsg(buf, size); EXPECT_FALSE(retResult); } HWTEST_F(UDSSessionTest, SendMsg_type1_002, TestSize.Level1) { const char *buf = nullptr; size_t size = 4; UDSSession sesObj(programName_, moduleType_, fd_); bool retResult = sesObj.SendMsg(buf, size); EXPECT_FALSE(retResult); } HWTEST_F(UDSSessionTest, SendMsg_type1_003, TestSize.Level1) { const char *buf = nullptr; size_t size = 0; UDSSession sesObj(programName_, moduleType_, fd_); bool retResult = sesObj.SendMsg(buf, size); EXPECT_FALSE(retResult); } HWTEST_F(UDSSessionTest, SendMsg_type1_004, TestSize.Level1) { const char *buf = "this unit data"; size_t size = 14; UDSSession sesObj(programName_, moduleType_, fd_); bool retResult = sesObj.SendMsg(buf, size); EXPECT_FALSE(retResult); } HWTEST_F(UDSSessionTest, SendMsg_type1_005, TestSize.Level1) { const char *buf = "this unit data"; size_t size = -1001; UDSSession sesObj(programName_, moduleType_, fd_); bool retResult = sesObj.SendMsg(buf, size); EXPECT_FALSE(retResult); } HWTEST_F(UDSSessionTest, SendMsg_type2_001, TestSize.Level1) { int32_t fd = -1; NetPacket newPacket(MmiMessageId::INVALID); UDSSession sesObj(programName_, moduleType_, fd); bool retResult = sesObj.SendMsg(newPacket); EXPECT_FALSE(retResult); } HWTEST_F(UDSSessionTest, SendMsg_type2_002, TestSize.Level1) { NetPacket newPacket(MmiMessageId::BEGIN); UDSSession sesObj(programName_, moduleType_, fd_); bool retResult = sesObj.SendMsg(newPacket); EXPECT_FALSE(retResult); } HWTEST_F(UDSSessionTest, SendMsg_type2_003, TestSize.Level1) { int32_t fd = -65535; NetPacket newPacket(MmiMessageId::BEGIN); UDSSession sesObj(programName_, moduleType_, fd); bool retResult = sesObj.SendMsg(newPacket); EXPECT_FALSE(retResult); } } // namespace
26.48062
75
0.721604
openharmony-gitee-mirror
71a7cb1b0aa87ccbbc1dde0f374cd02b583a74e5
2,310
cpp
C++
csrc/demo.cpp
DhruvKoolRajamani/ihmc-ros-control
80ce78de88f7b540d6a2b153f6899fb5cfe865fe
[ "Apache-2.0" ]
1
2022-01-05T01:38:01.000Z
2022-01-05T01:38:01.000Z
csrc/demo.cpp
DhruvKoolRajamani/ihmc-ros-control
80ce78de88f7b540d6a2b153f6899fb5cfe865fe
[ "Apache-2.0" ]
3
2016-06-15T18:26:56.000Z
2016-10-18T19:06:06.000Z
csrc/demo.cpp
DhruvKoolRajamani/ihmc-ros-control
80ce78de88f7b540d6a2b153f6899fb5cfe865fe
[ "Apache-2.0" ]
2
2016-10-25T23:36:45.000Z
2018-06-08T18:56:05.000Z
#include "jvmLauncher/launcher.h" #include <iostream> JNIEXPORT void JNICALL callVoidFunctionWithString (JNIEnv *env, jobject obj, jstring str) { const char * cstr = env->GetStringUTFChars(str, 0); std::cout << "Got string from java: " << cstr << std::endl; env->ReleaseStringUTFChars(str, cstr); } JNIEXPORT jint JNICALL callIntFunctionWithBoolean (JNIEnv *env, jobject obj, jboolean a, jboolean b) { return (a?1000:100) + (b?10:1); } timespec diff(timespec start, timespec end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return temp; } int main(int argc, char *argv[]) { Launcher launcher("-Djava.class.path=src/ihmcroscontrol/bin"); launcher.startVM(); launcher.registerNativeMethod("us.ihmc.rosControl.launcher.TestJVMLaunchCallback", "callVoidFunctionWithString", "(Ljava/lang/String;)V", (void *)&callVoidFunctionWithString); launcher.registerNativeMethod("us.ihmc.rosControl.launcher.TestJVMLaunchCallback", "callIntFunctionWithBoolean", "(ZZ)I", (void *)&callIntFunctionWithBoolean); JavaMethod* ctor = launcher.getJavaMethod("us.ihmc.rosControl.launcher.TestJVMLaunchCallback", "<init>", "(I)V"); JavaMethod* method = launcher.getJavaMethod("us.ihmc.rosControl.launcher.TestJVMLaunchCallback", "execute", "(I)V"); JavaMethod* add = launcher.getJavaMethod("us.ihmc.rosControl.launcher.TestJVMLaunchCallback", "add", "()V"); if(ctor && method && add) { jobject obj = launcher.createObject(ctor, 42); timespec start; timespec end; for(int c = 0; c < 10; c++) { clock_gettime(CLOCK_MONOTONIC, &start); for(int i = 0; i < 100000; i++) { launcher.call(add, obj); } clock_gettime(CLOCK_MONOTONIC, &end); timespec elapsed = diff(start, end); std::cout << "Took " << elapsed.tv_sec << "s, " << elapsed.tv_nsec << "nsec for 100000 iterations" << std::endl; } launcher.call(method, obj, 124); } launcher.stopVM(); }
27.831325
179
0.644156
DhruvKoolRajamani
71a8e84d1bee23bd95dc69a14bc2afb34cdc7ffb
4,306
cpp
C++
quad.cpp
mihalyvaghy/whiteboard
252d938157ff29740c2a9ba68904df9a0c8d28f0
[ "MIT" ]
null
null
null
quad.cpp
mihalyvaghy/whiteboard
252d938157ff29740c2a9ba68904df9a0c8d28f0
[ "MIT" ]
null
null
null
quad.cpp
mihalyvaghy/whiteboard
252d938157ff29740c2a9ba68904df9a0c8d28f0
[ "MIT" ]
null
null
null
#include <string> #include "quad.hpp" double QuadTree::Node::diffThreshold = 45.0; std::map<char, Color> QuadTree::Node::colorMap = QuadTree::Node::initializeColorMap(); std::map<char, Color> QuadTree::Node::initializeColorMap() { std::map<char, Color> res; res['k'] = Color::BLACK; res['b'] = Color::BLUE; res['g'] = Color::GREEN; res['r'] = Color::RED; res['w'] = Color::WHITE; return res; } QuadTree::Node::Node() : nw(nullptr), ne(nullptr), sw(nullptr), se(nullptr) {} QuadTree::Node::Node(cv::Mat image) : Node() { cv::Scalar mean, dev; cv::meanStdDev(image, mean, dev); int r = image.rows / 2, c = image.cols / 2; double min, max; cv::minMaxLoc(image, &min, &max); if (r != 0 && c != 0 && (max - min) > diffThreshold) { nw = new Node(image(cv::Range(0, r), cv::Range(0, c))); ne = new Node(image(cv::Range(0, r), cv::Range(c, image.cols))); sw = new Node(image(cv::Range(r, image.rows), cv::Range(0, c))); se = new Node(image(cv::Range(r, image.rows), cv::Range(c, image.cols))); } else color = scalar2Color(mean); } QuadTree::Node::Node(std::ifstream& file) : Node() { char tmp; file >> tmp; if (tmp == '|') { nw = new Node(file); ne = new Node(file); sw = new Node(file); se = new Node(file); } else setColor(tmp); } void QuadTree::Node::setColor(char _color) { color = QuadTree::Node::colorMap[_color]; } Color QuadTree::Node::scalar2Color(cv::Scalar s) { std::vector<int> v; v.push_back(cv::norm(s - cv::Scalar(0, 0, 0), cv::NORM_INF)); cv::Scalar c; for (int i = 0; i < 3; i++) { c = cv::Scalar(0, 0, 0); c[i] = 255; v.push_back(cv::norm(s - c, cv::NORM_INF)); } v.push_back(cv::norm(s - cv::Scalar(255, 255, 255), cv::NORM_INF)); return static_cast<Color>(std::distance(v.begin(), std::min_element(v.begin(), v.end()))); } cv::Scalar QuadTree::Node::color2Scalar(Color c) { cv::Scalar s; switch (c) { case Color::BLACK: s = cv::Scalar(0, 0, 0); break; case Color::BLUE: s = cv::Scalar(255, 0, 0); break; case Color::GREEN: s = cv::Scalar(0, 255, 0); break; case Color::RED: s = cv::Scalar(0, 0, 255); break; case Color::WHITE: s = cv::Scalar(255, 255, 255); break; default: s = cv::Scalar(255, 255, 255); break; } return s; } char QuadTree::Node::color2String(Color c) { char s; switch(c) { case Color::BLACK: s = 'k'; break; case Color::BLUE: s = 'b'; break; case Color::GREEN: s = 'g'; break; case Color::RED: s = 'r'; break; case Color::WHITE: s = 'w'; break; } return s; } void QuadTree::Node::destroy() { if (nw != nullptr) { nw->destroy(); ne->destroy(); sw->destroy(); se->destroy(); } delete this; (void*)0; } void QuadTree::Node::print(std::ofstream& file) { if (nw != nullptr) { file << "|"; nw->print(file); ne->print(file); sw->print(file); se->print(file); } else file << color2String(color); } QuadTree::QuadTree(std::string filename) { std::ifstream file(filename + std::string(".qd")); file >> size_x >> size_y; root = new Node(file); file.close(); } QuadTree::QuadTree(cv::Mat image) { size_x = image.cols; size_y = image.rows; root = new Node(image); } void QuadTree::print(std::string filename) { std::ofstream file(filename + std::string(".qd")); file << size_x << " " << size_y; root->print(file); file.close(); } QuadTree::~QuadTree() { root->destroy(); } cv::Mat QuadTree::Node::compose(int x, int y, bool grid) { cv::Mat image(y, x, CV_8UC3); if (nw != nullptr) { int r = image.rows / 2, c = image.cols / 2; nw->compose(c, r, grid).copyTo(image(cv::Range(0, r), cv::Range(0, c))); ne->compose(image.cols - c, r, grid).copyTo(image(cv::Range(0, r), cv::Range(c, image.cols))); sw->compose(c, image.rows - r, grid).copyTo(image(cv::Range(r, image.rows), cv::Range(0, c))); se->compose(image.cols - c, image.rows - r, grid).copyTo(image(cv::Range(r, image.rows), cv::Range(c, image.cols))); if (grid) { cv::line(image, cv::Point(0, r), cv::Point(image.cols, r), cv::Scalar(255, 0, 0), 1, cv::LINE_AA); cv::line(image, cv::Point(c, 0), cv::Point(c, image.rows), cv::Scalar(255, 0, 0), 1, cv::LINE_AA); } } else image = color2Scalar(color); return image; } cv::Mat QuadTree::getImage(bool grid) { return root->compose(size_x, size_y, grid); }
24.327684
118
0.602183
mihalyvaghy
71a975ed8787b8ddd826d80a98ed774f88982031
1,074
cpp
C++
solutions/c++/problems/[0265_Hard] Paint House II.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
6
2021-02-20T14:00:22.000Z
2022-03-31T15:26:44.000Z
solutions/c++/problems/[0265_Hard] Paint House II.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
null
null
null
solutions/c++/problems/[0265_Hard] Paint House II.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> getCurrCost(vector<int> prev, vector<int> curr) { int n = prev.size(); int min = 999; int min2 = 1000; for (int num: prev) { if (num < min) { min2 = min; min = num; } else if (num < min2) { min2 = num; } } vector<int> ans = vector<int>(n, 0); for (int i = 0; i < n; i++) { ans[i] = prev[i] == min ? min2 + curr[i] : min + curr[i]; } return ans; } int minCostII(vector<vector<int>> &costs) { int n = costs.size(); vector<vector<int>> ans = vector<vector<int>>(n, vector<int>{}); // base case ans[0] = costs[0]; for (int i = 1; i < n; i++) { auto prev = ans[i - 1]; auto curr = costs[i]; ans[i] = getCurrCost(prev, curr); } vector<int> last = ans.back(); return *min_element(last.begin(), last.end()); } };
27.538462
72
0.443203
RageBill
71ab6557ad4b2f5a609fadc31cdf93350e003176
1,378
cpp
C++
comp sci 3/homework2.cpp
MattPhilpot/RandomHomework
efa61590689c0af862a52104bad89c35bc133a65
[ "Apache-2.0" ]
null
null
null
comp sci 3/homework2.cpp
MattPhilpot/RandomHomework
efa61590689c0af862a52104bad89c35bc133a65
[ "Apache-2.0" ]
null
null
null
comp sci 3/homework2.cpp
MattPhilpot/RandomHomework
efa61590689c0af862a52104bad89c35bc133a65
[ "Apache-2.0" ]
null
null
null
// Matthew Philpot // Computer Science 3 // 3.21.10 #include <iostream> #include <string> #include <sstream> using namespace std; class Operations { public: void digits(string AintNoThang, int total) { string rawr; int test = 0; if(!AintNoThang.empty()) { rawr = AintNoThang[0]; istringstream buffer(rawr); buffer >> test; total += test; if(AintNoThang.length()>1) { cout << test << " + "; AintNoThang.erase(0,1); digits(AintNoThang, total); } else { cout << test << " = " << total << "\n" << endl; } } } void reverse(char* s) { if(*s != '\0') reverse(s+1); cout<<*(s); } }; int main() { Operations doIt; string option; bool exit = true; cout << "Hi! Please... Come in!" << endl; while(exit) { cout << "\nSelect one of {s}um of digits, {r}everse order, or {e}xit" << endl; cin >> option; if(option == "s") { string digits; cout << "Enter digits" << endl; cin >> digits; doIt.digits(digits,0); } if(option == "r") { string reverseIT; cout << "Enter phrase: "; do { getline(cin,reverseIT); } while(reverseIT.length()==0); cout << "The phrase is reversed: "; char *buff; buff = new char[reverseIT.length()]; strcpy(buff, reverseIT.c_str()); doIt.reverse(buff); cout << "" << endl; } if(option == "e") { exit = false; } } }
16.404762
80
0.559507
MattPhilpot
71ac1784b47660a2bd641055f45236018d8dda94
7,291
cpp
C++
BeaconCompilerBackend.cpp
beacon1096/Project-Guider
3dcb16da2e091878e340a33230e66ddd4b4c2be1
[ "Apache-2.0" ]
null
null
null
BeaconCompilerBackend.cpp
beacon1096/Project-Guider
3dcb16da2e091878e340a33230e66ddd4b4c2be1
[ "Apache-2.0" ]
null
null
null
BeaconCompilerBackend.cpp
beacon1096/Project-Guider
3dcb16da2e091878e340a33230e66ddd4b4c2be1
[ "Apache-2.0" ]
null
null
null
#include "BeaconCompilerBackend.h" BeaconCompilerBackend::BeaconCompilerBackend(QObject *parent) : QObject(parent) { QSettings settings; if(!settings.value("gccPath").toString().isEmpty()){ gcc.setProgram(settings.value("gccPath").toString()); gpp.setProgram(settings.value("gppPath").toString()); } else if(BeaconPlatformInfo::isLinux || BeaconPlatformInfo::isMacos){ gcc.setProgram("/usr/bin/gcc"); gpp.setProgram("/usr/bin/g++"); settings.setValue("gccPath","/usr/bin/gcc"); settings.setValue("gppPath","/usr/bin/g++"); if(BeaconPlatformInfo::isMacos){ QMessageBox::warning(NULL, "Clang | GCC", tr("Please be noticed that macOS automatically links Clang to GCC.\nIf you wish to use GCC, please install it yourself and change the settings."), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); } } else{ gcc.setProgram("C:/MinGW/bin/gcc.exe"); gpp.setProgram("C:/MinGW/bin/g++.exe"); settings.setValue("gccPath","C:/MinGW/bin/gcc.exe"); settings.setValue("gppPath","C:/MinGW/bin/g++.exe"); } connect(&gcc,SIGNAL(programExited(int,QProcess::ExitStatus)),this,SLOT(compileEnded(int,QProcess::ExitStatus))); connect(&gpp,SIGNAL(programExited(int,QProcess::ExitStatus)),this,SLOT(compileEnded(int,QProcess::ExitStatus))); connect(&gcc,SIGNAL(programLogUpdated(QString)),this,SLOT(_compileInfoUpdated(QString))); connect(&gpp,SIGNAL(programLogUpdated(QString)),this,SLOT(_compileInfoUpdated(QString))); } void BeaconCompilerBackend::_compileInfoUpdated(QString Content){ qDebug() << "[BeaconCompilerBackend]_cIU:" << Content; emit compileInfoUpdated(Content); } int BeaconCompilerBackend::compilerValidation(){ QString cCodeName=QDir::tempPath()+QDir::separator()+QCoreApplication::applicationName()+"_XXXXXX."+"c"; QString cppCodeName=QDir::tempPath()+QDir::separator()+QCoreApplication::applicationName()+"_XXXXXX."+"cpp"; QFile c(gcc.programPath),cpp(gpp.programPath); if(!c.exists() || !cpp.exists())return -1; QTemporaryFile ct(cCodeName); if(ct.open()){ BeaconFileIO::saveFileContent(ct.fileName(),BeaconFileIO::readFileContent(":/Resources/Code/test.c")); QStringList arg; arg.append(ct.fileName()); gcc.program.setArguments(arg); gcc.startProgram(); gcc.program.waitForFinished(); QString result=gcc.logOut; qDebug() << "gcc test result:" << result; qDebug() << "RT result:(1)" << lastCompileResult << ",(2)" << lastCompileStatus; if(lastCompileResult!=0)return -2; if(!result.isEmpty())return -2; } QTemporaryFile cppt(cppCodeName); if(cppt.open()){ BeaconFileIO::saveFileContent(cppt.fileName(),BeaconFileIO::readFileContent(":/Resources/Code/test.cpp")); QStringList arg; arg.append(cppt.fileName()); gpp.program.setArguments(arg); gpp.startProgram(); gpp.program.waitForFinished(); QString result=gpp.logOut; qDebug() << "g++ test result:" << result; qDebug() << "RT result:(1)" << lastCompileResult << ",(2)" << lastCompileStatus; if(lastCompileResult!=0)return -2; if(!result.isEmpty())return -2; } return 0; } bool BeaconCompilerBackend::configureCompilerPath(int lastError){ BeaconCompilerSetupInterface bcsi(lastError); bcsi.exec(); return !compilerValidation(); } void BeaconCompilerBackend::compileEnded(int result,QProcess::ExitStatus status){ lastCompileResult = result; lastCompileStatus = status; } void BeaconCompilerBackend::compileStart(QString filePath,QString executable,QTextBrowser* target){ QString suffix=filePath.split(".").last(); if(suffix=="c"){ QStringList arg; arg.append(filePath); arg.append("-o"); arg.append(executable); arg.append("-Wall"); gcc.clearLog(); gcc.setArguments(arg); qDebug() << "executing gcc " << arg; gcc.startProgram(); gcc.program.waitForFinished(); qDebug() << "result:(1)" << lastCompileResult << ",(2)" << lastCompileStatus; qDebug() << "logs:" << gcc.logOut; latestCompileLog=gcc.logOut; } else if(suffix=="cpp"){ QStringList arg; arg.append(filePath); arg.append("-o"); arg.append(executable); arg.append("-Wall"); gpp.clearLog(); gpp.setArguments(arg); qDebug() << "executing g++ " << arg; qDebug() << "compile command:[" << gpp.program.program() << " " << arg; gpp.startProgram(); gpp.program.waitForFinished(); qDebug() << "result:(1)" << lastCompileResult << ",(2)" << lastCompileStatus; qDebug() << "logs:" << gpp.logOut; latestCompileLog=gpp.logOut; } } BeaconCompilerSetupInterface::BeaconCompilerSetupInterface(int errorCode,QObject *parent) : QDialog(){ information = new QLabel; QSettings settings; if(errorCode==-1)information->setText(QString(tr("Could not find compiler in default Location.").append("\n").append(tr("Please specify where it is.")))); if(errorCode==-2)information->setText(QString(tr("Your compiler is unable to compile a simple test program.")).append("\n").append(tr("Please specify a working one."))); gccHL = new QHBoxLayout;gppHL = new QHBoxLayout; total = new QVBoxLayout; gcc = new QLabel("GCC:"); gpp = new QLabel("G++:"); gccL = new QLineEdit(); gppL = new QLineEdit(); gccS = new QToolButton(); gppS = new QToolButton(); gccS->setText("..."); gppS->setText("..."); confirm = new QPushButton("OK"); gccL->setText(settings.value("gccPath").toString()); gppL->setText(settings.value("gppPath").toString()); connect(gccS,SIGNAL(clicked()),this,SLOT(gccSClicked())); connect(gppS,SIGNAL(clicked()),this,SLOT(gppSClicked())); connect(confirm,SIGNAL(clicked()),this,SLOT(confirmClicked())); total->addWidget(information); gccHL->addWidget(gcc);gccHL->addWidget(gccL);gccHL->addWidget(gccS); gppHL->addWidget(gpp);gppHL->addWidget(gppL);gppHL->addWidget(gppS); total->addLayout(gccHL);total->addLayout(gppHL);total->addWidget(confirm); this->setLayout(total); } void BeaconCompilerSetupInterface::gppSClicked(){ QString path; if(BeaconPlatformInfo::isWindows) path = QFileDialog::getOpenFileName(this,tr("Select G++ Path"),"C:/","g++.exe"); else path = QFileDialog::getOpenFileName(this,tr("Select G++ Path"),"/",""); gppL->setText(path); } void BeaconCompilerSetupInterface::gccSClicked(){ QString path; if(BeaconPlatformInfo::isWindows) path = QFileDialog::getOpenFileName(this,tr("Select GCC Path"),"C:/","gcc.exe"); else path = QFileDialog::getOpenFileName(this,tr("Select GCC Path"),"/",""); gccL->setText(path); QString gppPath=path; gppPath.replace(gppPath.lastIndexOf("gcc"),3,"g++"); QFile gppTest(gppPath); if(gppTest.exists()) gppL->setText(gppPath); } void BeaconCompilerSetupInterface::confirmClicked(){ QSettings settings; settings.setValue("gccPath",this->gccL->text()); settings.setValue("gppPath",this->gppL->text()); this->close(); }
43.921687
255
0.654368
beacon1096
71b84c3a2426d6a1ffa72dbf69768504bf6bacf9
214
cpp
C++
SourceCode/main.cpp
Remsya/M2Process
b2ad03ed91cc32305a114de187ac6dbc463baae7
[ "MIT" ]
null
null
null
SourceCode/main.cpp
Remsya/M2Process
b2ad03ed91cc32305a114de187ac6dbc463baae7
[ "MIT" ]
null
null
null
SourceCode/main.cpp
Remsya/M2Process
b2ad03ed91cc32305a114de187ac6dbc463baae7
[ "MIT" ]
null
null
null
// // main.cpp // CauchyProcess, 1-dimension only // // Created by Rémi Carnec on 13/05/2020. // Copyright © 2020 Rémi Carnec. All rights reserved. // int main(int argc, const char * argv[]){ return 0; }
16.461538
54
0.640187
Remsya
71bc1fa5fd7927bc8e6cc6d9877f27f0c54aaae1
516
hpp
C++
source/Graphics/GLCheck.hpp
Dante12129/Pancake
35282814e2f3b2d5e155a539ca5ddee32e240d3e
[ "Zlib" ]
null
null
null
source/Graphics/GLCheck.hpp
Dante12129/Pancake
35282814e2f3b2d5e155a539ca5ddee32e240d3e
[ "Zlib" ]
null
null
null
source/Graphics/GLCheck.hpp
Dante12129/Pancake
35282814e2f3b2d5e155a539ca5ddee32e240d3e
[ "Zlib" ]
null
null
null
//File adapted from SFML source code, https://github.com/LaurentGomila/SFML #ifndef GLCHECK_HPP #define GLCHECK_HPP #include <string> namespace pcke { #ifdef PCKE_DEBUG // In debug mode, perform a test on every OpenGL call #define glCheck(x) x; pcke::glCheckError(__FILE__, __LINE__); #else // Else, we don't add any overhead #define glCheck(call) (call) #endif void glCheckError(const char* file, unsigned int line); } // namespace pcke #endif //GLCHECK_HPP
19.846154
75
0.676357
Dante12129
71cac75766a0c1076c05bec0aec9d7806d7bc9be
1,849
cpp
C++
windows/advcore/gdiplus/test/functest/cregions.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/advcore/gdiplus/test/functest/cregions.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/advcore/gdiplus/test/functest/cregions.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/******************************Module*Header*******************************\ * Module Name: CRegions.cpp * * This file contains the code to support the functionality test harness * for GDI+. This includes menu options and calling the appropriate * functions for execution. * * Created: 05-May-2000 - Jeff Vezina [t-jfvez] * * Copyright (c) 2000 Microsoft Corporation * \**************************************************************************/ #include "CRegions.h" #include <math.h> CRegions::CRegions(BOOL bRegression) { strcpy(m_szName,"Regions"); m_bRegression=bRegression; } CRegions::~CRegions() { } void CRegions::Draw(Graphics *g) { REAL width = 2; // Pen width PointF points[5]; REAL s, c, theta; REAL pi = 3.1415926535897932f; PointF orig((int)(TESTAREAWIDTH/2.0f), (int)(TESTAREAHEIGHT/2.0f)); theta = -pi/2; // Create a star shape. for(INT i = 0; i < 5; i++) { s = sinf(theta); c = cosf(theta); points[i].X = (int)(125.0f/250.0f*TESTAREAWIDTH)*c + orig.X; points[i].Y = (int)(125.0f/250.0f*TESTAREAHEIGHT)*s + orig.Y; theta += 0.8f*pi; } Color orangeColor(128, 255, 180, 0); SolidBrush orangeBrush(orangeColor); GraphicsPath* path = new GraphicsPath(FillModeAlternate); // Path* path = new GraphicsPath(Winding); path->AddPolygon(points, 5); Color blackColor(0, 0, 0); SolidBrush blackBrush(blackColor); Pen blackPen(&blackBrush, width); Region * region = new Region(path); g->FillRegion(&orangeBrush, region); // There is a BUG! // g->FillGraphicsPath(&orangeBrush, path); // Fill path works fine. blackPen.SetLineJoin(LineJoinMiter); g->DrawPath(&blackPen, path); delete path; delete region; }
27.191176
77
0.57166
npocmaka
71ce8ea516e381387939e641d93df8d5fe46cc76
422
cpp
C++
src/admin/migrate.cpp
victorvw/eos-wps
e115197eb78b6f6a851f253f68784324383fae14
[ "MIT" ]
4
2020-03-26T11:12:07.000Z
2020-04-19T02:07:31.000Z
src/admin/migrate.cpp
victorvw/eos-wps
e115197eb78b6f6a851f253f68784324383fae14
[ "MIT" ]
13
2019-12-12T21:33:49.000Z
2019-12-22T17:23:54.000Z
src/admin/migrate.cpp
victorvw/eos-wps
e115197eb78b6f6a851f253f68784324383fae14
[ "MIT" ]
4
2019-11-11T14:13:25.000Z
2020-03-15T17:44:38.000Z
void wps::migrate( const name type ) { require_auth( get_self() ); if (type == "del.comment"_n) { for ( auto row : _proposals ) { comments_table _comments( get_self(), row.proposal_name.value ); auto comment_itr = _comments.begin(); while ( comment_itr != _comments.end() ) { comment_itr = _comments.erase( comment_itr ); } } } }
30.142857
76
0.545024
victorvw
71d12fcc7be997f1276c986f63064be2cc843554
2,164
cc
C++
src/graphics/examples/vkproto/common/render_pass.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/graphics/examples/vkproto/common/render_pass.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/graphics/examples/vkproto/common/render_pass.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2018 The Fuchsia 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 "src/graphics/examples/vkproto/common/render_pass.h" #include "src/graphics/examples/vkproto/common/utils.h" namespace vkp { RenderPass::RenderPass(std::shared_ptr<vk::Device> device, const vk::Format &image_format, bool offscreen) : initialized_(false), device_(device), image_format_(image_format), offscreen_(offscreen) {} bool RenderPass::Init() { RTN_IF_MSG(false, initialized_, "RenderPass is already initialized.\n"); RTN_IF_MSG(false, !device_, "Device must be initialized.\n"); vk::AttachmentDescription color_attachment; if (offscreen_) { color_attachment.finalLayout = vk::ImageLayout::eTransferSrcOptimal; } else { color_attachment.finalLayout = vk::ImageLayout::ePresentSrcKHR; } color_attachment.format = image_format_; color_attachment.initialLayout = initial_layout_; color_attachment.loadOp = vk::AttachmentLoadOp::eClear; color_attachment.samples = vk::SampleCountFlagBits::e1; color_attachment.stencilLoadOp = vk::AttachmentLoadOp::eDontCare; color_attachment.stencilStoreOp = vk::AttachmentStoreOp::eDontCare; color_attachment.storeOp = vk::AttachmentStoreOp::eStore; vk::AttachmentReference color_attachment_ref; color_attachment_ref.attachment = 0; color_attachment_ref.layout = vk::ImageLayout::eColorAttachmentOptimal; vk::SubpassDescription subpass; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &color_attachment_ref; subpass.pipelineBindPoint = vk::PipelineBindPoint::eGraphics; vk::RenderPassCreateInfo render_pass_info; render_pass_info.attachmentCount = 1; render_pass_info.pAttachments = &color_attachment; render_pass_info.pSubpasses = &subpass; render_pass_info.subpassCount = 1; auto [r_render_pass, render_pass] = device_->createRenderPassUnique(render_pass_info); RTN_IF_VKH_ERR(false, r_render_pass, "Failed to create render pass.\n"); render_pass_ = std::move(render_pass); initialized_ = true; return true; } } // namespace vkp
37.964912
97
0.773105
allansrc
71d211f8f05affbfcb9d38d47caad40b91c5ae15
16,601
hpp
C++
SDK/ARKSurvivalEvolved_Dino_Character_BP_DivingFlyer_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Dino_Character_BP_DivingFlyer_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Dino_Character_BP_DivingFlyer_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Dino_Character_BP_DivingFlyer_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.OnDiveCrash struct ADino_Character_BP_DivingFlyer_C_OnDiveCrash_Params { class AActor* HitActor; // (Parm, ZeroConstructor, IsPlainOldData) class USceneComponent* HitComp; // (Parm, ZeroConstructor, IsPlainOldData) struct FHitResult HitResult; // (Parm) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPForceTurretFastTargeting struct ADino_Character_BP_DivingFlyer_C_BPForceTurretFastTargeting_Params { bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ReturnDivingFlyerToZeroPitchRotation struct ADino_Character_BP_DivingFlyer_C_ReturnDivingFlyerToZeroPitchRotation_Params { float DeltaTime; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ReduceDiverStamina struct ADino_Character_BP_DivingFlyer_C_ReduceDiverStamina_Params { float cost; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BP_OnStartLandingNotify struct ADino_Character_BP_DivingFlyer_C_BP_OnStartLandingNotify_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Diving Velocity Mult Ratio struct ADino_Character_BP_DivingFlyer_C_Get_Diving_Velocity_Mult_Ratio_Params { float Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Flyer Dive Velocity Max struct ADino_Character_BP_DivingFlyer_C_Get_Flyer_Dive_Velocity_Max_Params { float MaxVelocity; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Flyer Dive Velocity Ratio struct ADino_Character_BP_DivingFlyer_C_Get_Flyer_Dive_Velocity_Ratio_Params { float Ratio; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Has Diving Momentum struct ADino_Character_BP_DivingFlyer_C_Has_Diving_Momentum_Params { bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.UpdateDivingFX struct ADino_Character_BP_DivingFlyer_C_UpdateDivingFX_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ResetDivingVars struct ADino_Character_BP_DivingFlyer_C_ResetDivingVars_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Is Diver Moving Forward struct ADino_Character_BP_DivingFlyer_C_Is_Diver_Moving_Forward_Params { bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.GetDefaultMaxFlySpeed struct ADino_Character_BP_DivingFlyer_C_GetDefaultMaxFlySpeed_Params { float MaxFlySpeed; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Diving Required VelocityToStart struct ADino_Character_BP_DivingFlyer_C_Get_Diving_Required_VelocityToStart_Params { float _float; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.HasEnoughStaminaToDive struct ADino_Character_BP_DivingFlyer_C_HasEnoughStaminaToDive_Params { bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BP_OnSetRunning struct ADino_Character_BP_DivingFlyer_C_BP_OnSetRunning_Params { bool* bNewIsRunning; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BP_GetCustomModifier_RotationRate struct ADino_Character_BP_DivingFlyer_C_BP_GetCustomModifier_RotationRate_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BP_GetCustomModifier_MaxSpeed struct ADino_Character_BP_DivingFlyer_C_BP_GetCustomModifier_MaxSpeed_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPNotifyClearRider struct ADino_Character_BP_DivingFlyer_C_BPNotifyClearRider_Params { class AShooterCharacter** RiderClearing; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.IsDiving struct ADino_Character_BP_DivingFlyer_C_IsDiving_Params { bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Has Diving Momentum_Pure struct ADino_Character_BP_DivingFlyer_C_Has_Diving_Momentum_Pure_Params { bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPOnMovementModeChangedNotify struct ADino_Character_BP_DivingFlyer_C_BPOnMovementModeChangedNotify_Params { TEnumAsByte<EMovementMode>* PrevMovementMode; // (Parm, ZeroConstructor, IsPlainOldData) unsigned char* PreviousCustomMode; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Flyer Dive Velocity Ratio_Pure struct ADino_Character_BP_DivingFlyer_C_Get_Flyer_Dive_Velocity_Ratio_Pure_Params { float Ratio; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Flyer Dive Velocity MaxPure struct ADino_Character_BP_DivingFlyer_C_Get_Flyer_Dive_Velocity_MaxPure_Params { float MaxVelocity; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.CanFlyerDive struct ADino_Character_BP_DivingFlyer_C_CanFlyerDive_Params { bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.AllowDiving struct ADino_Character_BP_DivingFlyer_C_AllowDiving_Params { bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Diving_Tick struct ADino_Character_BP_DivingFlyer_C_Diving_Tick_Params { float DeltaSeconds; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Diving_Stop struct ADino_Character_BP_DivingFlyer_C_Diving_Stop_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Diving_Start struct ADino_Character_BP_DivingFlyer_C_Diving_Start_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Set Is Diving struct ADino_Character_BP_DivingFlyer_C_Set_Is_Diving_Params { bool newDiving; // (Parm, ZeroConstructor, IsPlainOldData) bool forceSet; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.OnRep_bIsDiving struct ADino_Character_BP_DivingFlyer_C_OnRep_bIsDiving_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Interp Diver Mesh struct ADino_Character_BP_DivingFlyer_C_Interp_Diver_Mesh_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Diving Velocity Mult Ratio_Pure struct ADino_Character_BP_DivingFlyer_C_Get_Diving_Velocity_Mult_Ratio_Pure_Params { float Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPNotifySetRider struct ADino_Character_BP_DivingFlyer_C_BPNotifySetRider_Params { class AShooterCharacter** RiderSetting; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPTimerNonDedicated struct ADino_Character_BP_DivingFlyer_C_BPTimerNonDedicated_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get DefaultDivingFlyer struct ADino_Character_BP_DivingFlyer_C_Get_DefaultDivingFlyer_Params { class ADino_Character_BP_DivingFlyer_C* Default; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPModifyFOV struct ADino_Character_BP_DivingFlyer_C_BPModifyFOV_Params { float* FOVIn; // (Parm, ZeroConstructor, IsPlainOldData) float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ReceiveHit struct ADino_Character_BP_DivingFlyer_C_ReceiveHit_Params { class UPrimitiveComponent** MyComp; // (Parm, ZeroConstructor, IsPlainOldData) class AActor** Other; // (Parm, ZeroConstructor, IsPlainOldData) class UPrimitiveComponent** OtherComp; // (Parm, ZeroConstructor, IsPlainOldData) bool* bSelfMoved; // (Parm, ZeroConstructor, IsPlainOldData) struct FVector* HitLocation; // (Parm, ZeroConstructor, IsPlainOldData) struct FVector* HitNormal; // (Parm, ZeroConstructor, IsPlainOldData) struct FVector* NormalImpulse; // (Parm, ZeroConstructor, IsPlainOldData) struct FHitResult Hit; // (Parm, OutParm, ReferenceParm) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.HasLocallyCarriedPlayer struct ADino_Character_BP_DivingFlyer_C_HasLocallyCarriedPlayer_Params { bool bLocallyCarried; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.DebugDiveVals struct ADino_Character_BP_DivingFlyer_C_DebugDiveVals_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.GetCurrentAcceleration struct ADino_Character_BP_DivingFlyer_C_GetCurrentAcceleration_Params { struct FVector ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.UserConstructionScript struct ADino_Character_BP_DivingFlyer_C_UserConstructionScript_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.AbortDive struct ADino_Character_BP_DivingFlyer_C_AbortDive_Params { bool bPlayAbortAnim; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.DiveBomb struct ADino_Character_BP_DivingFlyer_C_DiveBomb_Params { }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.OwningClientDiveBombCameraShake struct ADino_Character_BP_DivingFlyer_C_OwningClientDiveBombCameraShake_Params { float Intensity; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Multi_LandFromDive struct ADino_Character_BP_DivingFlyer_C_Multi_LandFromDive_Params { struct FRotator MeshRotation; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Server_SetIsDiving struct ADino_Character_BP_DivingFlyer_C_Server_SetIsDiving_Params { bool newDiving; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ReceiveTick struct ADino_Character_BP_DivingFlyer_C_ReceiveTick_Params { float* DeltaSeconds; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ExecuteUbergraph_Dino_Character_BP_DivingFlyer struct ADino_Character_BP_DivingFlyer_C_ExecuteUbergraph_Dino_Character_BP_DivingFlyer_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
52.369085
173
0.630805
2bite
71d3a70dd489985d0020b470d9b2197dc0a32681
1,818
hpp
C++
src/connectors/kokkos/include/impl/Kokkos_Profiling_DeviceInfo.hpp
cdwdirect/apollo
499f1b4bf111011e4d59b6d86da60559157b5474
[ "MIT" ]
14
2020-06-16T12:59:18.000Z
2022-01-31T17:40:52.000Z
src/connectors/kokkos/include/impl/Kokkos_Profiling_DeviceInfo.hpp
cdwdirect/apollo
499f1b4bf111011e4d59b6d86da60559157b5474
[ "MIT" ]
9
2020-08-11T01:18:26.000Z
2022-02-18T16:33:02.000Z
src/connectors/kokkos/include/impl/Kokkos_Profiling_DeviceInfo.hpp
cdwdirect/apollo
499f1b4bf111011e4d59b6d86da60559157b5474
[ "MIT" ]
8
2020-06-16T12:59:25.000Z
2021-06-21T20:33:04.000Z
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // 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. // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // @HEADER */ #ifndef KOKKOSP_DEVICE_INFO_HPP #define KOKKOSP_DEVICE_INFO_HPP #include <cstdint> #include <impl/Kokkos_Profiling_C_Interface.h> namespace Kokkos { namespace Profiling { using KokkosPDeviceInfo = Kokkos_Profiling_KokkosPDeviceInfo; } // namespace Profiling } // namespace Kokkos #endif
40.4
79
0.710671
cdwdirect
71d608089ed4ae5f8005a6345999d2f7f5d2b491
1,054
cpp
C++
UVa/uva 1056.cpp
Xi-Plus/OJ-Code
7ff6d691f34c9553d53dc9cddf90ad7dc7092349
[ "MIT" ]
null
null
null
UVa/uva 1056.cpp
Xi-Plus/OJ-Code
7ff6d691f34c9553d53dc9cddf90ad7dc7092349
[ "MIT" ]
null
null
null
UVa/uva 1056.cpp
Xi-Plus/OJ-Code
7ff6d691f34c9553d53dc9cddf90ad7dc7092349
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define endl '\n' using namespace std; const int BIGDIS = INT_MAX/2; int dis[55][55]; int main() { ios::sync_with_stdio(false); cin.tie(0); int P, R; string s1, s2; int t=1; while(cin>>P>>R, P||R){ map<string, int> pid; int pidcnt=0; for(int q=0; q<P; q++){ for(int w=0; w<P; w++){ dis[q][w]=BIGDIS; } } for(int q=0; q<P; q++){ dis[q][q]=0; } while(R--){ cin>>s1>>s2; if(pid.find(s1)==pid.end()){ pid[s1]=pidcnt++; } if(pid.find(s2)==pid.end()){ pid[s2]=pidcnt++; } dis[pid[s1]][pid[s2]]=1; dis[pid[s2]][pid[s1]]=1; } for(int k=0; k<P; k++){ for(int i=0; i<P; i++){ for(int j=0; j<P; j++){ if(dis[i][j]>dis[i][k]+dis[k][j]){ dis[i][j]=dis[i][k]+dis[k][j]; } } } } int maxdis=-1; for(int q=0; q<P; q++) { for(int w=q+1; w<P; w++){ maxdis=max(maxdis, dis[q][w]); } } if(maxdis==BIGDIS){ cout<<"Network "<<t++<<": DISCONNECTED"<<endl; }else{ cout<<"Network "<<t++<<": "<<maxdis<<endl; } cout<<endl; } }
18.491228
49
0.48482
Xi-Plus
71d8e080d688606526c691c0d060553c7978435d
2,084
cpp
C++
src/xmol/io/pdb/PdbRecord.cpp
sizmailov/pyxmolpp2
9395ba1b1ddc957e0b33dc6decccdb711e720764
[ "MIT" ]
4
2020-06-24T11:07:57.000Z
2022-01-15T23:00:30.000Z
src/xmol/io/pdb/PdbRecord.cpp
sizmailov/pyxmolpp2
9395ba1b1ddc957e0b33dc6decccdb711e720764
[ "MIT" ]
84
2018-04-22T12:29:31.000Z
2020-06-17T15:03:37.000Z
src/xmol/io/pdb/PdbRecord.cpp
sizmailov/pyxmolpp2
9395ba1b1ddc957e0b33dc6decccdb711e720764
[ "MIT" ]
6
2018-06-04T09:16:26.000Z
2022-03-12T11:05:54.000Z
#include "xmol/io/pdb/PdbRecord.h" #include "xmol/io/pdb/exceptions.h" #include <fstream> using namespace xmol::io; using namespace xmol::io::pdb; const std::vector<int>& PdbRecordType::getFieldColons(const FieldName& fieldName) const { auto col = fieldColons.find(fieldName); if (col != fieldColons.end()) { return col->second; } throw PdbUknownRecordField("Unknown field" +fieldName.str() + "`"); } void PdbRecordType::set_field(const FieldName& fieldName, const std::vector<int>& colons) { fieldColons[fieldName] = colons; } StandardPdbRecords::StandardPdbRecords() { this->recordTypes = detail::get_bundled_records(); } const PdbRecordType& AlteredPdbRecords::get_record( const RecordName& recordTypeName) const { auto it = recordTypes.find(recordTypeName); if (it != recordTypes.end()) { return it->second; } return basic->get_record(recordTypeName); } void AlteredPdbRecords::alter_record(RecordName recordTypeName, FieldName fieldName, std::vector<int> colons) { auto it = recordTypes.find(recordTypeName); if (it != recordTypes.end()) { // alter owned record it->second.set_field(fieldName, colons); } else { try { // copy record from backup and alter field auto record = recordTypes.emplace(recordTypeName, basic->get_record(recordTypeName)); record.first->second.set_field(fieldName, colons); } catch (std::out_of_range&) { // create new record with single field recordTypes.emplace(recordTypeName, PdbRecordType({{fieldName, colons}})); } } } const PdbRecordType& StandardPdbRecords::get_record(const RecordName& recordTypeName) const { auto col = recordTypes.find(recordTypeName); if (col != recordTypes.end()) { return col->second; } throw PdbUknownRecord("Unknown record `" + recordTypeName.str() + "`"); } const basic_PdbRecords& StandardPdbRecords::instance() { const static StandardPdbRecords singleton; return singleton; }
31.575758
80
0.675144
sizmailov
71d9e0440a273165a085872bb963684a3c3363db
1,496
cpp
C++
core/net/ntp.cpp
JartC0ding/horizon
2b9a75b45ac768a8da0f7a98f164a37690dc583f
[ "MIT" ]
4
2022-01-06T09:19:46.000Z
2022-03-27T18:08:36.000Z
core/net/ntp.cpp
JartC0ding/horizon
2b9a75b45ac768a8da0f7a98f164a37690dc583f
[ "MIT" ]
null
null
null
core/net/ntp.cpp
JartC0ding/horizon
2b9a75b45ac768a8da0f7a98f164a37690dc583f
[ "MIT" ]
1
2022-03-22T19:10:05.000Z
2022-03-22T19:10:05.000Z
#include <net/ntp.h> #include <utils/abort.h> #include <utils/log.h> #include <utils/string.h> #include <timer/timer.h> #include <utils/unix_time.h> using namespace net; network_time_protocol::network_time_protocol(udp_socket* socket) { this->socket = socket; } void network_time_protocol::on_udp_message(udp_socket *socket, uint8_t* data, size_t size) { debugf("ntp: got packet of size %d\n", size); last_packet = *(ntp_packet_t*) data; received_packet = true; } driver::clock_device::clock_result_t network_time_protocol::time() { debugf("ntp: sending request\n"); ntp_packet_t packet; memset(&packet, 0, sizeof(ntp_packet_t)); memset(&last_packet, 0, sizeof(ntp_packet_t)); received_packet = false; *((char*) &packet) = 0x1b; __asm__ __volatile__("sti"); // make sure interrupts are enabled this->socket->send((uint8_t*) &packet, sizeof(ntp_packet_t)); debugf("ntp: waiting for response\n"); int timeout = 1000; while(timeout--) { timer::global_timer->sleep(10); if(received_packet) { debugf("ntp: got response\n"); break; } } if(!received_packet) { abortf("ntp: no response\n"); } int unix_time = (__builtin_bswap32(last_packet.txTm_s) - 2208988800); debugf("ntp: unix time: %d\n", unix_time); driver::clock_device::clock_result_t result; memset(&result, 0, sizeof(driver::clock_device::clock_result_t)); from_unix_time(unix_time, &result.year, &result.month, &result.day, &result.hours, &result.minutes, &result.seconds); return result; }
25.793103
118
0.720588
JartC0ding
71e2482ff3f03d617c8f98ceb6049a692592375d
691
cpp
C++
libraries/lib-ffmpeg-support/wrappers/AVFrameWrapper.cpp
joshrose/audacity
e2b1a2be6b92661628bbb054f915bc50b211c020
[ "CC-BY-3.0" ]
7,892
2015-03-31T09:24:05.000Z
2022-03-31T12:30:32.000Z
libraries/lib-ffmpeg-support/wrappers/AVFrameWrapper.cpp
joshrose/audacity
e2b1a2be6b92661628bbb054f915bc50b211c020
[ "CC-BY-3.0" ]
2,050
2015-04-03T13:27:52.000Z
2022-03-31T19:14:10.000Z
libraries/lib-ffmpeg-support/wrappers/AVFrameWrapper.cpp
joshrose/audacity
e2b1a2be6b92661628bbb054f915bc50b211c020
[ "CC-BY-3.0" ]
2,613
2015-03-26T11:28:10.000Z
2022-03-30T13:17:03.000Z
/********************************************************************** Audacity: A Digital Audio Editor AVFrameWrapper.cpp Dmitry Vedenko **********************************************************************/ #include "AVFrameWrapper.h" #include "FFmpegFunctions.h" AVFrameWrapper::AVFrameWrapper(const FFmpegFunctions& ffmpeg) noexcept : mFFmpeg(ffmpeg) { mAVFrame = mFFmpeg.av_frame_alloc(); } AVFrame* AVFrameWrapper::GetWrappedValue() noexcept { return mAVFrame; } const AVFrame* AVFrameWrapper::GetWrappedValue() const noexcept { return mAVFrame; } AVFrameWrapper::~AVFrameWrapper() { if (mAVFrame != nullptr) mFFmpeg.av_frame_free(&mAVFrame); }
19.194444
71
0.586107
joshrose
71e387d3770567a10d0f161f181cf185497fa96b
6,358
cpp
C++
template_mp/src/utils/RCBot2/bot_accessclient.cpp
moeabm/VS2013
dd29099567b286acac7bb542a06f085df78ea480
[ "Unlicense" ]
null
null
null
template_mp/src/utils/RCBot2/bot_accessclient.cpp
moeabm/VS2013
dd29099567b286acac7bb542a06f085df78ea480
[ "Unlicense" ]
null
null
null
template_mp/src/utils/RCBot2/bot_accessclient.cpp
moeabm/VS2013
dd29099567b286acac7bb542a06f085df78ea480
[ "Unlicense" ]
null
null
null
/* * This file is part of RCBot. * * RCBot by Paul Murphy adapted from Botman's HPB Bot 2 template. * * RCBot 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. * * RCBot 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 RCBot; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * In addition, as a special exception, the author gives permission to * link the code of this program with the Half-Life Game Engine ("HL * Engine") and Modified Game Libraries ("MODs") developed by Valve, * L.L.C ("Valve"). You must obey the GNU General Public License in all * respects for all of the code used other than the HL Engine and MODs * from Valve. If you modify this file, you may extend this exception * to your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. * */ #include "bot.h" #include "bot_strings.h" #include "bot_accessclient.h" #include "bot_globals.h" #include <vector> using namespace std; /////////// vector<CAccessClient*> CAccessClients :: m_Clients; /////////// CAccessClient :: CAccessClient( char *szSteamId, int iAccessLevel ) { m_iAccessLevel = iAccessLevel; m_szSteamId = CStrings::getString(szSteamId); } bool CAccessClient :: forBot () { return isForSteamId("BOT"); } bool CAccessClient :: isForSteamId ( const char *szSteamId ) { return FStrEq(m_szSteamId,szSteamId); } void CAccessClient :: save ( FILE *fp ) { fprintf(fp,"\"%s\":%d\n",m_szSteamId,m_iAccessLevel); } void CAccessClient :: giveAccessToClient ( CClient *pClient ) { // notify player if ( !forBot() ) CBotGlobals::botMessage(pClient->getPlayer(),0,"%s authenticated for bot commands",pClient->getName()); // notify server CBotGlobals::botMessage(NULL,0,"%s authenticated for bot commands",pClient->getName()); pClient->setAccessLevel(m_iAccessLevel); } ////////////// void CAccessClients :: showUsers ( edict_t *pEntity ) { CAccessClient *pPlayer; CClient *pClient; CBotGlobals::botMessage(pEntity,0,"showing users..."); if ( m_Clients.empty() ) CBotGlobals::botMessage(NULL,0,"showUsers() : No users to show"); for ( unsigned int i = 0; i < m_Clients.size(); i ++ ) { pPlayer = m_Clients[i]; pClient = CClients::findClientBySteamID(pPlayer->getSteamID()); if ( pClient ) CBotGlobals::botMessage(pEntity,0,"[ID: %s]/[AL: %d] (currently playing as : %s)\n",pPlayer->getSteamID(),pPlayer->getAccessLevel(),pClient->getName()); else CBotGlobals::botMessage(pEntity,0,"[ID: %s]/[AL: %d]\n",pPlayer->getSteamID(),pPlayer->getAccessLevel()); } } void CAccessClients :: createFile () { char filename[1024]; CBotGlobals::buildFileName(filename,BOT_ACCESS_CLIENT_FILE,BOT_CONFIG_FOLDER,BOT_CONFIG_EXTENSION); FILE *fp = CBotGlobals::openFile(filename,"w"); CBotGlobals::botMessage(NULL,0,"Making an accessclients.ini file for you... Edit it in %s",filename); if ( fp ) { fprintf(fp,"# format is "); fprintf(fp,"# \"<STEAM ID>\" <access level>\n"); fprintf(fp,"# see http://rcbot.bots-united.com/accesslev.htm for access\n"); fprintf(fp,"# levels\n"); fprintf(fp,"#\n"); fprintf(fp,"# example:\n"); fprintf(fp,"#\n"); fprintf(fp,"# \"STEAM_0:123456789\" 63\n"); fprintf(fp,"# don't put one of '#' these before a line you want to be read \n"); fprintf(fp,"# by the bot!\n"); fprintf(fp,"# \n"); fclose(fp); } else CBotGlobals::botMessage(NULL,0,"Error! Couldn't create config file %s",filename); } void CAccessClients :: freeMemory () { for ( unsigned int i = 0; i < m_Clients.size(); i ++ ) { delete m_Clients[i]; m_Clients[i] = NULL; } m_Clients.clear(); } void CAccessClients :: load () { char filename[1024]; CBotGlobals::buildFileName(filename,BOT_ACCESS_CLIENT_FILE,BOT_CONFIG_FOLDER,BOT_CONFIG_EXTENSION); FILE *fp = CBotGlobals::openFile(filename,"r"); if ( fp ) { char buffer[256]; char szSteamId[32]; int iAccess; int i; int len; int n; int iLine = 0; while ( fgets(buffer,255,fp) != NULL ) { iLine++; buffer[255] = 0; if ( buffer[0] == 0 ) continue; if ( buffer[0] == '\n' ) continue; if ( buffer[0] == '#' ) continue; len = strlen(buffer); i = 0; while (( i < len ) && ((buffer[i] == '\"') || (buffer[i] == ' '))) i++; n = 0; // parse Steam ID while ( (n<31) && (i < len) && (buffer[i] != '\"') ) szSteamId[n++] = buffer[i++]; szSteamId[n] = 0; i++; while (( i < len ) && (buffer[i] == ' ')) i++; if ( i == len ) { CBotGlobals::botMessage(NULL,0,"line %d invalid in access client config, missing access level",iLine); continue; // invalid } iAccess = atoi(&buffer[i]); // invalid if ( (szSteamId[0] == 0) || (szSteamId[0] == ' ' ) ) { CBotGlobals::botMessage(NULL,0,"line %d invalid in access client config, steam id invalid",iLine); continue; } if ( iAccess == 0 ) { CBotGlobals::botMessage(NULL,0,"line %d invalid in access client config, access level can't be 0",iLine); continue; } m_Clients.push_back(new CAccessClient(szSteamId,iAccess)); } fclose(fp); } else CAccessClients :: createFile(); } void CAccessClients :: save () { char filename[1024]; CBotGlobals::buildFileName(filename,BOT_ACCESS_CLIENT_FILE,BOT_CONFIG_FOLDER,BOT_CONFIG_EXTENSION); FILE *fp = CBotGlobals::openFile(filename,"w"); if ( fp ) { for ( unsigned int i = 0; i < m_Clients.size(); i ++ ) { m_Clients[i]->save(fp); } fclose(fp); } } void CAccessClients :: checkClientAccess ( CClient *pClient ) { for ( unsigned int i = 0; i < m_Clients.size(); i ++ ) { CAccessClient *pAC = m_Clients[i]; if ( pAC->isForSteamId(pClient->getSteamID()) ) pAC->giveAccessToClient(pClient); } }
25.031496
155
0.651777
moeabm
71e4828fe3a91bf35c9f4748b2daa081a9dfb241
6,718
cpp
C++
lighthub/modules/in_ccs811_hdc1080.cpp
anklimov/lighthub
99e9c1a27aca52bf38efec000547720fb8f82860
[ "Apache-2.0" ]
83
2017-11-05T14:05:16.000Z
2022-02-21T16:34:53.000Z
lighthub/modules/in_ccs811_hdc1080.cpp
anklimov/lighthub
99e9c1a27aca52bf38efec000547720fb8f82860
[ "Apache-2.0" ]
27
2018-03-12T21:49:33.000Z
2022-01-20T19:06:05.000Z
lighthub/modules/in_ccs811_hdc1080.cpp
anklimov/lighthub
99e9c1a27aca52bf38efec000547720fb8f82860
[ "Apache-2.0" ]
20
2017-11-20T08:27:17.000Z
2022-03-28T02:26:17.000Z
#include "modules/in_ccs811_hdc1080.h" #include "Arduino.h" #include "options.h" #include "Streaming.h" #include "item.h" #include "main.h" #if defined(M5STACK) #include <M5Stack.h> #endif #ifndef CSSHDC_DISABLE static ClosedCube_HDC1080 hdc1080; static CCS811 ccs811(CCS811_ADDR); long ccs811Baseline; static bool HDC1080ready = false; static bool CCS811ready = false; int in_ccs811::Setup() { if (CCS811ready) {debugSerial<<F("ccs811 is already initialized")<<endl; return 0;} #ifdef WAK_PIN pinMode(WAK_PIN,OUTPUT); digitalWrite(WAK_PIN,LOW); #endif Serial.println("CCS811 Init"); Wire.begin(); //Inialize I2C Harware Wire.setClock(4000); //It is recommended to check return status on .begin(), but it is not //required. CCS811Core::status returnCode = ccs811.begin(); //CCS811Core::CC811_Status_e returnCode = ccs811.beginWithStatus(); if (returnCode != CCS811Core::SENSOR_SUCCESS) //if (returnCode != CCS811Core::CCS811_Stat_SUCCESS) { Serial.print("CCS811 Init error "); //Serial.println(ccs811.statusString(returnCode)); printDriverError(returnCode); return 0; } //ccs811.setBaseline(62000); CCS811ready = true; //returnCode = ccs811.setDriveMode(1); //printDriverError(returnCode); /* delay(2000);Poll(); delay(2000);Poll(); delay(2000);Poll(); delay(2000); */ return 1; } int in_hdc1080::Setup() { if (HDC1080ready) {debugSerial<<F("hdc1080 is already initialized")<<endl; return 0;} Serial.println("HDC1080 Init "); Wire.begin(); //Inialize I2C Harware // Default settings: // - Heater off // - 14 bit Temperature and Humidity Measurement Resolutions hdc1080.begin(0x40); Serial.print("Manufacturer ID=0x"); Serial.println(hdc1080.readManufacturerId(), HEX); // 0x5449 ID of Texas Instruments Serial.print("Device ID=0x"); Serial.println(hdc1080.readDeviceId(), HEX); // 0x1050 ID of the device printSerialNumber(); HDC1080ready = true; return 1; } void i2cReset(){ Wire.endTransmission(true); #if defined (SCL_RESET) SCL_LOW(); delay(300); SCL_HIGH(); #endif } int in_hdc1080::Poll(short cause) { float h,t; int reg; if (cause!=POLLING_SLOW) return 0; if (!HDC1080ready) {debugSerial<<F("HDC1080 not initialized")<<endl; return 0;} Serial.print("HDC Status="); Serial.println(reg=hdc1080.readRegister().rawData,HEX); if (reg!=0xff) { Serial.print(" T="); Serial.print(t=hdc1080.readTemperature()); Serial.print("C, RH="); Serial.print(h=hdc1080.readHumidity()); Serial.println("%"); #ifdef M5STACK M5.Lcd.print(" T="); //Returns calculated CO2 reading M5.Lcd.print(t=hdc1080.readTemperature()); M5.Lcd.print("C, RH="); //Returns calculated TVOC reading M5.Lcd.print(h=hdc1080.readHumidity()); M5.Lcd.print("%\n"); #endif // New tyle unified activities aJsonObject *actT = aJson.getObjectItem(in->inputObj, "temp"); aJsonObject *actH = aJson.getObjectItem(in->inputObj, "hum"); executeCommand(actT,-1,itemCmd(t)); executeCommand(actH,-1,itemCmd(h)); publish(t,"/T"); publish(h,"/H"); if (CCS811ready) ccs811.setEnvironmentalData(h,t); } else //ESP I2C glitch { Serial.println("I2C Reset"); i2cReset(); } return INTERVAL_SLOW_POLLING; } int in_ccs811::Poll(short cause) { if (!CCS811ready) {debugSerial<<F("ccs811 not initialized")<<endl; return 0;} #ifdef WAK_PIN digitalWrite(WAK_PIN,LOW); #endif delay(1); //Check to see if data is ready with .dataAvailable() if (ccs811.dataAvailable()) //if (1) { //If so, have the sensor read and calculate the results. //Get them later CCS811Core::status returnCode = ccs811.readAlgorithmResults(); printDriverError(returnCode); float co2,tvoc; Serial.print(" CO2["); //Returns calculated CO2 reading Serial.print(co2 = ccs811.getCO2()); Serial.print("] tVOC["); //Returns calculated TVOC reading Serial.print(tvoc = ccs811.getTVOC()); Serial.print("] baseline["); Serial.print(ccs811Baseline = ccs811.getBaseline()); #ifdef M5STACK M5.Lcd.print(" CO2["); //Returns calculated CO2 reading M5.Lcd.print(co2 = ccs811.getCO2()); M5.Lcd.print("] tVOC["); //Returns calculated TVOC reading M5.Lcd.print(tvoc = ccs811.getTVOC()); M5.Lcd.print("]\n"); #endif if (co2<10000.) //Spontaneous calculation error suppress { // New tyle unified activities aJsonObject *actCO2 = aJson.getObjectItem(in->inputObj, "co2"); aJsonObject *actTVOC = aJson.getObjectItem(in->inputObj, "tvoc"); executeCommand(actCO2,-1,itemCmd(co2)); executeCommand(actTVOC,-1,itemCmd(tvoc)); publish(co2,"/CO2"); publish(tvoc,"/TVOC"); publish(ccs811Baseline,"/base");} Serial.println("]"); printSensorError(); #ifdef WAK_PIN digitalWrite(WAK_PIN,HIGH); //Relax some time #endif } else {debugSerial<<F("ccs811: data not available")<<endl; return 0;} return 1; } void in_hdc1080::printSerialNumber() { Serial.print("Device Serial Number="); HDC1080_SerialNumber sernum = hdc1080.readSerialNumber(); char format[16]; sprintf(format, "%02X-%04X-%04X", sernum.serialFirst, sernum.serialMid, sernum.serialLast); Serial.println(format); } //printDriverError decodes the CCS811Core::status type and prints the //type of error to the serial terminal. // //Save the return value of any function of type CCS811Core::status, then pass //to this function to see what the output was. void in_ccs811::printDriverError( CCS811Core::status errorCode ) { switch ( errorCode ) { case CCS811Core::SENSOR_SUCCESS: Serial.print("SUCCESS"); break; case CCS811Core::SENSOR_ID_ERROR: Serial.print("ID_ERROR"); break; case CCS811Core::SENSOR_I2C_ERROR: Serial.print("I2C_ERROR"); break; case CCS811Core::SENSOR_INTERNAL_ERROR: Serial.print("INTERNAL_ERROR"); break; case CCS811Core::SENSOR_GENERIC_ERROR: Serial.print("GENERIC_ERROR"); break; default: Serial.print("Unspecified error."); } } //printSensorError gets, clears, then prints the errors //saved within the error register. void in_ccs811::printSensorError() { uint8_t error = ccs811.getErrorRegister(); if ( error == 0xFF ) //comm error { Serial.println("Failed to get ERROR_ID register."); } else { //Serial.print(""); if (error & 1 << 5) Serial.print("Error: HeaterSupply"); if (error & 1 << 4) Serial.print("Error: HeaterFault"); if (error & 1 << 3) Serial.print("Error: MaxResistance"); if (error & 1 << 2) Serial.print("Error: MeasModeInvalid"); if (error & 1 << 1) Serial.print("Error: ReadRegInvalid"); if (error & 1 << 0) Serial.print("Error: MsgInvalid"); Serial.println(); } } #endif
26.448819
91
0.686365
anklimov
71e90916fb1a1ee401320c25368a423298bb280a
5,873
cpp
C++
src/display/VRDisplayNode.cpp
elainejiang8/MinVR
d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7
[ "BSD-3-Clause" ]
null
null
null
src/display/VRDisplayNode.cpp
elainejiang8/MinVR
d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7
[ "BSD-3-Clause" ]
null
null
null
src/display/VRDisplayNode.cpp
elainejiang8/MinVR
d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright Regents of the University of Minnesota, 2016. This software is released under the following license: http://opensource.org/licenses/ * Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu). * * Code author(s): * Dan Orban (dtorban) */ #include "VRDisplayNode.h" #include <main/VRFactory.h> namespace MinVR { VRDisplayNode::VRDisplayNode(const std::string &name) : _name(name) { } VRDisplayNode::~VRDisplayNode() { clearChildren(true); } void VRDisplayNode::render(VRDataIndex *renderState, VRRenderHandler *renderHandler) { if (_children.size() > 0) { for (vector<VRDisplayNode*>::iterator it = _children.begin(); it != _children.end(); it++) { (*it)->render(renderState, renderHandler); } } else { renderHandler->onVRRenderScene(renderState, this); } } void VRDisplayNode::waitForRenderToComplete(VRDataIndex *renderState) { for (vector<VRDisplayNode*>::iterator it = _children.begin(); it != _children.end(); it++) { (*it)->waitForRenderToComplete(renderState); } } void VRDisplayNode::displayFinishedRendering(VRDataIndex *renderState) { for (vector<VRDisplayNode*>::iterator it = _children.begin(); it != _children.end(); it++) { (*it)->displayFinishedRendering(renderState); } } const std::vector<VRDisplayNode*>& VRDisplayNode::getChildren() const { return _children; } void VRDisplayNode::addChild(VRDisplayNode* child) { _children.push_back(child); } void VRDisplayNode::clearChildren(bool destroyChildren) { if (destroyChildren) { for (vector<VRDisplayNode*>::iterator it = _children.begin(); it != _children.end(); it++) { delete (*it); } } _children.clear(); } void VRDisplayNode::createChildren(VRMainInterface *vrMain, VRDataIndex *config, const std::string &nameSpace) { std::string validatedNameSpace = config->validateNameSpace(nameSpace); std::list<std::string> names = config->selectByAttribute("displaynodeType", "*", validatedNameSpace, true); for (std::list<std::string>::const_iterator it = names.begin(); it != names.end(); ++it) { // We only want to do this for direct children. The grandchildren // and their progeny will be addressed in turn. if (VRDataIndex::isChild(nameSpace, *it) == 1) { VRDisplayNode *child = vrMain->getFactory()->create<VRDisplayNode>(vrMain, config, *it); if (child != NULL) { addChild(child); } } } } /// Returns a list of the values added to the render state by this /// node, and its children nodes. std::map<std::string,std::string> VRDisplayNode::getValuesAdded() { std::map<std::string,std::string> out; // Stick the node name with the values added. if (_valuesAdded.size() > 0) { for (std::list<std::string>::iterator it = _valuesAdded.begin(); it != _valuesAdded.end(); it++) { out[*it] = _name + "(" + getType() + ")"; } } // Look through all the children nodes, and append their values to // the list, with the current node name on the front. if (_children.size() > 0) { for (vector<VRDisplayNode*>::iterator it = _children.begin(); it != _children.end(); it++) { std::map<std::string,std::string> childOut = (*it)->getValuesAdded(); if (childOut.size() > 0) { for (std::map<std::string,std::string>::iterator jt = childOut.begin(); jt != childOut.end(); jt++) { out[jt->first] = jt->second; } } } } return out; } void VRDisplayNode::auditValues(std::list<std::string> valuesSupplied) { // First check to see if all of the values needed appear in the // input list. bool found; if ((_valuesNeeded.size() > 0) && (valuesSupplied.size() > 0)) { for (std::list<std::string>::iterator it = _valuesNeeded.begin(); it != _valuesNeeded.end(); it++) { found = false; for (std::list<std::string>::iterator jt = valuesSupplied.begin(); jt != valuesSupplied.end(); jt++) { found = found || ((*it).compare(*jt) == 0); } // If we haven't found this needed value, throw an error. if (!found) throw std::runtime_error("Needed " + (*it) + " but didn't get it, in " + getName() + ":" + getType()); } } // Then add the valuesAdded to the input list and pass along to the // children nodes. valuesSupplied.insert(valuesSupplied.end(), _valuesAdded.begin(), _valuesAdded.end()); if (_children.size() > 0) { for (std::vector<VRDisplayNode*>::iterator it = _children.begin(); it != _children.end(); it++) { (*it)->auditValues(valuesSupplied); } } } std::string VRDisplayNode::printNode(const std::string &prefix) const { std::string name; if (_name.size() > 48) { name = _name.substr(0,15) + "..." + _name.substr(_name.size() - 33, std::string::npos); } else { name = _name; } std::string out = prefix + "<displayNode:" + name + ">"; out += "\n" + prefix + " Values Added"; for (std::list<std::string>::const_iterator it = _valuesAdded.begin(); it != _valuesAdded.end(); it++) { out += "\n" + prefix + " " + *it; } if (_valuesAdded.empty()) out += "\n" + prefix + " <none>"; out += "\n" + prefix + " Values Needed"; for (std::list<std::string>::const_iterator it = _valuesNeeded.begin(); it != _valuesNeeded.end(); it++) { out += "\n" + prefix + " " + *it; } if (_valuesNeeded.empty()) out += "\n" + prefix + " <none>"; for (std::vector<VRDisplayNode*>::const_iterator it = _children.begin(); it != _children.end(); it++) { out += "\n" + (*it)->printNode(prefix + "| "); } return out; } } /* namespace MinVR */
30.273196
146
0.612294
elainejiang8
71eae2207b9960d1915ef7957da7c589d508f102
1,882
cpp
C++
problems/codejam/2021/2/matrygons/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
problems/codejam/2021/2/matrygons/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
problems/codejam/2021/2/matrygons/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // ***** vector<int> primes, lp, nxt; auto get_divisors(const unordered_map<int, int>& factors) { vector<int> divs = {1}; for (const auto& [p, e] : factors) { int D = divs.size(); divs.resize(D * (e + 1)); for (int n = 1; n <= e; n++) { for (int d = 0; d < D; d++) { divs[d + n * D] = divs[d + (n - 1) * D] * p; } } } if (!divs.empty() && divs[0] == 1) { divs.erase(begin(divs)); } return divs; } auto least_prime_sieve(int N) { lp.assign(N + 1, 0), nxt.assign(N + 1, 0); nxt[1] = 1; for (int P = 0, n = 2; n <= N; n++) { if (lp[n] == 0) { lp[n] = n, primes.push_back(n), P++; } for (int i = 0; i < P && primes[i] <= lp[n] && n * primes[i] <= N; ++i) { lp[n * primes[i]] = primes[i], nxt[n * primes[i]] = n; } } return lp; } auto factor_primes(int n) { unordered_map<int, int> primes; while (n > 1) { primes[lp[n]]++, n = nxt[n]; } return primes; } constexpr int MAXN = 1'000'000; int dp3[MAXN + 1]; int dp2[MAXN + 1]; void setup_dp() { dp2[2] = 1; dp2[3] = dp3[3] = 1; for (int n = 4; n <= MAXN; n++) { auto divs = get_divisors(factor_primes(n)); dp2[n] = dp3[n] = 1; for (auto d : divs) { if (d > 2) { dp3[n] = max(dp3[n], 1 + dp2[n / d - 1]); } dp2[n] = max(dp2[n], 1 + dp2[n / d - 1]); } } } auto solve() { int N; cin >> N; return dp3[N]; } // ***** int main() { least_prime_sieve(2'000'000); setup_dp(); unsigned T; cin >> T >> ws; for (unsigned t = 1; t <= T; ++t) { auto solution = solve(); cout << "Case #" << t << ": " << solution << '\n'; } return 0; }
21.386364
81
0.425611
brunodccarvalho
71ec616984ec83f8c0d5bc35f4c489b5450206c5
690
hpp
C++
include/strf/fps.hpp
AnttiVainio/STRF
8c397a1efad0e35f76de0242c4fb82f48b48e824
[ "MIT" ]
null
null
null
include/strf/fps.hpp
AnttiVainio/STRF
8c397a1efad0e35f76de0242c4fb82f48b48e824
[ "MIT" ]
null
null
null
include/strf/fps.hpp
AnttiVainio/STRF
8c397a1efad0e35f76de0242c4fb82f48b48e824
[ "MIT" ]
null
null
null
/** fps.hpp **/ #ifndef STRF_FPS_HPP #define STRF_FPS_HPP #include <strf/global.hpp> #include <deque> namespace strf { #ifndef STRF_INIT_HPP DLL_EXPORT void DLL_CALL set_fps_draw_size(cfloat value = 40.0); #endif class DLL_EXPORT fps { private: fps(const fps &fps); //Copy constructor fps &operator=(const fps &fps); //Assign operator cdouble delay; double time; double timestamp; uchar undrawn_count; uchar drew_previous_frame; std::deque<double> real_delays; std::deque<double> delays; std::deque<double> sleeps; public: fps(cdouble new_fps); void draw() const; void wait(); void reset(); bool draw_frame() const; }; } #endif
17.692308
65
0.688406
AnttiVainio
71ecf89145d9edcafadc572248fecacead660f35
1,049
hpp
C++
include/SDPVer.hpp
Cyberunner23/libSDP
0c4cffc951980c618c6f0e04bb8c3b184f246226
[ "Apache-2.0" ]
3
2015-03-07T09:51:56.000Z
2017-05-13T20:17:15.000Z
include/SDPVer.hpp
Cyberunner23/libSDP
0c4cffc951980c618c6f0e04bb8c3b184f246226
[ "Apache-2.0" ]
null
null
null
include/SDPVer.hpp
Cyberunner23/libSDP
0c4cffc951980c618c6f0e04bb8c3b184f246226
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015 Alex Frappier Lachapelle 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 SDPVER_HPP #define SDPVER_HPP #include "Utils/Typedefs.hpp" namespace libSDP{ using namespace libSDP::Utils; class SDPVer{ public: //Vars struct SDPLibVerStruct{ uint8 major=0; uint8 minor=2; uint8 patch=0; } SDPLibVer; struct SDPSpecRevStruct{ uint8 major=1; uint8 minor=0; } SDPSpecRev; }; } #endif // SDPVER_HPP
21.854167
75
0.666349
Cyberunner23
71ecfa1dd87de1a6f3903e8a1189a73efa335ea3
4,231
hh
C++
src/patient/patient.hh
Apperta-IXN-for-the-NHS/GOSH-FHIRworks2020-datamaskgen
b8c075b01640f99730fcd39ad87c3009a510fa01
[ "Apache-2.0" ]
2
2020-03-10T04:35:17.000Z
2020-03-30T12:26:51.000Z
src/patient/patient.hh
Apperta-IXN-for-the-NHS/GOSH-FHIRworks2020-datamaskgen
b8c075b01640f99730fcd39ad87c3009a510fa01
[ "Apache-2.0" ]
4
2020-03-09T01:11:30.000Z
2020-03-10T03:12:43.000Z
src/patient/patient.hh
Apperta-IXN-for-the-NHS/GOSH-FHIRworks2020-datamaskgen
b8c075b01640f99730fcd39ad87c3009a510fa01
[ "Apache-2.0" ]
1
2020-05-29T14:38:49.000Z
2020-05-29T14:38:49.000Z
// // Created by Patrick Wu on 02/03/2020. // #ifndef GOSH_FHIRWORKS2020_DATAMASKGEN_PATIENT_HH #define GOSH_FHIRWORKS2020_DATAMASKGEN_PATIENT_HH #include <string> #include <ctime> #include <vector> #include <sstream> #include "name.hh" #include "address.hh" #include "language.hh" #include "telecom.hh" #include "identifier.hh" #include "gender.hh" #include "marital_status.hh" using namespace std; class patient { public: static string generate_current_timestamp () { time_t now; time(&now); char buf[sizeof "YYYY-MM-DDThh:mm:ssZ"]; strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now)); return buf; } bool operator == (const patient& p1) const { return uuid == p1.uuid; } string uuid; name name; gender gender; tm birthday; string extensions; vector<address> addresses; marital_status marital_status; vector<language> communication_languages; vector<telecom> telecoms; vector<identifier> identifiers; bool multiple_birth = false; int multiple_birth_count = 1; patient (string id, string pre, string gn, string fn, string gen, bool mul_birth, int mul_birth_count, string bday) : uuid(std::move(id)), name(std::move(pre), std::move(gn), std::move(fn)), multiple_birth(mul_birth), multiple_birth_count(mul_birth_count) { if (gen == "male") gender = MALE; else if (gen == "female") gender = FEMALE; else gender = OTHER; strptime(bday.c_str(), "%Y-%m-%d", &birthday); } patient (class name n, enum gender g, tm bday, vector<address> addrs, class marital_status m_status, vector<language> c_langs, vector<telecom> ts, vector<identifier> is, string exs, string uid, bool m_birth, int m_birth_count) : uuid(std::move(uid)), name(std::move(n)), gender(std::move(g)), birthday(std::move(bday)), addresses(std::move(addrs)), marital_status(std::move(m_status)), communication_languages(std::move(c_langs)), telecoms(std::move(ts)), identifiers(std::move(is)), extensions(exs), multiple_birth(m_birth), multiple_birth_count(m_birth_count) { } string jsonify () { stringstream ss; ss << R"({"fullUrl":"","resource":{"resourceType":"Patient","id":")" << uuid << "\","; ss << R"("meta":{"versionId":"4","lastUpdated":")" << generate_current_timestamp() << "\"},"; ss << R"("text":{"status":"generated","div":""},)"; ss << R"("extension":)" << extensions << ","; ss << "\"identifier\":["; for (size_t i = 0; i < identifiers.size() - 1; i++) ss << identifiers[i].jsonify() << ","; ss << identifiers.back().jsonify() << "],"; ss << name.jsonify() << ","; ss << "\"telecom\":["; for (size_t i = 0; i < telecoms.size() - 1; i++) ss << telecoms[i].jsonify() << ","; ss << telecoms.back().jsonify() << "],"; ss << "\"gender\":\""; switch (gender) { case MALE: ss << "male"; break; case FEMALE: ss << "female"; break; default: ss << "other"; break; } ss << "\","; ss << "\"birthDate\":\"" << birthday.tm_year + 1900 << "-" << birthday.tm_mon << "-" << birthday.tm_mday << "\","; ss << "\"address\":["; for (size_t i = 0; i < addresses.size() - 1; i++) ss << addresses[i].jsonify() << ","; ss << addresses.back().jsonify() << "],"; ss << marital_status.jsonify() << ","; if (!multiple_birth) ss << "\"multipleBirthBoolean\":" << multiple_birth << ","; else ss << "\"multipleBirthInteger\":" << multiple_birth_count << ","; ss << "\"communication\":["; for (size_t i = 0; i < communication_languages.size() - 1; i++) ss << communication_languages[i].jsonify() << ","; ss << communication_languages.back().jsonify() << "]"; ss << "}}"; return ss.str(); } }; namespace std { template<> struct hash<patient> { size_t operator() (const patient& p) const { return std::hash<string>()(p.uuid); } }; } #endif
35.855932
177
0.559679
Apperta-IXN-for-the-NHS