blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
531a20216388bd1ca74a2d10f182627ecb112b87 | 4b404aa7779cdcd31da4fe1a8de890d77f81948c | /3D팀/블레스맵툴/Reference/Headers/Line2D.h | 8e4dd7db2d600fed9aab292d596cb16d7136e8b9 | [] | no_license | Jisean/BlessProjectBackup | dd738a535d9180a364a88f1401ac8f027654cb04 | fc2fc079731bb6212ba860c40981f46afe97d603 | refs/heads/master | 2021-05-13T17:59:27.410635 | 2018-01-09T14:04:52 | 2018-01-09T14:04:52 | 116,822,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 773 | h | /*!
* \file Line2D.h
* \date 2016/03/09 13:17
*
* \author Administrator
* Contact: [email protected]
*
* \brief
*
* TODO: long description
*
* \note
*/
#ifndef Line2D_h__
#define Line2D_h__
#include "Engine_Include.h"
#include "Base.h"
BEGIN(Engine)
class ENGINE_DLL CLine2D : public CBase
{
public:
enum DIR {DIR_LEFT, DIR_RIGHT};
private:
CLine2D(void);
~CLine2D(void);
public:
HRESULT Init_Line(const D3DXVECTOR3* pStartPoint, const D3DXVECTOR3* pEndPoint);
DIR Check_Dir(const D3DXVECTOR2* pMoveEndPoint);
public:
D3DXVECTOR2 m_vStartPoint;
D3DXVECTOR2 m_vEndPoint;
D3DXVECTOR2 m_vNormal;
public:
static CLine2D* Create(const D3DXVECTOR3* pStartPoint, const D3DXVECTOR3* pEndPoint);
virtual void Free(void);
};
END
#endif // Line2D_h__ | [
"[email protected]"
] | |
c2eac0fd7e292c7fa28435f42c75735dffe846b0 | 4d2807b866a138f23affc236bbdd86f81e212946 | /proxy_url_extractor.cc | 0b1cc4a7fa9dbbef9c43dce4dbae880168c33693 | [] | no_license | bitkeli/Myproxy_url | 8a857cbd48f8f46772a9b3193a9b3f3055f8a7a8 | 0e18390b90f394f1866c97f5e887486f03d5bd07 | refs/heads/master | 2021-01-10T21:45:47.232192 | 2014-08-16T12:12:55 | 2014-08-16T12:12:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,019 | cc | #include "proxy_url_extractor.h"
#include <fstream>
#include <vector>
#include "tokener.h"
namespace qh
{
namespace {
template< class _StringVector,
class StringType,
class _DelimType>
inline void StringSplit(
const StringType& str,
const _DelimType& delims,
unsigned int maxSplits,
_StringVector& ret)
{
unsigned int numSplits = 0;
// Use STL methods
size_t start, pos;
start = 0;
do
{
pos = str.find_first_of( delims, start );
if ( pos == start )
{
ret.push_back(StringType());
start = pos + 1;
}
else if ( pos == StringType::npos || ( maxSplits && numSplits + 1== maxSplits ) )
{
// Copy the rest of the string
ret.push_back(StringType());
*(ret.rbegin()) = StringType(str.data() + start, str.size() - start);
break;
}
else
{
// Copy up to delimiter
//ret.push_back( str.substr( start, pos - start ) );
ret.push_back(StringType());
*(ret.rbegin()) = StringType(str.data() + start, pos - start);
start = pos + 1;
}
++numSplits;
}
while ( pos != StringType::npos );
}
}
ProxyURLExtractor::ProxyURLExtractor()
{
}
bool ProxyURLExtractor::Initialize( const std::string& param_keys_path )
{
std::ifstream ifs;
ifs.open(param_keys_path.data(), std::fstream::in);
typedef std::vector<std::string> stringvector;
stringvector keysvect;
while (!ifs.eof()) {
std::string line;
getline(ifs, line);
if (ifs.fail() && !ifs.eof()) {
fprintf(stderr, "SubUrlExtractor::LoadParamKeysFile readfile_error=[%s] error!!", param_keys_path.data());
ifs.close();
return false;
}
if (line.empty()) continue;
keysvect.clear();
StringSplit(line, ",", static_cast<unsigned int>(-1), keysvect);
assert(keysvect.size() >= 1);
keys_set_.insert(keysvect.begin(), keysvect.end());
keys_set_.erase("");
}
ifs.close();
return true;
}
std::string ProxyURLExtractor::Extract( const std::string& raw_url )
{
std::string sub_url;
ProxyURLExtractor::Extract(keys_set_, raw_url, sub_url);
return sub_url;
}
void ProxyURLExtractor::Extract( const KeyItems& keys, const std::string& raw_url, std::string& sub_url )
{
#if 1
//TODO 请面试者在这里添加自己的代码实现以完成所需功能
//其实原方法写的不错,就是有一些细节处理不到位样例集1通过,2局部不通过,我的核心思想是
//尽量利用原来比较成熟的方法,将样本2中的一些钉子户进行剪枝成为样例1中比较标准类型
std::string rawcp=raw_url;
int i=0;
int a[2]={0}; //a[0]放'='最后出现的位置,a[1]放'&'最后出现的位置
//下面开始对原始字符串进行剪枝,使得第二组中一些特殊样例全部变成第一组中的标准样例
//(因为原始方法已经能够通过第一组测试集)
//***************这里定义标准样例为'='与'&'交替出现,且'='较早出现******************//
//剪枝方法不仅能够排除异类,并且能够遍历一次的情况下解决问题
while(i<rawcp.size())
{
if(rawcp[i]=='=')
{
a[0]=i;
}
/****************************以下的if条件为了解决下列情况,'='后面紧接一个'&'
"http://www.microsofttranslator.com/bv.aspx?from=&to=zh-chs&xxx&query=&yyy", ""
这种情况下直接去掉'&query='这一段就能够同其他的情况做相同处理,变成
"http://www.microsofttranslator.com/bv.aspx?from=&to=zh-chs&xxx&yyy", ""
******************************************************************************/
if(i+1<rawcp.size()&&rawcp[i]=='='&&rawcp[i+1]=='&'&&a[1]>0)
{
rawcp=rawcp.substr(0,a[1])+rawcp.substr(i+1,rawcp.size()-i-1);
i++;
continue;
}
////////////////////////////////////////////////////////////////////////////////////
/****************************以下的if条件为了解决原有代码中不能够正确处理的
"http://www.microsofttranslator.com/bv.aspx?from=&to=zh-chs&xxx&query=http://hnujug.com/"
根本原因在于上述这种类型不再是"&""="交替出现,所以这里做了一个剪枝,连续出现的两个"&"之间
不会有关键信息,所以去掉"&xxx"这一段,变成
"http://www.microsofttranslator.com/bv.aspx?from=&to=zh-chs&query=http://hnujug.com/"
******************************************************************************/
if(rawcp[i]=='&'&&a[1]>a[0])
{
rawcp=rawcp.substr(0,a[1])+rawcp.substr(i,rawcp.size()-i);
i++;
continue;
}
////////////////////////////////////////////////////////////////////////////////////
if(rawcp[i]=='&')
{
a[1]=i;
}
i++;
}
/***************************下面的while循环意在解决这种情况:通过以上两道剪枝之后,还遗留下:
"http://lk.brand.sogou.com/svc/r.php?&%23&url=%68ttp%3A//23.80.77.123/22/e/4", "%68ttp%3A//23.80.77.123/22/e/4"
'&'第一次出现的位置比'='第一次出现位置早,那么直接减去第一次出现的'&'就成为标准的待处理url地址,变成
"http://lk.brand.sogou.com/svc/r.php?%23&url=%68ttp%3A//23.80.77.123/22/e/4", "%68ttp%3A//23.80.77.123/22/e/4"
*******************************************************************************/
i=0;
while(i<rawcp.size())
{
if(i+2<rawcp.size()&&rawcp[i]=='?'&&rawcp[i+1]=='&')
{
rawcp=rawcp.substr(0,i+1)+rawcp.substr(i+2,rawcp.size()-i-2);
break;
}
i++;
}
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////// 以上为我的剪枝
/////////////////////////////////////////////////////////////////////////
Tokener token(rawcp); // 输入的字符串不再是原始字符串,而是剪枝后的,剩下的都是原来处理方式
token.skipTo('?');
token.next(); //skip one char : '?'
std::string key;
while (!token.isEnd()) {
key = token.nextString('=');
if (keys.find(key) != keys.end()) {
const char* curpos = token.getCurReadPos();
int nreadable = token.getReadableSize();
/**
* case 1:
* raw_url="http://www.microsofttranslator.com/bv.aspx?from=&to=zh-chs&a=http://hnujug.com/&xx=yy"
* sub_url="http://hnujug.com/"
*/
sub_url = token.nextString('&');
if (sub_url.empty() && nreadable > 0) {
/**
* case 2:
* raw_url="http://www.microsofttranslator.com/bv.aspx?from=&to=zh-chs&a=http://hnujug.com/"
* sub_url="http://hnujug.com/"
*/
assert(curpos);
sub_url.assign(curpos, nreadable);
}
}
token.skipTo('&');
token.next();//skip one char : '&'
}
#else
//这是一份参考实现,但在特殊情况下工作不能符合预期
Tokener token(raw_url);
token.skipTo('?');
token.next(); //skip one char : '?'
std::string key;
while (!token.isEnd()) {
key = token.nextString('=');
if (keys.find(key) != keys.end()) {
const char* curpos = token.getCurReadPos();
int nreadable = token.getReadableSize();
/**
* case 1:
* raw_url="http://www.microsofttranslator.com/bv.aspx?from=&to=zh-chs&a=http://hnujug.com/&xx=yy"
* sub_url="http://hnujug.com/"
*/
sub_url = token.nextString('&');
if (sub_url.empty() && nreadable > 0) {
/**
* case 2:
* raw_url="http://www.microsofttranslator.com/bv.aspx?from=&to=zh-chs&a=http://hnujug.com/"
* sub_url="http://hnujug.com/"
*/
assert(curpos);
sub_url.assign(curpos, nreadable);
}
}
token.skipTo('&');
token.next();//skip one char : '&'
}
#endif
}
std::string ProxyURLExtractor::Extract( const KeyItems& keys, const std::string& raw_url )
{
std::string sub_url;
ProxyURLExtractor::Extract(keys, raw_url, sub_url);
return sub_url;
}
}
| [
"[email protected]"
] | |
84f774f8695284771f9688190ce2df7ae6911064 | 5a60d60fca2c2b8b44d602aca7016afb625bc628 | /aws-cpp-sdk-license-manager/include/aws/license-manager/model/CreateTokenResult.h | 9e83fb3bc69c17551e730a9a00062d13ac58c292 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | yuatpocketgems/aws-sdk-cpp | afaa0bb91b75082b63236cfc0126225c12771ed0 | a0dcbc69c6000577ff0e8171de998ccdc2159c88 | refs/heads/master | 2023-01-23T10:03:50.077672 | 2023-01-04T22:42:53 | 2023-01-04T22:42:53 | 134,497,260 | 0 | 1 | null | 2018-05-23T01:47:14 | 2018-05-23T01:47:14 | null | UTF-8 | C++ | false | false | 3,679 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/license-manager/LicenseManager_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/license-manager/model/TokenType.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace LicenseManager
{
namespace Model
{
class CreateTokenResult
{
public:
AWS_LICENSEMANAGER_API CreateTokenResult();
AWS_LICENSEMANAGER_API CreateTokenResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
AWS_LICENSEMANAGER_API CreateTokenResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>Token ID.</p>
*/
inline const Aws::String& GetTokenId() const{ return m_tokenId; }
/**
* <p>Token ID.</p>
*/
inline void SetTokenId(const Aws::String& value) { m_tokenId = value; }
/**
* <p>Token ID.</p>
*/
inline void SetTokenId(Aws::String&& value) { m_tokenId = std::move(value); }
/**
* <p>Token ID.</p>
*/
inline void SetTokenId(const char* value) { m_tokenId.assign(value); }
/**
* <p>Token ID.</p>
*/
inline CreateTokenResult& WithTokenId(const Aws::String& value) { SetTokenId(value); return *this;}
/**
* <p>Token ID.</p>
*/
inline CreateTokenResult& WithTokenId(Aws::String&& value) { SetTokenId(std::move(value)); return *this;}
/**
* <p>Token ID.</p>
*/
inline CreateTokenResult& WithTokenId(const char* value) { SetTokenId(value); return *this;}
/**
* <p>Token type.</p>
*/
inline const TokenType& GetTokenType() const{ return m_tokenType; }
/**
* <p>Token type.</p>
*/
inline void SetTokenType(const TokenType& value) { m_tokenType = value; }
/**
* <p>Token type.</p>
*/
inline void SetTokenType(TokenType&& value) { m_tokenType = std::move(value); }
/**
* <p>Token type.</p>
*/
inline CreateTokenResult& WithTokenType(const TokenType& value) { SetTokenType(value); return *this;}
/**
* <p>Token type.</p>
*/
inline CreateTokenResult& WithTokenType(TokenType&& value) { SetTokenType(std::move(value)); return *this;}
/**
* <p>Refresh token, encoded as a JWT token.</p>
*/
inline const Aws::String& GetToken() const{ return m_token; }
/**
* <p>Refresh token, encoded as a JWT token.</p>
*/
inline void SetToken(const Aws::String& value) { m_token = value; }
/**
* <p>Refresh token, encoded as a JWT token.</p>
*/
inline void SetToken(Aws::String&& value) { m_token = std::move(value); }
/**
* <p>Refresh token, encoded as a JWT token.</p>
*/
inline void SetToken(const char* value) { m_token.assign(value); }
/**
* <p>Refresh token, encoded as a JWT token.</p>
*/
inline CreateTokenResult& WithToken(const Aws::String& value) { SetToken(value); return *this;}
/**
* <p>Refresh token, encoded as a JWT token.</p>
*/
inline CreateTokenResult& WithToken(Aws::String&& value) { SetToken(std::move(value)); return *this;}
/**
* <p>Refresh token, encoded as a JWT token.</p>
*/
inline CreateTokenResult& WithToken(const char* value) { SetToken(value); return *this;}
private:
Aws::String m_tokenId;
TokenType m_tokenType;
Aws::String m_token;
};
} // namespace Model
} // namespace LicenseManager
} // namespace Aws
| [
"[email protected]"
] | |
d2935826bce1d598580763bea35b38aef69afe45 | 17ffa0cfce42c5c0254fe993643afb0c6d32a188 | /05-Research-Work-by-students.cpp | 996a7a512faba9ad0e79f4f78938b3b56b17de53 | [] | no_license | HarshitDahiya/Code-Combat | dd046cf41854a2a33375b115252042381cb519b7 | 895765b71ec05cfdcbf4b1921f20c2eaa7bf0db1 | refs/heads/master | 2020-04-20T16:09:26.298469 | 2019-02-03T17:39:15 | 2019-02-03T17:39:15 | 168,950,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | cpp | #include<iostream>
using namespace std;
#include<stdio.h>
int main(){
int n1,n2,a[1000],m[1000],i;
int max = 0, min = 100; //As attendence and marks ranges between 1 and 100.
cin>>n1>>n2; //Taking size of arrays
for(i=0;i<n1;i++){
cin>>a[i]; //Taking input for array one
if(a[i] > max)
max = a[i]; //Checking if input is greater than current maximum attendance. If True, storing it in max.
}
for(i=0;i<n2;i++){
cin>>m[i]; //Taking input for array two
if(m[i] < min)
min = m[i]; //Checking if input is less than current minumum marks. If true, storing it in min.
}
cout<<max<<endl<<min; //Printing result
return 0;
} | [
"[email protected]"
] | |
fc078c04ff67a96dd2857104b52d677aaa6e6224 | ae25bffa378345c49e5ef5a0347f2c121c7a0f31 | /ns-2.1b8a/diffserv/dsredq.h | 45b95a8436d8fb7dbf0a6ce68bffc3c5449758bf | [] | no_license | smilemare/NS-2.1b8a-MacOS | 49a00733c4aee95e86324d595bb7e85d98259be9 | b556e49bf6ff88df0bdd983baaae68a809676f88 | refs/heads/master | 2020-12-24T15:22:53.671307 | 2014-10-31T10:04:37 | 2014-10-31T10:04:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,922 | h | /*
* Copyright (c) 2000 Nortel Networks
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Nortel Networks.
* 4. The name of the Nortel Networks may not be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY NORTEL AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NORTEL OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Developed by: Farhan Shallwani, Jeremy Ethridge
* Peter Pieda, and Mandeep Baines
* Maintainer: Peter Pieda <[email protected]>
*/
#ifndef dsredq_h
#define dsredq_h
//#include "dsred.h"
#define MAX_PREC 3 // maximum number of virtual RED queues in one physical queue
enum mredModeType {rio_c, rio_d, wred, dropTail};
/*------------------------------------------------------------------------------
struct qParam
This structure specifies the parameters needed to be maintained for each
RED queue.
------------------------------------------------------------------------------*/
struct qParam {
edp edp_; // early drop parameters (see red.h)
edv edv_; // early drop variables (see red.h)
int qlen; // actual (not weighted) queue length in packets
double idletime_; // needed to calculate avg queue
bool idle_; // needed to calculate avg queue
};
/*------------------------------------------------------------------------------
class redQueue
This class provides specs for one physical queue.
------------------------------------------------------------------------------*/
class redQueue {
public:
int numPrec; // the current number of precedence levels (or virtual queues)
int qlim;
mredModeType mredMode;
redQueue();
void config(int prec, const char*const* argv); // configures one virtual RED queue
void initREDStateVar(void); // initializes RED state variables
void updateREDStateVar(int prec); // updates RED variables after dequing a packet
// enques packets into a physical queue
int enque(Packet *pkt, int prec, int ecn);
Packet* deque(void); // deques packets
double getWeightedLength();
int getRealLength(void); // queries length of a physical queue
// sets packet time constant values
//(needed for calc. avgQSize) for each virtual queue
void setPTC(double outLinkBW);
// sets mean packet size (needed to calculate avg. queue size)
void setMPS(int mps);
private:
PacketQueue *q_; // underlying FIFO queue
// used to maintain parameters for each of the virtual queues
qParam qParam_[MAX_PREC];
void calcAvg(int prec, int m); // to calculate avg. queue size of a virtual queue
};
#endif
| [
"[email protected]"
] | |
9a7e637dce8555bbac490cf2dc9edda453045e73 | 9a3fc0a5abe3bf504a63a643e6501a2f3452ba6d | /tc/testprograms/BuyingFlowers.cpp | d35c5091ae595dbf1d6605ce65b3b60f741ad854 | [] | no_license | rodolfo15625/algorithms | 7034f856487c69553205198700211d7afb885d4c | 9e198ff0c117512373ca2d9d706015009dac1d65 | refs/heads/master | 2021-01-18T08:30:19.777193 | 2014-10-20T13:15:09 | 2014-10-20T13:15:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,156 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define ll long long
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()
#define sz size()
#define pb push_back
#define mp make_pair
#define mem(x,i) memset(x,i,sizeof(x))
#define cpresent(V,e) (find(all(V),(e))!=(V).end())
#define foreach(c,it) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();++it)
using namespace std;
long long toi(string s){istringstream is(s);long long x;is>>x;return x;}
string tos(long long t){stringstream st; st<<t;return st.str();}
long long gcd(long long a, long long b){return __gcd(a,b);}
long long lcm(long long a,long long b){return a*(b/gcd(a,b));}
class BuyingFlowers {
public:
int buy(vector <int> roses, vector <int> lilies) {
int dev=1<<30;
for(int i=1;i<(1<<roses.sz);i++){
int a=0,b=0;
for(int j=0;j<roses.sz;j++)
if(i&(1<<j)){
a+=roses[j];
b+=lilies[j];
}
int x=a+b;
for(int k=1;k*k<=x+1 && abs(a-b)<=1;k++)
if(x%k==0 && k*(x/k)==x ){
dev=min(dev,abs(k-x/k));
}
}
return (dev==1<<30)?-1:dev;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, vector <int> p0, vector <int> p1, bool hasAnswer, int p2) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << p0[i];
}
cout << "}" << "," << "{";
for (int i = 0; int(p1.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << p1[i];
}
cout << "}";
cout << "]" << endl;
BuyingFlowers *obj;
int answer;
obj = new BuyingFlowers();
clock_t startTime = clock();
answer = obj->buy(p0, p1);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p2 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p2;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
vector <int> p0;
vector <int> p1;
int p2;
{
// ----- test 0 -----
int t0[] = {2,4};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {4,2};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = 1;
all_right = KawigiEdit_RunTest(0, p0, p1, true, p2) && all_right;
// ------------------
}
{
// ----- test 1 -----
int t0[] = {2,7,3};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {3,4,1};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = 0;
all_right = KawigiEdit_RunTest(1, p0, p1, true, p2) && all_right;
// ------------------
}
{
// ----- test 2 -----
int t0[] = {4,5,2,1};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {6,10,5,9};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = -1;
all_right = KawigiEdit_RunTest(2, p0, p1, true, p2) && all_right;
// ------------------
}
{
// ----- test 3 -----
int t0[] = {1,208,19,0,3,234,1,106,99,17};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {58,30,3,5,0,997,9,615,77,5};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = 36;
all_right = KawigiEdit_RunTest(3, p0, p1, true, p2) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
| [
"[email protected]"
] | |
96a2b17edcc506e8180a32ed370df14bca63cdb9 | 728736a5db6f66f1f134fad5a8129c8243a5b1c1 | /tests/core/allocatorTests.cpp | 0f0d49bf34bf8c85ec0e43ba3ae1807d1ec3ecb8 | [
"MIT"
] | permissive | blockspacer/babycpp | dc4a940b5b4f9461ef2bcca2c9f4f80f8b2164c3 | f7bc52c9a3f0ccc685ed89ae57edb16fda3f8d2d | refs/heads/master | 2020-04-27T11:01:26.212742 | 2017-11-25T08:54:50 | 2017-11-25T08:54:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,119 | cpp | #include "catch.hpp"
#include "codegen.h"
#include "factoryAST.h"
#include "slabAllocator.h"
#include <iostream>
using babycpp::memory::Slab;
using babycpp::memory::SlabAllocator;
TEST_CASE("Testing allocator not movable", "[memory]") {
REQUIRE(std::is_copy_constructible<SlabAllocator>::value == false);
REQUIRE(std::is_copy_assignable<SlabAllocator>::value == false);
}
TEST_CASE("Testing allocator instantiation", "[memory]") {
SlabAllocator slab;
REQUIRE(slab.currentSlab != nullptr);
// making sure there is at least one slab when istantiated
Slab &currSlab = *slab.currentSlab;
REQUIRE(slab.currentSlab != nullptr);
REQUIRE(slab.currentSlab == &slab.slabs[0]);
REQUIRE((currSlab.endp - currSlab.data) == babycpp::memory::SLAB_SIZE);
}
TEST_CASE("Testing allocator instantiation, not default slab size",
"[memory]") {
SlabAllocator slab(200);
REQUIRE(slab.currentSlab != nullptr);
// making sure there is at least one slab when istantiated
Slab &currSlab = *slab.currentSlab;
REQUIRE(slab.currentSlab != nullptr);
REQUIRE(slab.currentSlab == &slab.slabs[0]);
REQUIRE((currSlab.endp - currSlab.data) == 200);
}
TEST_CASE("Testing allocation of memory", "[memory]") {
SlabAllocator slab;
uint32_t allocSize = sizeof(babycpp::codegen::ExprAST);
slab.alloc(allocSize);
uint64_t offset = slab.getStackPtrOffset();
REQUIRE(offset == allocSize);
}
TEST_CASE("Testing allocation loop alloc and free", "[memory]") {
SlabAllocator slab;
uint32_t allocSize = sizeof(babycpp::codegen::ExprAST);
for (uint32_t i = 0; i < 20; ++i) {
auto *p = slab.alloc(allocSize);
REQUIRE(p != nullptr);
}
uint64_t offset = slab.getStackPtrOffset();
REQUIRE(offset == allocSize * 20);
}
TEST_CASE("Testing allocation slab-re-alloc", "[memory]") {
uint32_t allocSize = sizeof(babycpp::codegen::ExprAST);
SlabAllocator slab(allocSize * 30);
for (uint32_t i = 0; i < 30; ++i) {
auto *p = slab.alloc(allocSize);
REQUIRE(p != nullptr);
}
REQUIRE(slab.slabs.size() == 1);
// now we are exactly on the edge of the allocation, new allocation
// should trigger a new slab alloc
Slab *curr = slab.currentSlab;
auto *p = slab.alloc(allocSize);
REQUIRE(p != nullptr);
REQUIRE(curr != slab.currentSlab);
REQUIRE(slab.slabs.size() == 2);
// since there should be only one element in the new slab alloc
// the offset should be the size of one alloc
REQUIRE(slab.getStackPtrOffset() == allocSize);
}
TEST_CASE("Testing cleaning memory", "[memory]") {
uint32_t allocSize = sizeof(babycpp::codegen::ExprAST);
SlabAllocator slab(allocSize * 9);
for (uint32_t i = 0; i < 30; ++i) {
auto *p = slab.alloc(allocSize);
REQUIRE(p != nullptr);
}
REQUIRE(slab.slabs.size() == 4);
slab.clear();
REQUIRE(slab.slabs.size() == 1);
}
TEST_CASE("Testing factory nodes", "[memory]") {
using babycpp::codegen::VariableExprAST;
using babycpp::codegen::NumberExprAST;
using babycpp::codegen::BinaryExprAST;
using babycpp::codegen::CallExprAST;
using babycpp::codegen::PrototypeAST;
using babycpp::codegen::FunctionAST;
using babycpp::codegen::ExprAST;
using babycpp::codegen::Argument;
using babycpp::parser::Number;
using babycpp::lexer::Token;
std::string t = "test";
babycpp::memory::FactoryAST f;
auto *res = f.allocVariableAST(t, nullptr, 0);
uint32_t allocSize = sizeof(VariableExprAST);
REQUIRE(res != nullptr);
REQUIRE(res->name == "test");
REQUIRE(f.allocator.slabs.size() == 1);
REQUIRE(f.allocator.getStackPtrOffset() == allocSize);
allocSize += sizeof(NumberExprAST);
Number num;
num.integerNumber = 30;
auto *numbptr = f.allocNuberAST(num);
REQUIRE(numbptr != nullptr);
REQUIRE(numbptr->val.integerNumber == 30);
REQUIRE(f.allocator.slabs.size() == 1);
REQUIRE(f.allocator.getStackPtrOffset() == allocSize);
allocSize += sizeof(BinaryExprAST);
auto *binptr = f.allocBinaryAST(std::string("+"), nullptr, nullptr);
REQUIRE(binptr != nullptr);
REQUIRE(binptr->op == "+");
REQUIRE(f.allocator.slabs.size() == 1);
REQUIRE(f.allocator.getStackPtrOffset() == allocSize);
allocSize += sizeof(CallExprAST);
std::vector<ExprAST *> args;
auto *callptr = f.allocCallexprAST(std::string("func"), args);
REQUIRE(callptr != nullptr);
REQUIRE(callptr->callee == "func");
REQUIRE(f.allocator.slabs.size() == 1);
REQUIRE(f.allocator.getStackPtrOffset() == allocSize);
allocSize += sizeof(PrototypeAST);
std::vector<Argument> protoarg;
auto *protoptr = f.allocPrototypeAST(Token::tok_int, std::string("proto"),
protoarg, false);
REQUIRE(protoptr != nullptr);
REQUIRE(protoptr->name == "proto");
REQUIRE(protoptr->datatype == Token::tok_int);
REQUIRE(f.allocator.slabs.size() == 1);
REQUIRE(f.allocator.getStackPtrOffset() == allocSize);
allocSize += sizeof(FunctionAST);
std::vector<ExprAST*> funcbody;
auto *funcptr= f.allocFunctionAST(protoptr,funcbody);
REQUIRE(funcptr != nullptr);
REQUIRE(f.allocator.slabs.size() == 1);
REQUIRE(f.allocator.getStackPtrOffset() == allocSize);
}
| [
"[email protected]"
] | |
6019628d764fd5682d9e438b4e8cbea72d673d91 | df2c0b88f25c244a4cca6ea9939673ed951021d4 | /18-1/AI/puzzle.cpp | fc0b17aa98edc2ea4f30bdef83d00c67a680a691 | [] | no_license | gtslljzs/SKKU | 4d0586da2455bdc54a4c431933e28446e76bfd8a | dd624f5bb15c9b0d6fc8dce4c460f7310b7802fa | refs/heads/master | 2020-06-13T07:36:29.298158 | 2019-07-01T02:43:18 | 2019-07-01T02:43:18 | 194,574,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,621 | cpp | #include <iostream>
#include <queue>
#include <vector>
#include <cmath>
using namespace std;
class Tree {
public:
struct Node {
Node* parent;
Node* child1;
Node* child2;
Node* child3;
Node* child4;
int* state;
int cost, coste, heuri;
int blank;
int lev;
};
struct cmp : public binary_function< Node*, Node*, bool > {
bool operator() ( const Node* a, const Node* b ) const {
return a->cost > b->cost;
}
};
priority_queue< Node*, vector< Node* >, cmp > pq;
vector< int > start;
Node* root;
bool goal;
int visit;
int open;
public:
Tree() {
root = NULL;
visit = 0;
open = -0;
}
bool isEmpty() const {
return root == NULL;
}
void init( char** );
void setRoot( vector< int > );
void mdHeuri( Node* );
void oopHeuri( Node* );
bool movPuzzle( Node*, Node*, char );
bool isGoal( Node* );
void searchTree();
void build( char** );
};
void Tree::init( char** file ) {
int tmp;
goal = false;
FILE* fp = fopen( file[1], "r" );
while ( fscanf( fp, "%d", &tmp ) != EOF )
start.push_back( tmp );
fclose( fp );
}
void Tree::mdHeuri( Node* puzzle ) {
int h;
int tmp;
puzzle-> heuri = 0;
for ( int i = 0; i < 9; i++ ) {
tmp = puzzle->state[i] - 1;
h = abs( ( tmp % 3 ) - ( i % 3 ) ) + abs( ( tmp / 3 ) - ( i / 3 ) );
puzzle->heuri += h;
}
}
void Tree::oopHeuri( Node* puzzle ) {
puzzle->heuri = 0;
for ( int i = 0; i < 9; i++ )
if ( puzzle->state[i] != i + 1 )
puzzle->heuri++;
}
void Tree::setRoot( vector< int > start ) {
Node* tmp = new Node;
tmp->state = new int[9];
for ( int i = 0; i < 9; i++ )
tmp->state[i] = start[i];
tmp->parent = NULL;
tmp->child1 = NULL;
tmp->child2 = NULL;
tmp->child3 = NULL;
tmp->child4 = NULL;
tmp->lev = 0;
tmp->coste = 0;
//mdHeuri( tmp );
oopHeuri( tmp );
tmp->cost = tmp->coste + tmp->heuri;
for ( int i = 0; i < 9; i++ ) {
if ( tmp->state[i] == 9 )
tmp->blank = i;
}
if ( isEmpty() ) {
root = tmp;
pq.push( root );
open++;
}
}
bool Tree::movPuzzle( Node* cur, Node* next, char dir ) {
int tmp;
int bPos = cur->blank;
next->state = new int[9];
for ( int i = 0; i < 9; i++ )
next->state[i] = cur->state[i];
switch ( dir ) {
case 'u':
next->blank = bPos - 3;
if ( cur->parent != NULL )
if ( next->blank == cur->parent->blank )
return false;
tmp = next->state[bPos];
next->state[bPos] = next->state[bPos - 3];
next->state[bPos -3] = tmp;
cur->child1 = next;
break;
case 'd':
next->blank = bPos + 3;
if ( cur->parent != NULL )
if ( next->blank == cur->parent->blank )
return false;
tmp = next->state[bPos];
next->state[bPos] = next->state[bPos + 3];
next->state[bPos + 3] = tmp;
cur->child2 = next;
break;
case 'l':
next->blank = bPos - 1;
if ( cur->parent != NULL )
if ( next->blank == cur->parent->blank )
return false;
tmp = next->state[bPos];
next->state[bPos] = next->state[bPos - 1];
next->state[bPos - 1] = tmp;
cur->child3 = next;
break;
case 'r':
next->blank = bPos + 1;
if ( cur->parent != NULL )
if ( next->blank == cur->parent->blank )
return false;
tmp = next->state[bPos];
next->state[bPos] = next->state[bPos + 1];
next->state[bPos + 1] = tmp;
cur->child4 = next;
break;
}
return true;
}
bool Tree::isGoal( Node* cur ) {
for ( int i = 0; i < 9; i++ )
if ( cur->state[i] != i + 1 )
return false;
for ( int i = 0; i < 9; i++ )
printf( "%d ", cur->state[i] );
cout << endl;
cout << "visit: " << visit << endl;
cout << "open: " << open << endl;
cout << "len: " << cur->lev << endl;
goal = true;
return true;
}
void Tree::searchTree() {
Node* cur = pq.top();
pq.pop();
visit++;
if ( isGoal( cur ) )
return;
Node* c1 = new Node;
Node* c2 = new Node;
Node* c3 = new Node;
Node* c4 = new Node;
if ( cur->blank / 3 != 0 && movPuzzle( cur, c1, 'u' ) ) {
c1->lev = cur->lev + 1;
c1->coste = cur->coste + 1;
//mdHeuri( c1 );
oopHeuri( c1 );
c1->cost = c1->coste + c1->heuri;
c1->parent = cur;
c1->child1 = NULL;
c1->child2 = NULL;
c1->child3 = NULL;
c1->child4 = NULL;
pq.push( c1 );
open++;
}
if ( cur->blank / 3 != 2 && movPuzzle( cur, c2, 'd' ) ) {
c2->lev = cur->lev + 1;
c2->coste = cur->coste + 1;
//mdHeuri( c2 );
oopHeuri( c2 );
c2->cost = c2->coste + c2->heuri;
c2->parent = cur;
c2->child1 = NULL;
c2->child2 = NULL;
c2->child3 = NULL;
c2->child4 = NULL;
pq.push( c2 );
open++;
}
if ( cur->blank % 3 != 0 && movPuzzle( cur, c3, 'l' ) ) {
c3->lev = cur->lev + 1;
c3->coste = cur->coste + 1;
//mdHeuri( c3 );
oopHeuri( c3 );
c3->cost = c3->coste + c3->heuri;
c3->parent = cur;
c3->child1 = NULL;
c3->child2 = NULL;
c3->child3 = NULL;
c3->child4 = NULL;
pq.push( c3 );
open++;
}
if ( cur->blank % 3 != 2 && movPuzzle( cur, c4, 'r' ) ) {
c4->lev = cur->lev + 1;
c4->coste = cur->coste + 1;
//mdHeuri( c4 );
oopHeuri( c4 );
c4->cost = c4->coste + c4->heuri;
c4->parent = cur;
c4->child1 = NULL;
c4->child2 = NULL;
c4->child3 = NULL;
c4->child4 = NULL;
pq.push( c4 );
open++;
}
}
void Tree::build( char** file ) {
init( file );
setRoot( start );
while ( !goal )
searchTree();
}
int main( int argc, char** argv ) {
Tree T;
T.build( argv );
return 0;
}
| [
"[email protected]"
] | |
2fe1889b1b074861ee612849da0446e311162f0d | b4dc3314ebc2e8d3ba67fd777802960b4aedd84c | /brix-tools/iab/mfc/LucidApplicationBuilder/colourKey.h | 042ef0ee6ef45b81005558376a8c07af976b47b9 | [] | no_license | kamilWLca/brix | 4c3f504f647a74ba7f51b5ae083bca82f70b9340 | c3f2ad913a383bbb34ee64c0bf54980562661e2f | refs/heads/master | 2021-01-18T04:08:56.435574 | 2012-09-18T16:36:32 | 2012-09-18T16:36:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,200 | h | #if !defined(AFX_COLOURKEY_H__9010B458_1EB1_4E0B_8867_A1983D99483C__INCLUDED_)
#define AFX_COLOURKEY_H__9010B458_1EB1_4E0B_8867_A1983D99483C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// colourKey.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// ColourKey dialog
class ColourKey : public CDialog
{
// Construction
public:
ColourKey(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(ColourKey)
enum { IDD = IDD_COLOUR_KEY };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(ColourKey)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(ColourKey)
// NOTE: the ClassWizard will add member functions here
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_COLOURKEY_H__9010B458_1EB1_4E0B_8867_A1983D99483C__INCLUDED_)
| [
"kamil@kamil-PC.(none)"
] | kamil@kamil-PC.(none) |
2cc31cd4ea1a8a828a557e277829049c815746b9 | 20debb326ca307d921626285308393d3235ec554 | /src/Renderer/Model.cpp | 6e84be0a43ec018fc5efb2339383f779ef61c1fd | [] | no_license | laninivan/3dModelMaker | d52c6fdca27a81883af9e7794cec55a515efa117 | a3b347929597e15c47ca2bcdc1fc6238f60e8eb2 | refs/heads/master | 2023-08-29T13:30:42.466413 | 2021-10-04T08:59:36 | 2021-10-04T08:59:36 | 403,178,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,513 | cpp | #include <string>
#include "ShaderProgram.cpp"
#include "../Object/LightSource.cpp"
#include "../Camera/camera.h"
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Mesh.cpp"
#include "../AlgGeometric/AlgGeometric.h"
#ifndef MODEL
#define MODEL
class Model
{
public:
Model() {};
Model(std::vector<Mesh> meshes, glm::vec3 colorFace, glm::vec3 colorEdge, glm::vec3 location, glm::vec3 scale, float rotAngleX, float rotAngleY, float rotAngleZ, GLenum renderingMode)
{
this->meshes = std::vector(meshes);
this->location = location;
this->scale = scale;
this->rotAngleX = rotAngleX;
this->rotAngleY = rotAngleY;
this->rotAngleZ = rotAngleZ;
this->renderingMode = renderingMode;
this->colorFaces = colorFace;
this->colorEdges = colorEdge;
}
void drawFaces(Shader& shader, LightSourse lightSourse,Camera camera, const unsigned int SCR_WIDTH, const unsigned int SCR_HEIGHT)
{
glm::mat4 modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, location);
modelMatrix = glm::scale(modelMatrix, scale);
modelMatrix = glm::rotate(modelMatrix, rotAngleX, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleY, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleZ, glm::vec3(0.0f, 0.0f, 1.0f));
for (int i = 0; i < meshes.size(); i++)
{
meshes[i].draw(shader, colorFaces, lightSourse, camera, SCR_WIDTH, SCR_HEIGHT, modelMatrix,renderingMode);
}
}
void drawEdges(Shader& shader, LightSourse lightSourse, Camera camera, const unsigned int SCR_WIDTH, const unsigned int SCR_HEIGHT)
{
glm::mat4 modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, location);
modelMatrix = glm::scale(modelMatrix, scale);
modelMatrix = glm::rotate(modelMatrix, rotAngleX, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleY, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleZ, glm::vec3(0.0f, 0.0f, 1.0f));
for (int i = 0; i < meshes.size(); i++)
{
meshes[i].draw(shader, colorEdges, lightSourse, camera, SCR_WIDTH, SCR_HEIGHT, modelMatrix, GL_LINE_LOOP);
}
}
void drawAll(Shader& shader, Shader& shaderEdges, LightSourse lightSourse, Camera camera, const unsigned int SCR_WIDTH, const unsigned int SCR_HEIGHT)
{
drawFaces(shader, lightSourse,camera, SCR_WIDTH,SCR_HEIGHT);
drawEdges(shaderEdges, lightSourse,camera, SCR_WIDTH,SCR_HEIGHT);
}
void drawOneMesh(Shader& shader, Shader& shaderEdges, LightSourse lightSourse, Camera camera, const unsigned int SCR_WIDTH, const unsigned int SCR_HEIGHT, int indexSelectmesh)
{
glm::mat4 modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, location);
modelMatrix = glm::scale(modelMatrix, scale);
modelMatrix = glm::rotate(modelMatrix, rotAngleX, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleY, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleZ, glm::vec3(0.0f, 0.0f, 1.0f));
meshes[indexSelectmesh].draw(shader, colorFaces, lightSourse, camera, SCR_WIDTH, SCR_HEIGHT, modelMatrix, renderingMode);
meshes[indexSelectmesh].draw(shaderEdges, colorEdges, lightSourse, camera, SCR_WIDTH, SCR_HEIGHT, modelMatrix, GL_LINE_LOOP);
}
void drawOneFace(Shader& shader, Shader& shaderEdges, LightSourse lightSourse, Camera camera, const unsigned int SCR_WIDTH, const unsigned int SCR_HEIGHT, int indexSelectmesh, int indexSelectFace)
{
glm::mat4 modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, location);
modelMatrix = glm::scale(modelMatrix, scale);
modelMatrix = glm::rotate(modelMatrix, rotAngleX, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleY, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleZ, glm::vec3(0.0f, 0.0f, 1.0f));
meshes[indexSelectmesh].drawOneFace(shader, colorFaces, lightSourse, camera, SCR_WIDTH, SCR_HEIGHT, modelMatrix, renderingMode, indexSelectFace);
meshes[indexSelectmesh].drawOneFace(shaderEdges, colorEdges, lightSourse, camera, SCR_WIDTH, SCR_HEIGHT, modelMatrix, GL_LINE_LOOP, indexSelectFace);
}
void drawOneVertex(Shader& shader, Shader& shaderEdges, LightSourse lightSourse, Camera camera, const unsigned int SCR_WIDTH, const unsigned int SCR_HEIGHT, const unsigned int indexSelectMesh, int indexSelectFace, int indexSelectVertex)
{
glm::mat4 modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, location);
modelMatrix = glm::scale(modelMatrix, scale);
modelMatrix = glm::rotate(modelMatrix, rotAngleX, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleY, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleZ, glm::vec3(0.0f, 0.0f, 1.0f));
meshes[indexSelectMesh].drawOneVertex(shader, colorEdges, lightSourse, camera, SCR_WIDTH, SCR_HEIGHT, modelMatrix, indexSelectFace, indexSelectVertex);
}
void drawSelectMode(glm::vec3 color, Shader& shader, LightSourse lightSourse, Camera camera, const unsigned int SCR_WIDTH, const unsigned int SCR_HEIGHT)
{
glm::mat4 modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, location);
modelMatrix = glm::scale(modelMatrix, scale);
modelMatrix = glm::rotate(modelMatrix, rotAngleX, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleY, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleZ, glm::vec3(0.0f, 0.0f, 1.0f));
for (int i = 0; i < meshes.size(); i++)
{
color.y=0.01f * (i + 1);//y x
meshes[i].draw(shader, color, lightSourse, camera, SCR_WIDTH, SCR_HEIGHT, modelMatrix, renderingMode);
}
}
void setPos(glm::vec3 vecPos)
{
this->location = glm::vec3(vecPos.x, vecPos.y, vecPos.z );
}
void setScale(glm::vec3 vecScale)
{
this->scale= glm::vec3(vecScale.x, vecScale.y, vecScale.z);
}
void setRotation(float rotAngleX, float rotAngleY, float rotAngleZ )
{
this->rotAngleX = rotAngleX;
this->rotAngleY = rotAngleY;
this->rotAngleZ = rotAngleZ;
}
void setTranslateGeneralVertex(int indexMesh, int indexFace, int indexVertex, glm::vec3 transVec)
{
glm::vec3 beginPoint = meshes[indexMesh].getVertexInFaceByIndex(indexFace, indexVertex);
meshes[indexMesh].setTranslateGeneralVertex( indexFace, indexVertex, beginPoint+transVec);
}
void rotate(float rotAngleX, float rotAngleY, float rotAngleZ)
{
this->rotAngleX += rotAngleX;
this->rotAngleY += rotAngleY;
this->rotAngleZ += rotAngleZ;
}
void rotateMesh(int indexCurMesh, glm::vec3 rotVector)
{
glm::vec3 oldAngleVector(meshes[indexCurMesh].getRotAngleX(), meshes[indexCurMesh].getRotAngleY(), meshes[indexCurMesh].getRotAngleZ());
meshes[indexCurMesh].setRotangle(oldAngleVector+rotVector);
}
void translateMesh(int indexCurMesh, glm::vec3 vector)
{
meshes[indexCurMesh].setTranslate(meshes[indexCurMesh].getTranslate() + vector);
}
void scaleAddMesh(int indexCurMesh, glm::vec3 scale)
{
meshes[indexCurMesh].setScale(meshes[indexCurMesh].getScale() + scale);
}
void scaleAdd(glm::vec3 scale)
{
this->scale += scale;
}
void setColorsFaces(glm::vec3 color)
{
this->colorFaces= glm::vec3(color.x, color.y, color.z);
}
void setColorsEges(glm::vec3 color)
{
this->colorEdges= glm::vec3(color.x, color.y, color.z);
}
glm::vec3 getColorsFaces()
{
return this->colorFaces;
}
glm::vec3 getColorsEges()
{
return this->colorEdges;
}
glm::vec3 getPos()
{
return this->location;
}
void addMesh(Mesh newMesh)
{
meshes.push_back(newMesh);
}
void deleteMesh(int index)
{
meshes.erase(meshes.begin() + index);
}
void deleteFace(int indexMesh, int indexFaces)
{
meshes[indexMesh].deleteFace(indexFaces);
}
void deleteBufers()
{
for (int i = 0; i < meshes.size(); i++)
meshes[i].deleteBufer();
}
int getIndexSelectedFace(int indexMesh, Camera *camera)
{
glm::mat4 modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, location);
modelMatrix = glm::scale(modelMatrix, scale);
modelMatrix = glm::rotate(modelMatrix, rotAngleX, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleY, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotAngleZ, glm::vec3(0.0f, 0.0f, 1.0f));
glm::vec3 result;
int tempIndexFace = -1;
for (int i = 0; i < meshes[indexMesh].indFaces.size(); i++)
{
result=AlgGeometric::getPointFaceAndVector(meshes[indexMesh], i, &(*camera), modelMatrix);
if (result != glm::vec3(10000, 10000, 10000))
{
tempIndexFace = i;
break;
}
}
std::cout << "index Face:" << tempIndexFace << std::endl;
return tempIndexFace;
}
int getVertCountInFace(int indexMesh, int indexFace)
{
return meshes[indexMesh].getVertCountInFace(indexFace);
}
int getFacesCount(int indexMesh)
{
return meshes[indexMesh].getFacesCount();
}
int getCountMeshes()
{
return meshes.size();
}
void addInterVInFace(int indexMesh, int indexFace)
{
meshes[indexMesh].addInterVInFace(indexFace);
}
void trianglateFace(int indexCurMesh, int indexCurFace)
{
meshes[indexCurMesh].trianglateFace(indexCurFace);
}
private:
std::vector<Mesh> meshes;
glm::vec3 location;
glm::vec3 scale;
glm::vec3 colorFaces;
glm::vec3 colorEdges;
float rotAngleX;
float rotAngleY;
float rotAngleZ;
GLenum renderingMode;
};
#endif | [
"[email protected]"
] | |
3c1b757220ccd37732018fdcaea642ef10e1bba9 | af9f3ec2c6325092b77637ebd0a327e5b520b0f7 | /iOS/IncidentPlatform/IncidentPlatform/DSS/SmartBuffer.cpp | 56380361a16e06e016454674a5b495b007964ec5 | [] | no_license | IncidentTechnologies/IncidentPlatform | eb270d9ff0018ea19fbe04c9595ebdce8974341f | da3d96c7a7ef35791f3f2fc55805f43875f41fe0 | refs/heads/master | 2021-06-11T06:29:34.117387 | 2017-03-06T03:20:31 | 2017-03-06T03:20:31 | 17,033,548 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,349 | cpp | #include "SmartBuffer.h"
#include <string>
using namespace dss;
SmartBuffer::SmartBuffer( const char *pBuffer, int pBuffer_n) :
m_pBuffer(NULL),
m_pBuffer_n(0),
m_pBuffer_bn(0)
{
if(pBuffer == NULL)
ResetBuffer();
else if(pBuffer_n == 0)
ResetBuffer(pBuffer);
else
ResetBuffer(pBuffer, pBuffer_n);
}
SmartBuffer::SmartBuffer(SmartBuffer *psb) :
m_pBuffer(NULL),
m_pBuffer_n(0),
m_pBuffer_bn(0)
{
ResetBuffer(psb->GetBuffer(), psb->GetBufferLength());
}
SmartBuffer::~SmartBuffer() {
if(m_pBuffer != NULL) {
delete [] m_pBuffer;
m_pBuffer = NULL;
}
m_pBuffer_n = 0;
m_pBuffer_bn = 0;
}
RESULT SmartBuffer::IncrementBufferSize() {
RESULT r = R_SUCCESS;
char *SaveBuffer = NULL;
CPRM(m_pBuffer, "SmartBuffer is not initialized!\n");
CBRM((m_pBuffer_n > 0), "SmartBuffer size is 0!\n");
SaveBuffer = new char[m_pBuffer_n];
CNRM(SaveBuffer, "SmartBuffer: Failed to allocate memory for save pBuffer");
memcpy(SaveBuffer, m_pBuffer, m_pBuffer_n);
delete [] m_pBuffer;
m_pBuffer = NULL;
m_pBuffer_bn++;
m_pBuffer = new char[SMART_BUFFER_BLOCK_SIZE * (m_pBuffer_bn + 1)];
CNRM(m_pBuffer, "SmartBuffer: Failed to allocate memory for new pBuffer");
memset(m_pBuffer, 0, SMART_BUFFER_BLOCK_SIZE * (m_pBuffer_bn + 1));
memcpy(m_pBuffer, SaveBuffer, m_pBuffer_n);
delete [] SaveBuffer;
SaveBuffer = NULL;
Error:
return r;
}
RESULT SmartBuffer::ResetBuffer( const char *pszBuffer ) {
return ResetBuffer(pszBuffer, strlen(pszBuffer));
}
RESULT SmartBuffer::ResetBuffer( const char *pBuffer, int pBuffer_n ) {
RESULT r = R_SUCCESS;
CRM(ResetBuffer(), "ResetBuffer: Failed to reset pBuffer");
for(int i = 0; i < pBuffer_n; i++)
CRM(Append(pBuffer[i]), "ResetBuffer: Failed to append %c", pBuffer[i]);
Error:
return r;
}
RESULT SmartBuffer::ResetBuffer() {
RESULT r = R_SUCCESS;
m_pBuffer_n = 0;
m_pBuffer_bn = 0;
if(m_pBuffer != NULL)
delete [] m_pBuffer;
m_pBuffer = new char[(m_pBuffer_bn + 1)*SMART_BUFFER_BLOCK_SIZE];
memset(m_pBuffer, 0, (m_pBuffer_bn + 1)*SMART_BUFFER_BLOCK_SIZE);
Error:
return r;
}
RESULT SmartBuffer::Reset() {
return ResetBuffer();
}
RESULT SmartBuffer::reset() {
return ResetBuffer();
}
char * SmartBuffer::CreateBufferCopy() {
char *temp = new char[m_pBuffer_n + 1];
memset(temp, 0, m_pBuffer_n + 1);
memcpy(temp, m_pBuffer, m_pBuffer_n);
return temp;
}
bool SmartBuffer::NotAllWhitespace() {
for(int i = 0; i < m_pBuffer_n; i++) {
if(m_pBuffer[i] != ' ' &&
m_pBuffer[i] != '\t') {
return true;
}
}
return false;
}
RESULT SmartBuffer::Append( char byte ) {
RESULT r = R_SUCCESS;
if(m_pBuffer == NULL) {
m_pBuffer_bn = 0;
m_pBuffer_n = 0;
m_pBuffer = new char[(m_pBuffer_bn + 1)*SMART_BUFFER_BLOCK_SIZE];
memset(m_pBuffer, 0, (m_pBuffer_bn + 1)*SMART_BUFFER_BLOCK_SIZE);
}
*(m_pBuffer + m_pBuffer_n) = byte;
m_pBuffer_n++;
if(m_pBuffer_n >= (m_pBuffer_bn + 1) * SMART_BUFFER_BLOCK_SIZE)
CRM(IncrementBufferSize(), "SmartBuffer: Failed to increment the pBuffer size!");
Error:
return r;
}
RESULT SmartBuffer::Append( SmartBuffer sb ) {
RESULT r = R_SUCCESS;
char *TempBuffer = sb.GetBuffer();
for(int i = 0; i < sb.GetBufferLength(); i++)
CRM(Append(TempBuffer[i]), "SmartBuffer: Failed to append: %c", TempBuffer[i]);
Error:
return r;
}
char* SmartBuffer::GetBuffer() {
return m_pBuffer;
}
int SmartBuffer::GetBufferLength() {
return m_pBuffer_n;
}
int SmartBuffer::Length() {
return m_pBuffer_n;
}
int SmartBuffer::length() {
return m_pBuffer_n;
}
int SmartBuffer::GetBufferBlockCount() {
return m_pBuffer_bn;
}
SmartBuffer & SmartBuffer::operator=( const SmartBuffer &rhs ) {
if(this != &rhs) {
delete [] this->m_pBuffer;
this->m_pBuffer_n = rhs.m_pBuffer_n;
this->m_pBuffer_bn = rhs.m_pBuffer_bn;
this->m_pBuffer = new char[(this->m_pBuffer_bn + 1) * SMART_BUFFER_BLOCK_SIZE];
memset(this->m_pBuffer, 0, (this->m_pBuffer_bn + 1) * SMART_BUFFER_BLOCK_SIZE);
memcpy(this->m_pBuffer, rhs.m_pBuffer, this->m_pBuffer_n);
}
return *this;
}
SmartBuffer & SmartBuffer::operator+=( char byte ) {
this->Append(byte);
return *this;
}
SmartBuffer & SmartBuffer::operator+=( const SmartBuffer &rhs ) {
this->Append(rhs);
return *this;
}
SmartBuffer& SmartBuffer::operator+=(const char *psz) {
for(int i = 0; psz[i] != 0; i++)
this->Append(psz[i]);
return *this;
}
const SmartBuffer SmartBuffer::operator+( const char byte ) {
SmartBuffer *result = new SmartBuffer(this->m_pBuffer, this->m_pBuffer_n);
result->Append(byte);
return *result;
}
const SmartBuffer SmartBuffer::operator+(const char *psz) {
SmartBuffer *result = new SmartBuffer(this->m_pBuffer, this->m_pBuffer_n);
for(int i = 0; psz[i] != 0; i++)
result->Append(psz[i]);
return *result;
}
SmartBuffer & SmartBuffer::operator--(int) {
char *TempLastChar = this->m_pBuffer + m_pBuffer_n - 1;
this->RemoveCharacter(TempLastChar);
return *this;
}
const SmartBuffer SmartBuffer::operator-( const int n ) {
SmartBuffer *result = new SmartBuffer(this);
for(int i = 0; i < n; i++)
(*result)--;
return *result;
}
SmartBuffer & SmartBuffer::operator-=( int n ) {
for(int i = 0; i < n; i++)
(*this)--;
return *this;
}
const SmartBuffer SmartBuffer::operator-( const char byte ) {
SmartBuffer *result = new SmartBuffer(this);
char *pTempChar;
if(result->Find(byte, pTempChar) == R_SUCCESS)
result->RemoveCharacter(pTempChar);
return result;
}
const SmartBuffer SmartBuffer::operator %( const char byte ) {
SmartBuffer *result = new SmartBuffer(this);
char *pTempChar;
while(result->Find(byte, pTempChar) == R_SUCCESS)
result->RemoveCharacter(pTempChar);
return result;
}
SmartBuffer &SmartBuffer::operator %=(const char byte) {
char *pTempChar;
while(this->Find(byte, pTempChar) == R_SUCCESS)
this->RemoveCharacter(pTempChar);
return *this;
}
SmartBuffer &SmartBuffer::operator-=(const char byte) {
char *pTempChar;
if(this->Find(byte, pTempChar) == R_SUCCESS)
this->RemoveCharacter(pTempChar);
return *this;
}
const SmartBuffer SmartBuffer::operator+( const SmartBuffer &rhs ) {
SmartBuffer *result = new SmartBuffer(this->m_pBuffer, this->m_pBuffer_n);
result->Append(rhs);
return *result;
}
RESULT SmartBuffer::RemoveCharacter( char *pChar ) {
RESULT r = R_SUCCESS;
if((pChar < m_pBuffer) || (pChar > m_pBuffer + ((m_pBuffer_bn + 1) * SMART_BUFFER_BLOCK_SIZE)))
CBRM(0, "RemoveCharacter: Char pointer out of the bounds of the SmartBuffer Buffer");
// Two cases, either char is last character (then it's easy!) or not
if(pChar == m_pBuffer + m_pBuffer_n) {
m_pBuffer[m_pBuffer_n] = '\0';
m_pBuffer_n--;
}
else {
char *TempBuffer = new char[strlen(pChar + 1)];
strcpy(TempBuffer, pChar + 1);
memset(pChar, 0, m_pBuffer_n - (pChar - m_pBuffer));
strcat(m_pBuffer, TempBuffer);
m_pBuffer_n--;
}
Error:
return r;
}
// Finds the first instance of byte and returns a pointer to it
RESULT SmartBuffer::Find( const char byte, char *&r_pChar) {
RESULT r = R_SUCCESS;
r_pChar = m_pBuffer;
while((*r_pChar) != '\0' && (*r_pChar) != byte)
r_pChar++;
if((*r_pChar) == byte)
r = R_SUCCESS;
else
r = R_SB_CHAR_NOT_FOUND;
Error:
return r;
}
RESULT SmartBuffer::SaveToFile(char *pszFilename, bool fOverwrite = false) {
RESULT r = R_SUCCESS;
// First check to see file does not exist already
FILE *pFile = fopen(pszFilename, "r");
if(pFile == NULL || fOverwrite) {
if(pFile != NULL)
fclose(pFile);
pFile = fopen(pszFilename, "w");
fputs(m_pBuffer, pFile);
fclose(pFile);
}
else {
fclose(pFile);
CBRM(0, "File %s already exists!", pszFilename);
}
Error:
return r;
} | [
"[email protected]"
] | |
24a0b75bba9379f9da08e68f2bcf97649751edf2 | a3cecf2e1144bec5efca18582f5420c24835b687 | /20181206Motor_BT/20181206Motor_BT.ino | f56ecd0751000aa18d2083ee67963fcffb8943c3 | [] | no_license | vincenttang1227/Arduino | cbde08d5104889c0d8b7db5843f6312f5df29baf | 07d0af0b8680d8f2412bbf1b9336019f53415247 | refs/heads/master | 2020-04-02T16:04:23.953434 | 2019-09-12T10:02:53 | 2019-09-12T10:02:53 | 154,596,796 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,522 | ino | #include <SoftwareSerial.h>
#include <Servo.h>
Servo S1;
SoftwareSerial bt(7, 8);
int servoPin = 2;
int RmotorGo = 3;
int RmotorBk = 5;
int LmotorGo = 6;
int LmotorBk = 11;
int rSpeed = 150;
int lSpeed = 160;
int trig = 9;
int echo = 10;
int ledState = 0;
int carState = 0;
void setup() {
pinMode(RmotorGo, OUTPUT);
pinMode(RmotorBk, OUTPUT);
pinMode(LmotorGo, OUTPUT);
pinMode(LmotorBk, OUTPUT);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
S1.attach(servoPin);
bt.begin(38400);
Serial.begin(38400);
while (!Serial)
{
;
}
Serial.println("BT Starting~~");
S1.write(90);
for (int i = 90; i >= 0; i--)
{
S1.write(i);
delay(10);
}
for (int i = 0; i <= 180; i++)
{
S1.write(i);
delay(10);
}
for (int i = 180; i >= 90; i--)
{
S1.write(i);
delay(10);
}
}
void cGo()
{
digitalWrite(RmotorGo, HIGH);
analogWrite(RmotorGo, rSpeed);
analogWrite(RmotorBk, 0);
digitalWrite(LmotorGo, HIGH);
analogWrite(LmotorGo, lSpeed);
analogWrite(LmotorBk, 0);
delay(100);
}
void cBack()
{
digitalWrite(RmotorBk, HIGH);
analogWrite(RmotorBk, rSpeed);
analogWrite(RmotorGo, 0);
digitalWrite(LmotorBk, HIGH);
analogWrite(LmotorBk, lSpeed);
analogWrite(LmotorGo, 0);
delay(100);
}
void cStop()
{
analogWrite(RmotorGo, 0);
analogWrite(RmotorBk, 0);
analogWrite(LmotorGo, 0);
analogWrite(LmotorBk, 0);
delay(100);
}
void turnL()
{
digitalWrite(RmotorGo, HIGH);
analogWrite(RmotorGo, rSpeed);
analogWrite(RmotorBk, 0);
digitalWrite(LmotorGo, LOW);
analogWrite(LmotorGo, 0);
analogWrite(LmotorBk, 0);
delay(100);
}
void turnR()
{
digitalWrite(RmotorGo, LOW);
analogWrite(RmotorGo, 0);
analogWrite(RmotorBk, 0);
digitalWrite(LmotorGo, HIGH);
analogWrite(LmotorGo, lSpeed);
analogWrite(LmotorBk, 0);
delay(100);
}
void spinL()
{
digitalWrite(RmotorGo, HIGH);
digitalWrite(RmotorBk, LOW);
analogWrite(RmotorGo, rSpeed);
analogWrite(RmotorBk, 0);
digitalWrite(LmotorBk, HIGH);
digitalWrite(LmotorGo, LOW);
analogWrite(LmotorBk, lSpeed);
analogWrite(LmotorGo, 0);
delay(100);
}
void spinR()
{
digitalWrite(LmotorGo, HIGH);
digitalWrite(LmotorBk, LOW);
analogWrite(LmotorGo, lSpeed);
analogWrite(LmotorBk, 0);
digitalWrite(RmotorBk, HIGH);
digitalWrite(RmotorGo, LOW);
analogWrite(RmotorBk, rSpeed);
analogWrite(RmotorGo, 0);
delay(100);
}
float dist()
{
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
return pulseIn(echo, HIGH) / 58.2;
}
void servoTurn(int angle)
{
int nowAngle = S1.read();
if (nowAngle > angle)
{
for (int i = nowAngle; i >= angle; i--)
{
S1.write(i);
delay(10);
}
}
else
{
for (int i = nowAngle; i <= angle; i++)
{
S1.write(i);
delay(10);
}
}
}
void check() {
analogWrite(A1, 1024);
cStop();
delay(50);
float distR;
float distL;
servoTurn(0);
distR = dist();
delay(200);
servoTurn(180);
distL = dist();
delay(200);
servoTurn(90);
// Serial.print("右邊距離:");
// Serial.print(distR);
// Serial.print(" 左邊距離:");
// Serial.println(distL);
if (distR < 20 && distL < 20)
{
cBack();
delay(200);
check();
}
else if (distR > distL)
{
spinR();
delay(200);
}
else
{
spinL();
delay(200);
}
analogWrite(A1, 0);
cStop();
delay(200);
}
void freeGo()
{
cGo();
delay(2000);
for (int i = 0; i < 5; i++)
{
cBack();
delay(200);
}
cStop();
delay(200);
for (int i = 0; i < 5; i++)
{
turnL();
delay(200);
}
cStop();
delay(200);
for (int i = 0; i < 5; i++)
{
turnR();
delay(200);
}
cStop();
delay(200);
for (int i = 0; i < 5; i++)
{
spinL();
delay(200);
}
delay(500);
for (int i = 0; i < 5; i++)
{
spinR();
delay(200);
}
delay(500);
}
void loop()
{
float nowDist = dist();
constrain(nowDist, 0, 100);
// Serial.print("現在距離:");
// Serial.println(nowDist);
//設定前進與停車變數
if (ledState == 1)
{
if (carState == 0)
cStop();
else if (carState == 1)
cGo();
else if (carState == 2)
turnL();
else if (carState == 3)
turnR();
else if (carState == 4)
cBack();
else if (carState == 5)
{
if (nowDist > 20)
cGo();
else
check();
}
else if (carState == 6)
freeGo();
}
else
{
cStop();
carState = 0;
}
if (bt.available() > 0)
{
char ch = bt.read();
int num = bt.parseInt();
Serial.print(ch);
Serial.println(num);
//藍芽控制綠燈開關
if (ch == 'C' && num == 0)
{
if (ledState == 0)
{
ledState = 1;
analogWrite(A0, 1024);
}
}
if (ch == 'C' && num == 2)
{
if (ledState == 1)
{
ledState = 0;
analogWrite(A0, 0);
}
}
//設定藍芽控制前進與停止
if (ch == 'C' && num == 1)
carState = 1;//前進
if (ch == 'C' && num == 4)
carState = 0;//停止
if (ch == 'C' && num == 3)
carState = 2;//左轉
if (ch == 'C' && num == 5)
carState = 3;//右轉
if (ch == 'C' && num == 7)
carState = 4;//後退
if (ch == 'C' && num == 6)
carState = 5;//自走避障
if (ch == 'C' && num == 8)
carState = 6;//花式自走
}
// if (ledState == 1)
// analogWrite(A0, 1024);
// else
// analogWrite(A0, 0);
}
| [
"[email protected]"
] | |
b7f253b421cfcea7582da5cc523cbeba9f204d59 | 3f1619529291bcebdaf9d2faa94d8e07b7b7efda | /operator_Vivado/testing_area/vivadoIntDiv/div3/.autopilot/db/hls_design_meta.cpp | 9ddf36f74fd91efef7342599f9c8dbd0c0a83524 | [] | no_license | Victorlzd/High_Level_Synthesis_Trainee | 6efb431b0de4f5ef84cc4e5bad90a24c4c9b434d | 01350bb65de0fae9377aa52986a3541c27e6a9c2 | refs/heads/master | 2021-09-21T22:28:22.140443 | 2018-08-31T22:08:27 | 2018-08-31T22:08:27 | 137,374,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | cpp | #include "hls_design_meta.h"
const Port_Property HLS_Design_Meta::port_props[]={
Port_Property("ap_clk", 1, hls_in, -1, "", "", 1),
Port_Property("ap_rst", 1, hls_in, -1, "", "", 1),
Port_Property("ap_start", 1, hls_in, -1, "", "", 1),
Port_Property("ap_done", 1, hls_out, -1, "", "", 1),
Port_Property("ap_idle", 1, hls_out, -1, "", "", 1),
Port_Property("ap_ready", 1, hls_out, -1, "", "", 1),
Port_Property("a", 32, hls_in, 0, "ap_none", "in_data", 1),
Port_Property("ap_return", 32, hls_out, -1, "", "", 1),
};
const char* HLS_Design_Meta::dut_name = "int_div3";
| [
"[email protected]"
] | |
2a36cc3c1add7a27f9611b02d19c3c039784e4f4 | c63492da2e599eeae7805112b4529b4c0847240c | /archive/motor.h | 76e7b825dc44983b8a2e84c5113cbcd970013ad6 | [] | no_license | ut-ras/Region-5-2017-2018 | bc087283cf81e3de48393b61b2eb6a4b47e70f4a | 6760eb42d70ccaccf288c806cf974d6b2b7f0e79 | refs/heads/master | 2021-09-11T23:38:39.290264 | 2018-04-13T04:49:21 | 2018-04-13T04:49:21 | 105,088,512 | 4 | 1 | null | 2018-02-06T01:22:13 | 2017-09-28T01:40:41 | C++ | UTF-8 | C++ | false | false | 47 | h | class motor {
public:
motor(int pin);
};
| [
"[email protected]"
] | |
2cf8a7dc6987ff873264276eb12c389990d109bf | 85c3e18522388fc6d405d3fe504b787cd97937aa | /src/ThirdParty/sfml/src/SFML/Window/Unix/InputImpl.cpp | 7e04e533b04ff6167ded7849ae13119505817942 | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | blockspacer/FrankE | 2d454f77a15f02d8ac681c68730b20d189af131f | 72faca02759b54aaec842831f3c7a051e7cf5335 | refs/heads/master | 2021-05-21T10:01:23.650983 | 2019-11-12T17:44:54 | 2019-11-12T17:44:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,387 | cpp | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2015 Laurent Gomila ([email protected])
//
// 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.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window/Unix/InputImpl.hpp>
#include <SFML/Window/Window.hpp>
#include <SFML/Window/Unix/Display.hpp>
#include <X11/Xlib-xcb.h>
#include <X11/keysym.h>
#include <cstdlib>
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
bool InputImpl::isKeyPressed(Keyboard::Key key)
{
// Get the corresponding X11 keysym
KeySym keysym = 0;
switch (key)
{
case Keyboard::A: keysym = XK_A; break;
case Keyboard::B: keysym = XK_B; break;
case Keyboard::C: keysym = XK_C; break;
case Keyboard::D: keysym = XK_D; break;
case Keyboard::E: keysym = XK_E; break;
case Keyboard::F: keysym = XK_F; break;
case Keyboard::G: keysym = XK_G; break;
case Keyboard::H: keysym = XK_H; break;
case Keyboard::I: keysym = XK_I; break;
case Keyboard::J: keysym = XK_J; break;
case Keyboard::K: keysym = XK_K; break;
case Keyboard::L: keysym = XK_L; break;
case Keyboard::M: keysym = XK_M; break;
case Keyboard::N: keysym = XK_N; break;
case Keyboard::O: keysym = XK_O; break;
case Keyboard::P: keysym = XK_P; break;
case Keyboard::Q: keysym = XK_Q; break;
case Keyboard::R: keysym = XK_R; break;
case Keyboard::S: keysym = XK_S; break;
case Keyboard::T: keysym = XK_T; break;
case Keyboard::U: keysym = XK_U; break;
case Keyboard::V: keysym = XK_V; break;
case Keyboard::W: keysym = XK_W; break;
case Keyboard::X: keysym = XK_X; break;
case Keyboard::Y: keysym = XK_Y; break;
case Keyboard::Z: keysym = XK_Z; break;
case Keyboard::Num0: keysym = XK_0; break;
case Keyboard::Num1: keysym = XK_1; break;
case Keyboard::Num2: keysym = XK_2; break;
case Keyboard::Num3: keysym = XK_3; break;
case Keyboard::Num4: keysym = XK_4; break;
case Keyboard::Num5: keysym = XK_5; break;
case Keyboard::Num6: keysym = XK_6; break;
case Keyboard::Num7: keysym = XK_7; break;
case Keyboard::Num8: keysym = XK_8; break;
case Keyboard::Num9: keysym = XK_9; break;
case Keyboard::Escape: keysym = XK_Escape; break;
case Keyboard::LControl: keysym = XK_Control_L; break;
case Keyboard::LShift: keysym = XK_Shift_L; break;
case Keyboard::LAlt: keysym = XK_Alt_L; break;
case Keyboard::LSystem: keysym = XK_Super_L; break;
case Keyboard::RControl: keysym = XK_Control_R; break;
case Keyboard::RShift: keysym = XK_Shift_R; break;
case Keyboard::RAlt: keysym = XK_Alt_R; break;
case Keyboard::RSystem: keysym = XK_Super_R; break;
case Keyboard::Menu: keysym = XK_Menu; break;
case Keyboard::LBracket: keysym = XK_bracketleft; break;
case Keyboard::RBracket: keysym = XK_bracketright; break;
case Keyboard::SemiColon: keysym = XK_semicolon; break;
case Keyboard::Comma: keysym = XK_comma; break;
case Keyboard::Period: keysym = XK_period; break;
case Keyboard::Quote: keysym = XK_dead_acute; break;
case Keyboard::Slash: keysym = XK_slash; break;
case Keyboard::BackSlash: keysym = XK_backslash; break;
case Keyboard::Tilde: keysym = XK_dead_grave; break;
case Keyboard::Equal: keysym = XK_equal; break;
case Keyboard::Dash: keysym = XK_minus; break;
case Keyboard::Space: keysym = XK_space; break;
case Keyboard::Return: keysym = XK_Return; break;
case Keyboard::BackSpace: keysym = XK_BackSpace; break;
case Keyboard::Tab: keysym = XK_Tab; break;
case Keyboard::PageUp: keysym = XK_Prior; break;
case Keyboard::PageDown: keysym = XK_Next; break;
case Keyboard::End: keysym = XK_End; break;
case Keyboard::Home: keysym = XK_Home; break;
case Keyboard::Insert: keysym = XK_Insert; break;
case Keyboard::Delete: keysym = XK_Delete; break;
case Keyboard::Add: keysym = XK_KP_Add; break;
case Keyboard::Subtract: keysym = XK_KP_Subtract; break;
case Keyboard::Multiply: keysym = XK_KP_Multiply; break;
case Keyboard::Divide: keysym = XK_KP_Divide; break;
case Keyboard::Left: keysym = XK_Left; break;
case Keyboard::Right: keysym = XK_Right; break;
case Keyboard::Up: keysym = XK_Up; break;
case Keyboard::Down: keysym = XK_Down; break;
case Keyboard::Numpad0: keysym = XK_KP_0; break;
case Keyboard::Numpad1: keysym = XK_KP_1; break;
case Keyboard::Numpad2: keysym = XK_KP_2; break;
case Keyboard::Numpad3: keysym = XK_KP_3; break;
case Keyboard::Numpad4: keysym = XK_KP_4; break;
case Keyboard::Numpad5: keysym = XK_KP_5; break;
case Keyboard::Numpad6: keysym = XK_KP_6; break;
case Keyboard::Numpad7: keysym = XK_KP_7; break;
case Keyboard::Numpad8: keysym = XK_KP_8; break;
case Keyboard::Numpad9: keysym = XK_KP_9; break;
case Keyboard::F1: keysym = XK_F1; break;
case Keyboard::F2: keysym = XK_F2; break;
case Keyboard::F3: keysym = XK_F3; break;
case Keyboard::F4: keysym = XK_F4; break;
case Keyboard::F5: keysym = XK_F5; break;
case Keyboard::F6: keysym = XK_F6; break;
case Keyboard::F7: keysym = XK_F7; break;
case Keyboard::F8: keysym = XK_F8; break;
case Keyboard::F9: keysym = XK_F9; break;
case Keyboard::F10: keysym = XK_F10; break;
case Keyboard::F11: keysym = XK_F11; break;
case Keyboard::F12: keysym = XK_F12; break;
case Keyboard::F13: keysym = XK_F13; break;
case Keyboard::F14: keysym = XK_F14; break;
case Keyboard::F15: keysym = XK_F15; break;
case Keyboard::Pause: keysym = XK_Pause; break;
default: keysym = 0; break;
}
// Open a connection with the X server
Display* display = OpenDisplay();
xcb_connection_t* connection = XGetXCBConnection(display);
// Convert to keycode
KeyCode keycode = XKeysymToKeycode(display, keysym);
if (keycode != 0)
{
// Get the whole keyboard state
xcb_query_keymap_reply_t* keymap = xcb_query_keymap_reply(connection, xcb_query_keymap(connection), NULL);
// Close the connection with the X server
CloseDisplay(display);
// Check our keycode
bool isPressed = (keymap->keys[keycode / 8] & (1 << (keycode % 8))) != 0;
free(keymap);
return isPressed;
}
else
{
// Close the connection with the X server
CloseDisplay(display);
return false;
}
}
////////////////////////////////////////////////////////////
void InputImpl::setVirtualKeyboardVisible(bool /*visible*/)
{
// Not applicable
}
////////////////////////////////////////////////////////////
bool InputImpl::isMouseButtonPressed(Mouse::Button button)
{
// Open a connection with the X server
Display* display = OpenDisplay();
xcb_connection_t* connection = XGetXCBConnection(display);
// Get pointer mask
xcb_query_pointer_reply_t* pointer = xcb_query_pointer_reply(connection, xcb_query_pointer(connection, XDefaultRootWindow(display)), NULL);
uint16_t mask = pointer->mask;
free(pointer);
// Close the connection with the X server
CloseDisplay(display);
switch (button)
{
case Mouse::Left: return mask & XCB_BUTTON_MASK_1;
case Mouse::Right: return mask & XCB_BUTTON_MASK_3;
case Mouse::Middle: return mask & XCB_BUTTON_MASK_2;
case Mouse::XButton1: return false; // not supported by X
case Mouse::XButton2: return false; // not supported by X
default: return false;
}
}
////////////////////////////////////////////////////////////
Vector2i InputImpl::getMousePosition()
{
// Open a connection with the X server
Display* display = OpenDisplay();
xcb_connection_t* connection = XGetXCBConnection(display);
xcb_query_pointer_reply_t* pointer = xcb_query_pointer_reply(connection, xcb_query_pointer(connection, XDefaultRootWindow(display)), NULL);
// Close the connection with the X server
CloseDisplay(display);
// Prepare result.
Vector2i result(pointer->root_x, pointer->root_y);
free(pointer);
return result;
}
////////////////////////////////////////////////////////////
Vector2i InputImpl::getMousePosition(const Window& relativeTo)
{
WindowHandle handle = relativeTo.getSystemHandle();
if (handle)
{
// Open a connection with the X server
xcb_connection_t* connection = OpenConnection();
xcb_query_pointer_reply_t* pointer = xcb_query_pointer_reply(connection, xcb_query_pointer(connection, handle), NULL);
// Close the connection with the X server
CloseConnection(connection);
// Prepare result.
Vector2i result(pointer->win_x, pointer->win_y);
free(pointer);
return result;
}
else
{
return Vector2i();
}
}
////////////////////////////////////////////////////////////
void InputImpl::setMousePosition(const Vector2i& position)
{
// Open a connection with the X server
Display* display = OpenDisplay();
xcb_connection_t* connection = XGetXCBConnection(display);
xcb_warp_pointer(connection, None, XDefaultRootWindow(display), 0, 0, 0, 0, position.x, position.y);
xcb_flush(connection);
// Close the connection with the X server
CloseDisplay(display);
}
////////////////////////////////////////////////////////////
void InputImpl::setMousePosition(const Vector2i& position, const Window& relativeTo)
{
// Open a connection with the X server
xcb_connection_t* connection = OpenConnection();
WindowHandle handle = relativeTo.getSystemHandle();
if (handle)
{
xcb_warp_pointer(connection, None, handle, 0, 0, 0, 0, position.x, position.y);
xcb_flush(connection);
}
// Close the connection with the X server
CloseConnection(connection);
}
////////////////////////////////////////////////////////////
bool InputImpl::isTouchDown(unsigned int /*finger*/)
{
// Not applicable
return false;
}
////////////////////////////////////////////////////////////
Vector2i InputImpl::getTouchPosition(unsigned int /*finger*/)
{
// Not applicable
return Vector2i();
}
////////////////////////////////////////////////////////////
Vector2i InputImpl::getTouchPosition(unsigned int /*finger*/, const Window& /*relativeTo*/)
{
// Not applicable
return Vector2i();
}
} // namespace priv
} // namespace sf
| [
"[email protected]"
] | |
b17dc69ee18881bffc54246099e7afa8fa631208 | 1e944c61257df92db3e8fff37302cfa38e9f1717 | /src/ttf_system_init_error.hh | f1624112ca3b45710cb9a215813616e603b7bcb7 | [] | no_license | wilhelmtell/glasses | 273ece7c15d1940c468eed4553e18ff1a87fce8a | 650eabcc7170b064e8589ef1b35827861f05184c | refs/heads/master | 2021-01-17T12:54:31.700871 | 2016-07-24T14:18:00 | 2016-07-24T14:18:00 | 58,410,678 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | hh | #ifndef GLS_TTF_SYSTEM_INIT_ERROR_HH_
#define GLS_TTF_SYSTEM_INIT_ERROR_HH_
#include <stdexcept>
namespace gls {
struct ttf_system_init_error : std::runtime_error {
ttf_system_init_error() = default;
explicit ttf_system_init_error(char const* const m);
};
}
#endif
| [
"[email protected]"
] | |
e660168ea486c694b67efb4e1435974a1dc87490 | d8926582a0c721641433559617ebc1a33ee6d35e | /src/jnc_ct/jnc_ct_TypeMgr/jnc_ct_PropertyPtrType.cpp | d1239d65fd2cb448a4991075a5bdb7b3027398b7 | [
"MIT"
] | permissive | vovkos/jancy | 187ba9f7866b694a84bd334f2e9b1bdc0ab1a4b9 | c6d86984773765c1c6faf6e0da266d991962a0c5 | refs/heads/master | 2023-08-03T04:34:54.352189 | 2023-08-02T08:59:51 | 2023-08-02T08:59:51 | 76,837,658 | 61 | 12 | null | null | null | null | UTF-8 | C++ | false | false | 4,413 | cpp | //..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_PropertyPtrType.h"
#include "jnc_ct_Module.h"
#include "jnc_rt_Runtime.h"
namespace jnc {
namespace ct {
//..............................................................................
PropertyPtrType::PropertyPtrType() {
m_typeKind = TypeKind_PropertyPtr;
m_ptrTypeKind = PropertyPtrTypeKind_Normal;
m_alignment = sizeof(void*);
m_targetType = NULL;
}
sl::String
PropertyPtrType::createSignature(
PropertyType* propertyType,
TypeKind typeKind,
PropertyPtrTypeKind ptrTypeKind,
uint_t flags
) {
sl::String signature = typeKind == TypeKind_PropertyRef ? "RX" : "PX";
switch (ptrTypeKind) {
case PropertyPtrTypeKind_Thin:
signature += 't';
break;
case PropertyPtrTypeKind_Weak:
signature += 'w';
break;
}
signature += getPtrTypeFlagSignature(flags);
signature += propertyType->getSignature();
return signature;
}
void
PropertyPtrType::prepareTypeString() {
TypeStringTuple* tuple = getTypeStringTuple();
Type* returnType = m_targetType->getReturnType();
tuple->m_typeStringPrefix = returnType->getTypeStringPrefix();
sl::String ptrTypeFlagString = getPtrTypeFlagString(m_flags);
if (!ptrTypeFlagString.isEmpty()) {
tuple->m_typeStringPrefix += ' ';
tuple->m_typeStringPrefix += ptrTypeFlagString;
}
if (m_ptrTypeKind != PropertyPtrTypeKind_Normal) {
tuple->m_typeStringPrefix += ' ';
tuple->m_typeStringPrefix += getPropertyPtrTypeKindString(m_ptrTypeKind);
}
tuple->m_typeStringPrefix += m_typeKind == TypeKind_PropertyRef ? " property&" : " property*";
if (m_targetType->isIndexed())
tuple->m_typeStringSuffix += m_targetType->getGetterType()->getTypeStringSuffix();
tuple->m_typeStringSuffix += returnType->getTypeStringSuffix();
}
void
PropertyPtrType::prepareDoxyLinkedText() {
TypeStringTuple* tuple = getTypeStringTuple();
Type* returnType = m_targetType->getReturnType();
tuple->m_doxyLinkedTextPrefix = returnType->getDoxyLinkedTextPrefix();
sl::String ptrTypeFlagString = getPtrTypeFlagString(m_flags);
if (!ptrTypeFlagString.isEmpty()) {
tuple->m_doxyLinkedTextPrefix += ' ';
tuple->m_doxyLinkedTextPrefix += ptrTypeFlagString;
}
if (m_ptrTypeKind != PropertyPtrTypeKind_Normal) {
tuple->m_doxyLinkedTextPrefix += ' ';
tuple->m_doxyLinkedTextPrefix += getPropertyPtrTypeKindString(m_ptrTypeKind);
}
tuple->m_doxyLinkedTextPrefix += m_typeKind == TypeKind_PropertyRef ? " property&" : " property*";
if (m_targetType->isIndexed())
tuple->m_doxyLinkedTextSuffix += m_targetType->getGetterType()->getDoxyLinkedTextSuffix();
tuple->m_doxyLinkedTextSuffix += returnType->getDoxyLinkedTextSuffix();
}
void
PropertyPtrType::prepareDoxyTypeString() {
Type::prepareDoxyTypeString();
if (m_targetType->isIndexed())
getTypeStringTuple()->m_doxyTypeString += m_targetType->getGetterType()->getDoxyArgString();
}
void
PropertyPtrType::prepareLlvmType() {
m_llvmType = m_ptrTypeKind != PropertyPtrTypeKind_Thin ?
m_module->m_typeMgr.getStdType(StdType_PropertyPtrStruct)->getLlvmType() :
m_targetType->getVtableStructType()->getDataPtrType_c()->getLlvmType();
}
void
PropertyPtrType::prepareLlvmDiType() {
m_llvmDiType = m_ptrTypeKind != PropertyPtrTypeKind_Thin ?
m_module->m_typeMgr.getStdType(StdType_PropertyPtrStruct)->getLlvmDiType() :
m_targetType->getVtableStructType()->getDataPtrType_c()->getLlvmDiType();
}
void
PropertyPtrType::markGcRoots(
const void* p,
rt::GcHeap* gcHeap
) {
ASSERT(m_ptrTypeKind == PropertyPtrTypeKind_Normal || m_ptrTypeKind == PropertyPtrTypeKind_Weak);
PropertyPtr* ptr = (PropertyPtr*)p;
if (!ptr->m_closure)
return;
Box* box = ptr->m_closure->m_box;
if (m_ptrTypeKind == PropertyPtrTypeKind_Normal)
gcHeap->markClass(box);
else if (isClassType(box->m_type, ClassTypeKind_PropertyClosure))
gcHeap->weakMarkClosureClass(box);
else // simple weak closure
gcHeap->weakMark(box);
}
//..............................................................................
} // namespace ct
} // namespace jnc
| [
"[email protected]"
] | |
6d9edd9cce5d8aef3af65901fca2f0c63fb6c879 | a0c4ed3070ddff4503acf0593e4722140ea68026 | /source/CAIROLE/OLEAUTO/SRC/OLEDISP/TIUTIL.CPP | 8ae0b09a7b87ccc4e847fb7f37fab5e7df0dce5a | [] | no_license | cjacker/windows.xp.whistler | a88e464c820fbfafa64fbc66c7f359bbc43038d7 | 9f43e5fef59b44e47ba1da8c2b4197f8be4d4bc8 | refs/heads/master | 2022-12-10T06:47:33.086704 | 2020-09-19T15:06:48 | 2020-09-19T15:06:48 | 299,932,617 | 0 | 1 | null | 2020-09-30T13:43:42 | 2020-09-30T13:43:41 | null | UTF-8 | C++ | false | false | 3,100 | cpp | /***
*tiutil.cxx - TypeInfo/TypeLib Utilities
*
* Copyright (C) 1994, Microsoft Corporation. All Rights Reserved.
* Information Contained Herein Is Proprietary and Confidential.
*
*Purpose:
* This file contains misc TypeInfo/TypeLib releated utilities.
*
*Documentation:
*
*Revision History:
*
* [00] 23-Jun-94 bradlo: Created.
*
*Implementation Notes:
*
*****************************************************************************/
#include "oledisp.h"
ASSERTDATA
/***
*PUBLIC HRESULT IsDual
*Purpose:
* Answers if the given TypeInfo describes a dual interface.
*
*Entry:
* ptinfo = the typeinfo to check
*
*Exit:
* return value = HRESULT
* NOERROR if it is a dual interface, S_FALSE if not
*
***********************************************************************/
INTERNAL_(HRESULT)
IsDual(ITypeInfo FAR* ptinfo)
{
BOOL fIsDual;
TYPEATTR FAR* ptattr;
IfFailRet(ptinfo->GetTypeAttr(&ptattr));
fIsDual = (ptattr->wTypeFlags & TYPEFLAG_FDUAL)
&& (ptattr->typekind == TKIND_DISPATCH);
ptinfo->ReleaseTypeAttr(ptattr);
return fIsDual ? NOERROR : RESULT(S_FALSE);
}
/***
*PUBLIC HRESULT GetPrimaryInterface
*Purpose:
* Given a TypeInfo describing a Coclass, search for and return
* type TypeInfo that describes that class' primary interface.
*
*Entry:
* ptinfo = the TypeInfo of the base class.
*
*Exit:
* return value = HRESULT
*
* *ptinfoPrimary = the TypeInfo of the primary interface, NULL
* if the class does not have a primary interface.
*
***********************************************************************/
INTERNAL_(HRESULT)
GetPrimaryInterface(ITypeInfo *ptinfo, ITypeInfo **pptinfoPri)
{
BOOL fIsDual;
TYPEKIND tkind;
HRESULT hresult;
HREFTYPE hreftype;
int impltypeflags;
TYPEATTR *ptattr;
unsigned int iImplType, cImplTypes;
ITypeInfo *ptinfoRef;
ptinfoRef = NULL;
IfFailGo(ptinfo->GetTypeAttr(&ptattr), Error);
cImplTypes = ptattr->cImplTypes;
tkind = ptattr->typekind;
ptinfo->ReleaseTypeAttr(ptattr);
if(tkind != TKIND_COCLASS)
return RESULT(E_INVALIDARG);
// Look for the interface marked [default] and not [source]
for(iImplType = 0; iImplType < cImplTypes; ++iImplType){
IfFailGo(ptinfo->GetImplTypeFlags(iImplType, &impltypeflags), Error);
if(IMPLTYPEFLAG_FDEFAULT
== (impltypeflags & (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE)))
{
// Found It!
IfFailGo(ptinfo->GetRefTypeOfImplType(iImplType, &hreftype), Error);
IfFailGo(ptinfo->GetRefTypeInfo(hreftype, &ptinfoRef), Error);
// If its dual, get the interface protion
hresult = IsDual(ptinfoRef);
if(HRESULT_FAILED(hresult))
goto Error;
fIsDual = (hresult == NOERROR);
if (fIsDual) {
IfFailGo(ptinfoRef->GetRefTypeOfImplType(-1, &hreftype), Error);
IfFailGo(ptinfoRef->GetRefTypeInfo(hreftype, pptinfoPri), Error);
ptinfoRef->Release();
}
else {
*pptinfoPri = ptinfoRef;
}
return NOERROR;
}
}
// NotFound
*pptinfoPri = NULL;
return NOERROR;
Error:
if(ptinfoRef != NULL)
ptinfoRef->Release();
return hresult;
}
| [
"[email protected]"
] | |
188ff1fbd9e82ac82bfd3b6b21c44af62e257d93 | 94cb10457b3a3ade5b2cca4212d4b29f83af1dd6 | /Source/PortfolioApp/Private/ImagesHolder.cpp | f34f5daad921c84d32bab0cffe484a7fd6c56679 | [] | no_license | dy-dev/Portfolio | b371f1e3e5cbce62c9d3cce3874a22e1d8fa7b5f | 2f8af425a23a653c1b282f710d6c770100eb7c64 | refs/heads/master | 2021-04-30T23:08:25.091605 | 2016-06-07T09:34:38 | 2016-06-07T09:34:38 | 49,322,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "PortfolioApp.h"
#include "ImagesHolder.h"
UImagesHolder::UImagesHolder( )
{
}
UImagesHolder::~UImagesHolder()
{
}
| [
"[email protected]"
] | |
ead0974605ea463e4f4de0b9ad33268ca74c3923 | 05aed025ca65e1af573d7219047033e6541d7559 | /src/model/Stable/Hq.h | f4e47be373909cb98e5c2c6eba45263463506f18 | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Discookie/Warp | 02d9c8597174690a037abe41146c31467e7f8d0f | 532ab6269ee74a0fc34e396d45ba59e905628782 | refs/heads/master | 2022-08-30T08:38:22.085998 | 2020-05-22T21:25:35 | 2020-05-22T21:25:35 | 266,128,650 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 307 | h | #ifndef WARP_HQ_H
#define WARP_HQ_H
#include "Stable.h"
class Hq : public Stable {
public:
Hq(Coordinate position,
const std::shared_ptr<FieldEntityCallback> &game_model_callback) :
Stable(position, game_model_callback){
this->upgraded = true;
}
};
#endif //WARP_HQ_H
| [
"[email protected]"
] | |
c9ecb8c1b25f53875d135aeb694d30f969273ed7 | 4d4822b29e666cea6b2d99d5b9d9c41916b455a9 | /Example/Pods/Headers/Private/GeoFeatures/boost/geometry/algorithms/detail/is_valid/ring.hpp | ed0e2ff789327c2ef21ea2957306f05242b17535 | [
"BSL-1.0",
"Apache-2.0"
] | permissive | eswiss/geofeatures | 7346210128358cca5001a04b0e380afc9d19663b | 1ffd5fdc49d859b829bdb8a9147ba6543d8d46c4 | refs/heads/master | 2020-04-05T19:45:33.653377 | 2016-01-28T20:11:44 | 2016-01-28T20:11:44 | 50,859,811 | 0 | 0 | null | 2016-02-01T18:12:28 | 2016-02-01T18:12:28 | null | UTF-8 | C++ | false | false | 92 | hpp | ../../../../../../../../../../GeoFeatures/boost/geometry/algorithms/detail/is_valid/ring.hpp | [
"[email protected]"
] | |
7542b04daf116757e3c4a657d1d86c4be4244cce | 6388460fad6cc9236993cb34c77a08d677145b6a | /LogicTests/notAndOrCondTests.cpp | e7601f19a4c4493165cdb55b4e6149eadbff1a08 | [] | no_license | AlexHahnPublic/CPP_Practice | fe55b5600ea68a612ed8f006268fa35e57b0e6b5 | 47116984680cc54330d66bf55dc4efe9933316df | refs/heads/master | 2021-05-03T22:31:50.916435 | 2016-10-22T04:57:47 | 2016-10-22T04:57:47 | 71,617,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | cpp | #include <iostream>
using namespace std;
int main()
{
int num;
cout<<"Please input a number: ";
cin>>num;
cin.ignore();
if (num !=3 && num > 0) {
cout<<"Your number is positive AND not 3";
}
else if ( num <0 || num == 3) {
cout<<"Your number is negative OR is 3";
}
cin.get();
}
| [
"[email protected]"
] | |
de51571c57d2fc3515571d2287e29f878a3622c7 | 1c9d2c8488dd76250e39e6875429edbbf24de784 | /groups/bsl/bslmt/bslmt_mutexassert.t.cpp | 82b48961be6c74cee7e9a4640d5fabdf9cffdf69 | [
"Apache-2.0"
] | permissive | villevoutilainen/bde | 9cc68889c1fac9beca068c9ca732c36fd81b33e9 | b0f71ac6e3187ce752d2e8906c4562e3ec48b398 | refs/heads/master | 2020-05-15T03:43:36.725050 | 2019-10-03T12:28:54 | 2019-10-03T12:28:54 | 182,071,409 | 1 | 1 | Apache-2.0 | 2019-10-03T12:28:55 | 2019-04-18T10:59:27 | C++ | UTF-8 | C++ | false | false | 23,062 | cpp | // bslmt_mutexassert.t.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <bslmt_mutexassert.h>
#include <bslmt_mutex.h>
#include <bslmt_threadutil.h>
#include <bslim_testutil.h>
#include <bsls_atomic.h>
#include <bsl_cstdlib.h>
#include <bsl_cstring.h>
#include <bsl_deque.h>
#include <bsl_iostream.h>
#include <bsl_map.h>
#include <bsl_vector.h>
#include <bsls_atomic.h>
using namespace BloombergLP;
using namespace bsl;
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
// Two main testing strategies are employed here:
//: 1 Assert on a locked mutex and observe nothing happens.
//: 2 Assert on an unlocked mutex with an assert handler installed that will
//: throw an exception, catch the exception, and verify that an exception
//: was thrown.
//-----------------------------------------------------------------------------
// MACROS
//: o BSLMT_MUTEXASSERT_IS_LOCKED
//: o BSLMT_MUTEXASSERT_IS_LOCKED_SAFE
//: o BSLMT_MUTEXASSERT_IS_LOCKED_OPT
//-----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [ 4] USAGE EXAMPLE
// [ 2] CONCERN: Testing macros on mutexes locked by the current thread
// [ 2] CONCERN: Testing macros on unlocked mutexes
// [ 3] CONCERN: Testing macros on mutexes locked by a different thread
//-----------------------------------------------------------------------------
// ============================================================================
// STANDARD BDE ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
cout << "Error " __FILE__ "(" << line << "): " << message
<< " (failed)" << endl;
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLIM_TESTUTIL_ASSERT
#define ASSERTV BSLIM_TESTUTIL_ASSERTV
#define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT
#define Q BSLIM_TESTUTIL_Q // Quote identifier literally.
#define P BSLIM_TESTUTIL_P // Print identifier and value.
#define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLIM_TESTUTIL_L_ // current Line number
// ============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
// ----------------------------------------------------------------------------
int verbose;
int veryVerbose;
// -------------
// Usage Example
// -------------
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: Checking Consistency Within a Private Method
///- - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Sometimes multithreaded code is written such that the author of a function
// requires that a caller has already acquired a mutex. The
// 'BSLMT_MUTEXASSERT_IS_LOCKED*' family of assertions allows the programmers
// to verify, using defensive programming techniques, that the mutex in
// question is indeed locked.
//
// Suppose we have a fully thread-safe queue that contains 'int' values, and is
// guarded by an internal mutex. We can use 'BSLMT_MUTEXASSERT_IS_LOCKED_SAFE'
// to ensure (in appropriate build modes) that proper internal locking of the
// mutex is taking place.
//
// First, we define the container:
//..
class MyThreadSafeQueue {
// This 'class' provides a fully *thread-safe* unidirectional queue of
// 'int' values. See {'bsls_glossary'|Fully Thread-Safe}. All public
// manipulators operate as single, atomic actions.
// DATA
bsl::deque<int> d_deque; // underlying non-*thread-safe*
// standard container
mutable bslmt::Mutex d_mutex; // mutex to provide thread safety
// PRIVATE MANIPULATOR
int popImp(int *result);
// Assign the value at the front of the queue to the specified
// '*result', and remove the value at the front of the queue;
// return 0 if the queue was not initially empty, and a non-zero
// value (with no effect) otherwise. The behavior is undefined
// unless 'd_mutex' is locked.
public:
// ...
// MANIPULATORS
int pop(int *result);
// Assign the value at the front of the queue to the specified
// '*result', and remove the value at the front of the queue;
// return 0 if the queue was not initially empty, and a non-zero
// value (with no effect) otherwise.
void popAll(bsl::vector<int> *result);
// Assign the values of all the elements from this queue, in order,
// to the specified '*result', and remove them from this queue.
// Any previous contents of '*result' are discarded. Note that, as
// with the other public manipulators, this entire operation occurs
// as a single, atomic action.
void push(int value);
// ...
template <class INPUT_ITER>
void pushRange(const INPUT_ITER& first, const INPUT_ITER& last);
// ...
};
//..
// Notice that our public manipulators have two forms: push/pop a single
// element, and push/pop a collection of elements. Popping even a single
// element is non-trivial, so we factor this operation into a non-*thread-safe*
// private manipulator that performs the pop, and is used in both public 'pop'
// methods. This private manipulator requires that the mutex be locked, but
// cannot lock the mutex itself, since the correctness of 'popAll' demands that
// all of the pops be collectively performed using a single mutex lock/unlock.
//
// Then, we define the private manipulator:
//..
// PRIVATE MANIPULATOR
int MyThreadSafeQueue::popImp(int *result)
{
BSLMT_MUTEXASSERT_IS_LOCKED_SAFE(&d_mutex);
if (d_deque.empty()) {
return -1; // RETURN
}
else {
*result = d_deque.front();
d_deque.pop_front();
return 0; // RETURN
}
}
//..
// Notice that, on the very first line, the private manipulator verifies, as a
// precondition check, that the mutex has been acquired, using one of the
// 'BSLMT_MUTEXASSERT_IS_LOCKED*' macros. We use the '...IS_LOCKED_SAFE...'
// version of the macro so that the check, which on some platforms is as
// expensive as locking the mutex, is performed in only the safe build mode.
//
// Next, we define the public manipulators; each of which must acquire a lock
// on the mutex (note that there is a bug in 'popAll'):
//..
// MANIPULATORS
int MyThreadSafeQueue::pop(int *result)
{
BSLS_ASSERT(result);
d_mutex.lock();
int rc = popImp(result);
d_mutex.unlock();
return rc;
}
void MyThreadSafeQueue::popAll(bsl::vector<int> *result)
{
BSLS_ASSERT(result);
const int size = static_cast<int>(d_deque.size());
result->resize(size);
int *begin = result->begin();
for (int index = 0; index < size; ++index) {
int rc = popImp(&begin[index]);
BSLS_ASSERT(0 == rc);
}
}
void MyThreadSafeQueue::push(int value)
{
d_mutex.lock();
d_deque.push_back(value);
d_mutex.unlock();
}
template <class INPUT_ITER>
void MyThreadSafeQueue::pushRange(const INPUT_ITER& first,
const INPUT_ITER& last)
{
d_mutex.lock();
d_deque.insert(d_deque.begin(), first, last);
d_mutex.unlock();
}
//..
// Notice that, in 'popAll', we forgot to lock/unlock the mutex!
//
// Then, in our function 'example2Function', we make use of our class to create
// and exercise a 'MyThreadSafeQueue' object:
//..
void testThreadSafeQueue(bsl::ostream& stream)
{
MyThreadSafeQueue queue;
//..
// Next, we populate the queue using 'pushRange':
//..
const int rawData[] = { 17, 3, 21, -19, 4, 87, 29, 3, 101, 31, 36 };
enum { k_RAW_DATA_LENGTH = sizeof rawData / sizeof *rawData };
queue.pushRange(rawData + 0, rawData + k_RAW_DATA_LENGTH);
//..
// Then, we pop a few items off the front of the queue and verify their values:
//..
int value = -1;
ASSERT(0 == queue.pop(&value)); ASSERT(17 == value);
ASSERT(0 == queue.pop(&value)); ASSERT( 3 == value);
ASSERT(0 == queue.pop(&value)); ASSERT(21 == value);
//..
// Next, we attempt to empty the queue with 'popAll', which, if built in safe
// mode, would fail because it neglects to lock the mutex:
//..
bsl::vector<int> v;
queue.popAll(&v);
stream << "Remaining raw numbers: ";
for (bsl::size_t ti = 0; ti < v.size(); ++ti) {
stream << (ti ? ", " : "") << v[ti];
}
stream << bsl::endl;
}
//..
// Then, we build in non-safe mode and run:
//..
// Remaining raw numbers: -19, 4, 87, 29, 3, 101, 31, 36
//..
// Notice that, since the test case is being run in a single thread and our
// check is disabled, the bug where the mutex was not acquired does not
// manifest itself in a visible error, and we observe the seemingly correct
// output.
//
// Now, we build in safe mode (which enables our check), run the program (which
// calls 'example2Function'), and observe that, when we call 'popAll', the
// 'BSLMT_MUTEXASSERT_IS_LOCKED_SAFE(&d_mutex)' macro issues an error message
// and aborts:
//..
// Assertion failed: BSLMT_MUTEXASSERT_IS_LOCKED_SAFE(&d_mutex), file /bb/big
// storn/dev_framework/bchapman/git/bde-core/groups/bce/bslmt/unix-Linux-x86_6
// 4-2.6.18-gcc-4.6.1/bslmt_mutexassertislocked.t.cpp, line 137
// Aborted (core dumped)
//..
// Finally, note that the message printed above and the subsequent aborting of
// the program were the result of a call to 'bsls::Assert::invokeHandler',
// which in this case was configured (by default) to call
// 'bsls::Assert::failAbort'. Other handlers may be installed that produce
// different results, but in all cases should prevent the program from
// proceeding normally.
// ------
// case 3
// ------
struct TestCase3SubThread {
bslmt::Mutex *d_mutexToAssertOn;
bslmt::Mutex *d_mutexThatMainThreadWillUnlock;
bsls::AtomicInt *d_subthreadWillIncrementValue;
void operator()()
{
d_mutexToAssertOn->lock();
++*d_subthreadWillIncrementValue;
d_mutexThatMainThreadWillUnlock->lock();
}
};
// ------
// case 2
// ------
namespace TEST_CASE_2 {
enum AssortMode {
e_SAFE_MODE,
e_NORMAL_MODE,
e_OPT_MODE
} mode;
int expectedLine;
void myHandler(const char *text, const char *file, int line)
{
switch (mode) {
case e_SAFE_MODE: {
ASSERT(!bsl::strcmp("BSLMT_MUTEXASSERT_IS_LOCKED_SAFE(&mutex)", text));
} break;
case e_NORMAL_MODE: {
ASSERT(!bsl::strcmp("BSLMT_MUTEXASSERT_IS_LOCKED(&mutex)", text));
} break;
case e_OPT_MODE: {
ASSERT(!bsl::strcmp("BSLMT_MUTEXASSERT_IS_LOCKED_OPT(&mutex)", text));
} break;
default: {
ASSERT(0);
}
}
LOOP2_ASSERT(line, expectedLine, expectedLine == line);
ASSERT(!bsl::strcmp(__FILE__, file));
#ifdef BDE_BUILD_TARGET_EXC
throw 5;
#else
// We can't return to 'bsls::Assert::invokeHandler'. Make sure this test
// fails.
ASSERT(0 &&
"BSLMT_MUTEXASSERT_IS_LOCKED* failed wtih exceptions disabled");
abort();
#endif
}
} // close namespace TEST_CASE_2
// ============================================================================
// MAIN PROGRAM
// ----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
verbose = argc > 2;
veryVerbose = argc > 3;
cout << "TEST " << __FILE__ << " CASE " << test << endl;
switch (test) { case 0: // Zero is always the leading case.
case 4: {
// --------------------------------------------------------------------
// TESTING USAGE EXAMPLE
//
// Concerns:
//: 1 That the usage example compiles and functions as expected.
//
// Plan:
//: o Call 'testThreadSafeQueue', which implements and runs the usage
//: example, but don't call it in safe assert mode unless
//: 'veryVerbose' is selected, since it will abort in that mode.
// --------------------------------------------------------------------
if (verbose) cout << "USAGE EXAMPLE\n"
"=============\n";
#if defined(BSLS_ASSERT_SAFE_IS_ACTIVE)
if (!veryVerbose) {
cout << "Usage example not run in safe mode unless 'veryVerbose'"
" is set since it will abort\n";
break;
}
#endif
testThreadSafeQueue(cout);
} break;
case 3: {
// --------------------------------------------------------------------
// TESTING ON LOCK HELD BY ANOTHER THREAD
//
// Concerns:
//: 1 That 'BSLMT__ASSERTMUTEX_IS_LOCKED*' is never calling
//: 'bsls::Assert::invokeHandler' if the mutex is locked by another
//: thread.
//
// Plan:
//: o Spawn a subthread that will lock a mutex, then, once it has,
//: call the macros to assert that it is locked and observe that
//: no failures occur.
// --------------------------------------------------------------------
if (verbose) cout << "TESTING LOCK HELD BY OTHER THREAD\n"
"=================================\n";
bslmt::Mutex mutexToAssertOn;
bslmt::Mutex mutexThatMainThreadWillUnlock;
bsls::AtomicInt subthreadWillIncrementValue;
subthreadWillIncrementValue = 0;
mutexThatMainThreadWillUnlock.lock();
TestCase3SubThread functor;
functor.d_mutexToAssertOn = &mutexToAssertOn;
functor.d_mutexThatMainThreadWillUnlock =
&mutexThatMainThreadWillUnlock;
functor.d_subthreadWillIncrementValue = &subthreadWillIncrementValue;
bslmt::ThreadUtil::Handle handle;
int sts = bslmt::ThreadUtil::create(&handle, functor);
ASSERT(0 == sts);
bslmt::ThreadUtil::microSleep(10 * 1000);
while (0 == subthreadWillIncrementValue) {
; // do nothing
}
// The subthread has locked the mutex. Now observe that none of these
// macros blow up.
BSLMT_MUTEXASSERT_IS_LOCKED_SAFE(&mutexToAssertOn);
BSLMT_MUTEXASSERT_IS_LOCKED( &mutexToAssertOn);
BSLMT_MUTEXASSERT_IS_LOCKED_OPT( &mutexToAssertOn);
// The subthread is blocked waiting for us to unlock
// 'mutexThatMainThreadWillUnlock'. Unlock it so the subthread can
// finish and join the sub thread.
mutexThatMainThreadWillUnlock.unlock();
sts = bslmt::ThreadUtil::join(handle);
ASSERT(0 == sts);
// Both mutexes are locked, unlock them so they won't assert when
// destroyed.
mutexToAssertOn. unlock();
mutexThatMainThreadWillUnlock.unlock();
} break;
case 2: {
// --------------------------------------------------------------------
// TESTING 'BSLMT_MUTEXASSERT_IS_LOCKED*'
//
// Concerns:
//: 1 That 'BSLMT_MUTEXASSERT_IS_LOCKED*' is never calling
//: 'bsls::Assert::invokeHandler' if the mutex is locked.
//: 2 That, in appropriate build modes, 'invokeHandler' is in fact
//: called. This test is only run when exceptions are enabled.
//
//: Plan:
//: 1 With the mutex locked and the assert handler set to
//: 'bsls::failAbort' (the default), call all three '*_IS_LOCKED'
//: asserts and verify that they don't fail (C-1).
//: 2 Only if exceptions are enabled, unlock the mutex and set the
//: assert handler to 'TEST_CASE_2::myHandler' then call all 3
//: macros in try-catch blocks. Expect throws depending on the
//: build mode.
// --------------------------------------------------------------------
if (verbose) cout << "TESTING 'BSLMT_MUTEXASSERT_IS_LOCKED*'\n"
"=====================================\n";
bslmt::Mutex mutex;
mutex.lock();
if (veryVerbose) cout << "Plan 1: testing with mutex locked\n";
{
BSLMT_MUTEXASSERT_IS_LOCKED_SAFE(&mutex);
BSLMT_MUTEXASSERT_IS_LOCKED( &mutex);
BSLMT_MUTEXASSERT_IS_LOCKED_OPT( &mutex);
}
if (veryVerbose) cout << "Plan 2: testing with mutex unlocked\n";
{
mutex.unlock();
#ifdef BDE_BUILD_TARGET_EXC
bsls::Assert::setFailureHandler(&TEST_CASE_2::myHandler);
bool expectThrow;
#ifdef BSLS_ASSERT_SAFE_IS_ACTIVE
expectThrow = true;
#else
expectThrow = false;
#endif
try {
TEST_CASE_2::mode = TEST_CASE_2::e_SAFE_MODE;
TEST_CASE_2::expectedLine = __LINE__ + 1;
BSLMT_MUTEXASSERT_IS_LOCKED_SAFE(&mutex);
ASSERT(!expectThrow);
if (veryVerbose) cout << "Didn't throw SAFE\n";
} catch (int thrown) {
ASSERT(5 == thrown);
ASSERT(expectThrow);
if (veryVerbose) cout << "Threw SAFE\n";
}
#ifdef BSLS_ASSERT_IS_ACTIVE
expectThrow = true;
#else
expectThrow = false;
#endif
try {
TEST_CASE_2::mode = TEST_CASE_2::e_NORMAL_MODE;
TEST_CASE_2::expectedLine = __LINE__ + 1;
BSLMT_MUTEXASSERT_IS_LOCKED(&mutex);
ASSERT(!expectThrow);
if (veryVerbose) cout << "Didn't throw\n";
} catch (int thrown) {
ASSERT(5 == thrown);
ASSERT(expectThrow);
if (veryVerbose) cout << "Threw\n";
}
#ifdef BSLS_ASSERT_OPT_IS_ACTIVE
expectThrow = true;
#else
expectThrow = false;
#endif
try {
TEST_CASE_2::mode = TEST_CASE_2::e_OPT_MODE;
TEST_CASE_2::expectedLine = __LINE__ + 1;
BSLMT_MUTEXASSERT_IS_LOCKED_OPT(&mutex);
ASSERT(!expectThrow);
if (veryVerbose) cout << "Didn't throw OPT\n";
} catch (int thrown) {
ASSERT(5 == thrown);
ASSERT(expectThrow);
if (veryVerbose) cout << "Threw OPT\n";
}
bsls::Assert::setFailureHandler(&bsls::Assert::failAbort);
#endif
}
} break;
case 1: {
// ------------------------------------------------------------------
// Breathing test
//
// Create and destroy a mutex. Lock and verify that tryLock fails;
// unlock and verify that tryLock succeeds.
// ------------------------------------------------------------------
if (verbose) cout << "BREATHING TEST\n"
"==============\n";
bslmt::Mutex mutex;
mutex.lock();
// All of these asserts should pass.
BSLMT_MUTEXASSERT_IS_LOCKED_SAFE(&mutex);
BSLMT_MUTEXASSERT_IS_LOCKED( &mutex);
BSLMT_MUTEXASSERT_IS_LOCKED_OPT( &mutex);
mutex.unlock();
} break;
case -1: {
// ------------------------------------------------------------------
// TESTING 'BSLMT_MUTEXASSERT_IS_LOCKED_OPT'
// ------------------------------------------------------------------
if (verbose) cout << "WATCH ASSERT BLOW UP\n"
"====================\n";
bslmt::Mutex mutex;
cout << "Expect opt assert fail now, line number is: " <<
__LINE__ + 2 << endl;
BSLMT_MUTEXASSERT_IS_LOCKED_OPT(&mutex);
BSLS_ASSERT_OPT(0);
} break;
default: {
cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl;
testStatus = -1;
}
}
if (testStatus > 0) {
cerr << "Error, non-zero test status = "
<< testStatus << "." << endl;
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
| [
"[email protected]"
] | |
19147258c11470b81ed7154bad6e32bdc72f2348 | 9d87276ad5486c53343c50c6bc19bcb72384d6bb | /06design_pattern/01easy_factory/easy_factory.cpp | f4b262021c79a59e84df67af00493045467990a4 | [] | no_license | natural7/cpp-concurrent-test | 7eb004447e3e5a45cbc21cd07e2899f90a2d43d5 | 74bc224f504098623fbd3626c4ebe422487fcf5c | refs/heads/master | 2020-09-20T03:18:27.446196 | 2019-11-27T06:56:01 | 2019-11-27T06:56:01 | 224,365,367 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | cpp | #include "easy_factory.h"
// easy_factory::easy_factory()
// {
// cout << "easy_factory constructor"<<endl;
// }
shared_ptr<car> easy_factory::create_car(CAR car_type)
{
car *pcar = NULL;
switch (car_type)
{
case CAR_BWM:
pcar = new BMW();
break;
case CAR_Audi:
pcar = new Audi();
break;
default:
cout << "invalid type"<<endl;
}
shared_ptr<car> pscar(pcar);
return pscar;
} | [
"[email protected]"
] | |
4bfe077ca6fc7d25606b0f0da18f880554da6d0c | 062c4cab435b439e23714ba507cfac9dd7d3a765 | /core/math/src/K15_MatrixUtil.cpp | 283c81cd743b5cada680dc145d5b14a3042b0d31 | [] | no_license | jjzhang166/k15_engine_3d | 00df0896c7ea7073435e11d0480b2b489ad20898 | 01dd8255bafdb1c79bf0804a02db9888119b0720 | refs/heads/master | 2023-04-14T08:36:15.032928 | 2016-02-18T21:32:31 | 2016-02-18T21:32:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,395 | cpp | /**
* @file K15_MatrixUtil.cpp
* @author Felix Klinge <[email protected]>
* @version 1.0
* @date 2013/09/10
* @section LICENSE
*
* 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 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details at
* http://www.gnu.org/copyleft/gpl.html
*/
#include "K15_MatrixUtil.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
namespace K15_Engine { namespace Math {
/*********************************************************************************/
Matrix4 MatrixUtil::createPerspectiveMatrix(float p_FOV, float p_AspectRatio, float p_NearPlane, float p_FarPlane)
{
Matrix4 matProj;
glm::mat4 mat = glm::perspective(p_FOV, p_AspectRatio, p_NearPlane, p_FarPlane);
memcpy(&matProj, &mat, sizeof(Matrix4));
return matProj;
}
/*********************************************************************************/
Matrix4 MatrixUtil::createOrthographicMatrix(float p_Left, float p_Right, float p_Top, float p_Bottom, float p_NearPlane, float p_FarPlane)
{
Matrix4 matOrtho;
glm::mat4 mat = glm::ortho(p_Left, p_Right, p_Bottom, p_Top, p_NearPlane, p_FarPlane);
memcpy(&matOrtho, &mat, sizeof(Matrix4));
return matOrtho;
}
/*********************************************************************************/
Matrix4 MatrixUtil::translate(const Vector3& p_Translate)
{
Matrix4 matTrans;
glm::vec3 trans;
memcpy(&trans, &p_Translate, sizeof(Vector3));
glm::mat4 mat = glm::translate(glm::mat4(1.f), trans);
memcpy(&matTrans, &mat, sizeof(Matrix4));
return matTrans;
}
/*********************************************************************************/
Matrix4 MatrixUtil::scale(const Vector3& p_Scale)
{
Matrix4 matScale;
glm::vec3 scale;
memcpy(&scale, &p_Scale, sizeof(Vector3));
glm::mat4 mat = glm::scale(glm::mat4(1.f), scale);
memcpy(&matScale, &mat, sizeof(Matrix4));
return matScale;
}
/*********************************************************************************/
Matrix4 MatrixUtil::rotate(const Vector3& p_Axis, float p_AngleInRadian)
{
Matrix4 matRot;
glm::vec3 axis;
memcpy(&axis, &p_Axis, sizeof(Vector3));
glm::mat4 mat = glm::rotate(glm::mat4(1.f), p_AngleInRadian, axis);
memcpy(&matRot, &mat, sizeof(Matrix4));
return matRot;
}
/*********************************************************************************/
Matrix4 MatrixUtil::lookAt(const Vector3 &p_EyePos, const Vector3 &p_LookAt, const Vector3 &p_Up)
{
Matrix4 lookMat;
glm::vec3 eyepos, lookat, up;
memcpy(&eyepos, &p_EyePos, sizeof(Vector3));
memcpy(&lookat, &p_LookAt, sizeof(Vector3));
memcpy(&up, &p_Up, sizeof(Vector3));
glm::mat4 mat = glm::lookAt(eyepos, lookat, up);
memcpy(&lookMat, &mat, sizeof(Matrix4));
return lookMat;
}
/*********************************************************************************/
}} //end of K15_Engine::Math namespace
| [
"[email protected]"
] | |
7052b5aa19a8b83a826c79f892b0bd3a3433063c | 9f13c139d19e3bcfe9d0effa43da6734c2b83595 | /PoliKava/11636 - Hello World!/problem.cpp | de52d2e767c3da075f7a8c6aa4ab455ec88329b9 | [] | no_license | Kavarenshko/UVa-Problems | aaad1cb78fc33f54ca5b5bde42723ae22b63be82 | 4951ecd41941184f0ef03d7e9cbe846e9a2f36a6 | refs/heads/master | 2021-01-10T20:21:36.497280 | 2017-12-02T22:09:45 | 2017-12-02T22:09:45 | 40,658,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 969 | cpp | #include <bits/stdc++.h>
#define FOR(i, n) for(int i=0; i < n; i++)
#define FOR1(i, n) for(int i=1; i <= n; i++)
using namespace std;
constexpr int INF = 0x7fffffff;
typedef long long ll; // 19 digits
typedef unsigned long long llu;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<vi> graph;
typedef vector<vii> weighted_graph;
void print(const char* msg, ...);
int main()
{
int N;
FOR1(tc, INF)
{
scanf("%d", &N);
if (N < 0)
break;
printf("Case %d: ", tc);
if (N == 1)
{
printf("0\n");
continue;
}
int tot = 1, paste = 0;
while(tot != N)
{
if (tot * 2 <= N)
{
tot *= 2;
paste += 1;
}
else
{
tot += (N - tot);
paste += 1;
}
}
printf("%d\n", paste);
}
return EXIT_SUCCESS;
}
void print(const char* msg, ...)
{
#ifndef ONLINE_JUDGE
va_list argptr;
va_start(argptr, msg);
vfprintf(stderr, msg, argptr);
va_end(argptr);
#endif
} | [
"[email protected]"
] | |
8941ac6f85fd5057a3cdd0e6a6d8f58f34a723fe | bda21b2a379d16892e65d678f42985ba3ecd2ca1 | /Cppstudy/Problem03-2-2Main.cpp | 1df948ef9d605a351a7feacff84fcc72d9aa97ab | [] | no_license | hustle-dev/Cpp-studying | 41212bac033b455839a484d6702571d6c3b21f3d | 9fd9db60663673ee19e8c7c90684a3ae49dbb139 | refs/heads/master | 2023-02-20T12:53:21.473416 | 2021-01-24T13:26:53 | 2021-01-24T13:26:53 | 288,464,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 172 | cpp | #include "Problem03-2-2.h"
int main(void)
{
Printer pnt;
pnt.SetString("Hello world!");
pnt.ShowString();
pnt.SetString("I love C++");
pnt.ShowString();
return 0;
} | [
"[email protected]"
] | |
253d8d67a781fcaab92d2125d11bd4d93bf9377e | 321455ffddb9b2ceaac431771d703586499ab225 | /Blatt-08/Aufgabe0.cpp | 2005a406fe9aec139ae194c2aa829c86a4d0b70e | [] | no_license | Leongrim/Computational-Physics | 4be97cba7396fd580ab63ebd213f34f97f14082d | dfdba1fe3963819b1de89330080c4f91b4e411f0 | refs/heads/master | 2021-01-21T14:07:50.559592 | 2016-11-04T15:36:05 | 2016-11-04T15:36:05 | 57,361,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,760 | cpp | #include <iostream>
#include <cmath>
#include <stdint.h>
#include "fstream"
#include <string>
void logistik( int Iterationen , double AnfangswertWert , double R , std::string Save){
std::fstream Datei;
Datei.open( (Save + ".txt").data() , std::ios::trunc | std::ios::out );
double x = AnfangswertWert;
double x_temp;
Datei << "# R = " << R << std::endl;
for (int i = 0; i < Iterationen; ++i)
{
x_temp = R*x*(1.0-x);
Datei << x << "\t" << x_temp << std::endl;
Datei << x_temp << "\t" << x_temp << std::endl;
x = x_temp;
}
}
void Kubische( int Iterationen , double AnfangswertWert , double R , std::string Save){
std::fstream Datei;
Datei.open( (Save + ".txt").data() , std::ios::trunc | std::ios::out );
double x = AnfangswertWert;
double x_temp;
Datei << "# R = " << R << std::endl;
for (int i = 0; i < Iterationen; ++i)
{
x_temp = R*x - x*x*x;
Datei << x << "\t" << x_temp << std::endl;
Datei << x_temp << "\t" << x_temp << std::endl;
x = x_temp;
}
}
void PrintFunktion( void Funktion( int , double , double , std::string ) , int Iterationen , double Startwert , double Schrittweite , double WertR , int Anzahl , std::string Datei){
for (int i = 0; i < Anzahl ; ++i)
{
WertR += Schrittweite ;
Funktion( Iterationen , Startwert , WertR , (std::string) Datei + std::to_string( i + 1 ));
}
}
int main(){
int Iterationen = 100;
double Startwert = 0.01;
double WertR = 1.0;
double Schrittweite = 0.03;
std::string Datei = "Ergebnisse/Aufgabe1a/Ergebnis";
int Anzahl = 100;
PrintFunktion( logistik , Iterationen , Startwert , Schrittweite , WertR , Anzahl , Datei);
Datei = "Ergebnisse/Aufgabe1b/Ergebnis";
PrintFunktion( Kubische , Iterationen , Startwert , Schrittweite , WertR , Anzahl , Datei);
return 0;
} | [
"[email protected]"
] | |
7e1fcee6dd39b6740b56b30f8d0df02336e27747 | 16cdf667a50d9616a04a03cf41bceba141978bc4 | /LSM9DS1_Types.h | a62eedde47444fb7fe88706d6d756a603ef156df | [] | no_license | Orbitalspace/BBB-LSM9DS1-I2C | c1264c6fe31c328e5089a7afab16b4f193df948b | a11cbd1b87374232c01a8f32b769dd8017079694 | refs/heads/master | 2020-07-27T12:58:48.333541 | 2019-09-25T07:11:12 | 2019-09-25T07:11:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,462 | h | /******************************************************************************
LSM9DS1_Types.h
SFE_LSM9DS1 Library - LSM9DS1 Types and Enumerations
Jim Lindblom @ SparkFun Electronics
Original Creation Date: April 21, 2015
https://github.com/sparkfun/LSM9DS1_Breakout
This file defines all types and enumerations used by the LSM9DS1 class.
Development environment specifics:
IDE: Arduino 1.6.0
Hardware Platform: Arduino Uno
LSM9DS1 Breakout Version: 1.0
This code is beerware; if you see me (or any other SparkFun employee) at the
local, and you've found our code helpful, please buy us a round!
Distributed as-is; no warranty is given.
******************************************************************************/
#ifndef __LSM9DS1_Types_H__
#define __LSM9DS1_Types_H__
#include <cstdint>
#include "LSM9DS1_Registers.h"
// The LSM9DS1 functions over both I2C or SPI. This library supports both.
// But the interface mode used must be sent to the LSM9DS1 constructor. Use
// one of these two as the first parameter of the constructor.
enum interface_mode
{
IMU_MODE_SPI,
IMU_MODE_I2C,
};
// accel_scale defines all possible FSR's of the accelerometer:
enum accel_scale
{
A_SCALE_2G, // 00: 2g
A_SCALE_16G, // 01: 16g
A_SCALE_4G, // 10: 4g
A_SCALE_8G // 11: 8g
};
// gyro_scale defines the possible full-scale ranges of the gyroscope:
enum gyro_scale
{
G_SCALE_245DPS, // 00: 245 degrees per second
G_SCALE_500DPS, // 01: 500 dps
G_SCALE_2000DPS, // 11: 2000 dps
};
// mag_scale defines all possible FSR's of the magnetometer:
enum mag_scale
{
M_SCALE_4GS, // 00: 4Gs
M_SCALE_8GS, // 01: 8Gs
M_SCALE_12GS, // 10: 12Gs
M_SCALE_16GS, // 11: 16Gs
};
// gyro_odr defines all possible data rate/bandwidth combos of the gyro:
enum gyro_odr
{
//! TODO
G_ODR_PD, // Power down (0)
G_ODR_149, // 14.9 Hz (1)
G_ODR_595, // 59.5 Hz (2)
G_ODR_119, // 119 Hz (3)
G_ODR_238, // 238 Hz (4)
G_ODR_476, // 476 Hz (5)
G_ODR_952 // 952 Hz (6)
};
// accel_oder defines all possible output data rates of the accelerometer:
enum accel_odr
{
XL_POWER_DOWN, // Power-down mode (0x0)
XL_ODR_10, // 10 Hz (0x1)
XL_ODR_50, // 50 Hz (0x02)
XL_ODR_119, // 119 Hz (0x3)
XL_ODR_238, // 238 Hz (0x4)
XL_ODR_476, // 476 Hz (0x5)
XL_ODR_952 // 952 Hz (0x6)
};
// accel_abw defines all possible anti-aliasing filter rates of the accelerometer:
enum accel_abw
{
A_ABW_408, // 408 Hz (0x0)
A_ABW_211, // 211 Hz (0x1)
A_ABW_105, // 105 Hz (0x2)
A_ABW_50, // 50 Hz (0x3)
};
// mag_odr defines all possible output data rates of the magnetometer:
enum mag_odr
{
M_ODR_0625, // 0.625 Hz (0)
M_ODR_125, // 1.25 Hz (1)
M_ODR_250, // 2.5 Hz (2)
M_ODR_5, // 5 Hz (3)
M_ODR_10, // 10 Hz (4)
M_ODR_20, // 20 Hz (5)
M_ODR_40, // 40 Hz (6)
M_ODR_80 // 80 Hz (7)
};
enum interrupt_select
{
XG_INT1 = INT1_CTRL,
XG_INT2 = INT2_CTRL
};
enum interrupt_generators
{
INT_DRDY_XL = (1 << 0), // Accelerometer data ready (INT1 & INT2)
INT_DRDY_G = (1 << 1), // Gyroscope data ready (INT1 & INT2)
INT1_BOOT = (1 << 2), // Boot status (INT1)
INT2_DRDY_TEMP = (1 << 2), // Temp data ready (INT2)
INT_FTH = (1 << 3), // FIFO threshold interrupt (INT1 & INT2)
INT_OVR = (1 << 4), // Overrun interrupt (INT1 & INT2)
INT_FSS5 = (1 << 5), // FSS5 interrupt (INT1 & INT2)
INT_IG_XL = (1 << 6), // Accel interrupt generator (INT1)
INT1_IG_G = (1 << 7), // Gyro interrupt enable (INT1)
INT2_INACT = (1 << 7), // Inactivity interrupt output (INT2)
};
enum accel_interrupt_generator
{
XLIE_XL = (1 << 0),
XHIE_XL = (1 << 1),
YLIE_XL = (1 << 2),
YHIE_XL = (1 << 3),
ZLIE_XL = (1 << 4),
ZHIE_XL = (1 << 5),
GEN_6D = (1 << 6)
};
enum gyro_interrupt_generator
{
XLIE_G = (1 << 0),
XHIE_G = (1 << 1),
YLIE_G = (1 << 2),
YHIE_G = (1 << 3),
ZLIE_G = (1 << 4),
ZHIE_G = (1 << 5)
};
enum mag_interrupt_generator
{
ZIEN = (1 << 5),
YIEN = (1 << 6),
XIEN = (1 << 7)
};
enum h_lactive
{
INT_ACTIVE_HIGH,
INT_ACTIVE_LOW
};
enum pp_od
{
INT_PUSH_PULL,
INT_OPEN_DRAIN
};
enum fifoMode_type
{
FIFO_OFF = 0,
FIFO_THS = 1,
FIFO_CONT_TRIGGER = 3,
FIFO_OFF_TRIGGER = 4,
FIFO_CONT = 6
};
struct gyroSettings
{
// Gyroscope settings:
uint8_t enabled;
uint16_t scale; // Changed this to 16-bit
uint8_t sampleRate;
// New gyro stuff:
uint8_t bandwidth;
uint8_t lowPowerEnable;
uint8_t HPFEnable;
uint8_t HPFCutoff;
uint8_t flipX;
uint8_t flipY;
uint8_t flipZ;
uint8_t orientation;
uint8_t enableX;
uint8_t enableY;
uint8_t enableZ;
uint8_t latchInterrupt;
};
struct deviceSettings
{
uint8_t commInterface; // Can be I2C, SPI 4-wire or SPI 3-wire
uint8_t agAddress; // I2C address or SPI CS pin
uint8_t mAddress; // I2C address or SPI CS pin
};
struct accelSettings
{
// Accelerometer settings:
uint8_t enabled;
uint8_t scale;
uint8_t sampleRate;
// New accel stuff:
uint8_t enableX;
uint8_t enableY;
uint8_t enableZ;
int8_t bandwidth;
uint8_t highResEnable;
uint8_t highResBandwidth;
};
struct magSettings
{
// Magnetometer settings:
uint8_t enabled;
uint8_t scale;
uint8_t sampleRate;
// New mag stuff:
uint8_t tempCompensationEnable;
uint8_t XYPerformance;
uint8_t ZPerformance;
uint8_t lowPowerEnable;
uint8_t operatingMode;
};
struct temperatureSettings
{
// Temperature settings
uint8_t enabled;
};
struct IMUSettings
{
deviceSettings device;
gyroSettings gyro;
accelSettings accel;
magSettings mag;
temperatureSettings temp;
};
#endif | [
"[email protected]"
] | |
a80f4ee2fbbc2a87247aa88a46ad44253be6dc2f | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /tools/gn/filesystem_utils.h | c17ab39da9be27149d72b40b8ba0738fd09d5526 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown",
"MIT"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 12,222 | h | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef TOOLS_GN_FILESYSTEM_UTILS_H_
#define TOOLS_GN_FILESYSTEM_UTILS_H_
#include <stddef.h>
#include <string>
#include "base/files/file_path.h"
#include "base/strings/string_piece.h"
#include "tools/gn/settings.h"
#include "tools/gn/target.h"
class Err;
class Location;
class Value;
std::string FilePathToUTF8(const base::FilePath::StringType& str);
inline std::string FilePathToUTF8(const base::FilePath& path) {
return FilePathToUTF8(path.value());
}
base::FilePath UTF8ToFilePath(const base::StringPiece& sp);
// Extensions -----------------------------------------------------------------
// Returns the index of the extension (character after the last dot not after a
// slash). Returns std::string::npos if not found. Returns path.size() if the
// file ends with a dot.
size_t FindExtensionOffset(const std::string& path);
// Returns a string piece pointing into the input string identifying the
// extension. Note that the input pointer must outlive the output.
base::StringPiece FindExtension(const std::string* path);
// Filename parts -------------------------------------------------------------
// Returns the offset of the character following the last slash, or
// 0 if no slash was found. Returns path.size() if the path ends with a slash.
// Note that the input pointer must outlive the output.
size_t FindFilenameOffset(const std::string& path);
// Returns a string piece pointing into the input string identifying the
// file name (following the last slash, including the extension). Note that the
// input pointer must outlive the output.
base::StringPiece FindFilename(const std::string* path);
// Like FindFilename but does not include the extension.
base::StringPiece FindFilenameNoExtension(const std::string* path);
// Removes everything after the last slash. The last slash, if any, will be
// preserved.
void RemoveFilename(std::string* path);
// Returns if the given character is a slash. This allows both slashes and
// backslashes for consistency between Posix and Windows (as opposed to
// FilePath::IsSeparator which is based on the current platform).
inline bool IsSlash(const char ch) {
return ch == '/' || ch == '\\';
}
// Returns true if the given path ends with a slash.
bool EndsWithSlash(const std::string& s);
// Path parts -----------------------------------------------------------------
// Returns a string piece pointing into the input string identifying the
// directory name of the given path, including the last slash. Note that the
// input pointer must outlive the output.
base::StringPiece FindDir(const std::string* path);
// Returns the substring identifying the last component of the dir, or the
// empty substring if none. For example "//foo/bar/" -> "bar".
base::StringPiece FindLastDirComponent(const SourceDir& dir);
// Returns true if the given string is in the given output dir. This is pretty
// stupid and doesn't handle "." and "..", etc., it is designed for a sanity
// check to keep people from writing output files to the source directory
// accidentally.
bool IsStringInOutputDir(const SourceDir& output_dir, const std::string& str);
// Verifies that the given string references a file inside of the given
// directory. This just uses IsStringInOutputDir above.
//
// The origin will be blamed in the error.
//
// If the file isn't in the dir, returns false and sets the error. Otherwise
// returns true and leaves the error untouched.
bool EnsureStringIsInOutputDir(const SourceDir& output_dir,
const std::string& str,
const ParseNode* origin,
Err* err);
// ----------------------------------------------------------------------------
// Returns true if the input string is absolute. Double-slashes at the
// beginning are treated as source-relative paths. On Windows, this handles
// paths of both the native format: "C:/foo" and ours "/C:/foo"
bool IsPathAbsolute(const base::StringPiece& path);
// Returns true if the input string is source-absolute. Source-absolute
// paths begin with two forward slashes and resolve as if they are
// relative to the source root.
bool IsPathSourceAbsolute(const base::StringPiece& path);
// Given an absolute path, checks to see if is it is inside the source root.
// If it is, fills a source-absolute path into the given output and returns
// true. If it isn't, clears the dest and returns false.
//
// The source_root should be a base::FilePath converted to UTF-8. On Windows,
// it should begin with a "C:/" rather than being our SourceFile's style
// ("/C:/"). The source root can end with a slash or not.
//
// Note that this does not attempt to normalize slashes in the output.
bool MakeAbsolutePathRelativeIfPossible(const base::StringPiece& source_root,
const base::StringPiece& path,
std::string* dest);
// Collapses "." and sequential "/"s and evaluates "..". |path| may be
// system-absolute, source-absolute, or relative. If |path| is source-absolute
// and |source_root| is non-empty, |path| may be system absolute after this
// function returns, if |path| references the filesystem outside of
// |source_root| (ex. path = "//.."). In this case on Windows, |path| will have
// a leading slash. Otherwise, |path| will retain its relativity. |source_root|
// must not end with a slash.
void NormalizePath(std::string* path,
const base::StringPiece& source_root = base::StringPiece());
// Converts slashes to backslashes for Windows. Keeps the string unchanged
// for other systems.
void ConvertPathToSystem(std::string* path);
// Takes a path, |input|, and makes it relative to the given directory
// |dest_dir|. Both inputs may be source-relative (e.g. begins with
// with "//") or may be absolute.
//
// If supplied, the |source_root| parameter is the absolute path to
// the source root and not end in a slash. Unless you know that the
// inputs are always source relative, this should be supplied.
std::string RebasePath(
const std::string& input,
const SourceDir& dest_dir,
const base::StringPiece& source_root = base::StringPiece());
// Returns the given directory with no terminating slash at the end, such that
// appending a slash and more stuff will produce a valid path.
//
// If the directory refers to either the source or system root, we'll append
// a "." so this remains valid.
std::string DirectoryWithNoLastSlash(const SourceDir& dir);
// Returns the "best" SourceDir representing the given path. If it's inside the
// given source_root, a source-relative directory will be returned (e.g.
// "//foo/bar.cc". If it's outside of the source root or the source root is
// empty, a system-absolute directory will be returned.
SourceDir SourceDirForPath(const base::FilePath& source_root,
const base::FilePath& path);
// Like SourceDirForPath but returns the SourceDir representing the current
// directory.
SourceDir SourceDirForCurrentDirectory(const base::FilePath& source_root);
// Given the label of a toolchain and whether that toolchain is the default
// toolchain, returns the name of the subdirectory for that toolchain's
// output. This will be the empty string to indicate that the toolchain outputs
// go in the root build directory. Otherwise, the result will end in a slash.
std::string GetOutputSubdirName(const Label& toolchain_label, bool is_default);
// Returns true if the contents of the file and stream given are equal, false
// otherwise.
bool ContentsEqual(const base::FilePath& file_path, const std::string& data);
// Writes given stream contents to the given file if it differs from existing
// file contents. Returns true if new contents was successfully written or
// existing file contents doesn't need updating, false on write error. |err| is
// set on write error if not nullptr.
bool WriteFileIfChanged(const base::FilePath& file_path,
const std::string& data,
Err* err);
// Writes given stream contents to the given file. Returns true if data was
// successfully written, false otherwise. |err| is set on error if not nullptr.
bool WriteFile(const base::FilePath& file_path, const std::string& data,
Err* err);
// -----------------------------------------------------------------------------
enum class BuildDirType {
// Returns the root toolchain dir rather than the generated or output
// subdirectories. This is valid only for the toolchain directory getters.
// Asking for this for a target or source dir makes no sense.
TOOLCHAIN_ROOT,
// Generated file directory.
GEN,
// Output file directory.
OBJ,
};
// In different contexts, different information is known about the toolchain in
// question. If you have a Target or settings object, everything can be
// extracted from there. But when querying label information on something in
// another toolchain, for example, the only thing known (it may not even exist)
// is the toolchain label string and whether it matches the default toolchain.
//
// This object extracts the relevant information from a variety of input
// types for the convenience of the caller.
class BuildDirContext {
public:
// Extracts toolchain information associated with the given target.
explicit BuildDirContext(const Target* target);
// Extracts toolchain information associated with the given settings object.
explicit BuildDirContext(const Settings* settings);
// Extrats toolchain information from the current toolchain of the scope.
explicit BuildDirContext(const Scope* execution_scope);
// Extracts the default toolchain information from the given execution
// scope. The toolchain you want to query must be passed in. This doesn't
// use the settings object from the Scope so one can query other toolchains.
// If you want to use the scope's current toolchain, use the version above.
BuildDirContext(const Scope* execution_scope, const Label& toolchain_label);
// Specify all information manually.
BuildDirContext(const BuildSettings* build_settings,
const Label& toolchain_label,
bool is_default_toolchain);
const BuildSettings* build_settings;
const Label& toolchain_label;
bool is_default_toolchain;
};
// Returns the root, object, or generated file directory for the toolchain.
//
// The toolchain object file root is never exposed in GN (there is no
// root_obj_dir variable) so BuildDirType::OBJ would normally never be passed
// to this function except when it's called by one of the variants below that
// append paths to it.
SourceDir GetBuildDirAsSourceDir(const BuildDirContext& context,
BuildDirType type);
OutputFile GetBuildDirAsOutputFile(const BuildDirContext& context,
BuildDirType type);
// Returns the output or generated file directory corresponding to the given
// source directory.
SourceDir GetSubBuildDirAsSourceDir(const BuildDirContext& context,
const SourceDir& source_dir,
BuildDirType type);
OutputFile GetSubBuildDirAsOutputFile(const BuildDirContext& context,
const SourceDir& source_dir,
BuildDirType type);
// Returns the output or generated file directory corresponding to the given
// target.
SourceDir GetBuildDirForTargetAsSourceDir(const Target* target,
BuildDirType type);
OutputFile GetBuildDirForTargetAsOutputFile(const Target* target,
BuildDirType type);
// Returns the scope's current directory.
SourceDir GetScopeCurrentBuildDirAsSourceDir(const Scope* scope,
BuildDirType type);
// Lack of OutputDir version is due only to it not currently being needed,
// please add one if you need it.
#endif // TOOLS_GN_FILESYSTEM_UTILS_H_
| [
"[email protected]"
] | |
ad801b7a4188345036c2b90ca3202940519303d9 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/math/test/test_lexical_cast.cpp | 58909cbea27bc8d4bc7185c039e7c19d8d3d8018 | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,832 | cpp |
// Copyright (c) 2006 Johan Rade
// Copyright (c) 2011 Paul A. Bristow incorporated Boost.Math
// 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)
//#ifdef _MSC_VER
//# pragma warning(disable : 4127 4511 4512 4701 4702)
//#endif
#define BOOST_TEST_MAIN
#include <limits>
#include <locale>
#include <string>
#include <sstd/boost/lexical_cast.hpp>
#include <sstd/boost/test/auto_unit_test.hpp>
#include <sstd/boost/math/special_functions/nonfinite_num_facets.hpp>
#include <sstd/boost/math/special_functions/sign.hpp>
#include <sstd/boost/math/special_functions/fpclassify.hpp>
#include "almost_equal.ipp"
#include "s_.ipp"
namespace {
// the anonymous namespace resolves ambiguities on platforms
// with fpclassify etc functions at global scope
using boost::lexical_cast;
using namespace boost::math;
using boost::math::signbit;
using boost::math::changesign;
using boost::math::isnan;
//------------------------------------------------------------------------------
template<class CharType, class ValType> void lexical_cast_test_impl();
BOOST_AUTO_TEST_CASE(lexical_cast_test)
{
lexical_cast_test_impl<char, float>();
lexical_cast_test_impl<char, double>();
lexical_cast_test_impl<char, long double>();
lexical_cast_test_impl<wchar_t, float>();
lexical_cast_test_impl<wchar_t, double>();
lexical_cast_test_impl<wchar_t, long double>();
}
template<class CharType, class ValType> void lexical_cast_test_impl()
{
if((std::numeric_limits<ValType>::has_infinity == 0) || (std::numeric_limits<ValType>::infinity() == 0))
return;
if((std::numeric_limits<ValType>::has_quiet_NaN == 0) || (std::numeric_limits<ValType>::quiet_NaN() == 0))
return;
std::locale old_locale;
std::locale tmp_locale(old_locale,
new nonfinite_num_put<CharType>(signed_zero));
std::locale new_locale(tmp_locale, new nonfinite_num_get<CharType>);
std::locale::global(new_locale);
ValType a1 = static_cast<ValType>(0);
ValType a2 = static_cast<ValType>(13);
ValType a3 = std::numeric_limits<ValType>::infinity();
ValType a4 = std::numeric_limits<ValType>::quiet_NaN();
ValType a5 = std::numeric_limits<ValType>::signaling_NaN();
ValType a6 = (changesign)(static_cast<ValType>(0));
ValType a7 = static_cast<ValType>(-57);
ValType a8 = -std::numeric_limits<ValType>::infinity();
ValType a9 = (changesign)(std::numeric_limits<ValType>::quiet_NaN()); // -NaN
ValType a10 = (changesign)(std::numeric_limits<ValType>::signaling_NaN()); // -NaN
std::basic_string<CharType> s1 = S_("0");
std::basic_string<CharType> s2 = S_("13");
std::basic_string<CharType> s3 = S_("inf");
std::basic_string<CharType> s4 = S_("nan");
std::basic_string<CharType> s5 = S_("nan");
std::basic_string<CharType> s6 = S_("-0");
std::basic_string<CharType> s7 = S_("-57");
std::basic_string<CharType> s8 = S_("-inf");
std::basic_string<CharType> s9 = S_("-nan");
std::basic_string<CharType> s10 = S_("-nan");
BOOST_CHECK(lexical_cast<std::basic_string<CharType> >(a1) == s1);
BOOST_CHECK(lexical_cast<std::basic_string<CharType> >(a2) == s2);
BOOST_CHECK(lexical_cast<std::basic_string<CharType> >(a3) == s3);
BOOST_CHECK(lexical_cast<std::basic_string<CharType> >(a4) == s4);
BOOST_CHECK(lexical_cast<std::basic_string<CharType> >(a5) == s5);
BOOST_CHECK(lexical_cast<std::basic_string<CharType> >(a6) == s6);
BOOST_CHECK(lexical_cast<std::basic_string<CharType> >(a7) == s7);
BOOST_CHECK(lexical_cast<std::basic_string<CharType> >(a8) == s8);
BOOST_CHECK(lexical_cast<std::basic_string<CharType> >(a9) == s9);
BOOST_CHECK(lexical_cast<std::basic_string<CharType> >(a10) == s10);
BOOST_CHECK(lexical_cast<ValType>(s1) == a1);
BOOST_CHECK(!(signbit)(lexical_cast<ValType>(s1)));
BOOST_CHECK(lexical_cast<ValType>(s2) == a2);
BOOST_CHECK(lexical_cast<ValType>(s3) == a3);
BOOST_CHECK((isnan)(lexical_cast<ValType>(s4)));
BOOST_CHECK(!(signbit)(lexical_cast<ValType>(s4)));
BOOST_CHECK((isnan)(lexical_cast<ValType>(s5)));
BOOST_CHECK(!(signbit)(lexical_cast<ValType>(s5)));
BOOST_CHECK(lexical_cast<ValType>(a6) == a6);
BOOST_CHECK((signbit)(lexical_cast<ValType>(s6)));
BOOST_CHECK(lexical_cast<ValType>(s7) == a7);
BOOST_CHECK(lexical_cast<ValType>(s8) == a8);
BOOST_CHECK((isnan)(lexical_cast<ValType>(s9)));
BOOST_CHECK((signbit)(lexical_cast<ValType>(s9)));
BOOST_CHECK((isnan)(lexical_cast<ValType>(s10)));
BOOST_CHECK((signbit)(lexical_cast<ValType>(s10)));
std::locale::global(old_locale);
}
//------------------------------------------------------------------------------
} // anonymous namespace
| [
"[email protected]"
] | |
2971cc5855012a9053beee2b15484eb7579fa9f7 | f6e032a8a04bc6b819785e1f978d828773e35758 | /include/dazzle/metaobject.hpp | 74b1a41201481a6cee6a81aaeae27526792261e3 | [
"BSL-1.0"
] | permissive | guardianofetherra/mirror | cfd6b3d7caf5f3718413cbf0a84769949d3fb89c | 8cef943d6cc98788c8e862546ad4de4aebe4b8d9 | refs/heads/master | 2021-10-12T00:02:08.961121 | 2016-12-01T05:57:12 | 2016-12-01T05:57:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,407 | hpp | /**
* @file dazzle/metaobject.hpp
* @brief Declaration of metaobject and metaobject sequences
*
* Copyright Matus Chochlik.
* Distributed under the Boost Software License, Version 1.0.
* See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt
*/
#ifndef DAZZLE_METAOBJECT_1105240825_HPP
#define DAZZLE_METAOBJECT_1105240825_HPP
#include <mirror/metaobject.hpp>
#include <mirror/traits.hpp>
#include <mirror/get_base_name.hpp>
#include <mirror/get_full_name.hpp>
#include <mirror/get_display_name.hpp>
#include <mirror/get_aliased.hpp>
#include <mirror/get_type.hpp>
#include <mirror/get_scope.hpp>
#include <mirror/get_enumerators.hpp>
#include <mirror/get_data_members.hpp>
#include <mirror/get_public_data_members.hpp>
#include <mirror/get_member_types.hpp>
#include <mirror/get_public_member_types.hpp>
#include <mirror/get_base_classes.hpp>
#include <mirror/get_public_base_classes.hpp>
#include <mirror/get_base_class.hpp>
#include <mirror/get_constant.hpp>
#include <mirror/get_pointer.hpp>
#include <mirror/dereference.hpp>
#include <mirror/get_elaborated_type_specifier.hpp>
#include <mirror/get_access_specifier.hpp>
#include <mirror/is_private.hpp>
#include <mirror/is_protected.hpp>
#include <mirror/is_public.hpp>
#include <mirror/is_static.hpp>
#include <mirror/is_virtual.hpp>
#include <mirror/is_class.hpp>
#include <mirror/is_struct.hpp>
#include <mirror/is_union.hpp>
#include <mirror/is_enum.hpp>
#include <mirror/is_scoped_enum.hpp>
#include <mirror/get_reflected_type.hpp>
#include "sequence_ops.hpp"
#include "type.hpp"
namespace dazzle {
template <typename MO>
struct wrapped<mirror::metaobject<MO>>
{
using impl = mirror::metaobject<MO>;
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_base_name)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_full_name)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_display_name)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_aliased)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_type)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_scope)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_enumerators)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_data_members)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_public_data_members)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_member_types)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_public_member_types)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_base_classes)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_public_base_classes)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_base_class)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_constant)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_pointer)
template <typename T>
static constexpr auto& dereference(T& inst) {
return mirror::dereference<impl>::apply(inst);
}
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_elaborated_type_specifier)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_access_specifier)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(is_private)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(is_protected)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(is_public)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(is_static)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(is_virtual)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(is_class)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(is_struct)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(is_union)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(is_enum)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(is_scoped_enum)
DAZZLE_MEMFN_ENVELOP_MIRROR_OP(get_reflected_type)
};
template <typename MoS>
struct wrapped<mirror::metaobject_sequence<MoS>>
: sequence_ops<mirror::metaobject_sequence<MoS>>
{ };
} // namespace dazzle
#endif //include guard
| [
"[email protected]"
] | |
2d846f8389b8e42261e9b6f4764b1fd272d1512d | feae026136e8c2153b4544a95410014a0e4e9e2f | /tinyram_snark/gadgetlib1/gadgets/cpu_checkers/fooram/components/bar_gadget.hpp | dc3a1bc8d996735ac10b877f3c0deb4f18bf0a2f | [
"MIT"
] | permissive | Wind-Gone/osprey | 03d2be4843ce3bc9a9670d5a63c4b9ba811c7f92 | decbb328c9527751b8ea5b4e9b57dd12575c5a7d | refs/heads/master | 2023-04-23T08:10:15.739051 | 2021-05-14T05:20:25 | 2021-05-14T05:20:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,076 | hpp | /** @file
*****************************************************************************
Declaration of interfaces for an auxiliarry gadget for the FOORAM CPU.
*****************************************************************************
* @author This file is part of tinyram_snark, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef BAR_GADGET_HPP_
#define BAR_GADGET_HPP_
#include <tinyram_snark/gadgetlib1/gadget.hpp>
#include <tinyram_snark/gadgetlib1/gadgets/basic_gadgets.hpp>
namespace tinyram_snark {
/**
* The bar gadget checks linear combination
* Z = aX + bY (mod 2^w)
* for a, b - const, X, Y - vectors of w bits,
* where w is implicitly inferred, Z - a packed variable.
*
* This gadget is used four times in fooram:
* - PC' = PC + 1
* - load_addr = 2 * x + PC'
* - store_addr = x + PC
*/
template<typename FieldT>
class bar_gadget : public gadget<FieldT> {
public:
pb_linear_combination_array<FieldT> X;
FieldT a;
pb_linear_combination_array<FieldT> Y;
FieldT b;
pb_linear_combination<FieldT> Z_packed;
pb_variable_array<FieldT> Z_bits;
pb_variable<FieldT> result;
pb_variable_array<FieldT> overflow;
pb_variable_array<FieldT> unpacked_result;
std::shared_ptr<packing_gadget<FieldT> > unpack_result;
std::shared_ptr<packing_gadget<FieldT> > pack_Z;
size_t width;
bar_gadget(protoboard<FieldT> &pb,
const pb_linear_combination_array<FieldT> &X,
const FieldT &a,
const pb_linear_combination_array<FieldT> &Y,
const FieldT &b,
const pb_linear_combination<FieldT> &Z_packed,
const std::string &annotation_prefix);
void generate_r1cs_constraints();
void generate_r1cs_witness();
};
} // tinyram_snark
#include <tinyram_snark/gadgetlib1/gadgets/cpu_checkers/fooram/components/bar_gadget.tcc>
#endif // BAR_GADGET_HPP_
| [
"[email protected]"
] | |
ae777c0d695d52b5b27599491a16df71943d8b4c | 3442fa55ad884191a7b3f026a9632b7bffa89f36 | /qt-packages/Libraries/ThirdParty/eigen/Eigen/src/Geometry/Rotation2D.h | 6eb6de08de009579926823ccb1509c34af082c14 | [] | no_license | santiagoom/qt-packages | c109e683729b346ecdbc6d6f149fc3e43f1b0f07 | 6e2dc3b6f891003756b9566640a4315cd1bce41b | refs/heads/main | 2023-07-06T16:46:04.676604 | 2023-07-04T10:50:24 | 2023-07-04T10:50:24 | 312,006,629 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,061 | h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ROTATION2D_H
#define EIGEN_ROTATION2D_H
namespace Eigen {
/** \geometry_module \ingroup Geometry_Module
*
* \class Rotation2D
*
* \brief Represents a rotation/orientation in a 2 dimensional space.
*
* \tparam _Scalar the scalar type, i.e., the type of the coefficients
*
* This class is equivalent to a single scalar representing a counter clock wise rotation
* as a single angle in radian. It provides some additional features such as the automatic
* conversion from/to a 2x2 rotation matrix. Moreover this class aims to provide a similar
* interface to Quaternion in order to facilitate the writing of generic algorithms
* dealing with rotations.
*
* \sa class Quaternion, class Transform
*/
namespace internal {
template<typename _Scalar> struct traits<Rotation2D<_Scalar> >
{
typedef _Scalar Scalar;
};
} // end namespace internal
template<typename _Scalar>
class Rotation2D : public RotationBase<Rotation2D<_Scalar>,2>
{
typedef RotationBase<Rotation2D<_Scalar>,2> Base;
public:
using Base::operator*;
enum { Dim = 2 };
/** the scalar type of the coefficients */
typedef _Scalar Scalar;
typedef Matrix<Scalar,2,1> Vector2;
typedef Matrix<Scalar,2,2> Matrix2;
protected:
Scalar m_angle;
public:
/** Construct a 2D counter clock wise rotation from the angle \a a in radian. */
EIGEN_DEVICE_FUNC explicit inline Rotation2D(const Scalar& a) : m_angle(a) {}
/** Default constructor wihtout initialization. The represented rotation is undefined. */
EIGEN_DEVICE_FUNC Rotation2D() {}
/** Construct a 2D rotation from a 2x2 rotation matrix \a mat.
*
* \sa fromRotationMatrix()
*/
template<typename Derived>
EIGEN_DEVICE_FUNC explicit Rotation2D(const MatrixBase<Derived>& m)
{
fromRotationMatrix(m.derived());
}
/** \returns the rotation angle */
EIGEN_DEVICE_FUNC inline Scalar angle() const { return m_angle; }
/** \returns a read-write reference to the rotation angle */
EIGEN_DEVICE_FUNC inline Scalar& angle() { return m_angle; }
/** \returns the rotation angle in [0,2pi] */
EIGEN_DEVICE_FUNC inline Scalar smallestPositiveAngle() const {
Scalar tmp = numext::fmod(m_angle,Scalar(2*EIGEN_PI));
return tmp<Scalar(0) ? tmp + Scalar(2*EIGEN_PI) : tmp;
}
/** \returns the rotation angle in [-pi,pi] */
EIGEN_DEVICE_FUNC inline Scalar smallestAngle() const {
Scalar tmp = numext::fmod(m_angle,Scalar(2*EIGEN_PI));
if(tmp>Scalar(EIGEN_PI)) tmp -= Scalar(2*EIGEN_PI);
else if(tmp<-Scalar(EIGEN_PI)) tmp += Scalar(2*EIGEN_PI);
return tmp;
}
/** \returns the inverse rotation */
EIGEN_DEVICE_FUNC inline Rotation2D inverse() const { return Rotation2D(-m_angle); }
/** Concatenates two rotations */
EIGEN_DEVICE_FUNC inline Rotation2D operator*(const Rotation2D& other) const
{ return Rotation2D(m_angle + other.m_angle); }
/** Concatenates two rotations */
EIGEN_DEVICE_FUNC inline Rotation2D& operator*=(const Rotation2D& other)
{ m_angle += other.m_angle; return *this; }
/** Applies the rotation to a 2D vector */
EIGEN_DEVICE_FUNC Vector2 operator* (const Vector2& vec) const
{ return toRotationMatrix() * vec; }
template<typename Derived>
EIGEN_DEVICE_FUNC Rotation2D& fromRotationMatrix(const MatrixBase<Derived>& m);
EIGEN_DEVICE_FUNC Matrix2 toRotationMatrix() const;
/** Set \c *this from a 2x2 rotation matrix \a mat.
* In other words, this function extract the rotation angle from the rotation matrix.
*
* This method is an alias for fromRotationMatrix()
*
* \sa fromRotationMatrix()
*/
template<typename Derived>
EIGEN_DEVICE_FUNC Rotation2D& operator=(const MatrixBase<Derived>& m)
{ return fromRotationMatrix(m.derived()); }
/** \returns the spherical interpolation between \c *this and \a other using
* parameter \a t. It is in fact equivalent to a linear interpolation.
*/
EIGEN_DEVICE_FUNC inline Rotation2D slerp(const Scalar& t, const Rotation2D& other) const
{
Scalar dist = Rotation2D(other.m_angle-m_angle).smallestAngle();
return Rotation2D(m_angle + dist*t);
}
/** \returns \c *this with scalar type casted to \a NewScalarType
*
* Note that if \a NewScalarType is equal to the current scalar type of \c *this
* then this function smartly returns a const reference to \c *this.
*/
template<typename NewScalarType>
EIGEN_DEVICE_FUNC inline typename internal::cast_return_type<Rotation2D,Rotation2D<NewScalarType> >::type cast() const
{ return typename internal::cast_return_type<Rotation2D,Rotation2D<NewScalarType> >::type(*this); }
/** Copy constructor with scalar type conversion */
template<typename OtherScalarType>
EIGEN_DEVICE_FUNC inline explicit Rotation2D(const Rotation2D<OtherScalarType>& other)
{
m_angle = Scalar(other.angle());
}
EIGEN_DEVICE_FUNC static inline Rotation2D Identity() { return Rotation2D(0); }
/** \returns \c true if \c *this is approximately equal to \a other, within the precision
* determined by \a prec.
*
* \sa MatrixBase::isApprox() */
EIGEN_DEVICE_FUNC bool isApprox(const Rotation2D& other, const typename NumTraits<Scalar>::Real& prec = NumTraits<Scalar>::dummy_precision()) const
{ return internal::isApprox(m_angle,other.m_angle, prec); }
};
/** \ingroup Geometry_Module
* single precision 2D rotation type */
typedef Rotation2D<float> Rotation2Df;
/** \ingroup Geometry_Module
* double precision 2D rotation type */
typedef Rotation2D<double> Rotation2Dd;
/** Set \c *this from a 2x2 rotation matrix \a mat.
* In other words, this function extract the rotation angle
* from the rotation matrix.
*/
template<typename Scalar>
template<typename Derived>
EIGEN_DEVICE_FUNC Rotation2D<Scalar>& Rotation2D<Scalar>::fromRotationMatrix(const MatrixBase<Derived>& mat)
{
EIGEN_USING_STD(atan2)
EIGEN_STATIC_ASSERT(Derived::RowsAtCompileTime==2 && Derived::ColsAtCompileTime==2,YOU_MADE_A_PROGRAMMING_MISTAKE)
m_angle = atan2(mat.coeff(1,0), mat.coeff(0,0));
return *this;
}
/** Constructs and \returns an equivalent 2x2 rotation matrix.
*/
template<typename Scalar>
typename Rotation2D<Scalar>::Matrix2
EIGEN_DEVICE_FUNC Rotation2D<Scalar>::toRotationMatrix(void) const
{
EIGEN_USING_STD(sin)
EIGEN_USING_STD(cos)
Scalar sinA = sin(m_angle);
Scalar cosA = cos(m_angle);
return (Matrix2() << cosA, -sinA, sinA, cosA).finished();
}
} // end namespace Eigen
#endif // EIGEN_ROTATION2D_H
| [
"[email protected]"
] | |
b286e5d74c6b0a5507b9a5ab41277c126f20dad0 | ed43508ac111bc27b66bc019db26b112c271922b | /HelloTriangle/OpenGLES2Framework/InputManager.cpp | 71e84bd0ae85cf00833b449dacb73863df517e83 | [] | no_license | kc2809/Opengl3DFramework | 4a1b18b6d5ace3e23e3f3e259b1ba6b210f1bfe6 | c414634e907f7e5ef3c5c68ef82ee7ca2731e6fc | refs/heads/master | 2021-01-20T00:24:47.090000 | 2017-05-12T04:20:21 | 2017-05-12T04:20:21 | 89,129,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,206 | cpp | #include <stdlib.h>
#include "InputManager.h"
InputManager *InputManager::instance = 0;
InputManager::InputManager()
{
screenWidth = 1280;
screenHeight = 720;
keyPressed = 0;
state = -1;
}
InputManager *InputManager::GetInstance()
{
if (instance == 0)
{
instance = new InputManager;
}
return instance;
}
void InputManager::KeyPressed(char key){
switch (key)
{
case 'A':
{
keyPressed |= (1 << A);
}
break;
case 'W':
{
keyPressed |= (1 << W);
}
break;
case 'D':
{
keyPressed |= (1 << D);
}
break;
case 'S':
{
keyPressed |= (1 << S);
}
break;
case 'E':
{
keyPressed |= (1 << E);
}
break;
case 'X':
{
keyPressed |= (1 << X);
}
break;
case 37:
{
keyPressed |= (1 << LEFT);
}
break;
case 38:
{
keyPressed |= (1 << UP);
}
break;
case 39:
{
keyPressed |= (1 << RIGHT);
}
break;
case 40:
{
keyPressed |= (1 << DOWN);
}
break;
case 'J':
{
keyPressed |= (1 << J);
}
break;
case 'I':
{
keyPressed |= (1 << I);
}
break;
case 'L':
{
keyPressed |= (1 << L);
}
break;
case 'K':
{
keyPressed |= (1 << K);
}
break;
case 'N':
{
keyPressed |= (1 << N);
}
break;
case 'M':
{
keyPressed |= (1 << M);
}
break;
default:
break;
}
}
void InputManager::KeyReleased(char key)
{
switch (key)
{
case 'A':
{
keyPressed &= ~(1 << A);
}
break;
case 'W':
{
keyPressed &= ~(1 << W);
}
break;
case 'D':
{
keyPressed &= ~(1 << D);
}
break;
case 'S':
{
keyPressed &= ~(1 << S);
}
break;
case 'E':
{
keyPressed &= ~(1 << E);
}
break;
case 'X':
{
keyPressed &= ~(1 << X);
}
break;
case 37:
{
keyPressed &= ~(1 << LEFT);
}
break;
case 38:
{
keyPressed &= ~(1 << UP);
}
break;
case 39:
{
keyPressed &= ~(1 << RIGHT);
}
break;
case 40:
{
keyPressed &= ~(1 << DOWN);
}
break;
case 'J':
{
keyPressed &= ~(1 << J);
}
break;
case 'I':
{
keyPressed &= ~(1 << I);
}
break;
case 'L':
{
keyPressed &= ~(1 << L);
}
break;
case 'K':
{
keyPressed &= ~(1 << K);
}
break;
case 'N':
{
keyPressed &= ~(1 << N);
}
break;
case 'M':
{
keyPressed &= ~(1 << M);
}
break;
default:
break;
}
}
bool InputManager::IsPressed(char key)
{
return ((keyPressed &(1 << key)) != 0);
}
void InputManager::DestroyInstance()
{
if (instance)
{
delete instance;
instance = 0;
}
}
InputManager::~InputManager()
{
}
void InputManager::SetMouseClick(int type, int x, int y){
this->state = type;
if (type == 0){
xPressed = x - (float)screenWidth/2;
yPressed = -y + (float)screenHeight / 2;
}
else if(type>0){
xReleased = x - (float)screenWidth / 2;
yReleased = -y + (float)screenHeight / 2;
}
}
void InputManager::SetSize(int x, int y){
screenWidth = x;
screenHeight = y;
}
void InputManager::SetSize(GLfloat ratio){
screenWidth = SCREEN_DEFAULT_W;
screenHeight = (ratio!= 0.0)? SCREEN_DEFAULT_W/ratio: SCREEN_DEFAULT_H;
}
int InputManager::GetScreenWidth() const{
return screenWidth;
}
int InputManager::GetScreenHeight() const{
return screenHeight;
}
float InputManager::GetRatioWidth() const{
return (GLfloat) screenWidth / SCREEN_DEFAULT_W;
}
float InputManager::GetRatioHeight() const{
return (GLfloat) screenHeight/SCREEN_DEFAULT_H;
}
int InputManager::GetState(){
return state;
}
void InputManager::Reset(){
xPressed = -(float)screenWidth; xReleased = (float)screenWidth;
yPressed = -(float)screenHeight; yReleased = (float)screenHeight;
state = -1;
}
Vector2 InputManager::GetVectorDrag()
{
if (xPressed > screenWidth / 2 || xPressed<-screenWidth / 2 ||
xReleased>screenWidth / 2 || xReleased<-screenWidth / 2 ||
yPressed>screenHeight / 2 || yPressed<-screenHeight / 2 ||
yReleased>screenHeight / 2 || yReleased<-screenHeight / 2 ||
(abs(xReleased - xPressed) < 15) && (abs(yReleased - yPressed) < 15))
{
return Vector2(0.0, 0.0);
}
return Vector2(xReleased - xPressed, yReleased - yPressed);
}
Vector2 InputManager::GetCoordPress(){
return Vector2(xPressed, yPressed);
}
Vector2 InputManager::GetCoordRelease()
{
return Vector2(xReleased, yReleased);
}
| [
"[email protected]"
] | |
89a958a5f6174207984198288a1f4bda43aba12f | 524c0f8983fef4c282922a19a9437a320ccd0c45 | /aws-cpp-sdk-kendra/include/aws/kendra/model/SharePointConfiguration.h | 64ad795c7d2cb11d1f532ad2e329ea31b7ab5489 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | hardikmdev/aws-sdk-cpp | e79c39ad35433fbf41b3df7a90ac3b7bdb56728b | f34953a3f4cbd327db7c5340fcc140d63ac63e87 | refs/heads/main | 2023-09-06T03:43:07.646588 | 2021-11-16T20:27:23 | 2021-11-16T20:27:23 | 429,030,795 | 0 | 0 | Apache-2.0 | 2021-11-17T12:08:03 | 2021-11-17T12:08:02 | null | UTF-8 | C++ | false | false | 34,895 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/kendra/Kendra_EXPORTS.h>
#include <aws/kendra/model/SharePointVersion.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/kendra/model/DataSourceVpcConfiguration.h>
#include <aws/kendra/model/S3Path.h>
#include <aws/kendra/model/DataSourceToIndexFieldMapping.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace kendra
{
namespace Model
{
/**
* <p>Provides configuration information for connecting to a Microsoft SharePoint
* data source.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/kendra-2019-02-03/SharePointConfiguration">AWS
* API Reference</a></p>
*/
class AWS_KENDRA_API SharePointConfiguration
{
public:
SharePointConfiguration();
SharePointConfiguration(Aws::Utils::Json::JsonView jsonValue);
SharePointConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The version of Microsoft SharePoint that you are using as a data source.</p>
*/
inline const SharePointVersion& GetSharePointVersion() const{ return m_sharePointVersion; }
/**
* <p>The version of Microsoft SharePoint that you are using as a data source.</p>
*/
inline bool SharePointVersionHasBeenSet() const { return m_sharePointVersionHasBeenSet; }
/**
* <p>The version of Microsoft SharePoint that you are using as a data source.</p>
*/
inline void SetSharePointVersion(const SharePointVersion& value) { m_sharePointVersionHasBeenSet = true; m_sharePointVersion = value; }
/**
* <p>The version of Microsoft SharePoint that you are using as a data source.</p>
*/
inline void SetSharePointVersion(SharePointVersion&& value) { m_sharePointVersionHasBeenSet = true; m_sharePointVersion = std::move(value); }
/**
* <p>The version of Microsoft SharePoint that you are using as a data source.</p>
*/
inline SharePointConfiguration& WithSharePointVersion(const SharePointVersion& value) { SetSharePointVersion(value); return *this;}
/**
* <p>The version of Microsoft SharePoint that you are using as a data source.</p>
*/
inline SharePointConfiguration& WithSharePointVersion(SharePointVersion&& value) { SetSharePointVersion(std::move(value)); return *this;}
/**
* <p>The URLs of the Microsoft SharePoint site that contains the documents that
* should be indexed.</p>
*/
inline const Aws::Vector<Aws::String>& GetUrls() const{ return m_urls; }
/**
* <p>The URLs of the Microsoft SharePoint site that contains the documents that
* should be indexed.</p>
*/
inline bool UrlsHasBeenSet() const { return m_urlsHasBeenSet; }
/**
* <p>The URLs of the Microsoft SharePoint site that contains the documents that
* should be indexed.</p>
*/
inline void SetUrls(const Aws::Vector<Aws::String>& value) { m_urlsHasBeenSet = true; m_urls = value; }
/**
* <p>The URLs of the Microsoft SharePoint site that contains the documents that
* should be indexed.</p>
*/
inline void SetUrls(Aws::Vector<Aws::String>&& value) { m_urlsHasBeenSet = true; m_urls = std::move(value); }
/**
* <p>The URLs of the Microsoft SharePoint site that contains the documents that
* should be indexed.</p>
*/
inline SharePointConfiguration& WithUrls(const Aws::Vector<Aws::String>& value) { SetUrls(value); return *this;}
/**
* <p>The URLs of the Microsoft SharePoint site that contains the documents that
* should be indexed.</p>
*/
inline SharePointConfiguration& WithUrls(Aws::Vector<Aws::String>&& value) { SetUrls(std::move(value)); return *this;}
/**
* <p>The URLs of the Microsoft SharePoint site that contains the documents that
* should be indexed.</p>
*/
inline SharePointConfiguration& AddUrls(const Aws::String& value) { m_urlsHasBeenSet = true; m_urls.push_back(value); return *this; }
/**
* <p>The URLs of the Microsoft SharePoint site that contains the documents that
* should be indexed.</p>
*/
inline SharePointConfiguration& AddUrls(Aws::String&& value) { m_urlsHasBeenSet = true; m_urls.push_back(std::move(value)); return *this; }
/**
* <p>The URLs of the Microsoft SharePoint site that contains the documents that
* should be indexed.</p>
*/
inline SharePointConfiguration& AddUrls(const char* value) { m_urlsHasBeenSet = true; m_urls.push_back(value); return *this; }
/**
* <p>The Amazon Resource Name (ARN) of credentials stored in Secrets Manager. The
* credentials should be a user/password pair. If you use SharePoint Server, you
* also need to provide the sever domain name as part of the credentials. For more
* information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/data-source-sharepoint.html">Using
* a Microsoft SharePoint Data Source</a>. For more information about Secrets
* Manager, see <a
* href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">
* What Is Secrets Manager</a> in the <i>Secrets Manager </i> user guide.</p>
*/
inline const Aws::String& GetSecretArn() const{ return m_secretArn; }
/**
* <p>The Amazon Resource Name (ARN) of credentials stored in Secrets Manager. The
* credentials should be a user/password pair. If you use SharePoint Server, you
* also need to provide the sever domain name as part of the credentials. For more
* information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/data-source-sharepoint.html">Using
* a Microsoft SharePoint Data Source</a>. For more information about Secrets
* Manager, see <a
* href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">
* What Is Secrets Manager</a> in the <i>Secrets Manager </i> user guide.</p>
*/
inline bool SecretArnHasBeenSet() const { return m_secretArnHasBeenSet; }
/**
* <p>The Amazon Resource Name (ARN) of credentials stored in Secrets Manager. The
* credentials should be a user/password pair. If you use SharePoint Server, you
* also need to provide the sever domain name as part of the credentials. For more
* information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/data-source-sharepoint.html">Using
* a Microsoft SharePoint Data Source</a>. For more information about Secrets
* Manager, see <a
* href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">
* What Is Secrets Manager</a> in the <i>Secrets Manager </i> user guide.</p>
*/
inline void SetSecretArn(const Aws::String& value) { m_secretArnHasBeenSet = true; m_secretArn = value; }
/**
* <p>The Amazon Resource Name (ARN) of credentials stored in Secrets Manager. The
* credentials should be a user/password pair. If you use SharePoint Server, you
* also need to provide the sever domain name as part of the credentials. For more
* information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/data-source-sharepoint.html">Using
* a Microsoft SharePoint Data Source</a>. For more information about Secrets
* Manager, see <a
* href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">
* What Is Secrets Manager</a> in the <i>Secrets Manager </i> user guide.</p>
*/
inline void SetSecretArn(Aws::String&& value) { m_secretArnHasBeenSet = true; m_secretArn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of credentials stored in Secrets Manager. The
* credentials should be a user/password pair. If you use SharePoint Server, you
* also need to provide the sever domain name as part of the credentials. For more
* information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/data-source-sharepoint.html">Using
* a Microsoft SharePoint Data Source</a>. For more information about Secrets
* Manager, see <a
* href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">
* What Is Secrets Manager</a> in the <i>Secrets Manager </i> user guide.</p>
*/
inline void SetSecretArn(const char* value) { m_secretArnHasBeenSet = true; m_secretArn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of credentials stored in Secrets Manager. The
* credentials should be a user/password pair. If you use SharePoint Server, you
* also need to provide the sever domain name as part of the credentials. For more
* information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/data-source-sharepoint.html">Using
* a Microsoft SharePoint Data Source</a>. For more information about Secrets
* Manager, see <a
* href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">
* What Is Secrets Manager</a> in the <i>Secrets Manager </i> user guide.</p>
*/
inline SharePointConfiguration& WithSecretArn(const Aws::String& value) { SetSecretArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of credentials stored in Secrets Manager. The
* credentials should be a user/password pair. If you use SharePoint Server, you
* also need to provide the sever domain name as part of the credentials. For more
* information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/data-source-sharepoint.html">Using
* a Microsoft SharePoint Data Source</a>. For more information about Secrets
* Manager, see <a
* href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">
* What Is Secrets Manager</a> in the <i>Secrets Manager </i> user guide.</p>
*/
inline SharePointConfiguration& WithSecretArn(Aws::String&& value) { SetSecretArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of credentials stored in Secrets Manager. The
* credentials should be a user/password pair. If you use SharePoint Server, you
* also need to provide the sever domain name as part of the credentials. For more
* information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/data-source-sharepoint.html">Using
* a Microsoft SharePoint Data Source</a>. For more information about Secrets
* Manager, see <a
* href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">
* What Is Secrets Manager</a> in the <i>Secrets Manager </i> user guide.</p>
*/
inline SharePointConfiguration& WithSecretArn(const char* value) { SetSecretArn(value); return *this;}
/**
* <p> <code>TRUE</code> to include attachments to documents stored in your
* Microsoft SharePoint site in the index; otherwise, <code>FALSE</code>.</p>
*/
inline bool GetCrawlAttachments() const{ return m_crawlAttachments; }
/**
* <p> <code>TRUE</code> to include attachments to documents stored in your
* Microsoft SharePoint site in the index; otherwise, <code>FALSE</code>.</p>
*/
inline bool CrawlAttachmentsHasBeenSet() const { return m_crawlAttachmentsHasBeenSet; }
/**
* <p> <code>TRUE</code> to include attachments to documents stored in your
* Microsoft SharePoint site in the index; otherwise, <code>FALSE</code>.</p>
*/
inline void SetCrawlAttachments(bool value) { m_crawlAttachmentsHasBeenSet = true; m_crawlAttachments = value; }
/**
* <p> <code>TRUE</code> to include attachments to documents stored in your
* Microsoft SharePoint site in the index; otherwise, <code>FALSE</code>.</p>
*/
inline SharePointConfiguration& WithCrawlAttachments(bool value) { SetCrawlAttachments(value); return *this;}
/**
* <p>Set to <code>TRUE</code> to use the Microsoft SharePoint change log to
* determine the documents that need to be updated in the index. Depending on the
* size of the SharePoint change log, it may take longer for Amazon Kendra to use
* the change log than it takes it to determine the changed documents using the
* Amazon Kendra document crawler.</p>
*/
inline bool GetUseChangeLog() const{ return m_useChangeLog; }
/**
* <p>Set to <code>TRUE</code> to use the Microsoft SharePoint change log to
* determine the documents that need to be updated in the index. Depending on the
* size of the SharePoint change log, it may take longer for Amazon Kendra to use
* the change log than it takes it to determine the changed documents using the
* Amazon Kendra document crawler.</p>
*/
inline bool UseChangeLogHasBeenSet() const { return m_useChangeLogHasBeenSet; }
/**
* <p>Set to <code>TRUE</code> to use the Microsoft SharePoint change log to
* determine the documents that need to be updated in the index. Depending on the
* size of the SharePoint change log, it may take longer for Amazon Kendra to use
* the change log than it takes it to determine the changed documents using the
* Amazon Kendra document crawler.</p>
*/
inline void SetUseChangeLog(bool value) { m_useChangeLogHasBeenSet = true; m_useChangeLog = value; }
/**
* <p>Set to <code>TRUE</code> to use the Microsoft SharePoint change log to
* determine the documents that need to be updated in the index. Depending on the
* size of the SharePoint change log, it may take longer for Amazon Kendra to use
* the change log than it takes it to determine the changed documents using the
* Amazon Kendra document crawler.</p>
*/
inline SharePointConfiguration& WithUseChangeLog(bool value) { SetUseChangeLog(value); return *this;}
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* included in the index. Documents that don't match the patterns are excluded from
* the index. If a document matches both an inclusion pattern and an exclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline const Aws::Vector<Aws::String>& GetInclusionPatterns() const{ return m_inclusionPatterns; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* included in the index. Documents that don't match the patterns are excluded from
* the index. If a document matches both an inclusion pattern and an exclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline bool InclusionPatternsHasBeenSet() const { return m_inclusionPatternsHasBeenSet; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* included in the index. Documents that don't match the patterns are excluded from
* the index. If a document matches both an inclusion pattern and an exclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline void SetInclusionPatterns(const Aws::Vector<Aws::String>& value) { m_inclusionPatternsHasBeenSet = true; m_inclusionPatterns = value; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* included in the index. Documents that don't match the patterns are excluded from
* the index. If a document matches both an inclusion pattern and an exclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline void SetInclusionPatterns(Aws::Vector<Aws::String>&& value) { m_inclusionPatternsHasBeenSet = true; m_inclusionPatterns = std::move(value); }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* included in the index. Documents that don't match the patterns are excluded from
* the index. If a document matches both an inclusion pattern and an exclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline SharePointConfiguration& WithInclusionPatterns(const Aws::Vector<Aws::String>& value) { SetInclusionPatterns(value); return *this;}
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* included in the index. Documents that don't match the patterns are excluded from
* the index. If a document matches both an inclusion pattern and an exclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline SharePointConfiguration& WithInclusionPatterns(Aws::Vector<Aws::String>&& value) { SetInclusionPatterns(std::move(value)); return *this;}
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* included in the index. Documents that don't match the patterns are excluded from
* the index. If a document matches both an inclusion pattern and an exclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline SharePointConfiguration& AddInclusionPatterns(const Aws::String& value) { m_inclusionPatternsHasBeenSet = true; m_inclusionPatterns.push_back(value); return *this; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* included in the index. Documents that don't match the patterns are excluded from
* the index. If a document matches both an inclusion pattern and an exclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline SharePointConfiguration& AddInclusionPatterns(Aws::String&& value) { m_inclusionPatternsHasBeenSet = true; m_inclusionPatterns.push_back(std::move(value)); return *this; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* included in the index. Documents that don't match the patterns are excluded from
* the index. If a document matches both an inclusion pattern and an exclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline SharePointConfiguration& AddInclusionPatterns(const char* value) { m_inclusionPatternsHasBeenSet = true; m_inclusionPatterns.push_back(value); return *this; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* excluded from the index. Documents that don't match the patterns are included in
* the index. If a document matches both an exclusion pattern and an inclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline const Aws::Vector<Aws::String>& GetExclusionPatterns() const{ return m_exclusionPatterns; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* excluded from the index. Documents that don't match the patterns are included in
* the index. If a document matches both an exclusion pattern and an inclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline bool ExclusionPatternsHasBeenSet() const { return m_exclusionPatternsHasBeenSet; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* excluded from the index. Documents that don't match the patterns are included in
* the index. If a document matches both an exclusion pattern and an inclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline void SetExclusionPatterns(const Aws::Vector<Aws::String>& value) { m_exclusionPatternsHasBeenSet = true; m_exclusionPatterns = value; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* excluded from the index. Documents that don't match the patterns are included in
* the index. If a document matches both an exclusion pattern and an inclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline void SetExclusionPatterns(Aws::Vector<Aws::String>&& value) { m_exclusionPatternsHasBeenSet = true; m_exclusionPatterns = std::move(value); }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* excluded from the index. Documents that don't match the patterns are included in
* the index. If a document matches both an exclusion pattern and an inclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline SharePointConfiguration& WithExclusionPatterns(const Aws::Vector<Aws::String>& value) { SetExclusionPatterns(value); return *this;}
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* excluded from the index. Documents that don't match the patterns are included in
* the index. If a document matches both an exclusion pattern and an inclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline SharePointConfiguration& WithExclusionPatterns(Aws::Vector<Aws::String>&& value) { SetExclusionPatterns(std::move(value)); return *this;}
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* excluded from the index. Documents that don't match the patterns are included in
* the index. If a document matches both an exclusion pattern and an inclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline SharePointConfiguration& AddExclusionPatterns(const Aws::String& value) { m_exclusionPatternsHasBeenSet = true; m_exclusionPatterns.push_back(value); return *this; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* excluded from the index. Documents that don't match the patterns are included in
* the index. If a document matches both an exclusion pattern and an inclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline SharePointConfiguration& AddExclusionPatterns(Aws::String&& value) { m_exclusionPatternsHasBeenSet = true; m_exclusionPatterns.push_back(std::move(value)); return *this; }
/**
* <p>A list of regular expression patterns. Documents that match the patterns are
* excluded from the index. Documents that don't match the patterns are included in
* the index. If a document matches both an exclusion pattern and an inclusion
* pattern, the document is not included in the index.</p> <p>The regex is applied
* to the display URL of the SharePoint document.</p>
*/
inline SharePointConfiguration& AddExclusionPatterns(const char* value) { m_exclusionPatternsHasBeenSet = true; m_exclusionPatterns.push_back(value); return *this; }
inline const DataSourceVpcConfiguration& GetVpcConfiguration() const{ return m_vpcConfiguration; }
inline bool VpcConfigurationHasBeenSet() const { return m_vpcConfigurationHasBeenSet; }
inline void SetVpcConfiguration(const DataSourceVpcConfiguration& value) { m_vpcConfigurationHasBeenSet = true; m_vpcConfiguration = value; }
inline void SetVpcConfiguration(DataSourceVpcConfiguration&& value) { m_vpcConfigurationHasBeenSet = true; m_vpcConfiguration = std::move(value); }
inline SharePointConfiguration& WithVpcConfiguration(const DataSourceVpcConfiguration& value) { SetVpcConfiguration(value); return *this;}
inline SharePointConfiguration& WithVpcConfiguration(DataSourceVpcConfiguration&& value) { SetVpcConfiguration(std::move(value)); return *this;}
/**
* <p>A list of <code>DataSourceToIndexFieldMapping</code> objects that map
* Microsoft SharePoint attributes to custom fields in the Amazon Kendra index. You
* must first create the index fields using the <code>UpdateIndex</code> operation
* before you map SharePoint attributes. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* Data Source Fields</a>.</p>
*/
inline const Aws::Vector<DataSourceToIndexFieldMapping>& GetFieldMappings() const{ return m_fieldMappings; }
/**
* <p>A list of <code>DataSourceToIndexFieldMapping</code> objects that map
* Microsoft SharePoint attributes to custom fields in the Amazon Kendra index. You
* must first create the index fields using the <code>UpdateIndex</code> operation
* before you map SharePoint attributes. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* Data Source Fields</a>.</p>
*/
inline bool FieldMappingsHasBeenSet() const { return m_fieldMappingsHasBeenSet; }
/**
* <p>A list of <code>DataSourceToIndexFieldMapping</code> objects that map
* Microsoft SharePoint attributes to custom fields in the Amazon Kendra index. You
* must first create the index fields using the <code>UpdateIndex</code> operation
* before you map SharePoint attributes. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* Data Source Fields</a>.</p>
*/
inline void SetFieldMappings(const Aws::Vector<DataSourceToIndexFieldMapping>& value) { m_fieldMappingsHasBeenSet = true; m_fieldMappings = value; }
/**
* <p>A list of <code>DataSourceToIndexFieldMapping</code> objects that map
* Microsoft SharePoint attributes to custom fields in the Amazon Kendra index. You
* must first create the index fields using the <code>UpdateIndex</code> operation
* before you map SharePoint attributes. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* Data Source Fields</a>.</p>
*/
inline void SetFieldMappings(Aws::Vector<DataSourceToIndexFieldMapping>&& value) { m_fieldMappingsHasBeenSet = true; m_fieldMappings = std::move(value); }
/**
* <p>A list of <code>DataSourceToIndexFieldMapping</code> objects that map
* Microsoft SharePoint attributes to custom fields in the Amazon Kendra index. You
* must first create the index fields using the <code>UpdateIndex</code> operation
* before you map SharePoint attributes. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* Data Source Fields</a>.</p>
*/
inline SharePointConfiguration& WithFieldMappings(const Aws::Vector<DataSourceToIndexFieldMapping>& value) { SetFieldMappings(value); return *this;}
/**
* <p>A list of <code>DataSourceToIndexFieldMapping</code> objects that map
* Microsoft SharePoint attributes to custom fields in the Amazon Kendra index. You
* must first create the index fields using the <code>UpdateIndex</code> operation
* before you map SharePoint attributes. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* Data Source Fields</a>.</p>
*/
inline SharePointConfiguration& WithFieldMappings(Aws::Vector<DataSourceToIndexFieldMapping>&& value) { SetFieldMappings(std::move(value)); return *this;}
/**
* <p>A list of <code>DataSourceToIndexFieldMapping</code> objects that map
* Microsoft SharePoint attributes to custom fields in the Amazon Kendra index. You
* must first create the index fields using the <code>UpdateIndex</code> operation
* before you map SharePoint attributes. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* Data Source Fields</a>.</p>
*/
inline SharePointConfiguration& AddFieldMappings(const DataSourceToIndexFieldMapping& value) { m_fieldMappingsHasBeenSet = true; m_fieldMappings.push_back(value); return *this; }
/**
* <p>A list of <code>DataSourceToIndexFieldMapping</code> objects that map
* Microsoft SharePoint attributes to custom fields in the Amazon Kendra index. You
* must first create the index fields using the <code>UpdateIndex</code> operation
* before you map SharePoint attributes. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* Data Source Fields</a>.</p>
*/
inline SharePointConfiguration& AddFieldMappings(DataSourceToIndexFieldMapping&& value) { m_fieldMappingsHasBeenSet = true; m_fieldMappings.push_back(std::move(value)); return *this; }
/**
* <p>The Microsoft SharePoint attribute field that contains the title of the
* document.</p>
*/
inline const Aws::String& GetDocumentTitleFieldName() const{ return m_documentTitleFieldName; }
/**
* <p>The Microsoft SharePoint attribute field that contains the title of the
* document.</p>
*/
inline bool DocumentTitleFieldNameHasBeenSet() const { return m_documentTitleFieldNameHasBeenSet; }
/**
* <p>The Microsoft SharePoint attribute field that contains the title of the
* document.</p>
*/
inline void SetDocumentTitleFieldName(const Aws::String& value) { m_documentTitleFieldNameHasBeenSet = true; m_documentTitleFieldName = value; }
/**
* <p>The Microsoft SharePoint attribute field that contains the title of the
* document.</p>
*/
inline void SetDocumentTitleFieldName(Aws::String&& value) { m_documentTitleFieldNameHasBeenSet = true; m_documentTitleFieldName = std::move(value); }
/**
* <p>The Microsoft SharePoint attribute field that contains the title of the
* document.</p>
*/
inline void SetDocumentTitleFieldName(const char* value) { m_documentTitleFieldNameHasBeenSet = true; m_documentTitleFieldName.assign(value); }
/**
* <p>The Microsoft SharePoint attribute field that contains the title of the
* document.</p>
*/
inline SharePointConfiguration& WithDocumentTitleFieldName(const Aws::String& value) { SetDocumentTitleFieldName(value); return *this;}
/**
* <p>The Microsoft SharePoint attribute field that contains the title of the
* document.</p>
*/
inline SharePointConfiguration& WithDocumentTitleFieldName(Aws::String&& value) { SetDocumentTitleFieldName(std::move(value)); return *this;}
/**
* <p>The Microsoft SharePoint attribute field that contains the title of the
* document.</p>
*/
inline SharePointConfiguration& WithDocumentTitleFieldName(const char* value) { SetDocumentTitleFieldName(value); return *this;}
/**
* <p>A Boolean value that specifies whether local groups are disabled
* (<code>True</code>) or enabled (<code>False</code>). </p>
*/
inline bool GetDisableLocalGroups() const{ return m_disableLocalGroups; }
/**
* <p>A Boolean value that specifies whether local groups are disabled
* (<code>True</code>) or enabled (<code>False</code>). </p>
*/
inline bool DisableLocalGroupsHasBeenSet() const { return m_disableLocalGroupsHasBeenSet; }
/**
* <p>A Boolean value that specifies whether local groups are disabled
* (<code>True</code>) or enabled (<code>False</code>). </p>
*/
inline void SetDisableLocalGroups(bool value) { m_disableLocalGroupsHasBeenSet = true; m_disableLocalGroups = value; }
/**
* <p>A Boolean value that specifies whether local groups are disabled
* (<code>True</code>) or enabled (<code>False</code>). </p>
*/
inline SharePointConfiguration& WithDisableLocalGroups(bool value) { SetDisableLocalGroups(value); return *this;}
inline const S3Path& GetSslCertificateS3Path() const{ return m_sslCertificateS3Path; }
inline bool SslCertificateS3PathHasBeenSet() const { return m_sslCertificateS3PathHasBeenSet; }
inline void SetSslCertificateS3Path(const S3Path& value) { m_sslCertificateS3PathHasBeenSet = true; m_sslCertificateS3Path = value; }
inline void SetSslCertificateS3Path(S3Path&& value) { m_sslCertificateS3PathHasBeenSet = true; m_sslCertificateS3Path = std::move(value); }
inline SharePointConfiguration& WithSslCertificateS3Path(const S3Path& value) { SetSslCertificateS3Path(value); return *this;}
inline SharePointConfiguration& WithSslCertificateS3Path(S3Path&& value) { SetSslCertificateS3Path(std::move(value)); return *this;}
private:
SharePointVersion m_sharePointVersion;
bool m_sharePointVersionHasBeenSet;
Aws::Vector<Aws::String> m_urls;
bool m_urlsHasBeenSet;
Aws::String m_secretArn;
bool m_secretArnHasBeenSet;
bool m_crawlAttachments;
bool m_crawlAttachmentsHasBeenSet;
bool m_useChangeLog;
bool m_useChangeLogHasBeenSet;
Aws::Vector<Aws::String> m_inclusionPatterns;
bool m_inclusionPatternsHasBeenSet;
Aws::Vector<Aws::String> m_exclusionPatterns;
bool m_exclusionPatternsHasBeenSet;
DataSourceVpcConfiguration m_vpcConfiguration;
bool m_vpcConfigurationHasBeenSet;
Aws::Vector<DataSourceToIndexFieldMapping> m_fieldMappings;
bool m_fieldMappingsHasBeenSet;
Aws::String m_documentTitleFieldName;
bool m_documentTitleFieldNameHasBeenSet;
bool m_disableLocalGroups;
bool m_disableLocalGroupsHasBeenSet;
S3Path m_sslCertificateS3Path;
bool m_sslCertificateS3PathHasBeenSet;
};
} // namespace Model
} // namespace kendra
} // namespace Aws
| [
"[email protected]"
] | |
114bffdadde5db25d7f647e61b4197f94e58adca | e5a37a543ca382ed3eaab28c37d267b04ad667c0 | /probrems/SRM452div2/easy.cpp | 3f8eb49f0c2a1326ea3f54707d8cd19a82a0f599 | [] | no_license | akawashiro/competitiveProgramming | 6dfbe626c2e2433d5e702e9431ee9de2c41337ed | ee8a582c80dbd5716ae900a02e8ea67ff8daae4b | refs/heads/master | 2018-09-02T19:49:22.460865 | 2018-06-30T05:45:51 | 2018-06-30T05:45:51 | 71,694,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 169 | cpp | class EggCartons{
public:
int minCartons(int n)
{
int ans=n/8;
for(ans;0<=ans;ans--)
if((n-ans*8)%6==0)
return ans+(n-ans*8)/6;
return -1;
}
};
| [
"[email protected]"
] | |
1cf04fb44e72a33e73922f450d40eb9eba4e894b | b0ceac64262a5e14e320a4d821b90e184cf89cb5 | /src/Graphics/XGPU.h | 670c4ea94d076a20ed4d00b61e2fdda2eb70ebcc | [] | no_license | RegulusImpact/sadboy | 7bf82e825c662d5f0f13d867ef43a839eb0d1e9d | 89ac9618539a5d09789aceff066719be50c9b7a5 | refs/heads/master | 2022-11-04T03:25:51.950233 | 2018-04-17T22:26:19 | 2018-04-17T22:26:19 | 128,100,622 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,852 | h | // XGPU.h
#ifndef XGPU_H
#define XGPU_H
// uintX_t
#include <cstdint>
// size_t
#include <cstddef>
// X11 Support
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
// Interfaces
#include "iGPU.h"
// Other Classes
#include "../MMU.h"
#include "../Utils.h"
#include "../InterruptService.h"
// X11 programming reference
// http://math.msu.su/~vvb/2course/Borisenko/CppProjects/GWindow/xintro.html
class XGPU: public iGPU {
private:
// implementation specific
Display* display;
int screen;
Window window;
GC gc;
Colormap cmap;
uint32_t black, white;
XColor palette[4];
uint8_t windowScalar;
// functionality dependent
MMU* mmu;
void init_x();
void close_x();
void init_palette();
public:
XGPU();
XGPU(MMU* m, uint8_t ws);
~XGPU();
// Getters
std::uint8_t GetControl();
std::uint8_t GetLCDStat();
std::uint8_t GetScrollY();
std::uint8_t GetScrollX();
std::uint8_t GetScanline();
std::uint8_t GetLYC();
// Setters
void SetControl(std::uint8_t val);
void SetLCDStat(std::uint8_t val);
void SetScrollY(std::uint8_t val);
void SetScrollX(std::uint8_t val);
void SetScanline(std::uint8_t val);
void SetLYC(std::uint8_t val);
void IncrementScanline();
void ResetScanline();
void TriggerVBlank();
void TriggerLCDStat(uint8_t statusBit);
// Special Getters - pull values from memory at the startup / start step
void Sync();
// Special Setters - set values back into memory at end step
void SyncMemory();
// Rendering
void Step(uint32_t clockStep);
void Hblank();
void RenderScanline();
void RenderFrame();
void Draw(uint8_t color, uint8_t y, uint8_t x);
void Draw(XColor color, uint8_t y, uint8_t x);
void DumpTiles();
void DumpTileset();
};
#endif
| [
"[email protected]"
] | |
bf37ac63d9480d67754ef888d40be76c40094ab2 | 8d57489e484b2def01f27a8a00e41ee6932a4905 | /Multi4/NothingisSimple.cc | 96e8d56319a61f0b21b2bc2989329bf2a9dfba5b | [] | no_license | athelare/SourceCode-ACM | f8c3a5d4f308de3ffaabd371c85f22a4a0225613 | b0385ef8409f3f3b3dbf77e9ad326d13fed9171c | refs/heads/master | 2020-03-24T07:54:17.769303 | 2018-11-25T01:26:55 | 2018-11-25T01:26:55 | 142,578,771 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | cc | #include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef pair<int, int> P;
bool compare(P&a,P&b){
return a.second < b.second;
}
int main()
{
int T;
scanf("%d", &T);
int problems;
P p[105];
long long totalStudents;
while(T--){
scanf("%d%lld", &problems, &totalStudents);
for (int i = 0; i < problems;++i)
scanf("%d%d", &p[i].first, &p[i].second);
sort(p, p + problems, compare);
long long cur=1;
int i;
for (i = 0; i <= problems && cur <= totalStudents; ++i){
if(i == problems){
i++;
break;
}
cur *= (p[i].first + p[i].second);
}
printf("%d\n", i-1);
}
return 0;
} | [
"[email protected]"
] | |
a362331c7fb78c7879f77309c73aa2312f988a25 | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_gui_basics/widgets/juce_ToolbarItemComponent.cpp | f6c053ac71c70775cd26321c315f649df4318ea1 | [] | no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,755 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
BEGIN_JUCE_NAMESPACE
//==============================================================================
ToolbarItemFactory::ToolbarItemFactory()
{
}
ToolbarItemFactory::~ToolbarItemFactory()
{
}
//==============================================================================
class ItemDragAndDropOverlayComponent : public Component
{
public:
ItemDragAndDropOverlayComponent()
: isDragging (false)
{
setAlwaysOnTop (true);
setRepaintsOnMouseActivity (true);
setMouseCursor (MouseCursor::DraggingHandCursor);
}
void paint (Graphics& g)
{
ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
if (isMouseOverOrDragging()
&& tc != nullptr
&& tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
{
g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
g.drawRect (0, 0, getWidth(), getHeight(),
jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
}
}
void mouseDown (const MouseEvent& e)
{
isDragging = false;
ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
if (tc != nullptr)
{
tc->dragOffsetX = e.x;
tc->dragOffsetY = e.y;
}
}
void mouseDrag (const MouseEvent& e)
{
if (! (isDragging || e.mouseWasClicked()))
{
isDragging = true;
DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
if (dnd != nullptr)
{
dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
if (tc != nullptr)
{
tc->isBeingDragged = true;
if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
tc->setVisible (false);
}
}
}
}
void mouseUp (const MouseEvent&)
{
isDragging = false;
ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
if (tc != nullptr)
{
tc->isBeingDragged = false;
Toolbar* const tb = tc->getToolbar();
if (tb != nullptr)
tb->updateAllItemPositions (true);
else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
delete tc;
}
}
void parentSizeChanged()
{
setBounds (0, 0, getParentWidth(), getParentHeight());
}
private:
//==============================================================================
bool isDragging;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
};
//==============================================================================
ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
const String& labelText,
const bool isBeingUsedAsAButton_)
: Button (labelText),
itemId (itemId_),
mode (normalMode),
toolbarStyle (Toolbar::iconsOnly),
dragOffsetX (0),
dragOffsetY (0),
isActive (true),
isBeingDragged (false),
isBeingUsedAsAButton (isBeingUsedAsAButton_)
{
// Your item ID can't be 0!
jassert (itemId_ != 0);
}
ToolbarItemComponent::~ToolbarItemComponent()
{
overlayComp = nullptr;
}
Toolbar* ToolbarItemComponent::getToolbar() const
{
return dynamic_cast <Toolbar*> (getParentComponent());
}
bool ToolbarItemComponent::isToolbarVertical() const
{
const Toolbar* const t = getToolbar();
return t != nullptr && t->isVertical();
}
void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
{
if (toolbarStyle != newStyle)
{
toolbarStyle = newStyle;
repaint();
resized();
}
}
void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
{
if (isBeingUsedAsAButton)
getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
over, down, *this);
if (toolbarStyle != Toolbar::iconsOnly)
{
const int indent = contentArea.getX();
int y = indent;
int h = getHeight() - indent * 2;
if (toolbarStyle == Toolbar::iconsWithText)
{
y = contentArea.getBottom() + indent / 2;
h -= contentArea.getHeight();
}
getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
getButtonText(), *this);
}
if (! contentArea.isEmpty())
{
Graphics::ScopedSaveState ss (g);
g.reduceClipRegion (contentArea);
g.setOrigin (contentArea.getX(), contentArea.getY());
paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
}
}
void ToolbarItemComponent::resized()
{
if (toolbarStyle != Toolbar::textOnly)
{
const int indent = jmin (proportionOfWidth (0.08f),
proportionOfHeight (0.08f));
contentArea = Rectangle<int> (indent, indent,
getWidth() - indent * 2,
toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
: (getHeight() - indent * 2));
}
else
{
contentArea = Rectangle<int>();
}
contentAreaChanged (contentArea);
}
void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
{
if (mode != newMode)
{
mode = newMode;
repaint();
if (mode == normalMode)
{
overlayComp = nullptr;
}
else if (overlayComp == nullptr)
{
addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
overlayComp->parentSizeChanged();
}
resized();
}
}
END_JUCE_NAMESPACE
| [
"ow3nskip"
] | ow3nskip |
412e6a33c580074dfd38eadfe8d460b98aef462e | f7b4e2e208d3bc12321924bbcddfa6501cf258ef | /CodeforcesProblems/Two-gram.cf.cpp | 0b90eaee8351dbd58fef3c5efa706a39812c44ee | [] | no_license | Anik-Modak/OnlineJudgeProblemSolution | b476fecf1d112893bc71ea6012a17e26de75254d | a19076d346b1d6028cd75b4ee90b82c4e01cb9dc | refs/heads/master | 2020-05-04T18:24:37.248578 | 2019-04-26T19:53:13 | 2019-04-26T19:53:13 | 179,351,861 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
string s;
cin>>s;
int mx=0,c,id;
string sub[n];
for(int i=0; i<n-1; i++)
{
char b[3];
b[0]=s[i];
b[1]=s[i+1];
b[2]='\0';
sub[i]=b;
}
for(int i=0; i<n-1; i++)
{
c=0;
for(int j=i; j<n-1; j++) if(sub[i]==sub[j]) c++;
if(mx<c){
mx=c;
id=i;
}
}
cout<<sub[id]<<endl;
return 0;
}
| [
"[email protected]"
] | |
68eeec2dbb666225fa7064a6b9a875a6136f0347 | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_StagAnimBlueprint_parameters.hpp | 61f309fe6a3d5e6a4bedebb91ce964c4ef2ad168 | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 704 | hpp | #pragma once
// ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_StagAnimBlueprint_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function StagAnimBlueprint.StagAnimBlueprint_C.ExecuteUbergraph_StagAnimBlueprint
struct UStagAnimBlueprint_C_ExecuteUbergraph_StagAnimBlueprint_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
8ce150239c46454e1f5255d318ba74d6a0c2220b | 4a34f4ffda4039415c1105aa2d90487b7a67ca6e | /src/crypto/hmac_sha512.h | 950b6bf1b193ad826b9de61610fc0e64bffba93d | [
"MIT"
] | permissive | fast-bitcoin/FastBitcoin | 017f77b7c6bf766bf4ee6666c55bdfef71432e8f | f2cc12d1ff8521e103d1290c0c1d9c3ec09b4472 | refs/heads/master | 2020-06-29T00:52:32.317049 | 2019-09-11T05:32:59 | 2019-09-11T05:32:59 | 200,390,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 793 | h | // Copyright (c) 2014 The Fastbitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef FASTBITCOIN_CRYPTO_HMAC_SHA512_H
#define FASTBITCOIN_CRYPTO_HMAC_SHA512_H
#include "crypto/sha512.h"
#include <stdint.h>
#include <stdlib.h>
/** A hasher class for HMAC-SHA-512. */
class CHMAC_SHA512
{
private:
CSHA512 outer;
CSHA512 inner;
public:
static const size_t OUTPUT_SIZE = 64;
CHMAC_SHA512(const unsigned char* key, size_t keylen);
CHMAC_SHA512& Write(const unsigned char* data, size_t len)
{
inner.Write(data, len);
return *this;
}
void Finalize(unsigned char hash[OUTPUT_SIZE]);
};
#endif // FASTBITCOIN_CRYPTO_HMAC_SHA512_H
| [
"[email protected]"
] | |
99e1f27fc1a358a1ed7552c07a16552fb93a65b3 | 78a851fa6c5c5c35e95dc3cef779faed74c2790e | /test/backend/p2p.cpp | ba01e2fb8909163c18fb35b03a5faae3557e61cc | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | BiomedNMR/aura | 5fc671594376869a5337fdf122eaa14a1c04312e | d151492fde7035cf2a6726554597a24b17f221bc | refs/heads/develop | 2020-12-28T19:32:55.781464 | 2018-03-08T14:09:19 | 2018-03-08T14:09:19 | 34,114,517 | 1 | 0 | null | 2015-04-17T12:08:22 | 2015-04-17T12:08:22 | null | UTF-8 | C++ | false | false | 377 | cpp | #define BOOST_TEST_MODULE backend.p2p
#include <vector>
#include <stdio.h>
#include <boost/test/unit_test.hpp>
#include <boost/aura/backend.hpp>
using namespace boost::aura::backend;
// basic
// _____________________________________________________________________________
BOOST_AUTO_TEST_CASE(basic) {
initialize();
std::vector<int> mtrx = get_peer_access_matrix();
}
| [
"[email protected]"
] | |
3c92dcc06c03937cf01f2acd402f33c535b4a622 | 47de1c3720ee7df453ce7904e1767798bbc5f1c7 | /src/mavencore/maven/String.cpp | 0590727c14045f61ec1f5448fa5062330a5e0527 | [] | no_license | elliotchance/maven | 28a20058d8b83c0b364680f573b329941ad0573a | ea189bf5cea7cacf15ecfe071762d5560323d0ab | refs/heads/master | 2021-01-10T21:01:14.871430 | 2010-05-04T08:20:32 | 2010-05-04T08:20:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,223 | cpp | #include "String.h"
#include "Quad.h"
#include "../external/md5.h"
#include "../external/sha1.h"
#include "BoundsException.h"
namespace maven {
String::String() {
String("");
}
String::String(const mbyte* newString) {
len = strlen(newString);
s = (mbyte*) malloc(len + 1);
catchMalloc(s, "maven.String");
std::memmove(s, newString, len);
s[len] = 0;
// NOTE: we cannot simply use 'new maven::String()' this would cause an infinite
// loop of nested objects.
className = (maven::String*) malloc(sizeof(maven::String));
className->s = (char*) "maven.String";
className->retain = 1;
}
mint String::length() {
return len;
}
String* String::substring(mint length) {
mbyte* s2 = (mbyte*) malloc(length + 1);
strncpy(s2, s, length);
return new String(s2);
}
String* String::substring(mint start, mint length) {
mbyte* s2 = (mbyte*) malloc(length + 1);
strncpy(s2, s + start, length);
return new String(s2);
}
String* String::append(String* str) {
// FIXME: if(str == NULL) throw ObjectNilException;
mbyte* newString = new mbyte[len + str->len + 1];
memmove(newString, s, len);
memmove(newString + len, str->s, str->len);
newString[len + str->len] = 0;
len += str->len;
free(s);
s = newString;
return this;
}
mint String::compare(String* otherString) {
// FIXME: if(str == NULL) throw ObjectNilException;
return strcmp(s, otherString->s);
}
mboolean String::isEmpty() {
return (len == 0);
}
void String::erase() {
len = 0;
free(s);
}
mint String::indexOf(maven::String* otherString) {
// FIXME: if(str == NULL) throw ObjectNilException;
if(otherString->len > len) return -1;
for(int i = 0; i < len; ++i) {
if(s[i] == otherString->s[0]) {
// make sure all the other characters match in sequence
for(int j = 1; j < otherString->len; ++j)
if(s[i + j] != otherString->s[j]) return -1;
return i;
}
}
return -1;
}
mboolean String::toBoolean() {
return length() != 0;
}
mbyte String::toByte() {
return (mbyte) atoi(s);
}
mchar String::toCharacter() {
return (mchar) atoi(s);
}
maven::Data* String::toData() {
maven::Data* d = new maven::Data();
d->writeString(this);
return d;
}
mdouble String::toDouble() {
return atof(s);
}
mfloat String::toFloat() {
return atof(s);
}
mint String::toInteger() {
return atoi(s);
}
mlong String::toLong() {
return (mlong) atoi(s);
}
mquad String::toQuad() {
return (mquad) atof(s);
}
mshort String::toShort() {
return (mshort) atoi(s);
}
maven::String* String::toString() {
return this;
}
maven::String* String::valueOf(mboolean value) {
if(value)
return new maven::String("true");
return new maven::String("false");
}
maven::String* String::valueOf(mbyte value) {
char buf[20];
std::sprintf(buf, "%d", (int) value);
return new maven::String(buf);
}
maven::String* String::valueOf(mchar value) {
char buf[20];
std::sprintf(buf, "%d", (int) value);
return new maven::String(buf);
}
maven::String* String::valueOf(mdouble value) {
char buf[20];
std::sprintf(buf, "%g", value);
return new maven::String(buf);
}
maven::String* String::valueOf(mfloat value) {
char buf[20];
std::sprintf(buf, "%g", value);
return new maven::String(buf);
}
maven::String* String::valueOf(mint value) {
char buf[20];
std::sprintf(buf, "%d", value);
return new maven::String(buf);
}
maven::String* String::valueOf(mlong value) {
char buf[20];
std::sprintf(buf, "%d", (int) value);
return new maven::String(buf);
}
maven::String* String::valueOf(mquad value) {
char buf[20];
std::sprintf(buf, "%g", (double) value);
return new maven::String(buf);
}
maven::String* String::valueOf(mshort value) {
char buf[20];
std::sprintf(buf, "%d", (int) value);
return new maven::String(buf);
}
mint String::levenshtein(maven::String* otherString) {
if(len == 0) return otherString->len;
if(otherString->len == 0) return len;
// good form to declare a TYPEDEF
typedef std::vector< std::vector<int> > Tmatrix;
Tmatrix matrix(len + 1);
// Size the vectors in the 2nd dimension. Unfortunately C++ doesn't
// allow for allocation on declaration of 2nd dimension of vec of vec
for (int i = 0; i <= len; i++)
matrix[i].resize(otherString->len + 1);
// step 2
for(int i = 0; i <= len; i++) matrix[i][0] = i;
for(int j = 0; j <= otherString->len; j++) matrix[0][j] = j;
// step 3
for(int i = 1; i <= len; i++) {
const char s_i = s[i - 1];
// step 4
for(int j = 1; j <= otherString->len; j++) {
const char t_j = otherString->s[j - 1];
// step 5
int cost;
if(s_i == t_j) cost = 0;
else cost = 1;
// step 6
const int above = matrix[i - 1][j];
const int left = matrix[i][j - 1];
const int diag = matrix[i - 1][j - 1];
int cell = std::min(above + 1, std::min(left + 1, diag + cost));
// step 6A: Cover transposition, in addition to deletion,
// insertion and substitution. This step is taken from:
// Berghel, Hal ; Roach, David : "An Extension of Ukkonen's
// Enhanced Dynamic Programming ASM Algorithm"
// (http://www.acm.org/~hlb/publications/asm/asm.html)
if(i > 2 && j > 2) {
int trans = matrix[i - 2][j - 2] + 1;
if(s[i - 2] != t_j) trans++;
if(s_i != otherString->s[j - 2]) trans++;
if(cell > trans) cell = trans;
}
matrix[i][j] = cell;
}
}
// step 7
return matrix[len][otherString->len];
}
maven::String* String::md5() {
MD5_CTX ctx;
MD5* md5;
// init md5
md5->MD5Init(&ctx);
// update with our string
md5->MD5Update(&ctx, (unsigned char*) s, len);
// create the hash
unsigned char buff[16] = "";
md5->MD5Final((unsigned char*) buff, &ctx);
char asciihash[33];
int p = 0;
for(int i = 0; i < 16; i++) {
std::sprintf((char*) &asciihash[p], "%02x", buff[i]);
p += 2;
}
asciihash[32] = '\0';
return new maven::String((char*) asciihash);
}
maven::String* String::sha1() {
SHA1 sha;
unsigned int message_digest[5];
sha << (char*) s;
if(!sha.Result(message_digest))
return new String("");
char r[21];
std::sprintf(r, "%x%x%x%x%x", message_digest[0], message_digest[1],
message_digest[2], message_digest[3], message_digest[4]);
return new maven::String(r);
}
maven::String* String::operator_plus(maven::String* str2) {
maven::String* r = new maven::String();
r->s = this->s;
r->len = this->len;
r->append(str2);
return r;
}
maven::String* String::operator_plus(mquad str2) {
maven::String* r = new maven::String();
r->s = this->s;
r->len = this->len;
r->append(maven::String::valueOf(str2));
return r;
}
mboolean String::operator_equal(maven::String* str2) {
return this->compare(str2) == 0;
}
maven::String* String::operator_assignplus(maven::String* str2) {
maven::String* temp = this->append(str2);
// FIXME: free pergatory memory
s = temp->s;
len = temp->len;
return this;
}
mchar String::charAt(int index) {
// FIXME: must be in range
if(index >= len)
throw new maven::BoundsException();
return s[index];
}
}
| [
"[email protected]"
] | |
99fcfc5bea28df7c4680401ab11bc5f2fe942928 | bd33acd4b4d09619a0a0f839a4f0af60f2c5a67b | /cocos2d-x/cocos/editor-support/cocostudio/ActionTimeline/CCSkeletonNode.cpp | 42b9f2a7604fd7a2ed294b72fb58161dddadbbb5 | [] | no_license | StevenCoober/LHR2 | 656ea49ed0b5a8f35bd3c3bc1ec136bae52ddd8e | 19b5bfffe39702360fabfc46c7e50d7f7327374e | refs/heads/master | 2022-02-11T05:36:28.085709 | 2016-03-27T11:30:18 | 2016-03-27T11:30:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,771 | cpp | /****************************************************************************
Copyright (c) 2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCSkeletonNode.h"
#include "base/CCDirector.h"
#include "math/TransformUtils.h"
#include "renderer/CCRenderer.h"
#include "renderer/ccGLStateCache.h"
#include "renderer/CCGLProgramState.h"
#include <stack>
using namespace cocos2d::GL;
NS_TIMELINE_BEGIN
SkeletonNode* SkeletonNode::create()
{
SkeletonNode* skeletonNode = new (std::nothrow) SkeletonNode();
if (skeletonNode && skeletonNode->init())
{
skeletonNode->autorelease();
return skeletonNode;
}
CC_SAFE_DELETE(skeletonNode);
return nullptr;
}
bool SkeletonNode::init()
{
_rackLength = _rackWidth = 20;
updateVertices();
setGLProgramState(cocos2d::GLProgramState::getOrCreateWithGLProgramName(cocos2d::GLProgram::SHADER_NAME_POSITION_COLOR_NO_MVP));
_rootSkeleton = this;
return true;
}
cocos2d::Rect SkeletonNode::getBoundingBox() const
{
float minx, miny, maxx, maxy = 0;
minx = miny = maxx = maxy;
cocos2d::Rect boundingBox = getVisibleSkinsRect();
bool first = true;
if (!boundingBox.equals(cocos2d::Rect::ZERO))
{
minx = boundingBox.getMinX();
miny = boundingBox.getMinY();
maxx = boundingBox.getMaxX();
maxy = boundingBox.getMaxY();
first = false;
}
auto allbones = getAllSubBones();
for (const auto& bone : allbones)
{
cocos2d::Rect r = RectApplyAffineTransform(bone->getVisibleSkinsRect(),
bone->getNodeToParentAffineTransform(bone->getRootSkeletonNode()));
if (r.equals(cocos2d::Rect::ZERO))
continue;
if (first)
{
minx = r.getMinX();
miny = r.getMinY();
maxx = r.getMaxX();
maxy = r.getMaxY();
first = false;
}
else
{
minx = MIN(r.getMinX(), minx);
miny = MIN(r.getMinY(), miny);
maxx = MAX(r.getMaxX(), maxx);
maxy = MAX(r.getMaxY(), maxy);
}
}
boundingBox.setRect(minx, miny, maxx - minx, maxy - miny);
return RectApplyAffineTransform(boundingBox, this->getNodeToParentAffineTransform());;
}
SkeletonNode::SkeletonNode()
: BoneNode()
, _subBonesDirty(true)
, _subBonesOrderDirty(true)
, _batchedVeticesCount(0)
{
}
SkeletonNode::~SkeletonNode()
{
for (auto &bonepair : _subBonesMap)
{
setRootSkeleton(bonepair.second, nullptr);
}
}
void SkeletonNode::updateVertices()
{
if (_rackLength != _squareVertices[6].x - _anchorPointInPoints.x || _rackWidth != _squareVertices[3].y - _anchorPointInPoints.y)
{
const float radiusl = _rackLength * .5f;
const float radiusw = _rackWidth * .5f;
const float radiusl_2 = radiusl * .25f;
const float radiusw_2 = radiusw * .25f;
_squareVertices[5].y = _squareVertices[2].y = _squareVertices[1].y = _squareVertices[6].y
= _squareVertices[0].x = _squareVertices[4].x = _squareVertices[7].x = _squareVertices[3].x = .0f;
_squareVertices[5].x = -radiusl; _squareVertices[0].y = -radiusw;
_squareVertices[6].x = radiusl; _squareVertices[3].y = radiusw;
_squareVertices[1].x = radiusl_2; _squareVertices[7].y = radiusw_2;
_squareVertices[2].x = -radiusl_2; _squareVertices[4].y = -radiusw_2;
for (int i = 0; i < 8; i++)
{
_squareVertices[i] += _anchorPointInPoints;
}
_transformUpdated = _transformDirty = _inverseDirty = _contentSizeDirty = true;
}
}
void SkeletonNode::updateColor()
{
for (unsigned int i = 0; i < 8; i++)
{
_squareColors[i] = _rackColor;
}
_transformUpdated = _transformDirty = _inverseDirty = _contentSizeDirty = true;
}
void SkeletonNode::visit(cocos2d::Renderer *renderer, const cocos2d::Mat4& parentTransform, uint32_t parentFlags)
{
// quick return if not visible. children won't be drawn.
if (!_visible)
{
return;
}
uint32_t flags = processParentFlags(parentTransform, parentFlags);
// IMPORTANT:
// To ease the migration to v3.0, we still support the Mat4 stack,
// but it is deprecated and your code should not rely on it
_director->pushMatrix(cocos2d::MATRIX_STACK_TYPE::MATRIX_STACK_MODEL);
_director->loadMatrix(cocos2d::MATRIX_STACK_TYPE::MATRIX_STACK_MODEL, _modelTransform);
int i = 0;
if (!_children.empty())
{
sortAllChildren();
// draw children zOrder < 0
for (; i < _children.size(); i++)
{
auto node = _children.at(i);
if (node && node->getLocalZOrder() < 0)
node->visit(renderer, _modelTransform, flags);
else
break;
}
for (auto it = _children.cbegin() + i; it != _children.cend(); ++it)
(*it)->visit(renderer, _modelTransform, flags);
}
checkSubBonesDirty();
for (const auto& bone : _subOrderedAllBones)
{
visitSkins(renderer, bone);
}
if (_isRackShow)
{
this->draw(renderer, _modelTransform, flags);
// batch draw all sub bones
_batchBoneCommand.init(_globalZOrder, _modelTransform, parentFlags);
_batchBoneCommand.func = CC_CALLBACK_0(SkeletonNode::batchDrawAllSubBones, this, renderer, _modelTransform);
renderer->addCommand(&_batchBoneCommand);
}
_director->popMatrix(cocos2d::MATRIX_STACK_TYPE::MATRIX_STACK_MODEL);
// FIX ME: Why need to set _orderOfArrival to 0??
// Please refer to https://github.com/cocos2d/cocos2d-x/pull/6920
// reset for next frame
// _orderOfArrival = 0;
}
void SkeletonNode::draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags)
{
_customCommand.init(_globalZOrder, transform, flags);
_customCommand.func = CC_CALLBACK_0(SkeletonNode::onDraw, this, transform, flags);
renderer->addCommand(&_customCommand);
for (int i = 0; i < 8; ++i)
{
cocos2d::Vec4 pos;
pos.x = _squareVertices[i].x; pos.y = _squareVertices[i].y; pos.z = _positionZ;
pos.w = 1;
_modelTransform.transformVector(&pos);
_noMVPVertices[i] = cocos2d::Vec3(pos.x, pos.y, pos.z) / pos.w;
}
}
void SkeletonNode::batchDrawAllSubBones(cocos2d::Renderer* renderer, const cocos2d::Mat4 &transform)
{
checkSubBonesDirty();
_batchedVeticesCount = 0;
for (const auto& bone : _subOrderedAllBones)
{
batchBoneDrawToSkeleton(renderer, bone);
}
cocos2d::Vec3* vetices = _batchedBoneVetices.data();
cocos2d::Color4F* veticesColor = _batchedBoneColors.data();
getGLProgram()->use();
getGLProgram()->setUniformsForBuiltins(transform);
cocos2d::GL::enableVertexAttribs(cocos2d::GL::VERTEX_ATTRIB_FLAG_POSITION | cocos2d::GL::VERTEX_ATTRIB_FLAG_COLOR);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glVertexAttribPointer(cocos2d::GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, 0, vetices);
glVertexAttribPointer(cocos2d::GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_FLOAT, GL_FALSE, 0, veticesColor);
cocos2d::GL::blendFunc(_blendFunc.src, _blendFunc.dst);
#ifdef CC_STUDIO_ENABLED_VIEW
glLineWidth(1);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
for (int i = 0; i < _batchedVeticesCount; i += 8)
{
glDrawArrays(GL_TRIANGLE_FAN, i, 4);
glDrawArrays(GL_LINE_LOOP, i + 4, 4);
}
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, _batchedVeticesCount);
#else
for (int i = 0; i < _batchedVeticesCount; i += 4)
{
glDrawArrays(GL_TRIANGLE_FAN, i, 4);
}
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, _batchedVeticesCount);
#endif //CC_STUDIO_ENABLED_VIEW
}
void SkeletonNode::onDraw(const cocos2d::Mat4 &transform, uint32_t flags)
{
getGLProgram()->use();
getGLProgram()->setUniformsForBuiltins(transform);
cocos2d::GL::enableVertexAttribs(cocos2d::GL::VERTEX_ATTRIB_FLAG_POSITION | cocos2d::GL::VERTEX_ATTRIB_FLAG_COLOR);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glVertexAttribPointer(cocos2d::GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, 0, _noMVPVertices);
glVertexAttribPointer(cocos2d::GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_FLOAT, GL_FALSE, 0, _squareColors);
cocos2d::GL::blendFunc(_blendFunc.src, _blendFunc.dst);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDrawArrays(GL_TRIANGLE_STRIP, 4, 4);
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, 8);
}
void SkeletonNode::changeSkins(const std::map<std::string, std::string>& boneSkinNameMap)
{
for (auto &boneskin : boneSkinNameMap)
{
auto bone = getBoneNode(boneskin.first);
if (nullptr != bone)
bone->displaySkin(boneskin.second, true);
}
}
void SkeletonNode::changeSkins(const std::string& skinGroupName)
{
auto suit = _skinGroupMap.find(skinGroupName);
if (suit != _skinGroupMap.end())
{
changeSkins(suit->second);
}
}
BoneNode* SkeletonNode::getBoneNode(const std::string& boneName)
{
auto iter = _subBonesMap.find(boneName);
if (iter != _subBonesMap.end())
{
return iter->second;
}
return nullptr;
}
const cocos2d::Map<std::string, BoneNode*>& SkeletonNode::getAllSubBonesMap() const
{
return _subBonesMap;
}
void SkeletonNode::addSkinGroup(std::string groupName, std::map<std::string, std::string> boneSkinNameMap)
{
_skinGroupMap.insert(std::make_pair(groupName, boneSkinNameMap));
}
void SkeletonNode::checkSubBonesDirty()
{
if (_subBonesDirty)
{
updateOrderedAllbones();
_subBonesDirty = false;
}
if (_subBonesOrderDirty)
{
sortOrderedAllBones();
_subBonesOrderDirty = false;
}
}
void SkeletonNode::updateOrderedAllbones()
{
_subOrderedAllBones.clear();
// update sub bones, get All Visible SubBones
// get all sub bones as visit with visible
std::stack<BoneNode*> boneStack;
for (const auto& bone : _childBones)
{
if (bone->isVisible())
boneStack.push(bone);
}
while (boneStack.size() > 0)
{
auto top = boneStack.top();
_subOrderedAllBones.pushBack(top);
boneStack.pop();
auto topChildren = top->getChildBones();
for (const auto& childbone : topChildren)
{
if (childbone->isVisible())
boneStack.push(childbone);
}
}
}
void SkeletonNode::sortOrderedAllBones()
{
std::sort(_subOrderedAllBones.begin(), _subOrderedAllBones.end(), cocos2d::nodeComparisonLess);
}
NS_TIMELINE_END | [
"[email protected]"
] | |
254adc8f18061e87bbc490cd5f0bc46daf2638f5 | 7da7a716ff643ed79d5cd3ffa379a34b08fcf04b | /src/Vector3d.cpp | 5fb4fabdd756761f9bc053d9ac9b1efd0066fdc0 | [
"Unlicense"
] | permissive | KPO-2020-2021/zad5_1-ArkadiuszPlaza | ca8f0cfeaf42c5b382b8a6c85f27a90edf908f51 | 9704661214370268133b669e083c4e7a9c838b9a | refs/heads/master | 2023-05-28T10:10:18.540745 | 2021-06-05T19:40:56 | 2021-06-05T19:40:56 | 368,957,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25 | cpp | #include "Vector3d.hh"
| [
"[email protected]"
] | |
02ce3675c42cc93ef0cc9adbfa1d792aa378f7de | cec8cb82f07b6e3abe7d0746580f78c24f1da6a3 | /Lab 3/Lab 3/MySegment.cpp | 377f61d7fff803414ef5ff4363996cf14943f25b | [] | no_license | thomas-bouvier/insa-cpp-4eii | c5d7c0be9b97ce671c322217005c30cffbed8b5a | 754774c81cdb62e55d808db739bea3aae92afe43 | refs/heads/master | 2021-08-24T00:47:50.237651 | 2017-12-07T09:42:24 | 2017-12-07T09:42:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 253 | cpp | #include "MySegment.hpp"
MySegment::MySegment(int x, int y, Color color, int dx, int dy) : MyGraphicObject(x, y, color), dx_(dx), dy_(dy) {
}
MySegment::~MySegment() {
}
void MySegment::draw() {
Draw::line(x_, y_, x_ + dx_, y_ + dy_, 2, color_);
} | [
"[email protected]"
] | |
e6d29116d72c4bcaa8428d9f8379e106a16600d6 | 4177144cd307688db23efa1d7eae098544491010 | /InsertSort.h | 394c8ea0c538be2223f5d621b66b4d811dd5f5eb | [] | no_license | Monster-Girl/Data-Structure | e5dc5572e51fafcba5178bb758104aa916ad80fe | 532239885ffc6f0f62fc57f795d6f47227acdbce | refs/heads/master | 2021-01-17T12:46:56.822113 | 2017-08-17T09:28:40 | 2017-08-17T09:28:40 | 84,074,359 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 538 | h | #include<iostream>
using namespace std;
#include<assert.h>
void PrintSort(int* a, size_t n)
{
for (size_t i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void InsertSort(int* a, size_t n)
{
assert(a);
for (size_t i = 0; i < n-1; i++)
{
int tmp = a[i + 1];
int end = i;
while (end >= 0)
{
if (a[end]>tmp)
{
a[end + 1] = a[end];
--end;
}
else
break;
}
a[end + 1] = tmp;
PrintSort(a, 10);
}
}
void TestSort()
{
int a[] = { 2, 5, 4, 9, 3, 6, 8, 7, 1, 0 };
InsertSort(a, 10);
} | [
"[email protected]"
] | |
825aaaf147c0230e53cbd35a0cb34b22a461e517 | 8ddf1ae9e439d54e0ceda6705e0bc49df4c3c39f | /VR_Chatting/Plugins/AdvancedSessionsPlugin-4-22/AdvancedSessions/AdvancedSteamSessions/Intermediate/Build/Mac/UE4Editor/Development/AdvancedSteamSessions/Module.AdvancedSteamSessions.gen.cpp | cc941c5037350c948e1fd76d11e4397ca45cc17d | [
"MIT"
] | permissive | Yuni-Children/VR_Chatting | 4a951a33035c30247cf0c1b5930fcd05e4227e2c | 8cec0c224a9ca10ce32093901b5a0bc2323cc4a8 | refs/heads/master | 2022-07-15T00:58:36.856074 | 2020-05-19T10:23:15 | 2020-05-19T10:23:15 | 264,922,475 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,226 | cpp | // This file is automatically generated at compile-time to include some subset of the user-created cpp files.
#include "/Users/jhyeok/Downloads/senal_voice-2/Plugins/AdvancedSessionsPlugin-4-22/AdvancedSessions/AdvancedSteamSessions/Intermediate/Build/Mac/UE4Editor/Inc/AdvancedSteamSessions/AdvancedSteamFriendsLibrary.gen.cpp"
#include "/Users/jhyeok/Downloads/senal_voice-2/Plugins/AdvancedSessionsPlugin-4-22/AdvancedSessions/AdvancedSteamSessions/Intermediate/Build/Mac/UE4Editor/Inc/AdvancedSteamSessions/AdvancedSteamSessions.init.gen.cpp"
#include "/Users/jhyeok/Downloads/senal_voice-2/Plugins/AdvancedSessionsPlugin-4-22/AdvancedSessions/AdvancedSteamSessions/Intermediate/Build/Mac/UE4Editor/Inc/AdvancedSteamSessions/AdvancedSteamWorkshopLibrary.gen.cpp"
#include "/Users/jhyeok/Downloads/senal_voice-2/Plugins/AdvancedSessionsPlugin-4-22/AdvancedSessions/AdvancedSteamSessions/Intermediate/Build/Mac/UE4Editor/Inc/AdvancedSteamSessions/SteamRequestGroupOfficersCallbackProxy.gen.cpp"
#include "/Users/jhyeok/Downloads/senal_voice-2/Plugins/AdvancedSessionsPlugin-4-22/AdvancedSessions/AdvancedSteamSessions/Intermediate/Build/Mac/UE4Editor/Inc/AdvancedSteamSessions/SteamWSRequestUGCDetailsCallbackProxy.gen.cpp"
| [
"[email protected]"
] | |
b94bfd47f79278a3ec4de42be21b95be28a627ef | 10549922d157ce67b6a32759b09a8dee78aebe9c | /searchfw/coresearchfw/server/src/searchserver.cpp | 223e569cda897f23b0915e67af63992cbbcfd47e | [] | no_license | SymbianSource/oss.FCL.sf.app.organizer | c8be5fbc1c5d8fc7d54a63bb1793f8db823fa3d7 | e15734d1943a012120b188fe3ffd5dd7594d145f | refs/heads/master | 2021-01-10T22:41:15.449986 | 2010-11-03T11:42:22 | 2010-11-03T11:42:22 | 70,369,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,926 | cpp | /*
* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Create server
*
*/
// INCLUDE FILES
#include <searchplugin.h>
#include <e32def.h>
#include <ecom/ecom.h>
#include "searchserver.h"
#include "searchserversession.h"
#include "searchserverdefines.h"
// ====================================== MEMBER FUNCTIONS =========================================
// -------------------------------------------------------------------------------------------------
// CSearchServer::NewL
// Symbian OS 2 phased constructor.
// -------------------------------------------------------------------------------------------------
//
CSearchServer* CSearchServer::NewL()
{
CSearchServer* self = CSearchServer::NewLC();
CleanupStack::Pop( self );
return self;
}
// -------------------------------------------------------------------------------------------------
// CSearchServer::NewLC
// Symbian OS 2 phased constructor.
// -------------------------------------------------------------------------------------------------
//
CSearchServer* CSearchServer::NewLC()
{
CSearchServer* self = new( ELeave ) CSearchServer( EPriority );
CleanupStack::PushL( self );
self->ConstructL();
return self;
}
// -------------------------------------------------------------------------------------------------
// CSearchServer::~CSearchServer
// Destructor.
// -------------------------------------------------------------------------------------------------
//
CSearchServer::~CSearchServer()
{
if ( iSearchPluginInterface )
{
delete iSearchPluginInterface;
iSearchPluginInterface = NULL;
}
if (iServertimer)
{
delete iServertimer;
iServertimer = NULL;
}
}
// -------------------------------------------------------------------------------------------------
// CSearchServer::SessionCreated
// Informs the server that a session was created
// -------------------------------------------------------------------------------------------------
//
void CSearchServer::SessionCreatedL( )
{
iIncrementCount++;
if (iServertimer)
{
delete iServertimer;
iServertimer = NULL;
}
}
// -------------------------------------------------------------------------------------------------
// CSearchServer::SessionDestroyed
// Increments the session count
// -------------------------------------------------------------------------------------------------
//
void CSearchServer::SessionDestroyedL( )
{
iIncrementCount--;
//create sever timer
iServertimer = CSearchseverShutdown::NewL();
//start the timer
iServertimer->Start( );
}
// -------------------------------------------------------------------------------------------------
// CSearchServer::NewSessionL
// Creates a server-side session object.
// -------------------------------------------------------------------------------------------------
//
CSession2* CSearchServer::NewSessionL(
const TVersion& aVersion,
const RMessage2& ) const
{
if ( !User::QueryVersionSupported( Version(), aVersion ) )
{
User::Leave( KErrNotSupported );
}
return CSearchServerSession::NewL( *CONST_CAST( CSearchServer*, this ), iSearchPluginInterface );
}
// -------------------------------------------------------------------------------------------------
// CSearchServer::CSearchServer
// Performs the first phase of two phase construction.
// -------------------------------------------------------------------------------------------------
//
CSearchServer::CSearchServer( TInt aPriority )
: CServer2( aPriority )
{
}
// -------------------------------------------------------------------------------------------------
// CSearchServer::ConstructL
// Performs the second phase construction.
// -------------------------------------------------------------------------------------------------
//
void CSearchServer::ConstructL()
{
StartL(KServerName);
iSearchPluginInterface = CSearchPluginInterface::NewL();
iSearchPluginInterface->InstantiateAllPlugInsL();
}
// -------------------------------------------------------------------------------------------------
// CSearchServer::RunError
// Handling Error
// -------------------------------------------------------------------------------------------------
//
TInt CSearchServer::RunError( TInt aError )
{
if ( aError != KErrNone )
{
}
return KErrNone;
}
// End of File
| [
"none@none"
] | none@none |
303e5643f216aeba767f48684e6018308341c932 | e341516d373fa9ac86a8c13538252dad024aea0e | /src/Game.h | 28bff9236d91ffd1497ec7faddfe83186c04aee0 | [] | no_license | ajorians/nTowers | f992c8b671de8e4b66a6e4d74b236b4992b4690e | d10f52df2a87f01d02853d0858d3dfc6624af535 | refs/heads/master | 2020-03-26T10:19:27.097687 | 2016-01-26T21:15:43 | 2016-01-26T21:15:43 | 22,314,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,203 | h | #ifndef GAME_H
#define GAME_H
//#define USE_GRAPHIC_YOU_WIN//Use a static "You Win!!!" image instead of the animated one
extern "C"
{
#include <os.h>
#include "SDL/SDL.h"
#include "TowersLib/TowersLib.h"
}
#ifndef USE_GRAPHIC_YOU_WIN
#include "Message.h"
#endif
#include "Background.h"
#include "Config.h"
#include "Selector.h"
#include "Metrics.h"
#include "Timer.h"
#include "GameDrawer.h"
#include "Defines.h"
class Game
{
public:
Game(SDL_Surface* pScreen, TowersLib towers, int nLevelNumber, Config* pConfig);
~Game();
bool Loop();
protected:
bool CheckStateConditions();
bool PollEvents();
void DrawSelector();
void UpdateDisplay();
void Move(Direction eDirection);
void SetSpot(int nValue);
void IncrementSpot();
void Undo();
void Redo();
protected:
SDL_Surface *m_pScreen;//Does not own
Background m_Background;
#ifdef USE_GRAPHIC_YOU_WIN
SDL_Surface *m_pWinGraphic;
#else
Message m_YouWinMessage;
#endif
GameDrawer m_Drawer;
TowersLib m_Towers;
int m_nLevelNumber;
Config *m_pConfig;//Does not own
Selector m_Selector;
bool m_bGameOver;
Metrics m_BoardMetrics;
Timer m_Timer;
};
#endif
| [
"[email protected]"
] | |
3bcbf4f9d0073c44f5099c1321a14a2a1022f630 | 8b87aef4563331dbb9ec4c6d824bf5732c91da9e | /lab2.2/lab2.ino | 949b65a8c1a50e7034fa605295ad9db7cf667048 | [] | no_license | VuNguyen1994/Vehicle_System_Testbed | 10f4778d472e746b57c99a50330f097b51e7af30 | cb4e380fd9a9501db7a024cb1fac16786944c1a3 | refs/heads/master | 2023-03-12T14:10:48.814179 | 2021-03-06T07:18:01 | 2021-03-06T07:18:01 | 338,233,725 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,972 | ino | int ledpin[] = {13,11,5,6};
int i;
int pass;
int a,b,c,d;
int ina,inb,inc,ind;
int f0 = 2560;
int f1 = 1;
int f3 = 1;
int f4 = 1;
int flag0 =0, flag1=0, flag3=0, flag4 = 0; //init = 0, no impact
int count0 = 0;
int attempt = 0;
int cycle8bit = 245; // 245/1000 ms
void setup() {
pass = random(10000);
a = pass/1000;
b = (pass%1000)/100;
c = (pass%100)/10;
d = pass%10;
Serial.begin(9600);
Serial.println(pass);
for (i = 0; i <= 3; i++){
pinMode(ledpin[i],OUTPUT);
digitalWrite(ledpin[i],LOW);
}
noInterrupts();
// Timer 0
TCCR0A = 0;
TCCR0B = 0;
TCNT0 = 0;
TCCR0B |= (1 << WGM02); // CTC mode
TCCR0B |= (1 << CS02); // 256 prescaler
TIMSK0 |= (1 << OCIE0A);
OCR0A= 16000000 / (256 * f0);
// Timer 1
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
TIMSK1=0;
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS12) | (0<<CS11) | (0<<CS10); // 256 prescaler
TIMSK1 |= (1 << OCIE1A);
OCR1A= 16000000 / (256 * f1);
// Timer 3
TCCR3A=0;
TCCR3B=0;
TCNT3=0;
TIMSK3=0;
TCCR3B |= (1<<WGM32);
TCCR3B |= (1<<CS32) | (0<<CS31) | (0<<CS30);
TIMSK3 |= (1<<OCIE3A);
OCR3A= 16000000 / (256 * f3);
//Timer 4
TCCR4A = 0;
TCCR4B = 0;
TCNT4 = 0;
TCCR4B |= (1 << WGM42); // CTC mode
TCCR4B |= (1 << CS42)| (0<<CS41) | (0<<CS40); // 256 prescaler
TIMSK4 |= (1 << OCIE4A);
OCR4A= 16000000 / (256 * f4);
interrupts();
}
void loop() {
if(Serial.available() > 0) {
int inpass = Serial.parseInt();
attempt++;
if (attempt > 5){
Serial.println("Max attempt reached. Please reload!");
}
else if (attempt == 5){
Serial.println("Max attempt reached: 5. LEDs solid!");
flag0=2; flag1=2; flag3=2; flag4 = 2; // 2 to solid LED
}
else{ //only for attempt < 5
Serial.print("I received: "); Serial.println(inpass,DEC);
Serial.print("No. attempt: "); Serial.println(attempt,DEC);
ina = inpass/1000;
inb = (inpass%1000)/100;
inc = (inpass%100)/10;
ind = inpass%10;
if(a != ina){
f0 +=100;
cycle8bit /= 2;
}
else{
flag0 = 1;
}
if(b != inb){
f1 += 2;
OCR1A= 16000000 / (256 * f1);
}
else{
flag1 = 1;
}
if(c != inc){
f3 += 2;
OCR3A= 16000000 / (256 * f3);
}
else{
flag3=1;
}
if(d != ind){
f4 += 2;
OCR4A= 16000000 / (256 * f4);
}
else{
flag4=1;
}
}
}
}
ISR(TIMER0_COMPA_vect){
if (flag0 == 0){
count0 += 1;
if (count0 >= cycle8bit){
count0 = 0;
digitalWrite(ledpin[0],!digitalRead(ledpin[0]));
}
}
else if (flag0 == 1) {
digitalWrite(ledpin[0],LOW);
detachInterrupt(digitalPinToInterrupt(ledpin[0]));
}
else if (flag0 == 2) {
digitalWrite(ledpin[0],HIGH);
detachInterrupt(digitalPinToInterrupt(ledpin[0]));
}
}
ISR(TIMER1_COMPA_vect){
if (flag1 == 0){
digitalWrite(ledpin[1],!digitalRead(ledpin[1]));
}
else if (flag1 == 1)
{
digitalWrite(ledpin[1],LOW);
detachInterrupt(digitalPinToInterrupt(ledpin[1]));
}
else if (flag1 == 2) {
digitalWrite(ledpin[1],HIGH);
detachInterrupt(digitalPinToInterrupt(ledpin[1]));
}
}
ISR(TIMER3_COMPA_vect){
if (flag3 == 0){
digitalWrite(ledpin[2],!digitalRead(ledpin[2]));
}
else if (flag3 == 1)
{
digitalWrite(ledpin[2],LOW);
detachInterrupt(digitalPinToInterrupt(ledpin[2]));
}
else if (flag3 == 2) {
digitalWrite(ledpin[2],HIGH);
detachInterrupt(digitalPinToInterrupt(ledpin[2]));
}
}
ISR(TIMER4_COMPA_vect){
if (flag4 == 0){
digitalWrite(ledpin[3],!digitalRead(ledpin[3]));
}
else if (flag4 == 1)
{
digitalWrite(ledpin[3],LOW);
detachInterrupt(digitalPinToInterrupt(ledpin[3]));
}
else if (flag4 == 2) {
digitalWrite(ledpin[3],HIGH);
detachInterrupt(digitalPinToInterrupt(ledpin[3]));
}
}
| [
"[email protected]"
] | |
381c972160061ed7872af844ec06cf4c4fc17ac7 | a273e939b03b140cb2c092d17d2c13a4e5c4147c | /SemiExpression/ITokenCollection.h | 9a0c0d73d361d41558109a48e4e973cd513cce2a | [] | no_license | Deepika-L/LexicalScanner | bbd1c0d985d1a0d4e395be2a645ba9ff9a2d158b | 8b73881a3c332d7915870ac93a0095608434b960 | refs/heads/master | 2016-08-13T00:48:24.438384 | 2016-02-18T03:31:49 | 2016-02-18T03:31:49 | 51,974,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,830 | h | #ifndef ITOKCOLLECTION_H
#define ITOKCOLLECTION_H
/////////////////////////////////////////////////////////////////////////
// ITokCollection.h - package for the ITokCollection interface //
// ver 1.0 //
// Language: Visual C++ 2015 //
// Platform: HP Pavilion dv6, Windows 10 //
// Application: Parser component, CSE687 - Object Oriented Design //
// Source: Jim Fawcett, CST 4-187, Syracuse University //
// (315) 443-3948, [email protected] //
// Author: Deepika Lakshmanan //
// [email protected] //
/////////////////////////////////////////////////////////////////////////
/*
Module Purpose:
===============
ITokCollection is an interface that supports substitution of different
types of scanners for parsing. In this solution, we illustrate that
by binding SemiExp to this interface. This is illustrated in the test stubs
for the SemiExpression module.
Maintenance History:
====================
ver 1.0 : 02 Feb 2016
*/
struct ITokCollection
{
virtual bool get(bool clear = true) = 0;
virtual size_t length() = 0;
virtual std::string& operator[](int n) = 0;
virtual size_t find(const std::string& tok) = 0;
virtual void push_back(const std::string& tok) = 0;
virtual bool merge(const std::string& firstTok, const std::string& secondTok) = 0;
virtual bool remove(const std::string& tok) = 0;
virtual bool remove(size_t i) = 0;
virtual void toLower() = 0;
virtual void trimFront() = 0;
virtual void clear() = 0;
virtual std::string show(bool showNewLines = false) = 0;
virtual ~ITokCollection() {};
};
#endif
| [
"[email protected]"
] | |
37fe87e50554f2d42280cf57802addef15212a7a | 5d7d74570f37e0c4aa4a61edbd29f453a56a8d4c | /3rdparty/arpack++/include/arrscomp.h | cf1a657842151a544a60c4bad5e326c6da52a34d | [] | no_license | fanxiaochen/Point-Set-Registration | 9ff84f57046df788829854a0dd3f678884bd354b | fa3f3070a245f8e6eb95596edc4b8595f93515e6 | refs/heads/master | 2016-09-05T20:23:17.736878 | 2015-08-11T16:47:14 | 2015-08-11T16:47:14 | 39,198,189 | 8 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 9,432 | h | /*
ARPACK++ v1.2 2/20/2000
c++ interface to ARPACK code.
MODULE ARRSComp.h.
Arpack++ class ARrcCompStdEig definition.
ARPACK Authors
Richard Lehoucq
Danny Sorensen
Chao Yang
Dept. of Computational & Applied Mathematics
Rice University
Houston, Texas
*/
#ifndef ARRSCOMP_H
#define ARRSCOMP_H
#include <stddef.h>
#include "arch.h"
#include "arerror.h"
#include "debug.h"
#include "arrseig.h"
#include "caupp.h"
#include "ceupp.h"
template<class ARFLOAT>
class ARrcCompStdEig: virtual public ARrcStdEig<ARFLOAT, arcomplex<ARFLOAT> > {
protected:
// a) Protected functions:
// a.1) Memory control functions.
void WorkspaceAllocate();
// Allocates workspace for complex problems.
// a.2) Functions that handle original FORTRAN ARPACK code.
void Aupp();
// Interface to FORTRAN subroutines CNAUPD and ZNAUPD.
void Eupp();
// Interface to FORTRAN subroutines CNEUPD and ZNEUPD.
public:
// b) Public functions:
// b.1) Trace functions.
void Trace(const int digit = -5, const int getv0 = 0, const int aupd = 1,
const int aup2 = 0, const int aitr = 0, const int eigt = 0,
const int apps = 0, const int gets = 0, const int eupd = 0)
{
cTraceOn(digit, getv0, aupd, aup2, aitr, eigt, apps, gets, eupd);
}
// Turns on trace mode.
// b.2) Functions that perform all calculations in one step.
int Eigenvalues(arcomplex<ARFLOAT>* &EigValp, bool ivec = false,
bool ischur = false);
// Overrides array EigValp with the eigenvalues of the problem.
// Also calculates eigenvectors and Schur vectors if requested.
int EigenValVectors(arcomplex<ARFLOAT>* &EigVecp,
arcomplex<ARFLOAT>* &EigValp, bool ischur = false);
// Overrides array EigVecp sequentially with the eigenvectors of the
// given eigen-problem. Also stores the eigenvalues in EigValp.
// Calculates Schur vectors if requested.
// b.3) Functions that return elements of vectors and matrices.
arcomplex<ARFLOAT> Eigenvalue(int i);
// Provides i-eth eigenvalue.
arcomplex<ARFLOAT> Eigenvector(int i, int j);
// Provides element j of the i-eth eigenvector.
// b.4) Functions that use STL vector class.
#ifdef STL_VECTOR_H
vector<arcomplex<ARFLOAT> >* StlEigenvalues(bool ivec = false,
bool ischur = false);
// Calculates the eigenvalues and stores them in a single STL vector.
// Also calculates eigenvectors and Schur vectors if requested.
vector<arcomplex<ARFLOAT> >* StlEigenvector(int i);
// Returns the i-th eigenvector in a STL vector.
#endif // #ifdef STL_VECTOR_H.
// b.5) Constructors and destructor.
ARrcCompStdEig() { }
// Short constructor.
ARrcCompStdEig(int np, int nevp, char* whichp = "LM",
int ncvp = 0, ARFLOAT tolp = 0.0, int maxitp = 0,
arcomplex<ARFLOAT>* residp = NULL, bool ishiftp = true);
// Long constructor (regular mode).
ARrcCompStdEig(int np, int nevp, arcomplex<ARFLOAT> sigma,
char* whichp = "LM", int ncvp = 0, ARFLOAT tolp = 0.0,
int maxitp = 0, arcomplex<ARFLOAT>* residp = NULL,
bool ishiftp = true);
// Long constructor (shift and invert mode).
ARrcCompStdEig(const ARrcCompStdEig& other) { Copy(other); }
// Copy constructor.
virtual ~ARrcCompStdEig() { }
// Destructor.
// c) Operators.
ARrcCompStdEig& operator=(const ARrcCompStdEig& other);
// Assignment operator.
}; // class ARrcCompStdEig.
// ------------------------------------------------------------------------ //
// ARrcCompStdEig member functions definition. //
// ------------------------------------------------------------------------ //
template<class ARFLOAT>
inline void ARrcCompStdEig<ARFLOAT>::WorkspaceAllocate()
{
lworkl = ncv*(3*ncv+6);
lworkv = 2*ncv;
lrwork = ncv;
workl = new arcomplex<ARFLOAT>[lworkl+1];
workv = new arcomplex<ARFLOAT>[lworkv+1];
rwork = new ARFLOAT[lrwork+1];
} // WorkspaceAllocate.
template<class ARFLOAT>
inline void ARrcCompStdEig<ARFLOAT>::Aupp()
{
caupp(ido, bmat, n, which, nev, tol, resid, ncv, V, n,
iparam, ipntr, workd, workl, lworkl, rwork, info);
} // Aupp.
template<class ARFLOAT>
inline void ARrcCompStdEig<ARFLOAT>::Eupp()
{
ceupp(rvec, HowMny, EigValR, EigVec, n, sigmaR, workv,
bmat, n, which, nev, tol, resid, ncv, V, n, iparam,
ipntr, workd, workl, lworkl, rwork, info);
} // Eupp.
template<class ARFLOAT>
int ARrcCompStdEig<ARFLOAT>::
Eigenvalues(arcomplex<ARFLOAT>* &EigValp, bool ivec, bool ischur)
{
if (ValuesOK) { // Eigenvalues are available .
if (EigValp == NULL) { // Moving eigenvalues.
EigValp = EigValR;
EigValR = NULL;
newVal = false;
ValuesOK = false;
}
else { // Copying eigenvalues.
copy(nconv,EigValR,1,EigValp,1);
}
}
else {
if (newVal) {
delete[] EigValR;
newVal = false;
}
if (EigValp == NULL) {
try { EigValp = new arcomplex<ARFLOAT>[ValSize()]; }
catch (ArpackError) { return 0; }
}
EigValR = EigValp;
if (ivec) { // Finding eigenvalues and eigenvectors.
nconv = FindEigenvectors(ischur);
}
else { // Finding eigenvalues only.
nconv = FindEigenvalues();
}
EigValR = NULL;
}
return nconv;
} // Eigenvalues(EigValp, ivec, ischur).
template<class ARFLOAT>
int ARrcCompStdEig<ARFLOAT>::
EigenValVectors(arcomplex<ARFLOAT>* &EigVecp, arcomplex<ARFLOAT>* &EigValp,
bool ischur)
{
if (ValuesOK) { // Eigenvalues are already available.
nconv = Eigenvalues(EigValp, false);
nconv = Eigenvectors(EigVecp, ischur);
}
else { // Eigenvalues and vectors are not available.
if (newVec) {
delete[] EigVec;
newVec = false;
}
if (newVal) {
delete[] EigValR;
newVal = false;
}
try {
if (EigVecp == NULL) EigVecp = new arcomplex<ARFLOAT>[ValSize()*n];
if (EigValp == NULL) EigValp = new arcomplex<ARFLOAT>[ValSize()];
}
catch (ArpackError) { return 0; }
EigVec = EigVecp;
EigValR = EigValp;
nconv = FindEigenvectors(ischur);
EigVec = NULL;
EigValR = NULL;
}
return nconv;
} // EigenValVectors(EigVecp, EigValp, ischur).
template<class ARFLOAT>
inline arcomplex<ARFLOAT> ARrcCompStdEig<ARFLOAT>::Eigenvalue(int i)
// calcula e retorna um autovalor.
{
// Returning i-eth eigenvalue.
if (!ValuesOK) {
throw ArpackError(ArpackError::VALUES_NOT_OK, "Eigenvalue(i)");
}
else if ((i>=nconv)||(i<0)) {
throw ArpackError(ArpackError::RANGE_ERROR, "Eigenvalue(i)");
}
return EigValR[i];
} // Eigenvalue(i).
template<class ARFLOAT>
inline arcomplex<ARFLOAT> ARrcCompStdEig<ARFLOAT>::
Eigenvector(int i, int j)
{
// Returning element j of i-eth eigenvector.
if (!VectorsOK) {
throw ArpackError(ArpackError::VECTORS_NOT_OK, "Eigenvector(i,j)");
}
else if ((i>=nconv)||(i<0)||(j>=n)||(j<0)) {
throw ArpackError(ArpackError::RANGE_ERROR, "Eigenvector(i,j)");
}
return EigVec[i*n+j];
} // Eigenvector(i,j).
#ifdef STL_VECTOR_H
template<class ARFLOAT>
inline vector<arcomplex<ARFLOAT> >* ARrcCompStdEig<ARFLOAT>::
StlEigenvalues(bool ivec, bool ischur)
{
// Returning the eigenvalues in a STL vector.
vector<arcomplex<ARFLOAT> >* ValR;
arcomplex<ARFLOAT>* ValPtr;
try {
ValR = new vector<arcomplex<ARFLOAT> >(ValSize());
}
catch (ArpackError) { return NULL; }
ValPtr = ValR->begin();
nconv = Eigenvalues(ValPtr, ivec, ischur);
return ValR;
} // StlEigenvalues.
template<class ARFLOAT>
inline vector<arcomplex<ARFLOAT> >* ARrcCompStdEig<ARFLOAT>::
StlEigenvector(int i)
{
// Returning the i-th eigenvector in a STL vector.
vector<arcomplex<ARFLOAT> >* Vec;
if (!VectorsOK) {
throw ArpackError(ArpackError::VECTORS_NOT_OK, "StlEigenvector(i)");
}
else if ((i>=ValSize())||(i<0)) {
throw ArpackError(ArpackError::RANGE_ERROR, "StlEigenvector(i)");
}
try {
Vec = new vector<arcomplex<ARFLOAT> >(&EigVec[i*n], &EigVec[(i+1)*n]);
}
catch (ArpackError) { return NULL; }
return Vec;
} // StlEigenvector(i).
#endif // #ifdef STL_VECTOR_H.
template<class ARFLOAT>
inline ARrcCompStdEig<ARFLOAT>::
ARrcCompStdEig(int np, int nevp, char* whichp, int ncvp, ARFLOAT tolp,
int maxitp, arcomplex<ARFLOAT>* residp, bool ishiftp)
{
NoShift();
DefineParameters(np, nevp, whichp, ncvp, tolp, maxitp, residp, ishiftp);
} // Long constructor (regular mode).
template<class ARFLOAT>
inline ARrcCompStdEig<ARFLOAT>::
ARrcCompStdEig(int np, int nevp, arcomplex<ARFLOAT> sigmap,
char* whichp, int ncvp, ARFLOAT tolp, int maxitp,
arcomplex<ARFLOAT>* residp, bool ishiftp)
{
ChangeShift(sigmap);
DefineParameters(np, nevp, whichp, ncvp, tolp, maxitp, residp, ishiftp);
} // Long constructor (shift and invert mode).
template<class ARFLOAT>
ARrcCompStdEig<ARFLOAT>& ARrcCompStdEig<ARFLOAT>::
operator=(const ARrcCompStdEig<ARFLOAT>& other)
{
if (this != &other) { // Stroustrup suggestion.
ClearMem();
Copy(other);
}
return *this;
} // operator=.
#endif // ARRSCOMP_H
| [
"[email protected]"
] | |
e725b3529d7621f27ad6317c72a811b41b0ccf92 | 9c54d9d6e081bc38f5ba60fa8f50d93460d02b66 | /263_1.cpp | f293012b7a614375509436272ac37cbe32073662 | [] | no_license | HaiZeizhouyuan/HZOJ | 8444281e7ac8a30a507db810edc0ac1144044434 | 9b5adb02da476e19578327d3a90bf41d9e0e68ef | refs/heads/master | 2023-03-24T08:00:57.835764 | 2021-03-23T05:42:44 | 2021-03-23T05:42:44 | 274,556,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | cpp | /*************************************************************************
> File Name: 263_1.cpp
> Author: zhouyuan
> Mail: [email protected]
> Created Time: 2021年02月03日 星期三 07时54分58秒
************************************************************************/
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
#define MAX_N 20
int n, times = 20;
int nums[MAX_N + 5];
int sta[MAX_N + 5];
int is_out () {
int top = -1;
int sta_max = 0;
for (int i = 0; i < n; i++) {
while (sta_max < nums[i]) {
sta[++top] = (++sta_max);
}
if (top == -1 || (sta[top] != nums[i])) return 0;
top--;
}
return 1;
}
int main() {
cin >> n;
for (int i = 0; i < n;i++) nums[i] = i + 1;
do {
if (is_out()) {
for (int i = 0; i < n; i++) {
cout << nums[i];
}
cout << endl;
times--;
}
}while(times && next_permutation(nums, nums + n));
return 0;
}
| [
"[email protected]"
] | |
6fa7abbb07c68db0f9ab67f6542427891adf3a0a | c92c94e0299538b190da043d03ec809385edecea | /954B/string-typing.cpp | 8d8736e486f28435fac4a58231428171d06682e3 | [] | no_license | mohsinur1998du/Codeforces | 37bad820d15dc5e09188747141afee6170d481c3 | b1776ab50d597e4d7f3e58a59d08a5e8a30d580d | refs/heads/master | 2020-09-21T20:32:57.792046 | 2019-11-20T09:08:39 | 2019-11-20T09:08:39 | 224,919,230 | 1 | 0 | null | 2019-11-29T20:38:24 | 2019-11-29T20:38:24 | null | UTF-8 | C++ | false | false | 523 | cpp | #include <bits/stdc++.h>
using namespace std;
bool pands(string s) {
for (int i = 0; i < s.size() / 2; i++) {
if (s[i] != s[s.size() / 2 + i]) {
return false;
}
}
return true;
}
int main() {
int n;
cin >> n;
string s;
cin >> s;
int lmax = -1;
for (int i = 2; i <= n; i += 2) {
string t = s.substr(0, i);
if (pands(t)) {
lmax = max(lmax, i / 2);
}
}
if (lmax == -1) {
cout << s.size() << endl;
} else {
cout << s.size() - lmax + 1 << endl;
}
return 0;
}
| [
"[email protected]"
] | |
c4a0c8e9c9453c648a57cbcdd7fe1fcede81d66d | 3bde19e4a3385128883971163d05278abcefe735 | /MFCApplication1/Project_2_tap_3/MainFrm.cpp | 23ff06eeb210aedf22f65f3b23beb943745cab64 | [] | no_license | leeyunhome/MFC_start | cfb845f86ed16249f92f8c88d9fb263e9bb53fe8 | 6f2b902e7b3ec88b03767f50e0d39abd48479e09 | refs/heads/master | 2021-01-06T13:36:11.906563 | 2020-02-20T04:31:22 | 2020-02-20T04:31:22 | 241,344,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,889 | cpp |
// MainFrm.cpp : implementation of the CMainFrame class
//
#include "pch.h"
#include "framework.h"
#include "Project_2_tap_3.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd)
ON_WM_CREATE()
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// CMainFrame construction/destruction
CMainFrame::CMainFrame() noexcept
{
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
if (!m_wndStatusBar.Create(this))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));
// TODO: Delete these three lines if you don't want the toolbar to be dockable
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CMDIFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CMDIFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CMDIFrameWnd::Dump(dc);
}
#endif //_DEBUG
// CMainFrame message handlers
| [
"[email protected]"
] | |
cebf63269045d9bff358e2c05d00ae497781cf47 | 801ee73429ca869d7ee10d9fd39f434ed30e3ffd | /CameraJNI/jni/JNVPlayer/Common/JLThreadCtrl.h | 0b54aa120cd0afde5ddb9bcbe2c351c03b4e60fa | [] | no_license | yangbin1026/CameraJni | f28ffa7275e0977b9f01219baa698a78a06e1143 | 1392455c61e70aaf2f5e96abad20595e4435c6ed | refs/heads/master | 2020-03-10T04:56:40.917180 | 2018-04-16T12:18:40 | 2018-04-16T12:18:40 | 129,205,286 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,280 | h | // JLThreadCtrl.h: interface for the CJLThreadCtrl class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_JLTHREADCTRL_H_JSOCK__E038D85C_E4D1_4414_B4B1_D78EA4273387__INCLUDED_)
#define AFX_JLTHREADCTRL_H_JSOCK__E038D85C_E4D1_4414_B4B1_D78EA4273387__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//#include "jxj_lib_def.h"
#include "j_vs_ver.h"
#include "stdio.h"
#if (defined _WIN32) || (defined _WIN64)
// CJLThreadCtrl 类相关的宏定义 begin
#include "MutexLockWnd.h"
#define pthread_t DWORD
#define fJThRet DWORD WINAPI
typedef HANDLE PJHANDLE;
// CJLThreadCtrl 类相关的宏定义 end
#else
// CJLThreadCtrl 类相关的宏定义 begin
#include <pthread.h>
#include <unistd.h>
#include "MutexLockLinux.h"
#define fJThRet void*
// CJLThreadCtrl 类相关的宏定义 end
#endif
//void DbgStrOut(const TCHAR *fmt,... );
typedef fJThRet fcbJThread (void *);
#define THREAD_STATE_STOP 0x00000000 // 结束
#define THREAD_STATE_W_STOP 0x00001000 // 等待结束
#define THREAD_STATE_RUN 0x00000001 // 运行
#define THREAD_STATE_W_RUN 0x00001001 // 等待运行
#define THREAD_STATE_PAUSE 0x00000002 // 暂停
#define THREAD_MAX_WAIT_RET 10 // 最大等待10次
#define THREAD_PER_WAIT_TIME 40 // 每闪等待的毫秒数
#ifndef J_DGB_NAME_LEN
#define J_DGB_NAME_LEN 64
#endif
namespace JSocketCtrl
{
class CJLThreadCtrl
{
public:
CJLThreadCtrl(void* pOwner = NULL);
virtual ~CJLThreadCtrl();
// 开始线程函数
HANDLE StartThread(fcbJThread* pThreadFun);
// 结束线程函数
int StopThread(bool bWaitRet=true);
// 暂停线程函数
int PauseThread();
// 继续线程函数
int ContinueThread();
// 获取线程状态
DWORD GetThreadState();
// 通知结束
void NotifyStop();
// 返回下一次需的操作
// THREAD_STATE_STOP:表示线程应该要结束了;
// THREAD_STATE_RUN:表示正常运行;
// THREAD_STATE_PAUSE:表示需要暂停
DWORD GetNextAction();
// 获取相应的句柄
pthread_t GetHandle();
// 设置本变量的参数,供线程函数中调用
int SetParam(void* pParam);
// 获取本变量的参数,供线程函数中调用
void* GetParam();
// 设置本变量的所有者(在回调函数中使用)
int SetOwner(void* pParam);
// 获取本变量的所有者(在回调函数中使用)
void* GetOwner();
// 设置线程状态,注意:只是设置相应的状态值,并不做逻辑处理,一般只在线程函数中,设置结束状态
void SetThreadState(DWORD dwThreadState);
public:
char m_szName[J_DGB_NAME_LEN]; // 名称...调试用
protected:
pthread_t m_hThreadID; // 线程ID
HANDLE m_hThread; // 线程句柄
DWORD m_dwThreadState; // 线程状态
fcbJThread* m_pThreadFun; // 线程函数
void* m_pParam; // 参数(在回调函数中使用)
void* m_pOwner; // 所有者(在回调函数中使用)
// HANDLE m_hEventStop; // 停止事件
PJHANDLE m_hEventPause; // 暂停事件
};
}
using namespace JSocketCtrl;
#endif // !defined(AFX_JLTHREADCTRL_H_JSOCK__E038D85C_E4D1_4414_B4B1_D78EA4273387__INCLUDED_)
| [
"[email protected]"
] | |
6ec8950c860eaba549fa618ab17cc900dec00465 | d15466d6466de2b0a8c926e4e79653e4ec135617 | /src/GeoUtil.cpp | a68633c373f2598e5713b67e02978926499d3fb1 | [] | no_license | Cotrik/CotrikMeshing | f1c614e21175202016fdd5157b12d1011dd3ed4e | 7e9046bae242a1d782b8d20723339296264453d2 | refs/heads/master | 2021-05-03T20:19:24.590673 | 2016-10-06T19:35:55 | 2016-10-06T19:35:55 | 70,168,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,470 | cpp | /*
* GeoUtil.cpp
*
* Created on: Feb 6, 2015
* Author: cotrik
*/
#include "GeoUtil.h"
#include <iostream>
#include "Eigen/Core"
#include "Eigen/Eigen"
#include "Eigen/Dense"
#include "Eigen/Sparse"
#include "Eigen/Cholesky"
#include "Eigen/LU"
#include "Eigen/SVD"
#include "Eigen/SparseCore"
GeoUtil::GeoUtil()
{
// TODO Auto-generated constructor stub
}
GeoUtil::~GeoUtil()
{
// TODO Auto-generated destructor stub
}
void GeoUtil::GetMaxCoordinateValueOfVertex(const Vertex& vertex, Vertex& vertexMax)
{
if (vertex.x > vertexMax.x)
{
vertexMax.x = vertex.x;
}
if (vertex.y > vertexMax.y)
{
vertexMax.y = vertex.y;
}
if (vertex.z > vertexMax.z)
{
vertexMax.z = vertex.z;
}
}
void GeoUtil::GetMinCoordinateValueOfVertex(const Vertex& vertex, Vertex& vertexMin)
{
if (vertex.x < vertexMin.x)
{
vertexMin.x = vertex.x;
}
if (vertex.y < vertexMin.y)
{
vertexMin.y = vertex.y;
}
if (vertex.z < vertexMin.z)
{
vertexMin.z = vertex.z;
}
}
void GeoUtil::GetMaxMinCoordinateValueOfVertex(const Vertex& vertex, Vertex& vertexMax, Vertex& vertexMin)
{
GetMaxCoordinateValueOfVertex(vertex, vertexMax);
GetMinCoordinateValueOfVertex(vertex, vertexMin);
}
void GeoUtil::GetMaxMinCoordinateValueOfTriangle(const std::vector<Vertex*>& m_vecVertex, const Triangle& triangle, Vertex& vertexMax, Vertex& vertexMin)
{
GetMaxMinCoordinateValueOfVertex(*m_vecVertex[triangle.p0], vertexMax, vertexMin);
GetMaxMinCoordinateValueOfVertex(*m_vecVertex[triangle.p1], vertexMax, vertexMin);
GetMaxMinCoordinateValueOfVertex(*m_vecVertex[triangle.p2], vertexMax, vertexMin);
}
bool GeoUtil::IsPointInTriangle(const glm::vec3& P, const glm::vec3& A, const glm::vec3& B, const glm::vec3& C, const int i, const int j)
{
// Compute vectors
const glm::vec3 v0 = C - A;
const glm::vec3 v1 = B - A;
const glm::vec3 v2 = P - A;
// Compute dot products
const double dot00 = glm::dot(v0, v0);
const double dot01 = glm::dot(v0, v1);
const double dot02 = glm::dot(v0, v2);
const double dot11 = glm::dot(v1, v1);
const double dot12 = glm::dot(v1, v2);
// Compute barycentric coordinates
const double invDenom = 1.0 / (dot00 * dot11 - dot01 * dot01);
const double u = (dot11 * dot02 - dot01 * dot12) * invDenom;
const double v = (dot00 * dot12 - dot01 * dot02) * invDenom;
if (i == 327 || i == 10515 || i == 14266)
{
if(fabs(u) + fabs(v) < 1.3)
std::cout << "i = " << i << " j = " << j << " u = " << u << ", v = " << v << std::endl;
}
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1.0);
}
bool GeoUtil::IsPointCanProjectToTriangle(const glm::vec3& orig, const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2, glm::vec3& p)
{
glm::vec3 n = glm::cross(v1 - v0, v2 - v0);
double d = -glm::dot(n, v0);
double length = 1.0 / n.length();
n *= length;
d *= length;
double a = n.x;
double b = n.y;
double c = n.z;
double t = (glm::dot(orig, n) + d)/(a*a + b*b + c*c);
//glm::vec3 p(orig.x - a*t, orig.y - b*t, orig.z - c*t);
p.x = orig.x - a*t;
p.y = orig.y - a*t;
p.z = orig.z - a*t;
return IsPointInTriangle(p, v0, v1, v2);
}
bool GeoUtil::IsPointInTetrahedron(const Vertex& p, const Vertex& p0, const Vertex& p1, const Vertex& p2, const Vertex& p3)
{
glm::vec3 v03((p0.x - p3.x), (p0.y - p3.y), (p0.z - p3.z));
glm::vec3 v13((p1.x - p3.x), (p1.y - p3.y), (p1.z - p3.z));
glm::vec3 v23((p2.x - p3.x), (p2.y - p3.y), (p2.z - p3.z));
glm::vec3 r(p.x, p.y, p.z);
glm::vec3 r4(p3.x, p3.y, p3.z);
glm::vec3 rr4 = r - r4;
glm::mat3x3 T(v03, v13, v23);
glm::mat3x3 T_inverse = glm::inverse(T);
glm::vec3 lambda = T_inverse * (r - r4);
if (lambda.x > -1e-3 && lambda.y > -1e-3 && lambda.z > -1e-3 && (lambda.x + lambda.y + lambda.z) < 1.001)
{
return true;
}
return false;
}
bool GeoUtil::IsPointInTetrahedron(const Vertex& p, const Vertex& p0, const Vertex& p1, const Vertex& p2, const Vertex& p3, glm::vec3& uvw)
{
glm::vec3 v03((p0.x - p3.x), (p0.y - p3.y), (p0.z - p3.z));
glm::vec3 v13((p1.x - p3.x), (p1.y - p3.y), (p1.z - p3.z));
glm::vec3 v23((p2.x - p3.x), (p2.y - p3.y), (p2.z - p3.z));
glm::vec3 r(p.x, p.y, p.z);
glm::vec3 r4(p3.x, p3.y, p3.z);
glm::vec3 rr4 = r - r4;
glm::mat3x3 T(v03, v13, v23);
glm::mat3x3 T_inverse = glm::inverse(T);
glm::vec3 lambda = T_inverse * (r - r4);
if (lambda.x > -1e-3 && lambda.y > -1e-3 && lambda.z > -1e-3 && (lambda.x + lambda.y + lambda.z) < 1.001)
{
uvw.x = lambda.x;
uvw.y = lambda.y;
uvw.z = lambda.z;
return true;
}
return false;
}
bool GeoUtil::IsPointInTetrahedron_Robust(const Vertex& p, const Vertex& p0, const Vertex& p1, const Vertex& p2, const Vertex& p3, glm::vec4& uvwx)
{
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(4, 4);
A(0,0) = p0.x; A(0,1) = p1.x; A(0,2) = p2.x; A(0,3) = p3.x;
A(1,0) = p0.y; A(1,1) = p1.y; A(1,2) = p2.y; A(1,3) = p3.y;
A(2,0) = p0.z; A(2,1) = p1.z; A(2,2) = p2.z; A(2,3) = p3.z;
A(3,0) = 1.0; A(3,1) = 1.0; A(3,2) = 1.0; A(3,3) = 1.0;
Eigen::VectorXd b = Eigen::VectorXd::Zero(4);
b(0) = p.x; b(1) = p.y; b(2) = p.z; b(3) = 1.0;
Eigen::VectorXd lambda = A.llt().solve(b);
if (lambda(0) > 0 && lambda(1) > 0 && lambda(2) > 0 && lambda(3) > 0
&& lambda(0) + lambda(1) + lambda(2) + lambda(3) <= 1.000001
&& lambda(0) + lambda(1) + lambda(2) + lambda(3) >= 0.999999)
{
uvwx.x = lambda(0);
uvwx.y = lambda(1);
uvwx.z = lambda(2);
uvwx.w = lambda(3);
return true;
}
return false;
}
bool GeoUtil::IsPointInTetrahedron_Robust_test(const Vertex& p, const Vertex& p0, const Vertex& p1, const Vertex& p2, const Vertex& p3, glm::vec4& uvwx)
{
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3, 3);
A(0,0) = p0.x - p3.x; A(0,1) = p1.x - p3.x; A(0,2) = p2.x - p3.x;
A(1,0) = p0.y - p3.y; A(1,1) = p1.y - p3.y; A(1,2) = p2.y - p3.y;
A(2,0) = p0.z - p3.z; A(2,1) = p1.z - p3.z; A(2,2) = p2.z - p3.z;
Eigen::VectorXd b = Eigen::VectorXd::Zero(3);
b(0) = p.x - p3.x;
b(1) = p.y - p3.y;
b(2) = p.z - p3.z;
Eigen::VectorXd lambda = A.transpose()*b;
if (lambda(0) > 0 && lambda(1) > 0 && lambda(2) > 0
&& lambda(0) + lambda(1) + lambda(2) <= 1.000001)
{
uvwx.x = lambda(0);
uvwx.y = lambda(1);
uvwx.z = lambda(2);
uvwx.w = 1 - lambda(0) - lambda(1) - lambda(2);
return true;
}
return false;
}
bool GeoUtil::IsVertexInsideTetrahedron(const Vertex& vertex, const Cell& tet, const std::vector<Vertex>& vecVertex, glm::vec3& lambda)
{
bool bInside = false;
glm::vec4 v1(vecVertex[tet.at(0)].x, vecVertex[tet.at(0)].y, vecVertex[tet.at(0)].z, 1.0);
glm::vec4 v2(vecVertex[tet.at(1)].x, vecVertex[tet.at(1)].y, vecVertex[tet.at(1)].z, 1.0);
glm::vec4 v3(vecVertex[tet.at(2)].x, vecVertex[tet.at(2)].y, vecVertex[tet.at(2)].z, 1.0);
glm::vec4 v4(vecVertex[tet.at(3)].x, vecVertex[tet.at(3)].y, vecVertex[tet.at(3)].z, 1.0);
glm::vec4 v(vertex.x, vertex.y, vertex.z, 1.0);
glm::mat4x4 m0(v1, v2, v3, v4);
glm::mat4x4 m1(v, v2, v3, v4);
glm::mat4x4 m2(v1, v, v3, v4);
glm::mat4x4 m3(v1, v2, v, v4);
glm::mat4x4 m4(v1, v2, v3, v);
double d0 = glm::determinant(m0);
double d1 = glm::determinant(m1);
double d2 = glm::determinant(m2);
double d3 = glm::determinant(m3);
double d4 = glm::determinant(m4);
// if (d0 < 1e-7)
// std::cout << "Tet degenerated!" << std::endl;
//
// if (fabs(d1) < 1e-7 && fabs(d2) < 1e-7 && fabs(d3) < 1e-7 && fabs(d3) < 1e-7){
// lambda = glm::vec3(0.25, 0.25, 0.25);
// return true;
// }
if (((d0 > 0 && d1 > 0 && d2 > 0 && d3 > 0 && d4 > 0) || (d0 < 0 && d1 < 0 && d2 < 0 && d3 < 0 && d4 < 0))
&& fabs(d0 - d1 - d2 - d3 - d4) < 1e-7 && fabs(d0) > 1e-7)
{
lambda = glm::vec3(d1/d0, d2/d0, d3/d0);
bInside = true;
}
return bInside;
}
bool GeoUtil::IsVertexInsideTetrahedron_Robust(const Vertex& p, const Vertex& p0, const Vertex& p1, const Vertex& p2, const Vertex& p3, glm::vec3& lambda)
{
bool bInside = false;
glm::vec4 v1(p0.x, p0.y, p0.z, 1.0);
glm::vec4 v2(p1.x, p1.y, p1.z, 1.0);
glm::vec4 v3(p2.x, p2.y, p2.z, 1.0);
glm::vec4 v4(p3.x, p3.y, p3.z, 1.0);
glm::vec4 v(p.x, p.y, p.z, 1.0);
glm::mat4x4 m0(v1, v2, v3, v4);
glm::mat4x4 m1(v, v2, v3, v4);
glm::mat4x4 m2(v1, v, v3, v4);
glm::mat4x4 m3(v1, v2, v, v4);
glm::mat4x4 m4(v1, v2, v3, v);
std::vector<double> d(5);
d[0] = glm::determinant(m0);
d[1] = glm::determinant(m1);
d[2] = glm::determinant(m2);
d[3] = glm::determinant(m3);
d[4] = glm::determinant(m4);
int hasPostive = 0;
int hasNegtive = 0;
for (size_t i = 0; i < 5; i++)
{
if (d[i] > 0)
hasPostive = 1;
else if (d[i] < 0)
hasNegtive = -1;
}
bool isSameSign = (hasPostive == 1) ^ (hasNegtive == -1);
if (isSameSign && fabs(d[0]) > 1e-8 && fabs(d[0] - d[1] - d[2] - d[3] - d[4]) < 1e-9)
{
lambda = glm::vec3(d[1]/d[0], d[2]/d[0], d[3]/d[0]);
bInside = true;
}
return bInside;
}
bool GeoUtil::IsTetrahedronDegenerated(const Cell& tet, const std::vector<Vertex>& vecVertex, const double eps/* = 1e-9*/)
{
glm::vec4 v1(vecVertex[tet.at(0)].x, vecVertex[tet.at(0)].y, vecVertex[tet.at(0)].z, 1.0);
glm::vec4 v2(vecVertex[tet.at(1)].x, vecVertex[tet.at(1)].y, vecVertex[tet.at(1)].z, 1.0);
glm::vec4 v3(vecVertex[tet.at(2)].x, vecVertex[tet.at(2)].y, vecVertex[tet.at(2)].z, 1.0);
glm::vec4 v4(vecVertex[tet.at(3)].x, vecVertex[tet.at(3)].y, vecVertex[tet.at(3)].z, 1.0);
glm::mat4x4 m0(v1, v2, v3, v4);
double d0 = glm::determinant(m0);
if (fabs(d0) < eps)
{
// std::cout << "volume: " << d0;
return true;
}
else
return false;
}
FACE_TYPE GeoUtil::GetFaceType(const glm::vec3& normal)
{
const float l = glm::length(normal);
if (fabs(normal.x/l) > 0.8)
{
return FACE_X;
}
else if (fabs(normal.y/l) > 0.8)
{
return FACE_Y;
}
else if (fabs(normal.z/l) > 0.8)
{
return FACE_Z;
}
FACE_TYPE faceType = FACE_X;
double max = fabs(normal.x/l);
if (fabs(normal.y/l) > max)
{
max = fabs(normal.y/l);
faceType = FACE_Y;
}
if (fabs(normal.z/l) > max)
{
max = fabs(normal.z/l);
faceType = FACE_Z;
}
return faceType;
}
| [
"[email protected]"
] | |
41cca418dd5790dbd04ed5a53f2db9cfcfd3d181 | 31f5cddb9885fc03b5c05fba5f9727b2f775cf47 | /engine/modules/physx/shape/physx_shape.cpp | 06c9ba9916bf139cf8dbf48357975b7359142bdd | [
"MIT"
] | permissive | timi-liuliang/echo | 2935a34b80b598eeb2c2039d686a15d42907d6f7 | d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24 | refs/heads/master | 2023-08-17T05:35:08.104918 | 2023-08-11T18:10:35 | 2023-08-11T18:10:35 | 124,620,874 | 822 | 102 | MIT | 2021-06-11T14:29:03 | 2018-03-10T04:07:35 | C++ | UTF-8 | C++ | false | false | 1,598 | cpp | #include "physx_shape.h"
#include "../physx_module.h"
#include "../physx_body.h"
#include <engine/core/main/engine.h>
#include <engine/core/log/Log.h>
namespace Echo
{
PhysxShape::PhysxShape()
{
m_pxMaterial = PhysxModule::instance()->getPxPhysics()->createMaterial(0.5f, 0.5f, 0.5f);
}
PhysxShape::~PhysxShape()
{
if (m_pxShape)
{
PhysxBody* body = ECHO_DOWN_CAST<PhysxBody*>(getParent());
if (body && body->getPxBody())
{
body->getPxBody()->detachShape(*m_pxShape);
m_pxShape->release();
m_pxShape = nullptr;
}
}
}
void PhysxShape::bindMethods()
{
}
void PhysxShape::updateInternal(float elapsedTime)
{
if (m_isEnable && !m_pxShape)
{
PhysxBody* body = ECHO_DOWN_CAST<PhysxBody*>(getParent());
if (body && body->getPxBody())
{
if (body->getPxBody())
{
m_pxShape = createPxShape();
if (m_pxShape)
{
physx::PxTransform localTransform((physx::PxVec3&)getLocalPosition(), (physx::PxQuat&)getLocalOrientation());
m_pxShape->setLocalPose(localTransform);
physx::PxFilterData filterData;
filterData.word3 = 0xffff0000;
m_pxShape->setQueryFilterData(filterData);
body->getPxBody()->attachShape(*m_pxShape);
}
}
}
else
{
EchoLogError("Physx shape [%s]'s parent should be a PhysxBody", getNodePath().c_str());
}
}
if (m_pxShape)
{
if (!Engine::instance()->getConfig().m_isGame)
{
physx::PxTransform pxTransform((physx::PxVec3&)getLocalPosition(), (physx::PxQuat&)getLocalOrientation());
m_pxShape->setLocalPose(pxTransform);
}
}
}
} | [
"[email protected]"
] | |
3d1117ace964fdba3c0783eca99257a11a4c13de | 7d9c4abe4752b780b1c3cbf244c74af15eda8af2 | /Analyzer/util/optimize.cxx | c4750f1742f91058188dfd02f26cb9db99db6193 | [] | no_license | othrif/SUSYAnalysis | edd65db09ac129cb747ec386ec99b1191c525797 | 6e7cb51d9cd039b828cb8f8deae64f623fb92f36 | refs/heads/master | 2020-05-31T02:17:06.498212 | 2018-08-08T09:05:03 | 2018-08-08T09:05:03 | 190,062,040 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,402 | cxx | /*****************************************************************************/
/* */
/* File Name : analyze.cxx */
/* */
/* Author : Othmane Rifki */
/* Email : [email protected] */
/* */
/* Description : Applies Object Definition and Selection for SS/3L */
/* Runs over MiniNtuple */
/* Produces histograms for SR/VR/CRs */
/* To run: analyze <foldername> <filename> <rootfiles> */
/* e.g. analzye testfolder data data/DAOD_SUSY2*.root */
/* */
/* */
/***** C 2016 ****************************************************************/
//here are the project-specific files
#include "Analyzer/my_objects.h"
#include "Root/my_objects.cxx"
#include "Analyzer/DileptonTriggerWeight.h"
#include "Root/DileptonTriggerWeight.cxx"
#include "GoodRunsLists/TGoodRunsListReader.h"
#include "GoodRunsLists/GoodRunsListSelectionTool.h"
#include "PileupReweighting/PileupReweightingTool.h"
#include "xAODEventInfo/EventInfo.h"
#include "xAODEventInfo/EventInfoContainer.h"
#include "xAODEventInfo/EventInfoAuxContainer.h"
#include "SUSYTools/SUSYCrossSection.h"
#include "CPAnalysisExamples/errorcheck.h"
//#include "LHAPDF/PDFSet.h"
//#include "LHAPDF/Reweighting.h"
//#include "LHAPDF/LHAPDF.h"
#include "FakeObjectTools/TwoLepSSFakeBkg.h"
#include "Analyzer/MCTemplateCorr.h"
// PILEUP REWEIGHTING
// The application's name:
const char* APP_NAME = "Monstres tronats";
//------------------------------------------------------------------------
// -= General Declarations =-
//------------------------------------------------------------------------
#define luminosity 36470.16
// lumi 2016: 33257.2 +- 4.5%
// lumi 2015: 3212.96 +- 2.1%
// lumi 2015+2016: 36470.16 +- 4.1%
bool GG = false; // Gluino mediated processes
bool BB = false; // sbottom mediated processes
bool strong = false; // strong production for NUHM2
bool applyOR = true;
bool cutflow = false; // to activate cutflow
bool useTTbarHT = true; // only HT or MET is true, not both
bool useTTbarMET = false;
bool noXsection = true;
bool debugme = false;
void declarestructs(TTree* tree, myevt* evt);
//------------------------------------------------------------------------
// -= Main loop =-
//------------------------------------------------------------------------
int main_loop(TChain* oldtree, char* name, char* ftag) {
std::cout << " \n------- " << ftag << " ------- " << std::endl;
myevt evt;
std::map<unsigned int, std::set<ULong64_t> > evtmap;
//-----------------------------------------------------------------------
if (!oldtree)
return 1;
Long64_t tree_Entries = (Long64_t) oldtree->GetEntries();
if (tree_Entries == 0)
return 1;
oldtree->GetEntry(0);
declarestructs(oldtree->GetTree(), &evt);
int treeno = ((TChain*) oldtree)->GetTreeNumber();
TString filename = oldtree->GetFile()->GetName();
TString oldfilename = oldtree->GetFile()->GetName();
int numtrees = ((TChain*) oldtree)->GetNtrees();
// std::cout << "file: " << filename << ", number of trees: " << numtrees << "\n";
std::cout << "Expect to process " << tree_Entries << " entries in " << numtrees << " file(s).\n";
// std::cout << "file: " << filename << ", treeno: " << treeno << "\n";
// Check the filename to select processes contributing to charge flip
// bool isCFSource = false;
// if(filename.Index("_ttbar_") > 0 || filename.Index("_Zee") > 0 || filename.Index("_Zmumu") > 0 || filename.Index("_Ztautau") > 0 || filename.Index("_llvv.") > 0 ){
// isCFSource = true;
// std::cout << "source of charge flip sample!!" << std::endl;
// }
// For signal cross sections
if(filename.Index("_GG_") > 0 )
GG = true;
if(filename.Index("_BB_") > 0 )
BB = true;
if(filename.Index("strong") > 0 )
strong = true;
if(filename.Index("_GG_2stepWZ") > 0 )
GG = false;
// PileupReweighing
CP::PileupReweightingTool* m_Pileup;
xAOD::EventInfo* eventInfo;
xAOD::EventInfoContainer* eInfos;
m_Pileup = new CP::PileupReweightingTool("Pileup");
std::vector<std::string> confFiles;
std::vector<std::string> lcalcFiles;
oldtree->GetEntry(0);
std::cout << "MC15c sample" << std::endl;
confFiles.push_back("/cvmfs/atlas.cern.ch/repo/sw/database/GroupData/dev/SUSYTools/merged_prw_mc15c.root");
lcalcFiles.push_back("/afs/cern.ch/work/o/othrif/workarea/myFramework/Analyzer/data/ilumicalc_histograms_None_276262-284484.root");
lcalcFiles.push_back("/afs/cern.ch/work/o/othrif/workarea/myFramework/Analyzer/data/ilumicalc_histograms_None_297730-311481_OflLumi-13TeV-005.root");
CHECK(m_Pileup->setProperty( "ConfigFiles", confFiles) );
CHECK(m_Pileup->setProperty( "DefaultChannel",410000) );
CHECK(m_Pileup->setProperty( "LumiCalcFiles", lcalcFiles) );
CHECK(m_Pileup->setProperty( "DataScaleFactor", 1.0/1.09) );
CHECK(m_Pileup->setProperty( "DataScaleFactorUP", 1.0/1.0) );
CHECK(m_Pileup->setProperty( "DataScaleFactorDOWN", 1.0/1.18) );
CHECK(m_Pileup->initialize());
// Dummy EventInfo object to manipulate later
eInfos = new xAOD::EventInfoContainer();
eInfos->setStore(new xAOD::EventInfoAuxContainer());
eInfos->push_back(new xAOD::EventInfo());
eventInfo = eInfos->at(0);
// GoodRunsLists
GoodRunsListSelectionTool *m_grl;
m_grl = new GoodRunsListSelectionTool("GoodRunsListSelectionTool");
std::vector<std::string> myvals;
myvals.push_back("/afs/cern.ch/work/o/othrif/workarea/myFramework/Analyzer/data/data15_13TeV.periodAllYear_DetStatus-v79-repro20-02_DQDefects-00-02-02_PHYS_StandardGRL_All_Good_25ns.xml");
myvals.push_back("/afs/cern.ch/work/o/othrif/workarea/myFramework/Analyzer/data/data16_13TeV.periodAllYear_DetStatus-v83-pro20-15_DQDefects-00-02-04_PHYS_StandardGRL_All_Good_25ns.xml");
CHECK( m_grl->setProperty( "GoodRunsListVec", myvals) );
CHECK( m_grl->setProperty("PassThrough", false) );
CHECK( m_grl->initialize() );
// Cross Sections
SUSY::CrossSectionDB myXsection("/afs/cern.ch/work/o/othrif/workarea/myFramework/Analyzer/data/mc15_13TeV/");
// Dilepton trigger weight
DileptonTriggerWeight dtwTool;
// MC template correction
MCTemplateCorr fakeCorr;
// create folder
char fpath[512];
sprintf(fpath, "/afs/cern.ch/work/o/othrif/workarea/results");
int res = mkdir(fpath, 0700);
if ( res == -1) {
std::cout << "WARNING: Folder " << fpath << " already exists!" << std::endl;
}
sprintf(fpath, "/afs/cern.ch/work/o/othrif/workarea/results/v48");
res = mkdir(fpath, 0700);
if ( res == -1) {
std::cout << "WARNING: Folder " << fpath << " already exists!" << std::endl;
}
sprintf(fpath, "/afs/cern.ch/work/o/othrif/workarea/results/v48/%s", name);
res = mkdir(fpath, 0700);
if ( res == -1) {
std::cout << "WARNING: Folder " << fpath << " already exists!" << std::endl;
}
// logs
char lpath[512];
sprintf(lpath, "/afs/cern.ch/work/o/othrif/workarea/results/v48/%s/logs", name);
int res_log = mkdir(lpath, 0700);
if ( res_log == -1) {
std::cout << "WARNING: Folder " << lpath << " already exists!" << std::endl;
}
// output file
char fname[512];
sprintf(fname, "/afs/cern.ch/work/o/othrif/workarea/results/v48/%s/%s.root", name,ftag);
TFile file(fname, "RECREATE");
// Save log file
char logfile[512];
sprintf(logfile,"/afs/cern.ch/work/o/othrif/workarea/results/v48/%s/logs/%s.log", name,ftag);
FILE *fp;
fp=fopen(logfile, "w+");
if(!fp)
std::cout << "ERROR: Cannot write to log file!" << std::endl;
sprintf(logfile,"/afs/cern.ch/work/o/othrif/workarea/results/v48/%s/logs/%s_debug.log", name,ftag);
FILE *fpd;
fpd=fopen(logfile, "w+");
if(!fpd)
std::cout << "ERROR: Cannot write to debug log file!" << std::endl;
sprintf(logfile,"/afs/cern.ch/work/o/othrif/workarea/results/v48/%s/logs/yields_per_file.log", name);
FILE *fpy;
fpy=fopen(logfile, "a+");
if(!fpy)
std::cout << "ERROR: Cannot write to debug log file!" << std::endl;
// SS/3L
//-----------------------------------------------------------------------
// General information
//-----------------------------------------------------------------------
// vertex information
TH1D *num_vtx_noPRW = new TH1D("num_vtx_noPRW", "num_vtx_noPRW;# prim. vtx.;entries", 40, 0, 40);
num_vtx_noPRW->Sumw2();
TH1D *num_vtx_PRW = new TH1D("num_vtx_PRW", "num_vtx_PRW;# prim. vtx.;entries", 40, 0, 40);
num_vtx_PRW->Sumw2();
// averageIntPerXing
TH1D *averageIntPerXing_noPRW = new TH1D("averageIntPerXing_noPRW", "averageIntPerXing_noPRW;averageIntPerXing;entries", 40, 0, 40);
averageIntPerXing_noPRW->Sumw2();
TH1D *averageIntPerXing_PRW = new TH1D("averageIntPerXing_PRW", "averageIntPerXing_PRW;averageIntPerXing;entries", 40, 0, 40);
averageIntPerXing_PRW->Sumw2();
TH1D *averageIntPerXing_PRW_SS3L = new TH1D("averageIntPerXing_PRW_SS3L", "averageIntPerXing_PRW_SS3L;averageIntPerXing;entries", 40, 0, 40);
averageIntPerXing_PRW_SS3L->Sumw2();
//number of leptons
TH1D *num_of_leptons_noPRW = new TH1D("num_of_leptons_noPRW", "num_of_leptons_noPRW;N_{lep};Events", 11, -0.5, 10.5);
num_of_leptons_noPRW->Sumw2();
TH1D *num_of_leptons_PRW = new TH1D("num_of_leptons_PRW", "num_of_leptons_PRW;N_{lep}; Events", 11, -0.5, 10.5);
num_of_leptons_PRW->Sumw2();
//number of jets
TH1D *num_of_jets_noPRW = new TH1D("num_of_jets_noPRW", "num_of_jets_noPRW ;N_{jet}; Events", 21, -0.5, 20.5);
num_of_jets_noPRW->Sumw2();
TH1D *num_of_jets_PRW = new TH1D("num_of_jets_PRW", "num_of_jets_PRW;N_{jet}; Events", 21, -0.5, 20.5);
num_of_jets_PRW->Sumw2();
// b-tagging weight
TH1D *btag_weight_noPRW = new TH1D("btag_weight_noPRW", "btag_weight_noPRW MV2c20;btag_weight MV2c20;entries", 30, -1.5, 1.5);
btag_weight_noPRW->Sumw2();
TH1D *btag_weight_PRW = new TH1D("btag_weight_PRW", "btag_weight_PRW MV2c20;btag_weight MV2c20;entries", 30, -1.5, 1.5);
btag_weight_PRW->Sumw2();
// Total Event weight
TH1D *event_weight_noXsec = new TH1D("event_weight_noXsec", "event_weight_noXsec ;Total Event Weight (NoXsec);entries", 300, 0, 1.5);
event_weight_noXsec->Sumw2();
// Correlations
TH2D *btagwgh_mu_noPRW = new TH2D("btagwgh_mu_noPRW", "btag_weight vs. #mu_noPRW;averageIntPerXing;btag_weight MV2c20;entries", 40, 0, 40, 30, -1.5, 1.5);
btagwgh_mu_noPRW->Sumw2();
TH2D *evtwgh_mu_noXsec = new TH2D("evtwgh_mu_noXsec", "event_weight vs. #mu_noXsec;averageIntPerXing;Total Event Weight (NoXsec);entries", 40, 0, 40, 300, 0, 1.5);
evtwgh_mu_noXsec->Sumw2();
TH2D *btagwgh_mu_PRW = new TH2D("btagwgh_mu_PRW", "btag_weight vs. #mu_PRW;averageIntPerXing;btag_weight MV2c20;entries", 40, 0, 40, 30, -1.5, 1.5);
btagwgh_mu_PRW->Sumw2();
// Cutflow
//-----------------------------------------------------------------------
TH1D* cut_flow = new TH1D("cut_flow", "cut_flow for the baseline selection", 100, 0, 100);
cut_flow->Sumw2();
TH1D* cut_flow_ee_ss = new TH1D("cut_flow_ee_ss", "cut_flow for ee_ss selection", 40, 0, 40);
cut_flow_ee_ss->Sumw2();
TH1D* cut_flow_em_ss = new TH1D("cut_flow_em_ss", "cut_flow for em_ss selection", 40, 0, 40);
cut_flow_em_ss->Sumw2();
TH1D* cut_flow_mm_ss = new TH1D("cut_flow_mm_ss", "cut_flow for mm_ss selection", 40, 0, 40);
cut_flow_mm_ss->Sumw2();
// Checks
//-----------------------------------------------------------------------
TH1D* hscaled = new TH1D("hscaled", "Sanity Checks", 10, 0, 10);
hscaled->Sumw2();
hscaled->GetXaxis()->FindBin("All");
hscaled->GetXaxis()->FindBin("SS ee+e#mu+#mu#mu");
hscaled->GetXaxis()->FindBin("SS ee");
hscaled->GetXaxis()->FindBin("SS e#mu");
hscaled->GetXaxis()->FindBin("SS #mu#mu");
hscaled->GetXaxis()->FindBin("OS ee+e#mu+#mu#mu");
hscaled->GetXaxis()->FindBin("OS ee");
hscaled->GetXaxis()->FindBin("OS e#mu");
hscaled->GetXaxis()->FindBin("OS #mu#mu");
TH1D* hraw = (TH1D*)hscaled->Clone("hraw");
hraw->Sumw2();
// Composition:
TH1D* composition_3lss = new TH1D("composition_3lss", "Background Composition;;Events", 9, 0, 9);
composition_3lss->Sumw2();
composition_3lss->GetXaxis()->FindBin("All");
composition_3lss->GetXaxis()->FindBin("All Prompt");
composition_3lss->GetXaxis()->FindBin("2 Prompt & 1 Fake");
composition_3lss->GetXaxis()->FindBin("2 Prompt & 1 MisId");
composition_3lss->GetXaxis()->FindBin("1 Prompt & 1 Fake & 1 MisId");
composition_3lss->GetXaxis()->FindBin("1 Prompt & 2 Fake & 0 MisId");
composition_3lss->GetXaxis()->FindBin("1 Prompt & 0 Fake & 2 MisId");
composition_3lss->GetXaxis()->FindBin("All fakes or charge flips");
composition_3lss->GetXaxis()->FindBin("Rest");
// SR N-1 plots
//-----------------------------------------------------------------------
TH1D *SR3LmMET = new TH1D("MET_SR3LmMET_SS3L", "mEt (N-1);E_{T}^{miss} (N-1) [GeV];Events / 25 GeV", 7, 50, 225);
SR3LmMET->Sumw2();
TH1D *SR0bmMET = new TH1D("MET_SR0bmMET_SS3L", "mEt (N-1);E_{T}^{miss} (N-1) [GeV];Events / 25 GeV", 5, 50, 175);
SR0bmMET->Sumw2();
TH1D *SR1bmMET = new TH1D("MET_SR1bmMET_SS3L", "mEt (N-1);E_{T}^{miss} (N-1) [GeV];Events / 25 GeV", 5, 50, 175);
SR1bmMET->Sumw2();
TH1D *SR3bmMET = new TH1D("MET_SR3bmMET_SS3L", "mEt (N-1);E_{T}^{miss} (N-1) [GeV];Events / 25 GeV", 5, 50, 175);
SR3bmMET->Sumw2();
TH1D *SRrpv0bmMeff = new TH1D("Meff_SRrpv0bmMeff_SS3L", "effective mass (N-1); m_{eff} (N-1) [GeV] ;Events / 100 GeV", 5, 600, 1600);
SRrpv0bmMeff->Sumw2();
TH1D *SRrpv1bmMeff = new TH1D("Meff_SRrpv1bmMeff_SS3L", "effective mass (N-1); m_{eff} (N-1) [GeV] ;Events / 100 GeV", 7, 600, 2000);
SRrpv1bmMeff->Sumw2();
TH1D *SRrpv3bmMeff = new TH1D("Meff_SRrpv3bmMeff_SS3L", "effective mass (N-1); m_{eff} (N-1) [GeV] ;Events / 100 GeV", 7, 600, 1300);
SRrpv3bmMeff->Sumw2();
// Initialize variables
//-----------------------------------------------------------------------
// other
double pileupwgh=1.0;
// Book histograms to be filled later
//-----------------------------------------------------------------------
if(!cutflow)
{
// BookHistos_Channel(ftag, "OS");
// BookHistos_Channel(ftag, "SS3L");
// BookHistos_Channel(ftag, "SS3L_noZ");
// BookHistos_Channel(ftag, "SS");
// BookHistos_Channel(ftag, "3L");
}
bool unique;
// Fake and charge flip backgrounds
//-----------------------------------------------------------------------
TwoLepSSFakeBkg stdMxmTool;
stdMxmTool.UseSplitErrBySource_OStoSS(true);
// Optimization
//-----------------------------------------------------------------------
vector<Float_t> lepptmax_cut= {75, 100, LargeNum};
vector<Float_t> lepptmin_cut= {10,20};
vector<Float_t> jetptmax_cut= {LargeNum};
vector<Float_t> jetptmin_cut= {25};
vector<Float_t> njets_cut= {6};
vector<Float_t> bjets_cut= {3};//0,1,2,3,4,5}; // Working points [30, 50, 60, 70, 77, 85]
vector<Float_t> bjetptmax_cut= {LargeNum};
vector<Float_t> bjetptmin_cut= {20};
vector<Float_t> nbjets_cut= {1,2,3};
vector<Float_t> metmax_cut= {LargeNum};
vector<Float_t> metmin_cut= {0, 100, 150, 200, 220, 250, 300, 350, 400};
vector<Float_t> mtMmax_cut= {LargeNum};
vector<Float_t> mtMmin_cut= {0};
vector<Float_t> meff_cut= {0,600,700,800,900,1000,1100,1200};
vector<Float_t> metOmeff_cut= {0,0.2,0.25,0.3};
Int_t optbins=1;
optbins*=lepptmax_cut.size(); // lep1
optbins*=lepptmin_cut.size(); // lep1
optbins*=lepptmax_cut.size(); // lep2
optbins*=lepptmin_cut.size(); // lep2
optbins*=jetptmax_cut.size();
optbins*=jetptmin_cut.size();
optbins*=njets_cut.size();
optbins*=bjets_cut.size();
optbins*=bjetptmax_cut.size();
optbins*=bjetptmin_cut.size();
optbins*=nbjets_cut.size();
optbins*=metmax_cut.size();
optbins*=metmin_cut.size();
optbins*=mtMmax_cut.size();
optbins*=mtMmin_cut.size();
optbins*=meff_cut.size();
optbins*=metOmeff_cut.size();
std::cout << "Optimization ===============> Number of Bins=" << optbins << std::endl;
TH1F* hyield= new TH1F("hyield","hyield",optbins,1,optbins+1);
hyield->Sumw2();
TH1F* hyield_weighted= new TH1F("hyield_weighted","hyield weighted",optbins,1,optbins+1);
hyield_weighted->Sumw2();
int processed=0;
float scaled=0, Xsect=0, sumWeight=0;
bool newtree=false;
// Main event loop
//-----------------------------------------------------------------------
for (Long64_t entr_ind = 0; entr_ind < tree_Entries; entr_ind++) {
oldtree->GetEntry(entr_ind);
if (treeno != ((TChain*) oldtree)->GetTreeNumber()) {
declarestructs(oldtree->GetTree(), &evt);
oldtree->GetEntry(entr_ind);
treeno = ((TChain*) oldtree)->GetTreeNumber();
filename = oldtree->GetFile()->GetName();
newtree=true;
}
// Extend ttbar samples using HT samples
// HT Sliced samples: 407009 || 407010 || 407011
if(!useTTbarHT && (evt.ChannelNumber == 407009 || evt.ChannelNumber == 407010 || evt.ChannelNumber == 407011 ))
continue;
if( useTTbarHT && evt.ChannelNumber == 410000 && evt.GenFiltHT > 600000 )
continue;
// Extend ttbar samples using MET samples
// ChannelNumber: 407012
if(!useTTbarMET && evt.ChannelNumber == 407012)
continue;
if(useTTbarMET && evt.ChannelNumber == 410000 && evt.GenFiltMET > 200000 )
continue;
// Sanity checks
num_vtx_noPRW->Fill(evt.Nvtx, evt.EventWeight);
averageIntPerXing_noPRW->Fill(evt.AvgMu, evt.EventWeight);
num_of_leptons_noPRW->Fill(evt.NEl + evt.NMu, evt.EventWeight);
num_of_jets_noPRW->Fill(evt.NJet, evt.EventWeight);
for (int ijet=0; ijet<evt.NJet; ijet++){
btag_weight_noPRW->Fill(evt.Jet_MV2c20[ijet], evt.EventWeight);
btagwgh_mu_noPRW->Fill(evt.AvgMu, evt.Jet_MV2c20[ijet], evt.EventWeight);
}
eventInfo->setEventNumber(evt.EventNumber);
eventInfo->setRunNumber(evt.RunNb);
eventInfo->setLumiBlock(evt.LB);
if(evt.isMC){
// Put the ntuple variables into EventInfo
eventInfo->setMCChannelNumber(evt.ChannelNumber);
eventInfo->setEventTypeBitmask( xAOD::EventInfo::IS_SIMULATION );
eventInfo->setAverageInteractionsPerCrossing(evt.AvgMu);
vector<float> w;
w.clear();
w.push_back(evt.EventWeight);
eventInfo->setMCEventWeights( w );
// Pileup reweighting
pileupwgh = 1.0;
// nominal case
CP::SystematicSet defaultSet;
CHECK(m_Pileup->applySystematicVariation(defaultSet) );
// produces a decoration in Eventinfo
CHECK(m_Pileup->apply(*eventInfo,false) );
// example to retrieve decoration:
pileupwgh = eventInfo->auxdata< float >( "PileupWeight" );
// apply prw
evt.EventWeight *= pileupwgh;
num_vtx_PRW->Fill(evt.Nvtx, pileupwgh);
averageIntPerXing_PRW->Fill(evt.AvgMu, pileupwgh);
num_of_leptons_PRW->Fill(evt.NEl + evt.NMu, pileupwgh);
num_of_jets_PRW->Fill(evt.NJet, pileupwgh);
for (int ijet=0; ijet<evt.NJet; ijet++){
btag_weight_PRW->Fill(evt.Jet_MV2c20[ijet], pileupwgh);
btagwgh_mu_PRW->Fill(evt.AvgMu, evt.Jet_MV2c20[ijet], evt.EventWeight);
}
}
evt.EventWeight /= pileupwgh;
//========================================================================
// General Selection
//========================================================================
// Analyzer
//-----------------------------------------------------------------------
cut_flow->Fill(0.1, 1.0);//evt.EventWeight);
if(!newtree)
processed+=1;
// good run lists
bool muo_GRL = true;
if (!evt.isMC) {
muo_GRL = m_grl->passRunLB(eventInfo->runNumber(), eventInfo->lumiBlock()); //(my_grl.HasRunLumiBlock(evt.RunNb, evt.LB));
}
if (!muo_GRL )
continue;
cut_flow->Fill(1.1, 1.0);//evt.EventWeight);
// we test if the event is unique (in data)
if (!evt.isMC) {
unique = (evtmap[evt.RunNb].insert(evt.EventNumber)).second;
if (!unique) {
std::cout << "\nWarning: duplicate event in RunNb=" << evt.RunNb << std::endl;
continue;
}
}
// primary vertex
bool goodPV = (evt.PV_z > -999);
if(!goodPV)
continue;
cut_flow->Fill(2.1,1.0);//evt.EventWeight);
// trigger
bool trigger = true;
int RunNum=1;
if(evt.isMC)
RunNum =m_Pileup->getRandomRunNumber( *eventInfo , true);
else
RunNum = evt.RunNb;
evt.trigRND = RunNum;
if(RunNum > 290000){
// 2016 strategy
if(evt.Etmiss_TST_Et <= 250000)
trigger = ( evt.HLT_2e17_lhvloose_nod0 || evt.HLT_e17_lhloose_nod0_mu14 || evt.HLT_mu22_mu8noL1 );
else if(evt.Etmiss_TST_Et > 250000)
trigger = ( evt.HLT_2e17_lhvloose_nod0 || evt.HLT_e17_lhloose_nod0_mu14 || evt.HLT_mu22_mu8noL1 || evt.HLT_xe100_mht_L1XE50 || evt.HLT_xe110_mht_L1XE50);
}
else {
// 2015 strategy
if(evt.Etmiss_TST_Et <= 250000)
trigger = (evt.HLT_2e12_lhloose_L12EM10VH || evt.HLT_mu18_mu8noL1 || evt.HLT_e17_lhloose_mu14 );
else if(evt.Etmiss_TST_Et > 250000)
trigger = (evt.HLT_2e12_lhloose_L12EM10VH || evt.HLT_mu18_mu8noL1 || evt.HLT_e17_lhloose_mu14 || evt.HLT_xe70);
}
if(!trigger)
continue;
cut_flow->Fill(3.1,1.0);//evt.EventWeight);
// global flags
bool global = (evt.DetError == 1);
if(global)
continue;
cut_flow->Fill(4.1,1.0);//evt.EventWeight);
// muon cleaning
bool nobadmuon = true;
for (int mui = 0; mui < evt.NMu; mui++)
if(is_baseline_muon(&evt, mui))
nobadmuon &= !evt.Mu_isBad[mui];
if(!nobadmuon)
continue;
cut_flow->Fill(5.1,1.0);//evt.EventWeight);
// Overlap removal
//-----------------------------------------------------------------------
my_jets jet;
my_leptons lep_baseline;
// check jet OR
jet.num_jets = 0;
for (int jetk = 0; jetk < evt.NJet; jetk++)
if( (is_baseline_jet(&evt, jetk) && evt.Jet_passOR[jetk]) || !applyOR){
jet.index[jet.num_jets] = jetk;
jet.E[jet.num_jets] = evt.Jet_E[jetk];
jet.pT[jet.num_jets] = evt.Jet_pT[jetk];
jet.eta[jet.num_jets] = evt.Jet_eta[jetk];
jet.phi[jet.num_jets] = evt.Jet_phi[jetk];
jet.MV2c20[jet.num_jets] = evt.Jet_MV2c20[jetk];
jet.num_jets++;
}
if(cutflow){
if(jet.num_jets < 1)
continue;
cut_flow->Fill(6.1,1.0);//evt.EventWeight);
}
// check el and mu OR
lep_baseline.num_leptons = 0;
for (int eli = 0; eli < evt.NEl ; eli++)
if( (is_baseline_electron(&evt, eli) && evt.El_passOR[eli]) || !applyOR)
{
lep_baseline.index[lep_baseline.num_leptons] = eli;
lep_baseline.m[lep_baseline.num_leptons] = electron_mass;
lep_baseline.E[lep_baseline.num_leptons] = evt.El_E[eli];
lep_baseline.pT[lep_baseline.num_leptons] = evt.El_pT[eli];
lep_baseline.phi[lep_baseline.num_leptons] = evt.El_phi[eli];
lep_baseline.eta[lep_baseline.num_leptons] = evt.El_eta[eli];
lep_baseline.SFw[lep_baseline.num_leptons] = evt.El_SFwTightLH[eli];
lep_baseline.is_electron[lep_baseline.num_leptons] = true;
lep_baseline.charge[lep_baseline.num_leptons] = evt.El_charge[eli];
lep_baseline.num_leptons++;
}
//rm muon overlapping with electron
for (int mui = 0; mui < evt.NMu ; mui++)
if( (is_baseline_muon(&evt, mui) && evt.Mu_passOR[mui]) || !applyOR)
{
lep_baseline.index[lep_baseline.num_leptons] = mui;
lep_baseline.m[lep_baseline.num_leptons] = muon_mass;
lep_baseline.pT[lep_baseline.num_leptons] = evt.Mu_pT[mui];
lep_baseline.phi[lep_baseline.num_leptons] = evt.Mu_phi[mui];
lep_baseline.eta[lep_baseline.num_leptons] = evt.Mu_eta[mui];
lep_baseline.SFw[lep_baseline.num_leptons] = evt.Mu_SFw[mui];
lep_baseline.is_electron[lep_baseline.num_leptons] = false;
lep_baseline.charge[lep_baseline.num_leptons] = evt.Mu_charge[mui];
lep_baseline.num_leptons++;
}
// End Overlap Removal
// jet cleaning; check all eta
bool nobadjet = true;
for (int jetk = 0; jetk < jet.num_jets; jetk++)
nobadjet &= (evt.Jet_quality[jet.index[jetk]] == 0);
if(!nobadjet )
continue;
cut_flow->Fill(7.1,1.0);//evt.EventWeight);
my_jets jet_signal;
jet_signal.num_jets = 0;
for (int jeti = 0; jeti < jet.num_jets; jeti++)
if(is_signal_jet(&evt, jet.index[jeti]))
{
jet_signal.index[jet_signal.num_jets] = jet.index[jeti];
jet_signal.E[jet_signal.num_jets] = jet.E[jeti];
jet_signal.pT[jet_signal.num_jets] = jet.pT[jeti];
jet_signal.eta[jet_signal.num_jets] = jet.eta[jeti];
jet_signal.phi[jet_signal.num_jets] = jet.phi[jeti];
jet_signal.MV2c20[jet_signal.num_jets] = jet.MV2c20[jeti];
jet_signal.num_jets++;
}
vector<my_jets> bjet_signal(bjets_cut.size());
for (unsigned int icut=0; icut < bjets_cut.size();icut++){
bjet_signal[icut].num_jets = 0;
for (int jeti = 0; jeti < jet.num_jets; jeti++)
if(is_signal_bjet(&evt, jet.index[jeti],bjets_cut[icut])){
bjet_signal[icut].index[bjet_signal[icut].num_jets] = jet.index[jeti];
bjet_signal[icut].E[bjet_signal[icut].num_jets] = jet.E[jeti];
bjet_signal[icut].pT[bjet_signal[icut].num_jets] = jet.pT[jeti];
bjet_signal[icut].eta[bjet_signal[icut].num_jets] = jet.eta[jeti];
bjet_signal[icut].phi[bjet_signal[icut].num_jets] = jet.phi[jeti];
bjet_signal[icut].MV2c20[bjet_signal[icut].num_jets] = jet.MV2c20[jeti];
bjet_signal[icut].num_jets++;
}
}
int n_jets_50 = 0;
for (int jeti = 0; jeti < jet_signal.num_jets; jeti++)
if(jet_signal.pT[jeti]>50000)
n_jets_50++;
int n_jets_25 = 0;
for (int jeti = 0; jeti < jet_signal.num_jets; jeti++)
if(jet_signal.pT[jeti]>25000)
n_jets_25++;
int n_jets_30 = 0;
for (int jeti = 0; jeti < jet_signal.num_jets; jeti++)
if(jet_signal.pT[jeti]>30000)
n_jets_30++;
int n_jets_40 = 0;
for (int jeti = 0; jeti < jet_signal.num_jets; jeti++)
if(jet_signal.pT[jeti]>40000)
n_jets_40++;
// int n_bjets = bjet_signal.num_jets;
vector<int> n_bjets( bjets_cut.size());
for (unsigned int icut=0; icut < bjets_cut.size();icut++){
n_bjets[icut] = bjet_signal[icut].num_jets;
}
if(cutflow){
if(jet_signal.num_jets <1)
continue;
}
cut_flow->Fill(8.1,1.0);//evt.EventWeight);
//sort leptons
sortLeptons(&lep_baseline);
// cosmic veto
bool nocosmicveto = NoCosmicMuon(&evt, &lep_baseline);
if(!nocosmicveto)
continue;
cut_flow->Fill(9.1,1.0);//evt.EventWeight);
// >=2 baseline leptons
if( (lep_baseline.num_leptons) <2)
continue;
cut_flow->Fill(10.1,1.0);//evt.EventWeight);
my_leptons lep_signal;
lep_signal.num_leptons = 0;
for (int lepi = 0; lepi < lep_baseline.num_leptons; lepi++)
if(((is_signal_electron(&evt, lep_baseline.index[lepi]) && lep_baseline.is_electron[lepi]) || (is_signal_muon(&evt, lep_baseline.index[lepi]) && !lep_baseline.is_electron[lepi])))
{
lep_signal.index[lep_signal.num_leptons] = lep_baseline.index[lepi];
lep_signal.m[lep_signal.num_leptons] = lep_baseline.m[lepi];
if(lep_baseline.is_electron[lepi])
lep_signal.E[lep_signal.num_leptons] = lep_baseline.E[lepi];
lep_signal.pT[lep_signal.num_leptons] = lep_baseline.pT[lepi];
lep_signal.phi[lep_signal.num_leptons] = lep_baseline.phi[lepi];
lep_signal.eta[lep_signal.num_leptons] = lep_baseline.eta[lepi];
lep_signal.SFw[lep_signal.num_leptons] = lep_baseline.SFw[lepi];
lep_signal.is_electron[lep_signal.num_leptons] = lep_baseline.is_electron[lepi];
lep_signal.charge[lep_signal.num_leptons] = lep_baseline.charge[lepi];
lep_signal.num_leptons++;
}
lep_signal.num_leptons_baseline = lep_baseline.num_leptons;
int num20GeVLept = 0;
for (int lepi = 0; lepi < lep_signal.num_leptons; lepi++)
if(lep_signal.pT[lepi] > LeptPt){
num20GeVLept++;
}
int numLept = 0;
for (int lepi = 0; lepi < lep_signal.num_leptons; lepi++)
{
numLept++;
}
// >=2 signal leptons with pT > 20 GeV
if(num20GeVLept < 2)
continue;
cut_flow->Fill(11.1,1.0);//evt.EventWeight);
//sort jets
sortJets(&jet_signal);
// sortJets(&bjet_signal);
for (unsigned int icut=0; icut < bjets_cut.size();icut++)
sortJets(&bjet_signal[icut]);
// Event contains Z
containsZ(&evt, &lep_signal);
dilepton_mass_comb(&evt, &lep_signal);
// Separate events into ee em mm
// SetChannelSeparation(&lep_signal);
// Determine fake and charge flipped leptons
// classify_leptons(&evt, &lep_signal);
// classify_leptons_custom(&evt, &lep_signal);
// if(isCFSource){
// classify_leptons_custom(&evt, &lep_signal);
// }
// Trigger matching
if(!cutflow){
if(!checkTriggerMatching(&evt, &lep_signal))
continue;
}
// same sign
// if(cutflow){
// if(!lep_signal.has_ss)
// continue;
// }
// cut_flow->Fill(12.1,1.0);//evt.EventWeight);
//miss-Et variables
float mis_Ex = evt.Etmiss_TST_Etx;
float mis_Ey = evt.Etmiss_TST_Ety;
float met = sqrt(mis_Ex * mis_Ex + mis_Ey * mis_Ey);
//========================================================================
// re-weighting
//========================================================================
if(evt.isMC){
// Apply pileupwgh
evt.EventWeight *= pileupwgh;
// Cross sections
double weightXsection = 1.;
double XsecXeff = myXsection.xsectTimesEff(evt.ChannelNumber);
if( !GG && !BB && !strong )
XsecXeff = myXsection.xsectTimesEff(evt.ChannelNumber);
else if(GG)
XsecXeff = myXsection.xsectTimesEff(evt.ChannelNumber,2);
else if(BB)
XsecXeff = myXsection.xsectTimesEff(evt.ChannelNumber,51);
else if(strong){ // NUHM2
XsecXeff = myXsection.xsectTimesEff(evt.ChannelNumber,2);
}
if(XsecXeff>0)
weightXsection = (luminosity*XsecXeff/evt.sumWeight);
else{
weightXsection = -999.0;
if(noXsection){
cout << "================0 weight=============" << std::endl;
std::cout << evt.ChannelNumber << " " << XsecXeff << " " << weightXsection << std::endl;
cout << "=====================================" << std::endl;
noXsection = false;
}
}
static int lastChanNum = -99999;
if(lastChanNum != evt.ChannelNumber){
std::cout << "ChannelNum " << evt.ChannelNumber << ", XsecXeff " << XsecXeff << ", sumWeight " << evt.sumWeight << ", luminosity " << luminosity << ", weight " << weightXsection << ", FullSim " << is_FullSim(&evt) << std::endl;
lastChanNum = evt.ChannelNumber;
}
evt.EventWeight *= weightXsection;
if(!newtree){
Xsect=XsecXeff;
sumWeight=evt.sumWeight;
}
if(sumWeight) {};
double lepW = 1.;
double elW = 1.;
double muW = 1.;
// lepton scale factors
for (int lepi = 0; lepi < lep_signal.num_leptons; lepi++)
{
if(lep_signal.is_electron[lepi]) // electron scale factor
{
if(evt.El_isMediumLH[lep_signal.index[lepi]]){
elW *= evt.El_SFwMediumLH[lep_signal.index[lepi]]*evt.El_IsoSFwMediumLH[lep_signal.index[lepi]];
}
else
elW *= 1.;
} else {// muon scale factor
muW *= evt.Mu_SFw[lep_signal.index[lepi]]*evt.Mu_IsoSFw[lep_signal.index[lepi]];
}
}
lepW = elW * muW;
evt.EventWeight *= lepW;
double jetW = 1.;
double jetjvt = 1.;
for (int jeti = 0; jeti < jet_signal.num_jets; jeti++)
if(fabs(jet_signal.eta[jeti])<2.5){
jetW *= evt.Jet_SFw[jet_signal.index[jeti]]*evt.Jet_JVTsf[jet_signal.index[jeti]];
jetjvt *= evt.Jet_JVTsf[jet_signal.index[jeti]];
}
evt.EventWeight *= jetW;
event_weight_noXsec->Fill(evt.EventWeight/weightXsection,evt.EventWeight);
evtwgh_mu_noXsec->Fill(evt.AvgMu, evt.EventWeight/weightXsection,evt.EventWeight);
}
//========================================================================
// Main part of the optimization
//========================================================================
double meff = 0.0;
double ht = 0.0;
double metOmeff = 0.0;
// double mtM = transverse_mass_min(&evt, &lep_signal);
double mtM = transverse_mass(&evt, &lep_signal);
vector<int> njets(jetptmin_cut.size(),0);
vector<vector<int>> nbjets(bjets_cut.size(), vector<int>(bjetptmin_cut.size(),0));
// leptons pt
for (int i = 0; i < lep_signal.num_leptons; i++)
meff += lep_signal.pT[i];
// jets pt
for (int i = 0; i < jet_signal.num_jets; i++)
meff += jet_signal.pT[i];
ht = meff; if(ht) {};
meff += met;
metOmeff = met/meff;
for(unsigned int i_jetpt=0;i_jetpt<jetptmin_cut.size();i_jetpt++)
for (int i = 0; i < jet_signal.num_jets; i++)
if(jet_signal.pT[i]/1000.0>jetptmin_cut[i_jetpt])
njets[i_jetpt]++;
for(unsigned int i_bjet_cut=0;i_bjet_cut<bjets_cut.size();i_bjet_cut++)
for(unsigned int i_bjetpt=0;i_bjetpt<bjetptmin_cut.size();i_bjetpt++)
for (int i = 0; i < bjet_signal[i_bjet_cut].num_jets; i++)
if(bjet_signal[i_bjet_cut].pT[i]/1000.0>bjetptmin_cut[i_bjetpt])
nbjets[i_bjet_cut][i_bjetpt]++;
double tmp_evtWgh = evt.EventWeight;
for(unsigned int i_lepptmax2=0;i_lepptmax2<lepptmax_cut.size();i_lepptmax2++)
for(unsigned int i_lepptmin2=0;i_lepptmin2<lepptmin_cut.size();i_lepptmin2++)
for(unsigned int i_lepptmax1=0;i_lepptmax1<lepptmax_cut.size();i_lepptmax1++)
for(unsigned int i_lepptmin1=0;i_lepptmin1<lepptmin_cut.size();i_lepptmin1++)
{
// Separate events into ee em mm
SetChannelSeparation(&lep_signal, lepptmin_cut[i_lepptmin1], lepptmax_cut[i_lepptmax1], lepptmin_cut[i_lepptmin2],lepptmax_cut[i_lepptmax2]);
// same sign and passed lepton pt cuts
if(!lep_signal.has_ss)
continue;
if(evt.isMC){
// DileptonTriggerWeight
double dtW = 1.;
bool passMET = false;
if( RunNum > 290000 && met>250000 && (evt.HLT_xe100_mht_L1XE50 || evt.HLT_xe110_mht_L1XE50)) passMET = true;
if( RunNum <= 290000 && met>250000 && evt.HLT_xe70) passMET = true;
bool failMET = ( (RunNum <= 290000 && (met < 250000 || !evt.HLT_xe70)) || (RunNum > 290000 && (met < 250000 || (!evt.HLT_xe100_mht_L1XE50 && !evt.HLT_xe110_mht_L1XE50))) );
if( failMET )
{
if(passMET)
std::cout << "Problem with MET selection for DileptonTriggerWeight in RunNum=" << RunNum << ", with met=" << met << std::endl;
// lepton scale factors
for (int lepi = 0; lepi < lep_signal.num_leptons; lepi++)
{
if(lep_signal.is_electron[lepi]) // electron scale factor
dtwTool.AddElectron(lep_signal.pT[lepi],lep_signal.eta[lepi],RunNum, is_FullSim(&evt));
else // muon scale factor
dtwTool.AddMuon(lep_signal.pT[lepi],lep_signal.eta[lepi],lep_signal.phi[lepi], RunNum);
}
double uncertainty;
dtW = dtwTool.GetScaleFactor(uncertainty);
} else
dtW = 1.;
double fakeW=1;
if(lep_signal.has_ss){
// fake correction factors
for (int lepi = 0; lepi < lep_signal.num_leptons; lepi++)
{
if(lep_signal.is_electron[lepi])
fakeCorr.AddElectron(evt.ChannelNumber, lep_signal.pT[lepi], lep_signal.charge[lepi], evt.El_truthType[lep_signal.index[lepi]], evt.El_truthOrigin[lep_signal.index[lepi]], evt.El_firstEgMotherPdgId[lep_signal.index[lepi]]);
else
fakeCorr.AddMuon(evt.ChannelNumber, lep_signal.pT[lepi], lep_signal.charge[lepi], evt.Mu_type[lep_signal.index[lepi]], evt.Mu_origin[lep_signal.index[lepi]]);
}
double uncertainty;
fakeW = fakeCorr.GetFakeCorrection(uncertainty);
}
else
fakeW = 1.;
fakeW = 1.;
evt.EventWeight = tmp_evtWgh*dtW*fakeW;
}
for(unsigned int i_bjets=0;i_bjets<bjets_cut.size();i_bjets++)
for(unsigned int i_bjetptmax=0;i_bjetptmax<bjetptmax_cut.size();i_bjetptmax++)
for(unsigned int i_bjetptmin=0;i_bjetptmin<bjetptmin_cut.size();i_bjetptmin++)
for(unsigned int i_nbjets=0;i_nbjets<nbjets_cut.size();i_nbjets++)
if(nbjets[i_bjets][i_bjetptmin] == nbjets_cut[i_nbjets]) // missing case where we require exactly 0bjets
for(unsigned int i_jetptmax=0;i_jetptmax<jetptmax_cut.size();i_jetptmax++)
for(unsigned int i_jetptmin=0;i_jetptmin<jetptmin_cut.size();i_jetptmin++)
for(unsigned int i_njets=0;i_njets<njets_cut.size();i_njets++)
if(njets[i_jetptmin]>=njets_cut[i_njets])
for(unsigned int i_metmax=0;i_metmax<metmax_cut.size();i_metmax++)
if(met/1000.0<metmax_cut[i_metmax])
for(unsigned int i_metmin=0;i_metmin<metmin_cut.size();i_metmin++)
if(met/1000.0>metmin_cut[i_metmin] && metmin_cut[i_metmin]<metmax_cut[i_metmax]) {
// float baseMeff=metmin_cut[i_metmin]+njets_cut[i_njets]*jetptmin_cut[i_jetptmin]+lepptmin_cut[i_lepptmin1]+lepptmin_cut[i_lepptmin2];
for(unsigned int i_mtMmax=0;i_mtMmax<mtMmax_cut.size();i_mtMmax++)
if(mtM/1000.0<mtMmax_cut[i_mtMmax] )
for(unsigned int i_mtMmin=0;i_mtMmin<mtMmin_cut.size();i_mtMmin++)
if(mtM/1000.0>mtMmin_cut[i_mtMmin] && mtMmin_cut[i_mtMmin]<mtMmax_cut[i_mtMmax])
for(unsigned int i_meff=0;i_meff<meff_cut.size();i_meff++)
if (meff/1000.0>(/*baseMeff+*/meff_cut[i_meff]))
for(unsigned int i_metOmeff=0;i_metOmeff<metOmeff_cut.size();i_metOmeff++)
if (metOmeff>metOmeff_cut[i_metOmeff])
{
int bin=1;
bin += i_metOmeff;
bin += i_meff*metOmeff_cut.size();
bin += i_mtMmin*metOmeff_cut.size()*meff_cut.size();
bin += i_mtMmax*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size();
bin += i_metmin*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size();
bin += i_metmax*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size();
bin += i_njets*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size();
bin += i_jetptmin*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size()*njets_cut.size();
bin += i_jetptmax*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size()*njets_cut.size()*jetptmin_cut.size();
bin += i_nbjets*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size()*njets_cut.size()*jetptmin_cut.size()*jetptmax_cut.size();
bin += i_bjetptmin*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size()*njets_cut.size()*jetptmin_cut.size()*jetptmax_cut.size()*nbjets_cut.size();
bin += i_bjetptmax*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size()*njets_cut.size()*jetptmin_cut.size()*jetptmax_cut.size()*nbjets_cut.size()*bjetptmin_cut.size();
bin += i_bjets*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size()*njets_cut.size()*jetptmin_cut.size()*jetptmax_cut.size()*nbjets_cut.size()*bjetptmin_cut.size()*bjetptmax_cut.size();
bin += i_lepptmin1*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size()*njets_cut.size()*jetptmin_cut.size()*jetptmax_cut.size()*nbjets_cut.size()*bjetptmin_cut.size()*bjetptmax_cut.size()*bjets_cut.size();
bin += i_lepptmax1*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size()*njets_cut.size()*jetptmin_cut.size()*jetptmax_cut.size()*nbjets_cut.size()*bjetptmin_cut.size()*bjetptmax_cut.size()*bjets_cut.size()*lepptmin_cut.size();
bin += i_lepptmin2*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size()*njets_cut.size()*jetptmin_cut.size()*jetptmax_cut.size()*nbjets_cut.size()*bjetptmin_cut.size()*bjetptmax_cut.size()*bjets_cut.size()*lepptmin_cut.size()*lepptmax_cut.size();
bin += i_lepptmax2*metOmeff_cut.size()*meff_cut.size()*mtMmin_cut.size()*mtMmax_cut.size()*metmin_cut.size()*metmax_cut.size()*njets_cut.size()*jetptmin_cut.size()*jetptmax_cut.size()*nbjets_cut.size()*bjetptmin_cut.size()*bjetptmax_cut.size()*bjets_cut.size()*lepptmin_cut.size()*lepptmax_cut.size()*lepptmin_cut.size();
hyield->Fill(bin);
hyield_weighted->Fill(bin,evt.EventWeight);
}
}
} // End of lepton loop
} // End of event loop
fprintf(fp, "\nlepptmax2_cut = [");
for(unsigned int i_lepptmax2=0;i_lepptmax2<lepptmax_cut.size();i_lepptmax2++)
fprintf(fp, "%.0f, ", lepptmax_cut[i_lepptmax2]);
fprintf(fp, "]\nlepptmin2_cut = [ ");
for(unsigned int i_lepptmin2=0;i_lepptmin2<lepptmin_cut.size();i_lepptmin2++)
fprintf(fp, "%.0f, ", lepptmin_cut[i_lepptmin2]);
fprintf(fp, "]\nlepptmax1_cut = [ ");
for(unsigned int i_lepptmax1=0;i_lepptmax1<lepptmax_cut.size();i_lepptmax1++)
fprintf(fp, "%.0f, ", lepptmax_cut[i_lepptmax1]);
fprintf(fp, "]\nlepptmin1_cut = [ ");
for(unsigned int i_lepptmin1=0;i_lepptmin1<lepptmin_cut.size();i_lepptmin1++)
fprintf(fp, "%.0f, ", lepptmin_cut[i_lepptmin1]);
fprintf(fp, "]\nbjets_cut = [ ");
for(unsigned int i_bjets=0;i_bjets<bjets_cut.size();i_bjets++)
fprintf(fp, "%.0f, ", bjets_cut[i_bjets]);
fprintf(fp, "]\nbjetptmax_cut = [ ");
for(unsigned int i_bjetptmax=0;i_bjetptmax<bjetptmax_cut.size();i_bjetptmax++)
fprintf(fp, "%.0f, ", bjetptmax_cut[i_bjetptmax]);
fprintf(fp, "]\nbjetptmin_cut = [ ");
for(unsigned int i_bjetptmin=0;i_bjetptmin<bjetptmin_cut.size();i_bjetptmin++)
fprintf(fp, "%.0f, ", bjetptmin_cut[i_bjetptmin]);
fprintf(fp, "]\nnbjets_cut = [ ");
for(unsigned int i_nbjets=0;i_nbjets<nbjets_cut.size();i_nbjets++)
fprintf(fp, "%.0f, ", nbjets_cut[i_nbjets]);
fprintf(fp, "]\njetptmax_cut = [ ");
for(unsigned int i_jetptmax=0;i_jetptmax<jetptmax_cut.size();i_jetptmax++)
fprintf(fp, "%.0f, ", jetptmax_cut[i_jetptmax]);
fprintf(fp, "]\njetptmin_cut = [ ");
for(unsigned int i_jetptmin=0;i_jetptmin<jetptmin_cut.size();i_jetptmin++)
fprintf(fp, "%.0f, ", jetptmin_cut[i_jetptmin]);
fprintf(fp, "]\nnjets_cut = [ ");
for(unsigned int i_njets=0;i_njets<njets_cut.size();i_njets++)
fprintf(fp, "%.0f, ", njets_cut[i_njets]);
fprintf(fp, "]\nmetmax_cut = [ ");
for(unsigned int i_metmax=0;i_metmax<metmax_cut.size();i_metmax++)
fprintf(fp, "%.0f, ", metmax_cut[i_metmax]);
fprintf(fp, "]\nmetmin_cut = [ ");
for(unsigned int i_metmin=0;i_metmin<metmin_cut.size();i_metmin++)
fprintf(fp, "%.0f, ", metmin_cut[i_metmin]);
fprintf(fp, "]\nmtMmax_cut = [ ");
for(unsigned int i_mtMmax=0;i_mtMmax<mtMmax_cut.size();i_mtMmax++)
fprintf(fp, "%.0f, ", mtMmax_cut[i_mtMmax]);
fprintf(fp, "]\nmtMmin_cut = [ ");
for(unsigned int i_mtMmin=0;i_mtMmin<mtMmin_cut.size();i_mtMmin++)
fprintf(fp, "%.0f, ", mtMmin_cut[i_mtMmin]);
fprintf(fp, "]\nmeff_cut = [ ");
for(unsigned int i_meff=0;i_meff<meff_cut.size();i_meff++)
fprintf(fp, "%.0f, ", meff_cut[i_meff]);
fprintf(fp, "]\nmetOmeff_cut = [ ");
for(unsigned int i_metOmeff=0;i_metOmeff<metOmeff_cut.size();i_metOmeff++)
fprintf(fp, "%.2f, ", metOmeff_cut[i_metOmeff]);
fprintf(fp, "]\n");
file.Write();
fclose(fp);
fclose(fpy);
fclose(fpd);
return 0;
}
//-----------------------------------------------------------------------
int main(int argc, char **argv) {
TChain tc("MiniNtuple");
// show usage
if (argc < 3) {
std::cout << "Usage: " << argv[0] << " foldername filename /my_folder/file-list.root\n";
return 1;
}
for (int i = 3; i < argc; i++) {
tc.Add(argv[i]);
}
return main_loop(&tc, argv[1], argv[2]);
}
// Debugging statements
// std::cout << evt.EventNumber << std::endl;
// if(evt.EventNumber == -1 || evt.EventNumber == -1 || evt.EventNumber == -1)
// debug_printall(&evt);
// debug_lept(&evt, &lep_baseline);
// debug_jet(&evt, &jet);
// debug_objects(&evt, &lep_baseline, &jet_signal, fp, true);
// debug_SR_VR(&evt, &lep_signal, &jet_signal, &bjet_signal, fp, true);
/* if( evt.EventNumber == 1051409 ){
std::cout << "just before trigger ..." << std::endl;
std::cout << "RunNb=" << RunNum <<
", MET " << evt.Etmiss_TST_Et <<
", HLT_2e17_lhvloose_nod0 " << evt.HLT_2e17_lhvloose_nod0 <<
", HLT_e17_lhloose_nod0_mu14 " << evt.HLT_e17_lhloose_nod0_mu14 <<
", HLT_mu20_mu8noL1 " << evt.HLT_mu20_mu8noL1 <<
", HLT_xe80_tc_lcw_L1XE50 " << evt.HLT_xe80_tc_lcw_L1XE50 <<
std::endl;
std::cout << "2015 Config" <<
", MET " << evt.Etmiss_TST_Et <<
", HLT_2e12_lhloose_L12EM10VH " << evt.HLT_2e12_lhloose_L12EM10VH <<
", HLT_mu18_mu8noL1 " << evt.HLT_mu18_mu8noL1 <<
", HLT_e17_lhloose_mu14 " << evt.HLT_e17_lhloose_mu14 <<
", HLT_xe70 " << evt.HLT_xe70 <<
std::endl;
}*/
| [
"[email protected]"
] | |
9bb75e93253036674440c56f6c0294d69acddf5f | 0932a1d94a15ef74294acde30e1bc3267084e3f4 | /Classification/ACdream/字符串/1125.cpp | d79dab66775a7725d434cd935916f50e45016445 | [] | no_license | wuzhen247/ACM-ICPC | 9e585cb425cb0a5d2698f4c603f04a04ade84b88 | 65b5ab5e86c07e9f1d7c5c8e42f704bbabc8c20d | refs/heads/master | 2020-05-17T19:51:48.804361 | 2016-09-03T12:21:59 | 2016-09-03T12:21:59 | 33,580,771 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 567 | cpp | //求s中任意子串不同的字典序最小的串
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
char s[1100];
int main()
{
int t, n, m, len;
scanf("%d", &t);
while (t--)
{
scanf("%s", s);
len = strlen(s);
n = m = 0;
for (int i = 0; i < len; i++)
{
if (s[i] == 'A')
m++;
else
m = 0;
n = max(n, m);
}
n++;
while (n--)
printf("A");
printf("\n");
}
return 0;
}
| [
"[email protected]"
] | |
a37b26a3e768db53a03aa84f28898b7609dc579d | 41154f2fc66a4e018010b8b902e9e4821aee84ea | /Dijkstra using MinHeap with graph as adjacency list.cpp | 66190539a70bc0cdfd210ca2659f02e2baec0624 | [] | no_license | ApurboStarry/CPP-programming-files | 02cc621d8331c5060dd3a9905d107cc94fe42314 | 880794490f1334a4c0475eebd7a9e70f4df46450 | refs/heads/master | 2020-04-02T23:26:47.241750 | 2018-11-28T16:07:28 | 2018-11-28T16:07:28 | 154,867,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,744 | cpp | #include <bits/stdc++.h>
#include <huday.h>
#define INFINITE 99999
using namespace std;
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
struct Node {
int dist;
int vertex;
};
void swapNode(Node *a, Node *b) {
Node temp = *a;
*a = *b;
*b = temp;
}
class MinHEAP {
Node *heapArray;
int *index;
int heapSize;
int capacity;
public:
MinHEAP(int capacity);
int parent(int i) {return (i-1) / 2;}
int left(int i) {return 2*i + 1;}
int right(int i) {return 2*i + 2;}
void insertNode(Node a);
void minHeapify(int i);
void decreaseKey(int vertex, int dist);
bool isEmpty() {return heapSize == 0;};
Node extractMin();
void print();
Node check();
int indexOf(int vertex) {return index[vertex];}
};
Node MinHEAP::check() {
Node a;
a.dist = 3;
a.vertex = 4;
return a;
}
void MinHEAP::print() {
cout << "Vertex Distance Index" << endl;
for(int i = 0; i < heapSize; i++) {
cout << heapArray[i].vertex << "\t" << heapArray[i].dist << "\t\t" << index[heapArray[i].vertex] << endl;
}
cout << endl;
}
Node MinHEAP::extractMin() {
if(heapSize <= 0) {
cout << "Heap is already empty" << endl;
//return INT_MAX;
}
if(heapSize == 1) {
heapSize--;
return heapArray[0];
}
Node root = heapArray[0];
heapArray[0] = heapArray[heapSize - 1];
index[heapArray[0].vertex] = 0;
heapSize--;
minHeapify(0);
return root;
}
void MinHEAP::decreaseKey(int vertex, int dist) {
int i = index[vertex];
heapArray[i].dist = dist;
while (i != 0 && heapArray[parent(i)].dist > heapArray[i].dist) {
swapNode(&heapArray[i], &heapArray[parent(i)]);
swap(&index[heapArray[i].vertex], &index[heapArray[parent(i)].vertex]);
i = parent(i);
}
}
void MinHEAP::minHeapify(int i) {
int l = left(i);
int r = right(i);
int smallest = i;
if(l < heapSize && heapArray[l].dist < heapArray[i].dist) {
smallest = l;
}
if(r < heapSize && heapArray[r].dist < heapArray[smallest].dist) {
smallest = r;
}
if(smallest != i) {
swapNode(&heapArray[smallest], &heapArray[i]);
swap(&index[heapArray[smallest].vertex], &index[heapArray[i].vertex]);
minHeapify(smallest);
}
}
void MinHEAP::insertNode(Node a) {
if(heapSize == capacity) {
cout << "Overload" << endl;
return;
}
heapSize++;
int i = heapSize - 1;
heapArray[i] = a;
index[a.vertex] = i;
while(i != 0 && heapArray[parent(i)].dist > heapArray[i].dist) {
swapNode(&heapArray[parent(i)], &heapArray[i]);
swap(&index[heapArray[parent(i)].vertex], &index[heapArray[i].vertex]);
i = parent(i);
}
}
MinHEAP::MinHEAP(int cap) {
heapArray = new Node[cap];
capacity = cap;
heapSize = 0;
index = new int[cap];
}
///-----------------------------------------------------------------------------------///
void printSolution(int dist[], int V) {
cout << "Vertex Distance" << endl;
for(int i = 0; i < V; i++) {
cout << i << "\t" << dist[i] << endl;
}
}
void dijkstra(vector<pair<int, int>> adj[], int V, int src) {
int dist[V];
bool sptSet[V];
int prev[V];
for(int i = 0; i < V; i++) {
dist[i] = INFINITE;
prev[i] = -1;
sptSet[i] = false;
}
dist[src] = 0;
MinHEAP h(V);
for(int i = 0; i < V; i++) {
Node a;
a.vertex = i;
a.dist = dist[i];
h.insertNode(a);
}
while(!h.isEmpty()) {
Node extracted = h.extractMin();
int u = extracted.vertex;
for(auto it = adj[u].begin(); it != adj[u].end(); it++) {
int v = it->first;
int wt = it->second;
if(sptSet[v] == false && dist[u] != INFINITE && dist[v] > dist[u] + wt) {
dist[v] = dist[u] + wt;
prev[v] = u;
h.decreaseKey(v, dist[v]);
}
}
}
printSolution(dist, V);
}
void addEdge(vector<pair<int, int>> adj[], int u, int v, int wt) {
adj[u].push_back(make_pair(v, wt));
adj[v].push_back(make_pair(u, wt));
}
int main() {
/*
int V = 9;
vector<pair<int, int>> adj[V];
addEdge(adj, 0, 1, 4);
addEdge(adj, 0, 7, 8);
addEdge(adj, 1, 7, 11);
addEdge(adj, 1, 2, 8);
addEdge(adj, 2, 3, 7);
addEdge(adj, 2, 8, 2);
addEdge(adj, 7, 8, 7);
addEdge(adj, 7, 6, 1);
addEdge(adj, 6, 8, 6);
addEdge(adj, 6, 5, 2);
addEdge(adj, 2, 5, 4);
addEdge(adj, 3, 4, 9);
addEdge(adj, 3, 5, 14);
addEdge(adj, 5, 4, 10);
dijkstra(adj, V, 0);
*/
foo();
}
| [
"[email protected]"
] | |
b57d1eb05bff7f97ff2657d3dcdd652f05ed6936 | 0b52c11533f7394cea35b66b0448ff00bdea9511 | /build-Blackstone-Desktop_Qt_5_12_5_MinGW_32_bit-Debug/debug/moc_blackstone.cpp | c4ca70678d3ed82b25bc013030799d3ddf1f121c | [] | no_license | Neilio3264/Rook1 | 8459131e954449178c38239cebb30c7de26a14db | 1ac4fdcc3882588ff65963b54eee6ed48222ac3a | refs/heads/master | 2020-08-21T19:49:52.781172 | 2019-10-20T14:19:34 | 2019-10-20T14:19:34 | 216,233,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,408 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'blackstone.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.5)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../Blackstone/blackstone.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'blackstone.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.12.5. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_Blackstone_t {
QByteArrayData data[32];
char stringdata0[629];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Blackstone_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Blackstone_t qt_meta_stringdata_Blackstone = {
{
QT_MOC_LITERAL(0, 0, 10), // "Blackstone"
QT_MOC_LITERAL(1, 11, 9), // "pushLogin"
QT_MOC_LITERAL(2, 21, 0), // ""
QT_MOC_LITERAL(3, 22, 6), // "sortBy"
QT_MOC_LITERAL(4, 29, 22), // "on_loginButton_clicked"
QT_MOC_LITERAL(5, 52, 23), // "on_pushButton_2_clicked"
QT_MOC_LITERAL(6, 76, 22), // "on_ContinueBtn_clicked"
QT_MOC_LITERAL(7, 99, 23), // "on_pushButton_5_clicked"
QT_MOC_LITERAL(8, 123, 24), // "on_ContinueBtn_2_clicked"
QT_MOC_LITERAL(9, 148, 23), // "on_pushButton_6_clicked"
QT_MOC_LITERAL(10, 172, 21), // "on_noneButton_clicked"
QT_MOC_LITERAL(11, 194, 21), // "on_skimButton_clicked"
QT_MOC_LITERAL(12, 216, 20), // "on_fatButton_clicked"
QT_MOC_LITERAL(13, 237, 31), // "on_horizontalSlider_sliderMoved"
QT_MOC_LITERAL(14, 269, 8), // "position"
QT_MOC_LITERAL(15, 278, 33), // "on_horizontalSlider_2_sliderM..."
QT_MOC_LITERAL(16, 312, 21), // "on_comboBox_activated"
QT_MOC_LITERAL(17, 334, 4), // "arg1"
QT_MOC_LITERAL(18, 339, 23), // "on_comboBox_2_activated"
QT_MOC_LITERAL(19, 363, 20), // "on_CoffeePop_clicked"
QT_MOC_LITERAL(20, 384, 21), // "on_lightCheck_clicked"
QT_MOC_LITERAL(21, 406, 20), // "on_DarkCheck_clicked"
QT_MOC_LITERAL(22, 427, 20), // "on_coldCheck_clicked"
QT_MOC_LITERAL(23, 448, 19), // "on_hotCheck_clicked"
QT_MOC_LITERAL(24, 468, 23), // "on_nodairyCheck_clicked"
QT_MOC_LITERAL(25, 492, 20), // "on_skimCheck_clicked"
QT_MOC_LITERAL(26, 513, 21), // "on_wholeCheck_clicked"
QT_MOC_LITERAL(27, 535, 23), // "on_pushButton_4_clicked"
QT_MOC_LITERAL(28, 559, 21), // "on_pushButton_clicked"
QT_MOC_LITERAL(29, 581, 25), // "on_listWidget_itemClicked"
QT_MOC_LITERAL(30, 607, 16), // "QListWidgetItem*"
QT_MOC_LITERAL(31, 624, 4) // "item"
},
"Blackstone\0pushLogin\0\0sortBy\0"
"on_loginButton_clicked\0on_pushButton_2_clicked\0"
"on_ContinueBtn_clicked\0on_pushButton_5_clicked\0"
"on_ContinueBtn_2_clicked\0"
"on_pushButton_6_clicked\0on_noneButton_clicked\0"
"on_skimButton_clicked\0on_fatButton_clicked\0"
"on_horizontalSlider_sliderMoved\0"
"position\0on_horizontalSlider_2_sliderMoved\0"
"on_comboBox_activated\0arg1\0"
"on_comboBox_2_activated\0on_CoffeePop_clicked\0"
"on_lightCheck_clicked\0on_DarkCheck_clicked\0"
"on_coldCheck_clicked\0on_hotCheck_clicked\0"
"on_nodairyCheck_clicked\0on_skimCheck_clicked\0"
"on_wholeCheck_clicked\0on_pushButton_4_clicked\0"
"on_pushButton_clicked\0on_listWidget_itemClicked\0"
"QListWidgetItem*\0item"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Blackstone[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
26, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 144, 2, 0x08 /* Private */,
3, 0, 145, 2, 0x08 /* Private */,
4, 0, 146, 2, 0x08 /* Private */,
5, 0, 147, 2, 0x08 /* Private */,
6, 0, 148, 2, 0x08 /* Private */,
7, 0, 149, 2, 0x08 /* Private */,
8, 0, 150, 2, 0x08 /* Private */,
9, 0, 151, 2, 0x08 /* Private */,
10, 0, 152, 2, 0x08 /* Private */,
11, 0, 153, 2, 0x08 /* Private */,
12, 0, 154, 2, 0x08 /* Private */,
13, 1, 155, 2, 0x08 /* Private */,
15, 1, 158, 2, 0x08 /* Private */,
16, 1, 161, 2, 0x08 /* Private */,
18, 1, 164, 2, 0x08 /* Private */,
19, 0, 167, 2, 0x08 /* Private */,
20, 0, 168, 2, 0x08 /* Private */,
21, 0, 169, 2, 0x08 /* Private */,
22, 0, 170, 2, 0x08 /* Private */,
23, 0, 171, 2, 0x08 /* Private */,
24, 0, 172, 2, 0x08 /* Private */,
25, 0, 173, 2, 0x08 /* Private */,
26, 0, 174, 2, 0x08 /* Private */,
27, 0, 175, 2, 0x08 /* Private */,
28, 0, 176, 2, 0x08 /* Private */,
29, 1, 177, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Bool,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, 14,
QMetaType::Void, QMetaType::Int, 14,
QMetaType::Void, QMetaType::QString, 17,
QMetaType::Void, QMetaType::QString, 17,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 30, 31,
0 // eod
};
void Blackstone::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<Blackstone *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: { bool _r = _t->pushLogin();
if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = std::move(_r); } break;
case 1: _t->sortBy(); break;
case 2: _t->on_loginButton_clicked(); break;
case 3: _t->on_pushButton_2_clicked(); break;
case 4: _t->on_ContinueBtn_clicked(); break;
case 5: _t->on_pushButton_5_clicked(); break;
case 6: _t->on_ContinueBtn_2_clicked(); break;
case 7: _t->on_pushButton_6_clicked(); break;
case 8: _t->on_noneButton_clicked(); break;
case 9: _t->on_skimButton_clicked(); break;
case 10: _t->on_fatButton_clicked(); break;
case 11: _t->on_horizontalSlider_sliderMoved((*reinterpret_cast< int(*)>(_a[1]))); break;
case 12: _t->on_horizontalSlider_2_sliderMoved((*reinterpret_cast< int(*)>(_a[1]))); break;
case 13: _t->on_comboBox_activated((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 14: _t->on_comboBox_2_activated((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 15: _t->on_CoffeePop_clicked(); break;
case 16: _t->on_lightCheck_clicked(); break;
case 17: _t->on_DarkCheck_clicked(); break;
case 18: _t->on_coldCheck_clicked(); break;
case 19: _t->on_hotCheck_clicked(); break;
case 20: _t->on_nodairyCheck_clicked(); break;
case 21: _t->on_skimCheck_clicked(); break;
case 22: _t->on_wholeCheck_clicked(); break;
case 23: _t->on_pushButton_4_clicked(); break;
case 24: _t->on_pushButton_clicked(); break;
case 25: _t->on_listWidget_itemClicked((*reinterpret_cast< QListWidgetItem*(*)>(_a[1]))); break;
default: ;
}
}
}
QT_INIT_METAOBJECT const QMetaObject Blackstone::staticMetaObject = { {
&QMainWindow::staticMetaObject,
qt_meta_stringdata_Blackstone.data,
qt_meta_data_Blackstone,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *Blackstone::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Blackstone::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_Blackstone.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int Blackstone::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 26)
qt_static_metacall(this, _c, _id, _a);
_id -= 26;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 26)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 26;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
fc239eeab5da24619a8b9846bad1aa2f292c0d9b | 91092b67de4b25ed3e95f70624a73473f97ee096 | /glsandbox/Shader.cpp | 7de0c21aaac99ec527cbb6a2cee20e4fc58be23d | [] | no_license | leonlol-dev/Graphics-Pipeline-example | 12bbf289707a05ee69ca9a88441051304796c981 | cac4804f8f915920a5fb6df1b33f212c33568afc | refs/heads/main | 2023-04-20T08:12:34.467431 | 2021-05-06T15:54:11 | 2021-05-06T15:54:11 | 354,406,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,815 | cpp | #include <exception>
#include "Shader.h"
Shader::Shader(const char* vertexShader, const char* fragmentShader)
{
//Debugging purposes
GLint success = 0;
//Fragment Shader
const GLchar* fragmentShaderSrc = fragmentShader;
// Create a new fragment shader, attach source code, compile it and
// check for errors.
GLuint fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShaderId, 1, &fragmentShaderSrc, NULL);
glCompileShader(fragmentShaderId);
glGetShaderiv(fragmentShaderId, GL_COMPILE_STATUS, &success);
if (!success)
{
GLint maxLength = 0;
glGetShaderiv(fragmentShaderId, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> errorLog(maxLength);
glGetShaderInfoLog(fragmentShaderId, maxLength, &maxLength, &errorLog.at(0));
std::cout << &errorLog.at(0) << std::endl;
throw std::exception();
}
//Vertex Shader
const GLchar* vertexShaderSrc = vertexShader;
// Create a new vertex shader, attach source code, compile it and
// check for errors.
GLuint vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShaderId, 1, &vertexShaderSrc, NULL);
glCompileShader(vertexShaderId);
glGetShaderiv(vertexShaderId, GL_COMPILE_STATUS, &success);
if (!success)
{
GLint maxLength = 0;
glGetShaderiv(vertexShaderId, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> errorLog(maxLength);
glGetShaderInfoLog(vertexShaderId, maxLength, &maxLength, &errorLog.at(0));
std::cout << &errorLog.at(0) << std::endl;
throw std::exception();
}
//Create program and bind shader
GLuint programId = glCreateProgram();
glAttachShader(programId, vertexShaderId);
glAttachShader(programId, fragmentShaderId);
// Ensure the VAO "position" attribute stream gets set as the first position
// during the link.
glBindAttribLocation(programId, 0, "a_Position");
glBindAttribLocation(programId, 1, "u_Color");
glBindAttribLocation(programId, 1, "a_TexCoord");
glLinkProgram(programId);
glGetProgramiv(programId, GL_LINK_STATUS, &success);
if (!success)
{
throw std::exception();
}
// Find uniform locations
GLint modelLoc = glGetUniformLocation(programId, "u_Model");
GLint viewLoc = glGetUniformLocation(programId, "u_View");
GLint projectionLoc = glGetUniformLocation(programId, "u_Projection");
GLint uniformId = glGetUniformLocation(programId, "u_Texture");
glUseProgram(programId);
}
Shader::~Shader()
{
glDetachShader(programId, vertexShaderId);
glDeleteShader(vertexShaderId);
glDetachShader(programId, fragmentShaderId);
glDeleteShader(fragmentShaderId);
if (!success)
{
throw std::exception();
}
}
void Shader::draw(VertexArray* vertexArray)
{
//Display cat
glDrawArrays(GL_TRIANGLES, 0, vertexArray->getVertCount());
}
void Shader::setUniform(std::string uniform, glm::vec4 value)
{
// upload the model matrix
glUseProgram(id);
glUniform4f(glGetUniformLocation(id, uniform.c_str()), value.x, value.y, value.z, value.w);
glUseProgram(0);
}
void Shader::setUniform(std::string uniform, glm::mat4 value)
{
// upload the view matrix
glUseProgram(id);
glUniformMatrix4fv(glGetUniformLocation(id, uniform.c_str()), 1, GL_FALSE, glm::value_ptr(glm::inverse(value)));
glUseProgram(0);
}
void Shader::setUniform(std::string uniform, float value)
{
// Upload the projection matrix
glUseProgram(id);
glUniform1f(glGetUniformLocation(id, uniform.c_str()), value);
glUseProgram(0);
}
void Shader::setUniform(std::string uniform, Texture* texture)
{
glUseProgram(id);
glUniform1i(glGetUniformLocation(id, uniform.c_str()), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->getId());
glUseProgram(0);
}
GLuint Shader::getId()
{
return id;
}
GLint Shader::getFragmentId()
{
return fragmentShaderId;
}
GLint Shader::getVertexId()
{
return vertexShaderId;
}
| [
"[email protected]"
] | |
9d15ad4a6e66c2b16370d58d085a3ceee38bcf16 | 0a2781b763578e8f1d8174fcbb534bdca4819c84 | /DisplayMonofieldGames.cpp | 76fc42a5b53716992ae89f07473ae0029445954f | [] | no_license | GunzAndCoProjects/online_games | c537e840ee96833ae57d64bbcea075831955cb8b | 7c7491cb4c9ff864407bb8666752e8c9c19f36f3 | refs/heads/master | 2020-04-27T13:31:03.860410 | 2015-04-26T21:46:21 | 2015-04-26T21:46:21 | 31,923,942 | 0 | 3 | null | 2015-04-23T17:53:02 | 2015-03-09T21:34:09 | C++ | UTF-8 | C++ | false | false | 1,767 | cpp | #include "DisplayMonofieldGames.h"
#include "FieldInfo.h"
void DisplayMonofieldGames::ShowField(const IDataTransfer &FieldContainer)
{
FieldInfo Field = *((FieldInfo*) FieldContainer.GetData());
int heigh = Field.Field.size();
int width = Field.Field[0].size();
int ALetter = 65; //ASCII code of A
int QuantOfLetters = 26;
int BottomDigits = 1;
std::vector <std::string> TempField;
//Show Bottom Digits
std::cout << "\n\t";
std::cout << " ";
for (int i = 0; i < width; i++)
{
if (BottomDigits < 9)
{
std::cout << " " << BottomDigits << " ";
BottomDigits++;
} else
{
std::cout << " " << BottomDigits << " ";
BottomDigits++;
}
}
std::cout << "\n";
int tempheigh = 0;
while (tempheigh < heigh)
{
//Show Gorisontal Lines
std::cout << "\t ";
for (int i = 0; i < width; i++)
{
std::cout << "+---";
}
std::cout << "+\n";
std::cout << "\t";
//Show Vertical Letters
std::cout << (char) ALetter << " ";
//Show Gorisontal Lines + Symbols
for (int i = 0; i < width; i++)
{
int NumericCell = Field.Field[tempheigh][i];
char CharCell = Field.TokenMapping[NumericCell];
std::cout << "| ";
std::cout << CharCell; //Replace by map & vector
std::cout << " ";
}
std::cout << "|\n";
tempheigh++;
//Increment Letter
ALetter++;
}
//Show Last Gorisontal Line
std::cout << "\t ";
for (int i = 0; i < width; i++)
{
std::cout << "+---";
}
std::cout << "+\n";
} | [
"[email protected]"
] | |
41b3b861bc6885d9e24d06cc5a8d385b5b983f2a | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/spirit/classic/test/post_skips.cpp | 0cea7dbffccf51541710b0caf66f1c912b56b4d6 | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,371 | cpp | /*=============================================================================
Copyright (c) 2004 Joao Abecasis
http://spirit.sourceforge.net/
Use, modification and distribution is subject to 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 <sstd/boost/spirit/include/classic_parser.hpp>
#include <sstd/boost/spirit/include/classic_skipper.hpp>
#include <sstd/boost/spirit/include/classic_primitives.hpp>
#include <sstd/boost/spirit/include/classic_optional.hpp>
#include <sstd/boost/spirit/include/classic_sequence.hpp>
#include <sstd/boost/spirit/include/classic_ast.hpp>
#include <sstd/boost/spirit/include/classic_parse_tree.hpp>
#include <sstd/boost/detail/lightweight_test.hpp>
using namespace BOOST_SPIRIT_CLASSIC_NS;
char const * test1 = " 12345 ";
char const * test2 = " 12345 x";
void parse_tests()
{
parse_info<> info;
// Warming up...
info = parse(test1, str_p("12345"));
BOOST_TEST(!info.hit);
// No post-skips!
info = parse(test1, str_p("12345"), blank_p);
BOOST_TEST(info.hit);
BOOST_TEST(!info.full);
// Require a full match
info = parse(test1, str_p("12345") >> end_p, blank_p);
BOOST_TEST(info.full);
info = parse(test2, str_p("12345") >> end_p, blank_p);
BOOST_TEST(!info.hit);
// Check for a full match but don't make it a requirement
info = parse(test1, str_p("12345") >> !end_p, blank_p);
BOOST_TEST(info.full);
info = parse(test2, str_p("12345") >> !end_p, blank_p);
BOOST_TEST(info.hit);
BOOST_TEST(!info.full);
}
void ast_parse_tests()
{
tree_parse_info<> info;
// Warming up...
info = ast_parse(test1, str_p("12345"));
BOOST_TEST(!info.match);
// No post-skips!
info = ast_parse(test1, str_p("12345"), blank_p);
BOOST_TEST(info.match);
BOOST_TEST(!info.full);
// Require a full match
info = ast_parse(test1, str_p("12345") >> end_p, blank_p);
BOOST_TEST(info.full);
info = ast_parse(test2, str_p("12345") >> end_p, blank_p);
BOOST_TEST(!info.match);
// Check for a full match but don't make it a requirement
info = ast_parse(test1, str_p("12345") >> !end_p, blank_p);
BOOST_TEST(info.full);
info = ast_parse(test2, str_p("12345") >> !end_p, blank_p);
BOOST_TEST(info.match);
BOOST_TEST(!info.full);
}
void pt_parse_tests()
{
tree_parse_info<> info;
// Warming up...
info = pt_parse(test1, str_p("12345"));
BOOST_TEST(!info.match);
// No post-skips!
info = pt_parse(test1, str_p("12345"), blank_p);
BOOST_TEST(info.match);
BOOST_TEST(!info.full);
// Require a full match
info = pt_parse(test1, str_p("12345") >> end_p, blank_p);
BOOST_TEST(info.full);
info = pt_parse(test2, str_p("12345") >> end_p, blank_p);
BOOST_TEST(!info.match);
// Check for a full match but don't make it a requirement
info = pt_parse(test1, str_p("12345") >> !end_p, blank_p);
BOOST_TEST(info.full);
info = pt_parse(test2, str_p("12345") >> !end_p, blank_p);
BOOST_TEST(info.match);
BOOST_TEST(!info.full);
}
int main()
{
parse_tests();
ast_parse_tests();
pt_parse_tests();
return boost::report_errors();
}
| [
"[email protected]"
] | |
cfbb817228287bde4eb4ae9f50788e290106a12b | 3973b94a7dcba661ab119760e6c42197e4c4a4d0 | /Baekjun/DynamicProgramming1/boj_20500.cpp | e9172db7d3cd421692f2e4ce821cce2d7f802460 | [] | no_license | minsang0850/Program_Solving | b7fbd050cf15f3ba94828347fce810186045c9fd | 0f40032f77c7d6c529d1c1e7f103b4cc72e1a8e1 | refs/heads/master | 2023-08-15T10:07:00.097160 | 2021-10-15T09:10:59 | 2021-10-15T09:10:59 | 372,394,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | #include <iostream>
#define MOD 1000000007
using namespace std;
int n;
int DP[2000][2000];
int ncr(int n, int r){
if(DP[n][r]!=0)
return DP[n][r];
if(r==0){
DP[n][r]=1;
return 1;
}
if(r==1){
DP[n][r]=n;
return n;
}
if(n==r)
return 1;
DP[n][r]=(ncr(n-1,r-1)+ncr(n-1,r))%MOD;
return DP[n][r];
}
int main(){
int answer=0;
cin>>n;
for(int a=1; a<=n; a++){
int b=n-a;
if((a*5+b)%3==0){
answer+=ncr(n-1,a-1);
answer%=MOD;
}
}
cout<<answer;
} | [
"[email protected]"
] | |
3efac505e1ca0b53bfde652e3982102d06114ea2 | 383dbc71b7131c2ac2d225cce7658afde3048ea5 | /include/halcon_pose_estimation/pcl_viz.h | 8c81e2ae80988a874d5fa88d1e3b9e215b73c079 | [] | no_license | eirikwha/halcon_pose_estimation | f6db446117e8050fcf6104ed9bb2f85cb657ffed | 0ad19152516071566020212f776d17d933afc096 | refs/heads/master | 2022-12-25T18:54:23.480722 | 2020-10-03T16:39:01 | 2020-10-03T16:39:01 | 189,892,768 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,003 | h | //
// Created by eirik on 04.03.19.
//
# pragma once
#ifndef POSE_ESTIMATOR_PCLVISUALIZATION_H
#define POSE_ESTIMATOR_PCLVISUALIZATION_H
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/visualization/pcl_visualizer.h>
namespace PCLViz {
pcl::visualization::PCLVisualizer simpleVisXYZ(pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud);
pcl::visualization::PCLVisualizer simpleVisXYZRGB(pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud);
pcl::visualization::PCLVisualizer twoViewportsVis(
pcl::PolygonMesh::ConstPtr cloud1, pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud2);
/*pcl::visualization::PCLVisualizer twoInOneVis(
pcl::PolygonMesh::ConstPtr cloud1, pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud2);
*/
pcl::visualization::PCLVisualizer twoInOneVis(
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud1, pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud2);
}
#endif //HALCONMATCHING_PCLVISUALIZATION_H
| [
"[email protected]"
] | |
8be14cc195bbbc3c7aaf84aa3aad5a3cfb488e75 | 24f26275ffcd9324998d7570ea9fda82578eeb9e | /chrome/browser/policy/chrome_browser_policy_connector.cc | 637c861be75d9532cfd8f1f1cefe8efca4e669df | [
"BSD-3-Clause"
] | permissive | Vizionnation/chromenohistory | 70a51193c8538d7b995000a1b2a654e70603040f | 146feeb85985a6835f4b8826ad67be9195455402 | refs/heads/master | 2022-12-15T07:02:54.461083 | 2019-10-25T15:07:06 | 2019-10-25T15:07:06 | 217,557,501 | 2 | 1 | BSD-3-Clause | 2022-11-19T06:53:07 | 2019-10-25T14:58:54 | null | UTF-8 | C++ | false | false | 8,496 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include <memory>
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/task/post_task.h"
#include "build/branding_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/policy/configuration_policy_handler_list_factory.h"
#include "chrome/browser/policy/device_management_service_configuration.h"
#include "chrome/common/chrome_paths.h"
#include "components/policy/core/common/async_policy_provider.h"
#include "components/policy/core/common/cloud/cloud_external_data_manager.h"
#include "components/policy/core/common/cloud/cloud_policy_client_registration_helper.h"
#include "components/policy/core/common/cloud/device_management_service.h"
#include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
#include "components/policy/core/common/configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/core/common/policy_service.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/policy_constants.h"
#include "extensions/buildflags/buildflags.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#if defined(OS_WIN)
#include "base/win/registry.h"
#include "components/policy/core/common/policy_loader_win.h"
#elif defined(OS_MACOSX)
#include <CoreFoundation/CoreFoundation.h>
#include "base/mac/foundation_util.h"
#include "base/strings/sys_string_conversions.h"
#include "components/policy/core/common/policy_loader_mac.h"
#include "components/policy/core/common/preferences_mac.h"
#elif defined(OS_POSIX) && !defined(OS_ANDROID)
#include "components/policy/core/common/config_dir_policy_loader.h"
#elif defined(OS_ANDROID)
#include "components/policy/core/browser/android/android_combined_policy_provider.h"
#endif
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
#include "chrome/browser/policy/chrome_browser_cloud_management_controller.h"
#include "components/policy/core/common/cloud/machine_level_user_cloud_policy_manager.h"
#endif
#if defined(OS_WIN)
#include "chrome/browser/browser_switcher/browser_switcher_policy_migrator.h"
#endif
namespace policy {
namespace {
void AddMigrators(ConfigurationPolicyProvider* provider) {
#if defined(OS_WIN)
provider->AddMigrator(
std::make_unique<browser_switcher::BrowserSwitcherPolicyMigrator>());
#endif
}
bool ProviderHasPolicies(const ConfigurationPolicyProvider* provider) {
if (!provider)
return false;
for (const auto& pair : provider->policies()) {
if (!pair.second->empty())
return true;
}
return false;
}
} // namespace
ChromeBrowserPolicyConnector::ChromeBrowserPolicyConnector()
: BrowserPolicyConnector(base::Bind(&BuildHandlerList)) {
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
chrome_browser_cloud_management_controller_ =
std::make_unique<ChromeBrowserCloudManagementController>();
#endif
}
ChromeBrowserPolicyConnector::~ChromeBrowserPolicyConnector() {}
void ChromeBrowserPolicyConnector::OnResourceBundleCreated() {
BrowserPolicyConnectorBase::OnResourceBundleCreated();
}
void ChromeBrowserPolicyConnector::Init(
PrefService* local_state,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
std::unique_ptr<DeviceManagementService::Configuration> configuration(
new DeviceManagementServiceConfiguration(
BrowserPolicyConnector::GetDeviceManagementUrl(),
BrowserPolicyConnector::GetRealtimeReportingUrl()));
std::unique_ptr<DeviceManagementService> device_management_service(
new DeviceManagementService(std::move(configuration)));
device_management_service->ScheduleInitialization(
kServiceInitializationStartupDelay);
InitInternal(local_state, std::move(device_management_service));
}
bool ChromeBrowserPolicyConnector::IsEnterpriseManaged() const {
NOTREACHED() << "This method is only defined for Chrome OS";
return false;
}
bool ChromeBrowserPolicyConnector::HasMachineLevelPolicies() {
if (ProviderHasPolicies(GetPlatformProvider()))
return true;
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
if (ProviderHasPolicies(machine_level_user_cloud_policy_manager_))
return true;
#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
return false;
}
void ChromeBrowserPolicyConnector::Shutdown() {
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
// Reset the controller before calling base class so that
// shutdown occurs in correct sequence.
chrome_browser_cloud_management_controller_.reset();
#endif
BrowserPolicyConnector::Shutdown();
}
ConfigurationPolicyProvider*
ChromeBrowserPolicyConnector::GetPlatformProvider() {
ConfigurationPolicyProvider* provider =
BrowserPolicyConnectorBase::GetPolicyProviderForTesting();
return provider ? provider : platform_provider_;
}
std::vector<std::unique_ptr<policy::ConfigurationPolicyProvider>>
ChromeBrowserPolicyConnector::CreatePolicyProviders() {
auto providers = BrowserPolicyConnector::CreatePolicyProviders();
std::unique_ptr<ConfigurationPolicyProvider> platform_provider =
CreatePlatformProvider();
if (platform_provider) {
AddMigrators(platform_provider.get());
platform_provider_ = platform_provider.get();
// PlatformProvider should be before all other providers (highest priority).
providers.insert(providers.begin(), std::move(platform_provider));
}
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
std::unique_ptr<MachineLevelUserCloudPolicyManager>
machine_level_user_cloud_policy_manager =
ChromeBrowserCloudManagementController::CreatePolicyManager(
platform_provider_);
if (machine_level_user_cloud_policy_manager) {
AddMigrators(machine_level_user_cloud_policy_manager.get());
machine_level_user_cloud_policy_manager_ =
machine_level_user_cloud_policy_manager.get();
providers.push_back(std::move(machine_level_user_cloud_policy_manager));
}
#endif
return providers;
}
std::unique_ptr<ConfigurationPolicyProvider>
ChromeBrowserPolicyConnector::CreatePlatformProvider() {
#if defined(OS_WIN)
std::unique_ptr<AsyncPolicyLoader> loader(PolicyLoaderWin::Create(
base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(),
base::TaskPriority::BEST_EFFORT}),
kRegistryChromePolicyKey));
return std::make_unique<AsyncPolicyProvider>(GetSchemaRegistry(),
std::move(loader));
#elif defined(OS_MACOSX)
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
// Explicitly watch the "com.google.Chrome" bundle ID, no matter what this
// app's bundle ID actually is. All channels of Chrome should obey the same
// policies.
CFStringRef bundle_id = CFSTR("com.google.Chrome");
#else
base::ScopedCFTypeRef<CFStringRef> bundle_id(
base::SysUTF8ToCFStringRef(base::mac::BaseBundleID()));
#endif
auto loader = std::make_unique<PolicyLoaderMac>(
base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(),
base::TaskPriority::BEST_EFFORT}),
policy::PolicyLoaderMac::GetManagedPolicyPath(bundle_id),
new MacPreferences(), bundle_id);
return std::make_unique<AsyncPolicyProvider>(GetSchemaRegistry(),
std::move(loader));
#elif defined(OS_POSIX) && !defined(OS_ANDROID)
base::FilePath config_dir_path;
if (base::PathService::Get(chrome::DIR_POLICY_FILES, &config_dir_path)) {
std::unique_ptr<AsyncPolicyLoader> loader(new ConfigDirPolicyLoader(
base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(),
base::TaskPriority::BEST_EFFORT}),
config_dir_path, POLICY_SCOPE_MACHINE));
return std::make_unique<AsyncPolicyProvider>(GetSchemaRegistry(),
std::move(loader));
} else {
return nullptr;
}
#elif defined(OS_ANDROID)
return std::make_unique<policy::android::AndroidCombinedPolicyProvider>(
GetSchemaRegistry());
#else
return nullptr;
#endif
}
} // namespace policy
| [
"[email protected]"
] | |
300196b6221b21268134989efda92943712bf8c0 | 3b5f4e06669a7580c685fa33db1c64260897e213 | /src/solverconf.h | 8efeb3637c03b6623f9be4e0121ab7dcc50b744a | [
"MIT"
] | permissive | PlumpMath/cryptominisat | e8484efb7d80ffe23501e208b5467e7e140b44ce | a76fe59450292d89f973f68e006917177c4ebf3f | refs/heads/master | 2021-01-18T20:12:58.440815 | 2017-03-29T23:29:56 | 2017-03-29T23:32:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,160 | h | /******************************************
Copyright (c) 2016, Mate Soos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
***********************************************/
#ifndef SOLVERCONF_H
#define SOLVERCONF_H
#include <string>
#include <vector>
#include <cstdlib>
#include <cassert>
#include "gaussconfig.h"
using std::string;
namespace CMSat {
enum class ClauseClean {
glue = 0
, activity = 1
};
inline unsigned clean_to_int(ClauseClean t)
{
switch(t)
{
case ClauseClean::glue:
return 0;
case ClauseClean::activity:
return 1;
}
assert(false);
}
enum class PolarityMode {
polarmode_pos
, polarmode_neg
, polarmode_rnd
, polarmode_automatic
};
enum class Restart {
glue
, geom
, glue_geom
, luby
, never
};
inline std::string getNameOfRestartType(Restart rest_type)
{
switch(rest_type) {
case Restart::glue :
return "glue";
case Restart::geom:
return "geometric";
case Restart::luby:
return "luby";
case Restart::never:
return "never";
default:
release_assert(false && "Unknown clause cleaning type?");
};
}
inline std::string getNameOfCleanType(ClauseClean clauseCleaningType)
{
switch(clauseCleaningType) {
case ClauseClean::glue :
return "glue";
case ClauseClean::activity:
return "activity";
default:
assert(false && "Unknown clause cleaning type?");
std::exit(-1);
};
}
enum class ElimStrategy {
heuristic
, calculate_exactly
};
inline std::string getNameOfElimStrategy(ElimStrategy strategy)
{
switch(strategy)
{
case ElimStrategy::heuristic:
return "heuristic";
case ElimStrategy::calculate_exactly:
return "calculate";
}
assert(false && "Unknown elimination strategy type");
}
class DLL_PUBLIC SolverConf
{
public:
SolverConf();
std::string print_times(
const double time_used
, const bool time_out
, const double time_remain
) const;
std::string print_times(
const double time_used
, const bool time_out
) const;
std::string print_times(
const double time_used
) const;
//Variable activities
double var_inc_start;
double var_decay_start;
double var_decay_max;
double random_var_freq;
PolarityMode polarity_mode;
//Clause cleaning
//if non-zero, we reduce at every X conflicts.
//Reduced according to whether it's been used recently
//Otherwise, we *never* reduce
unsigned every_lev1_reduce;
//if non-zero, we reduce at every X conflicts.
//Otherwise we geometrically keep around max_temp_lev2_learnt_clauses*(inc**N)
unsigned every_lev2_reduce;
uint32_t must_touch_lev1_within;
unsigned max_temp_lev2_learnt_clauses;
double inc_max_temp_lev2_red_cls;
unsigned protect_cl_if_improved_glue_below_this_glue_for_one_turn;
double ratio_keep_clauses[2]; ///< Remove this ratio of clauses at every database reduction round
double clause_decay;
unsigned min_time_in_db_before_eligible_for_cleaning;
unsigned glue_put_lev0_if_below_or_eq;
unsigned glue_put_lev1_if_below_or_eq;
//If too many (in percentage) low glues after min_num_confl_adjust_glue_cutoff, adjust glue lower
double adjust_glue_if_too_many_low;
uint64_t min_num_confl_adjust_glue_cutoff;
int guess_cl_effectiveness;
//For restarting
unsigned restart_first; ///<The initial restart limit. (default 100)
double restart_inc; ///<The factor with which the restart limit is multiplied in each restart. (default 1.5)
unsigned burst_search_len;
Restart restartType; ///<If set, the solver will always choose the given restart strategy
int do_blocking_restart;
unsigned blocking_restart_trail_hist_length;
double blocking_restart_multip;
int maple;
double local_glue_multiplier;
unsigned shortTermHistorySize; ///< Rolling avg. glue window size
unsigned lower_bound_for_blocking_restart;
int more_otf_shrink_with_cache;
int more_otf_shrink_with_stamp;
//Clause minimisation
int doRecursiveMinim;
int doMinimRedMore; ///<Perform learnt clause minimisation using watchists' binary and tertiary clauses? ("strong minimization" in PrecoSat)
int doAlwaysFMinim; ///< Always try to minimise clause with cache&gates
unsigned max_glue_more_minim;
unsigned max_size_more_minim;
unsigned more_red_minim_limit_cache;
unsigned more_red_minim_limit_binary;
unsigned max_num_lits_more_red_min;
//Verbosity
int verbosity; ///<Verbosity level. 0=silent, 1=some progress report, 2=lots of report, 3 = all report (default 2) preferentiality is turned off (i.e. picked randomly between [0, all])
int doPrintGateDot; ///< Print DOT file of gates
int doPrintConflDot; ///< Print DOT file for each conflict
int print_full_restart_stat;
int verbStats;
int do_print_times; ///Print times during verbose output
int print_restart_line_every_n_confl;
//Limits
double maxTime;
long maxConfl;
//Glues
int update_glues_on_prop;
int update_glues_on_analyze;
//OTF stuff
int otfHyperbin;
int doOTFSubsume;
int doOTFSubsumeOnlyAtOrBelowGlue;
int rewardShortenedClauseWithConfl; //Shortened through OTF subsumption
//SQL
bool dump_individual_search_time;
bool dump_individual_restarts_and_clauses;
//Steps
double step_size = 0.40;
double step_size_dec = 0.000001;
double min_step_size = 0.06;
//Var-elim
int doVarElim; ///<Perform variable elimination
uint64_t varelim_cutoff_too_many_clauses;
int do_empty_varelim;
long long empty_varelim_time_limitM;
long long varelim_time_limitM;
int updateVarElimComplexityOTF;
unsigned updateVarElimComplexityOTF_limitvars;
unsigned updateVarElimComplexityOTF_limitavg;
ElimStrategy var_elim_strategy; ///<Guess varelim order, or calculate?
int varElimCostEstimateStrategy;
double varElimRatioPerIter;
int skip_some_bve_resolvents;
int velim_resolvent_too_large; //-1 == no limit
//Subs, str limits for simplifier
long long subsumption_time_limitM;
long long strengthening_time_limitM;
long long aggressive_elim_time_limitM;
//BVA
int do_bva;
unsigned bva_limit_per_call;
int bva_also_twolit_diff;
long bva_extra_lit_and_red_start;
long long bva_time_limitM;
//Probing
int doProbe;
int doIntreeProbe;
unsigned long long probe_bogoprops_time_limitM;
unsigned long long intree_time_limitM;
unsigned long long intree_scc_varreplace_time_limitM;
int doBothProp;
int doTransRed; ///<Should carry out transitive reduction
int doStamp;
int doCache;
unsigned cacheUpdateCutoff;
unsigned maxCacheSizeMB;
unsigned long long otf_hyper_time_limitM;
double otf_hyper_ratio_limit;
double single_probe_time_limit_perc;
//XORs
int doFindXors;
unsigned maxXorToFind;
int useCacheWhenFindingXors;
int doEchelonizeXOR;
unsigned long long maxXORMatrix;
long long xor_finder_time_limitM;
//Var-replacement
int doFindAndReplaceEqLits;
int doExtendedSCC;
double sccFindPercent;
int max_scc_depth;
//Iterative Alo Scheduling
int simplify_at_startup; //simplify at 1st startup (only)
int simplify_at_every_startup; //always simplify at startup, not only at 1st startup
int do_simplify_problem;
int full_simplify_at_startup;
int never_stop_search;
uint64_t num_conflicts_of_search;
double num_conflicts_of_search_inc;
double num_conflicts_of_search_inc_max;
string simplify_schedule_startup;
string simplify_schedule_nonstartup;
string simplify_schedule_preproc;
//Simplification
int perform_occur_based_simp;
int do_strengthen_with_occur; ///<Perform self-subsuming resolution
unsigned maxRedLinkInSize;
unsigned maxOccurIrredMB;
unsigned maxOccurRedMB;
unsigned long long maxOccurRedLitLinkedM;
double subsume_gothrough_multip;
//Distillation
uint32_t distill_queue_by;
int do_distill_clauses;
unsigned long long distill_long_irred_cls_time_limitM;
long watch_cache_stamp_based_str_time_limitM;
long long distill_time_limitM;
//Memory savings
int doRenumberVars;
int doSaveMem;
//Component handling
int doCompHandler;
unsigned handlerFromSimpNum;
size_t compVarLimit;
unsigned long long comp_find_time_limitM;
//Misc Optimisations
int doStrSubImplicit;
long long subsume_implicit_time_limitM;
long long distill_implicit_with_implicit_time_limitM;
//Gates
int doGateFind; ///< Find OR gates
unsigned maxGateBasedClReduceSize;
int doShortenWithOrGates; ///<Shorten clauses with or gates during subsumption
int doRemClWithAndGates; ///<Remove clauses using and gates during subsumption
int doFindEqLitsWithGates; ///<Find equivalent literals using gates during subsumption
long long gatefinder_time_limitM;
long long shorten_with_gates_time_limitM;
long long remove_cl_with_gates_time_limitM;
//Gauss
GaussConf gaussconf;
//Greedy undef
int greedy_undef;
std::vector<uint32_t>* independent_vars;
//Timeouts
double orig_global_timeout_multiplier;
double global_timeout_multiplier;
double global_timeout_multiplier_multiplier;
double global_multiplier_multiplier_max;
//Misc
unsigned origSeed;
unsigned long long sync_every_confl;
unsigned reconfigure_val;
unsigned reconfigure_at;
unsigned preprocess;
std::string simplified_cnf;
std::string solution_file;
std::string saved_state_file;
};
} //end namespace
#endif //SOLVERCONF_H
| [
"[email protected]"
] | |
29bad03abeaf6afa89f678dead16e54f82bac627 | 40369e672737733bc9ff162750da1c5d00009d1e | /updated the header file | 76c074bc12a3dbd813ce562265a68a64828d4c52 | [] | no_license | alsc2164/Scheele_CSCI2270_FinalProject | ed413c51538a5ba5e8e53041ffd9b13a33819a90 | d987b57bed012aec116920f20ae7f8e013992637 | refs/heads/master | 2016-09-06T07:42:30.493532 | 2015-05-03T04:03:37 | 2015-05-03T04:03:37 | 33,935,855 | 1 | 4 | null | 2015-05-03T16:29:43 | 2015-04-14T14:14:09 | C++ | UTF-8 | C++ | false | false | 845 | #ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED
#include <vector>
struct node
{
int value;
node* parent;
node* left;
node* right;
};
class tree
{
private:
node* root;
std::vector<int> order;
int sum;
int height;
int average;
int mode;
int treeHEIGHT;
node *searchTree(node *treeNode, int v);
//node *searchTreeValueCount(node *treeNode, int v);
node *print(node *n);
node *build(node *n);
int treeHeight(node *p);
//node* maximum(node* n);
public:
tree();
~tree();
void addNode(int v);
void deleteNode(int v);
void printOrder();
int maximum();
int minimum();
int ave();
int total();
int frequency(int n);
int print_numbers_forward_and_backward();
int treeH();
void output();
int length();
};
#endif // TREE_H_INCLUDED
| [
"[email protected]"
] | ||
812fc05c5ec8471e4cf61c770f199b71f262d9b6 | 48e83e5dd44809080b2c4cfadba9fd2d68c37b79 | /Grove - Digital_Light_Sensor/Digital_Light_TSL2561.cpp | 7229018f13314cc523970af7547bd4cc4a0a30e3 | [
"MIT"
] | permissive | guzenyin/Grove-RaspberryPi | 1dabd14604ea297e26ac1db8116b6f5f80bfce09 | 3f6d4d81e79243986bc5e6a1e2cb8352c5d73541 | refs/heads/master | 2021-01-16T21:18:09.432558 | 2014-02-13T01:58:53 | 2014-02-13T01:58:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,150 | cpp | /*
TSL2561 library V1.0
2010 Copyright (c) Seeed Technology Inc. All right reserved.
Original Author: zhangkun
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <inttypes.h>
#include "Digital_Light_TSL2561.h"
Digital_Light_TSL2561::Digital_Light_TSL2561(uint16_t deviceAddress)
{
device_address = deviceAddress;
init();
}
Digital_Light_TSL2561::~Digital_Light_TSL2561()
{
}
uint16_t Digital_Light_TSL2561::readRegister(uint16_t deviceAddress, uint16_t address)
{
uint16_t value;
int file;
uint16_t buf[1] = {address};
uint16_t reBuf[1] = {0};
if ( (file = open("/dev/i2c-1", O_RDWR)) < 0 ) {
printf("Failed to open the bus.");
}
if(ioctl(file,I2C_SLAVE,deviceAddress) < 0) {
printf("Failed to acquire bus access and/or talk to slave.\n");
}
/* send the register address which want read */
write(file, buf, 1);
read(file, reBuf, 1);
close(file);
return reBuf[0];
}
void Digital_Light_TSL2561::writeRegister(uint16_t deviceAddress, uint16_t address, uint16_t val)
{
int file; // fd
char buf[2] = {0}; // buffer for write.
/* open the i2c dev */
if((file = open("/dev/i2c-1",O_RDWR)) < 0) {
printf("Failed to open the bus.");
}
if(ioctl(file,I2C_SLAVE,deviceAddress) < 0) {
printf("Failed to acquire bus access and/or talk to slave.\n");
}
buf[0] = (char)address;
buf[1] = (char)val;
// printf("Write Register\n");
// printf("address %d, val %d \n", &address, &val);
write(file,buf,2);
close(file);
}
void Digital_Light_TSL2561::getLux(void)
{
CH0_LOW=readRegister(device_address,TSL2561_CHANNAL0L);
CH0_HIGH=readRegister(device_address,TSL2561_CHANNAL0H);
//read two bytes from registers 0x0E and 0x0F
CH1_LOW=readRegister(device_address,TSL2561_CHANNAL1L);
CH1_HIGH=readRegister(device_address,TSL2561_CHANNAL1H);
channel0=CH0_HIGH*256+CH0_LOW;
channel1=CH1_HIGH*256+CH1_LOW;
}
void Digital_Light_TSL2561::init()
{
writeRegister(device_address,TSL2561_CONTROL,0x03); // POWER UP
writeRegister(device_address,TSL2561_TIMING,0x11); //High Gain (16x), integration time of 101ms
writeRegister(device_address,TSL2561_INTERRUPT,0x00);
}
uint32_t Digital_Light_TSL2561::calculateLux(uint16_t iGain, uint16_t tInt, uint16_t iType)
{
switch (tInt)
{
case 0: // 13.7 msec
chScale = CHSCALE_TINT0;
break;
case 1: // 101 msec
chScale = CHSCALE_TINT1;
break;
default: // assume no scaling
chScale = (1 << CH_SCALE);
break;
}
if (!iGain) chScale = chScale << 4; // scale 1X to 16X
// scale the channel values
channel0 = (channel0 * chScale) >> CH_SCALE;
channel1 = (channel1 * chScale) >> CH_SCALE;
ratio1 = 0;
if (channel0!= 0) ratio1 = (channel1 << (RATIO_SCALE+1))/channel0;
// round the ratio value
uint16_t ratio = (ratio1 + 1) >> 1;
switch (iType)
{
case 0: // T package
if ((ratio >= 0) && (ratio <= K1T))
{b=B1T; m=M1T;}
else if (ratio <= K2T)
{b=B2T; m=M2T;}
else if (ratio <= K3T)
{b=B3T; m=M3T;}
else if (ratio <= K4T)
{b=B4T; m=M4T;}
else if (ratio <= K5T)
{b=B5T; m=M5T;}
else if (ratio <= K6T)
{b=B6T; m=M6T;}
else if (ratio <= K7T)
{b=B7T; m=M7T;}
else if (ratio > K8T)
{b=B8T; m=M8T;}
break;
case 1:// CS package
if ((ratio >= 0) && (ratio <= K1C))
{b=B1C; m=M1C;}
else if (ratio <= K2C)
{b=B2C; m=M2C;}
else if (ratio <= K3C)
{b=B3C; m=M3C;}
else if (ratio <= K4C)
{b=B4C; m=M4C;}
else if (ratio <= K5C)
{b=B5C; m=M5C;}
else if (ratio <= K6C)
{b=B6C; m=M6C;}
else if (ratio <= K7C)
{b=B7C; m=M7C;}
}
temp=((channel0*b)-(channel1*m));
if(temp<0) temp=0;
temp+=(1<<LUX_SCALE-1);
// strip off fractional portion
lux=temp>>LUX_SCALE;
return (lux);
}
| [
"[email protected]"
] | |
2cf8b8ddb8c2d1952705b46f2c188db0a48cf774 | 2e0e6808b914e6d9baa9dfdbdc97c484e163a828 | /sort/quicksort.cpp | e812eee3083dda9e016ac30e3b0c08e6851a30f8 | [] | no_license | mcarmenjc/programming_exercises | a75bf83be24040ad76f0fe939cafb37759c86ed3 | cab40862574b5e9bae2cbb7d0aadddeaa6d600ec | refs/heads/master | 2021-07-01T09:58:54.984848 | 2017-09-21T21:36:03 | 2017-09-21T21:36:03 | 103,063,599 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,632 | cpp | /*
QUICKSORT
*/
#include <vector>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
enum class Pivot {
First,
Last,
Random,
Median
};
int ChoosePivot(std::vector<int> &array, int start, int end, Pivot type){
if (type == Pivot::First){
return start;
}
else if (type == Pivot::Last){
return end;
}
else if (type == Pivot::Random){
return (rand() % (end - start + 1) + start);
}
else if (type == Pivot::Median){
//look for implementation for this
return start;
}
return end;
}
void SwapElements(std::vector<int> &array, int pos1, int pos2){
int temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
}
int RearrangeElementsInArray(std::vector<int> &array, int start, int end, int pivot_position){
SwapElements(array, end, pivot_position);
pivot_position = end;
int it_start = start;
int it_end = end-1;
while (it_start <= it_end){
if (array[it_start] < array[end]){
++it_start;
}
if (array[it_end] >= array[end]){
--it_end;
}
if (it_start < it_end &&
array[it_start] >= array[end] &&
array[it_end] < array[end]){
SwapElements(array, it_start, it_end);
++it_start;
--it_end;
}
}
SwapElements(array, end, it_start);
return it_start;
}
void Quicksort(std::vector<int> &array, int start, int end, Pivot type){
if (start >= end){
return;
}
int pivot_position = ChoosePivot(array, start, end, type);
pivot_position = RearrangeElementsInArray(array, start, end, pivot_position);
Quicksort(array, start, pivot_position - 1, type);
Quicksort(array, pivot_position + 1, end, type);
}
void Print(const std::vector<int> &numbers){
for (int n : numbers){
std::cout << n << " ";
}
std::cout << std::endl;
}
int main(){
srand (time(NULL));
std::vector<int> example1 = {};
Print(example1);
Quicksort(example1, 0, example1.size()-1, Pivot::Last);
Print(example1);
std::cout << "-----------------------------------------------------------------------------------" << std::endl;
std::vector<int> example2 = {2};
Print(example2);
Quicksort(example2, 0, example2.size()-1, Pivot::Last);
Print(example2);
std::cout << "-----------------------------------------------------------------------------------" << std::endl;
std::vector<int> example3 = {4, 3, 7, 1, 9, 5, 3, 4, 11, 14};
Print(example3);
Quicksort(example3, 0, example3.size()-1, Pivot::Last);
Print(example3);
std::cout << "-----------------------------------------------------------------------------------" << std::endl;
std::vector<int> example4 = {2, 4, 1};
Print(example4);
Quicksort(example4, 0, example4.size()-1, Pivot::Last);
Print(example4);
std::cout << "-----------------------------------------------------------------------------------" << std::endl;
std::vector<int> example5 = {4, 3, 7, 1, 9, 5, 3, 4, 11, 14};
Print(example5);
Quicksort(example5, 0, example5.size()-1, Pivot::First);
Print(example5);
std::cout << "-----------------------------------------------------------------------------------" << std::endl;
std::vector<int> example6 = {4, 3, 7, 1, 9, 5, 3, 4, 11, 14};
Print(example6);
Quicksort(example6, 0, example6.size()-1, Pivot::Random);
Print(example6);
std::cout << "-----------------------------------------------------------------------------------" << std::endl;
} | [
"[email protected]"
] | |
79a4195f8eaffdf413aaf14d0cfa6444b20f0445 | 0d1a4017d9c002f98e652e573fbc53f6b7db0d0d | /dataStruct/binTree/binTree_Implement.h | 36e8297b888f1fa8106141b58a1c5adcf7b24385 | [] | no_license | zha0x1n/cppProject | 6aa13ac37ad9a2ce6035e573bfe2cd65cfd3ae4a | bec8e0906f85734e2dcc4f63b9888156f57bbdb5 | refs/heads/master | 2023-07-06T09:54:25.884213 | 2023-06-25T00:54:45 | 2023-06-25T00:54:45 | 227,996,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,915 | h | #ifndef __BINTREE_IMPLEMENT__
#define __BINTREE_IMPLEMENT__
#include <cstdlib>
#include <memory>
#include <algorithm>
using namespace std;
template <typename T> int BinTree<T>::updateHeight(BinNodePosi(T) x)
{ return x->height = 1 + max( stature(x->lc), stature(x->rc)); }
template <typename T> void BinTree<T>::updateHeightAbove(BinNodePosi(T) x)
{ while(x) { updateHeight(x); x = x->parent; } }
template <typename T> BinNodePosi(T) BinTree<T>::insertAsRoot(T const& e)
{ _size = 1; return _root = new BinNode<T>(e); }
template <typename T> BinNodePosi(T) BinTree<T>::insertAsLC(BinNodePosi(T) x, T const& e)
{ _size++; x->insertAsLC(e); updateHeightAbove(x); return x->lc; }
template <typename T> BinNodePosi(T) BinTree<T>::insertAsRC(BinNodePosi(T) x, T const& e)
{ _size++; x->insertAsRC(e); updateHeightAbove(x); return x->rc; }
template <typename T>
BinNodePosi(T) BinTree<T>::attachAsLC(BinNodePosi(T) x, BinTree<T>* &S) {
if(x->lc = S->_root) x->lc->parent = x;
_size += S->_size; updateHeightAbove(x);
S->_root = NULL; S->_size = 0; release(S); S = NULL;
return x;
}
template <typename T>
BinNodePosi(T) BinTree<T>::attachAsRC(BinNodePosi(T) x, BinTree<T>* &S) {
if(x->rc = S->_root) x->rc->parent = x;
_size += S->_size; updateHeightAbove(x);
S->_root = NULL; S->_size = 0; release(S); S = NULL;
return x;
}
template <typename T>
int BinTree<T>::remove(BinNodePosi(T) x) {
FromParentTo(*x) = NULL;
updateHeightAbove(x->parent);
int n = removeAt(x); _size -= n; return n;
}
template <typename T>
static int removeAt(BinNodePosi(T) x) {
if(!x) return 0;
int n = 1 + removeAt(x->lc) + removeAt(x->rc);
delete []x; return n;
}
template <typename T>
BinTree<T>* BinTree<T>::secede(BinNodePosi(T) x) {
FromParentTo(x) = NULL;
updateHeightAbove(x->parent);
BinTree<T>* S = new BinTree<T>; S->_root = x; x->parent = NULL;
S->_size = x->size(); _size -= S->_size;
return S;
}
#endif
| [
"[email protected]"
] | |
3dbab41f31954a37c7ab492fe3a8e06b42ec40fc | 5cdcc9f2f0f62faa4be1bc9d8312c1e9ec3223fc | /lcd_i2c/lcd_i2c.ino | a83c9feeb543517a1aea2d19049c084f4970b8c2 | [] | no_license | eilamsher/Arduino-windows | 5c0e575b3f9c6127c974f7fa268e9f5ff607eda4 | 6d548b4e00f503398e7ebcf6e9b2d288347adf94 | refs/heads/master | 2021-05-24T08:32:28.334099 | 2020-07-01T15:39:35 | 2020-07-01T15:39:35 | 253,470,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,243 | ino | #include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4); // set the LCD address to 0x27 for a 16 chars and 2 line display
unsigned long preMillis = 0;
unsigned long preMicro = 0;
int sec = 13;
int micro=6000;
void setup()
{
lcd.init(); // initialize the lcd
lcd.init();
// Print a message to the LCD.
lcd.backlight();
}
void loop()
{
lcd.setCursor(0, 1);
lcd.print("I am YELLOW");
if (sec == 0) {
lcd.clear();
lcd.setCursor(0, 1);
lcd.print("BOOM BOOM BOOM");
delay(100000000000);
}
if (sec > 60) {
if (millis() - preMillis >= 1000) {
lcd.setCursor(0, 0);
preMillis = millis();
sec--;
lcd.print(sec / 60);
lcd.print(":");
if (sec % 60 < 10)
lcd.print("0");
lcd.print(sec % 60);
}
}
else {
if (millis() - preMillis >= 1000) {
lcd.setCursor(0, 0);
preMillis = millis();
preMicro=preMillis;
sec--;
if (sec % 60 < 10)
lcd.print("0");
lcd.print(sec % 60);
lcd.print(":");
}
if (millis() - preMicro >= 500) {
lcd.setCursor(3, 0);
preMicro = millis();
micro--;
lcd.print(micro % 10);
}
}
}
| [
"[email protected]"
] | |
a27b5172d9d37ac4cd9b96b70a5c855ce852ea20 | 019bf33edb4bc12daf20d11ae4e495dfa4af8699 | /hw6 (另一個副本)/src/cir/cirGate.h | e9e7074ded4496e5a280e30a2109d6ff5fa1c11d | [] | no_license | codingbaobao/DSnP | 46500e8143237241ee7850a4384134dba3420113 | 8314888e978a6fda99aadcdf0b27d931df0d7129 | refs/heads/master | 2020-05-23T08:19:10.135967 | 2017-03-10T09:05:51 | 2017-03-10T09:05:51 | 70,121,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,023 | h | /****************************************************************************
FileName [ cirGate.h ]
PackageName [ cir ]
Synopsis [ Define basic gate data structures ]
Author [ Chung-Yang (Ric) Huang ]
Copyright [ Copyleft(c) 2008-present LaDs(III), GIEE, NTU, Taiwan ]
****************************************************************************/
#ifndef CIR_GATE_H
#define CIR_GATE_H
#include <string>
#include <vector>
#include <iostream>
#include "cirDef.h"
using namespace std;
class CirGate;
//------------------------------------------------------------------------
// Define classes
//------------------------------------------------------------------------
// TODO: Define your own data members and member functions, or classes
class CirGate
{
friend class CirMgr;
public:
CirGate(unsigned l,unsigned v,GateType ggg)
:lineno(l),varno(v),ref(0),gg(ggg),expression("") {}
virtual ~CirGate() {}
unsigned getLineNo() const { return lineno; }
unsigned getVarNo() const { return varno; }
string getTypeStr() const
{
switch(gg)
{
case UNDEF_GATE:
return "UNDEF";
case PI_GATE:
return "PI";
case PO_GATE:
return "PO";
case AIG_GATE:
return "AIG";
case CONST_GATE:
return "CONST";
default:
return "haha";
}
}
// Printing functions
void reportGate() const;
void reportFanin(int level);
void reportFanout(int level);
private:
vector<size_t> fanin;
vector<size_t> fanout;
unsigned lineno;
unsigned varno;
size_t ref;
static size_t globalref;
GateType gg;
string expression;
static CirGate* getGatePtr(size_t fan) { return (CirGate*)(fan & ~size_t(0x1)); }
static bool isInv(size_t fan) { return (fan & 0x1); }
bool isglobal() { return (ref==globalref); }
bool notglobal() { return (ref!=globalref); }
void setToglobal() { ref=globalref; }
static void setglobal() { ++globalref; }
void printGate(unsigned&) const;
void reachable(IdList&);
void subfan(int,unsigned&,bool);
};
#endif // CIR_GATE_H
| [
"[email protected]"
] | |
345894a8c48ec0e738cdae47491a1430fd53f85d | c1d3ef708ecf73d761cbebdc0fa750d7bad7f8ba | /plugin-dev2/analyzer/StructPrmsAnalyzer.cpp | 685cf102dddb2c36c9412454be93c87c6c41c892 | [] | no_license | FengqianLi/CPSA | 6d85d02c664e35bbadc0955b045f00b6b2e46d2d | 9c4d3a9ead65f96d47313ea49a6fa4443d5b0f74 | refs/heads/master | 2021-01-20T06:57:12.588876 | 2013-08-11T16:04:49 | 2013-08-11T16:04:49 | 12,038,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,382 | cpp | /*
* StructPrmsAnalyzer.cpp
*
* Created on: 2012-11-6
* Author: dandelion
*/
#include "include/StructPrmsAnalyzer.h"
#include "../core/include/NodeProcessor.h"
#include "../core/include/ReportManager.h"
#include "../core/include/TotalProblem.h"
#include "../util/include/Util.h"
#include <iostream>
using std::endl;
#include <sstream>
using std::stringstream;
StructPrmsAnalyzer::StructPrmsAnalyzer()
{
setAnalyzerNodeType("function_decl");
judged = false;
}
StructPrmsAnalyzer::~StructPrmsAnalyzer()
{
}
void
StructPrmsAnalyzer::analyzeNode(GNode* node,const vector<int>& context)
{
if (!NodeProcessor::isCurrentFunctionDecl(node)){
return ;
}
if (judged){
return ;
}
judged = true;
GNode* funTypeNode = NodeProcessor::getFuncTypeNode(node);
if (funTypeNode == NULL){
return ;
}
if (NodeProcessor::isFunctionReturnRecordType(funTypeNode)){
int lineNumber = 1;
if (node->getProperty("srcp") != NULL){
string srcpStr = node->getProperty("srcp")->mStringProperty;
srcpStr = srcpStr.substr(srcpStr.find(":") + 1);
lineNumber = Util::stringToInt(srcpStr);
}
stringstream reportMsgStream;
reportMsgStream<<"StructPrmsAnalyzer: return value is record type ";
string reportMsg = reportMsgStream.str();
ReportManager::getInstance().insertReport(SrcManager::getInstance().getFullFileName(),lineNumber,reportMsg);
ProblemList::GetInstance().Add((char*)"StructPrmsAnalyzer", SrcManager::getInstance().getFullFileName(), lineNumber);
}
if (NodeProcessor::isFunctionPrmsRecordType(funTypeNode)){
int lineNumber = 1;
if (node->getProperty("srcp") != NULL){
string srcpStr = node->getProperty("srcp")->mStringProperty;
srcpStr = srcpStr.substr(srcpStr.find(":") + 1);
lineNumber = Util::stringToInt(srcpStr);
}
stringstream reportMsgStream;
reportMsgStream<<"StructPrmsAnalyzer: parameter is record type ";
string reportMsg = reportMsgStream.str();
ReportManager::getInstance().insertReport(SrcManager::getInstance().getFullFileName(),lineNumber,reportMsg);
ProblemList::GetInstance().Add((char*)"StructPrmsAnalyzer", SrcManager::getInstance().getFullFileName(), lineNumber);
}
}
void
StructPrmsAnalyzer::startAnalyze(){
}
void
StructPrmsAnalyzer::finishAnalyze(){
}
void
StructPrmsAnalyzer::clearAnalyzerState(){
judged = false;
}
| [
"[email protected]"
] | |
f4857cdf116e6e16f5bf52359ac6fb034e419092 | 8f3a2c9335f13cd7cddfa3dba09ac217ef79837f | /src/Piece_factory.cpp | 2db2ed3d52206415109b2a30208ce7d3bd7d0ded | [] | no_license | azhu7/Chess | f4576b3e4b2e5a97cf7d4d2a810d25e3664d7e88 | 9a54067ccf21ecd0842154c423c7b2ad0c057d23 | refs/heads/master | 2020-06-28T19:34:44.891383 | 2017-06-06T04:57:40 | 2017-06-06T04:57:40 | 74,479,704 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,059 | cpp | /**
Author: Alexander Zhu
Date Created: April 12, 2017
Description: Implementation for Piece factory
*/
#include "Piece_factory.h"
#include "Bishop.h"
#include "King.h"
#include "Knight.h"
#include "Pawn.h"
#include "Queen.h"
#include "Rook.h"
#include "Utility.h"
#include <string>
using std::string;
using std::shared_ptr; using std::make_shared;
// Allocates and initializes piece based on supplied information. Throws error
// on invalid type.
shared_ptr<Piece> create_piece(Player player, Tile pos, char type) {
string id{ string{} + (char)('0' + player) + type }; // Example: 1P
switch (type) {
case 'P': return make_shared<Pawn>(id, player, pos);
case 'N': return make_shared<Knight>(id, player, pos);
case 'B': return make_shared<Bishop>(id, player, pos);
case 'R': return make_shared<Rook>(id, player, pos);
case 'Q': return make_shared<Queen>(id, player, pos);
case 'K': return make_shared<King>(id, player, pos);
}
throw Error{ "Invalid piece type!" };
}
| [
"Alex@DESKTOP-Q5SC353"
] | Alex@DESKTOP-Q5SC353 |
5ae7bcbfe2c94a1f69936dcf11ab5e56a43359a2 | 3fbb471831a550b143fe5f222f17376b003c7b8c | /Competitions-Challenges/HackerEarth/MaxMul/solution.cpp | 2b0b9aa496ad8681da818c3be472d60ad76aa3b4 | [
"MIT"
] | permissive | tanaytoshniwal/Data-Structures-Algorithms | e5656844685e2659caebbe62f00b2b4a8c2b9670 | 6c3b0645bce2f0900d13b4ca50c25ecb0cd532ae | refs/heads/master | 2021-12-19T02:53:18.120249 | 2021-12-06T04:48:46 | 2021-12-06T04:48:46 | 127,022,551 | 34 | 22 | MIT | 2021-12-06T04:48:47 | 2018-03-27T17:28:44 | C++ | UTF-8 | C++ | false | false | 881 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
ll* arr = new ll[n];
int flag = 0;
for(int i=0;i<n;i++){
cin >> arr[i];
if(arr[i]<0) flag++;
}
ll pos_a = LONG_MIN, pos_b = LONG_MIN, neg_a = LONG_MAX, neg_b = LONG_MAX;
for(int i=0;i<n;i++){
if(arr[i] > pos_a){
pos_b = pos_a;
pos_a = arr[i];
}
else if(arr[i] > pos_b) pos_b = arr[i];
if(arr[i] < neg_a){
neg_b = neg_a;
neg_a = arr[i];
}
else if(arr[i] < neg_b) neg_b = arr[i];
}
if(flag>1) cout << max(pos_a*pos_b, neg_a*neg_b) << endl;
else cout << pos_a * pos_b << endl;
}
return 0;
} | [
"[email protected]"
] | |
6f0f8c862b5bb46cb6aba1a9f10c99c54b607e93 | 85beab6ec7f3eb0830491bbe14e3a1e4fac5b921 | /Vertex.cpp | 8511e3362fa146923e59b3af69c98e197866e850 | [] | no_license | VietKhangLH/Graph-Theory | e0163ea3d9ccaababc4652fb8d7fc9844bcebeac | 43fe4c96f8fcf529d47dee8b0834db5642b2360e | refs/heads/master | 2021-01-10T14:31:26.377981 | 2016-03-17T21:35:41 | 2016-03-17T21:35:41 | 54,071,240 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | #include "Vertex.h"
int Vertex::_currentId = 0;
constexpr int FALSE_ID = -1;
Vertex::Vertex(bool valid) :
_id(valid ? _currentId++ : FALSE_ID)
{}
int Vertex::id() const
{
return _id;
}
bool Vertex::valid() const
{
return id() != FALSE_ID;
}
bool Vertex::operator<(const Vertex & v) const
{
return id() < v.id();
}
| [
"[email protected]"
] | |
3c90edcf9692fb380883a2e12d4637b4755bae4e | 24b25d408510eb9460280ff664f96b003c5473d5 | /ThreadPool.h | 17912e76b3b6bb35acc2e1b0dd0283576204ffbb | [] | no_license | Tait4198/websocket-img | 50b64bd34fc602d0441a4729308b4baf197e5cce | aa8be95d482ae2617d9319110ff58f02285fb3f0 | refs/heads/main | 2023-06-13T07:03:30.123195 | 2021-07-09T06:59:40 | 2021-07-09T06:59:40 | 360,189,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,729 | h | // https://github.com/progschj/ThreadPool
#ifndef THREADPOOL_H
#define THREADPOOL_H
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
class ThreadPool {
public:
ThreadPool(size_t);
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
~ThreadPool();
private:
// need to keep track of threads so we can join them
std::vector< std::thread > workers;
// the task queue
std::queue< std::function<void()> > tasks;
// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
for(size_t i = 0;i<threads;++i)
workers.emplace_back(
[this]
{
for(;;)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this]{ return this->stop || !this->tasks.empty(); });
if(this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
);
}
// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task](){ (*task)(); });
}
condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}
#endif //THREADPOOL_H
| [
"[email protected]"
] | |
3df547b9cd4d83844fc24051c0fa0abfc8f00426 | 04251e142abab46720229970dab4f7060456d361 | /lib/rosetta/source/src/core/scoring/elec/GroupElec.hh | ad502f1d2e7c29b4fb0cb4566f9a0aa87428785b | [] | no_license | sailfish009/binding_affinity_calculator | 216257449a627d196709f9743ca58d8764043f12 | 7af9ce221519e373aa823dadc2005de7a377670d | refs/heads/master | 2022-12-29T11:15:45.164881 | 2020-10-22T09:35:32 | 2020-10-22T09:35:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,472 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: [email protected].
/// @file core/scoring/methods/FA_ElecEnergy.hh
/// @brief Electrostatic energy with a distance-dependant dielectric
/// @author Phil Bradley, modifed by James Gleixner
#ifndef INCLUDED_core_scoring_elec_GroupElec_hh
#define INCLUDED_core_scoring_elec_GroupElec_hh
// Package headers
//#include <core/scoring/elec/ElecAtom.hh>
//#include <core/scoring/hbonds/HBondSet.hh>
#include <core/scoring/etable/coulomb/Coulomb.hh>
#include <core/scoring/DerivVectorPair.hh>
// Project headers
#include <core/types.hh>
#include <core/chemical/ResidueType.fwd.hh>
#include <core/pose/Pose.fwd.hh>
#include <core/scoring/methods/EnergyMethodOptions.fwd.hh>
#include <core/scoring/etable/count_pair/CountPairFunction.hh>
// Utility headers
#include <utility/VirtualBase.hh>
#include <utility/vector1.hh>
#include <utility/pointer/owning_ptr.hh>
// C++ headers
#include <cmath>
namespace core {
namespace scoring {
namespace elec {
struct ElecGroup
{
utility::vector1< core::Size > atms;
utility::vector1< core::Size > comatms;
Size n_acceptor;
Size n_donor;
Real qeps;
};
typedef utility::vector1< ElecGroup > ResElecGroup;
//typedef utility::pointer::shared_ptr< ResElecGroup const > ResElecGroupCOP;
class GroupElec : public utility::VirtualBase
{
public:
GroupElec( GroupElec const & src );
GroupElec( methods::EnergyMethodOptions const & options );
~GroupElec() override;
void initialize( etable::coulomb::Coulomb const &coulomb );
Real
eval_respair_group_coulomb(
conformation::Residue const & rsd1,
conformation::Residue const & rsd2
//hbonds::HBondSet const & hbond_set
) const;
void
eval_respair_group_derivatives(
conformation::Residue const & rsd1,
conformation::Residue const & rsd2,
//hbonds::HBondSet const & hbond_set,
utility::vector1< DerivVectorPair > & r1_atom_derivs,
utility::vector1< DerivVectorPair > & r2_atom_derivs,
core::Real const elec_weight,
core::Real & Erespair
) const;
private:
void
build_groupinfo( std::string const & group_file,
bool const extra = false );
ResElecGroup const &
get_group( core::chemical::ResidueType const &rsdtype ) const;
Vector
get_grpdis2( conformation::Residue const & rsd1,
conformation::Residue const & rsd2,
utility::vector1< Size > const &com1atms,
utility::vector1< Size > const &com2atms,
core::Vector &com1,
core::Vector &com2
) const ;
bool
fade_hbonding_group_score( ElecGroup const &grp1,
ElecGroup const &grp2,
Real & group_score,
Real & dw_dE ) const;
Real
get_grp_countpair(
utility::vector1< Size > const &grp1atms,
utility::vector1< Size > const &grp2atms,
etable::count_pair::CountPairFunctionCOP cpfxn,
Size &path_dist
) const;
inline
Real
eval_standard_coulomb( Real const &q1, Real const &q2,
Real const &dis2,
bool const &eval_deriv,
Real &dE_dr
) const;
inline
Real
eval_grp_trunc( bool const &use_switch,
Real const &grpdis2,
bool const &eval_deriv,
Real &dsw_dr
) const;
inline std::string fade_type() const { return fade_type_; }
protected:
inline
etable::coulomb::Coulomb const &
coulomb() const {return *coulomb_; }
etable::coulomb::CoulombCOP coulomb_;
private:
// mutable std::map< std::string, ElecGroup > rsdgrps_;
mutable std::map< std::string const , ResElecGroup > rsdgrps_;
utility::vector1< Real > cpfxn_weight_;
// for standard coulomb
std::string fade_type_;
core::Real fade_param1_;
core::Real fade_param2_;
bool fade_hbond_;
std::string group_file_;
bool grp_cpfxn_;
//std::string grp_cpfxn_mode_;
/// @delete in its current form GroupElec is not assignable due to presense of std::map< const std::string, ...>
/// but compiler tries to generate assigment operator anyway
GroupElec & operator= ( const GroupElec & ) = delete;
}; // class GroupElec
inline
Real
GroupElec::eval_grp_trunc( bool const &use_switch,
Real const &grpdis2,
bool const &eval_deriv,
Real &dsw_dr
) const
{
dsw_dr = 0.0;
Real const &max_dis2( coulomb().max_dis2() );
Real const &max_dis( coulomb().max_dis() );
if ( grpdis2 > max_dis2 ) return 0.0;
core::Real const grpdis( std::sqrt(grpdis2) );
core::Real const dis_sw( fade_param1_ );
core::Real const min_sw( max_dis - dis_sw );
// switch function stuffs
core::Real const sw_dis2 = (max_dis - dis_sw)*(max_dis - dis_sw);
core::Real const R3on_off( max_dis2 - 3.0*sw_dis2 );
core::Real Ron_off( 1.0/(max_dis2 - sw_dis2) );
core::Real const Ron_off_3( Ron_off*Ron_off*Ron_off );
core::Real dr1(max_dis2 - grpdis2);
core::Real dr2(R3on_off + 2.0*max_dis2);
// shift function
core::Size const nexp = (core::Size)( fade_param2_ );
Real arg = 1.0;
for ( core::Size iexp = 1; iexp <= nexp; ++iexp ) {
arg *= (grpdis-min_sw)/dis_sw * (grpdis-min_sw)/dis_sw;
}
Real const sf1 = 1.0 - arg;
Real const darg = 2.0*nexp*arg/((grpdis-min_sw)*grpdis);
// fade function
core::Real sw( 1.0 );
if ( grpdis2 > sw_dis2 ) {
if ( use_switch ) {
sw = dr1*dr1*dr2*Ron_off_3;
} else {
sw = sf1*sf1;
}
}
if ( eval_deriv ) {
// fade function
if ( grpdis2 > sw_dis2 ) {
if ( use_switch ) {
dsw_dr = 4.0*dr1*Ron_off_3*(dr1-dr2);
} else {
dsw_dr = -2.0*darg*sf1;
}
}
}
return sw;
}
// hpark 09/24/2014
// this was made to reproduce physical numbers by following molecular mechanics way;
// original implementation had deviation from the real Coulomb energy when constant-dielectric is turned on
// looks not too different when using distance-dependent dielectric though
inline
Real
GroupElec::eval_standard_coulomb( Real const &q1, Real const &q2,
Real const &dis2,
bool const &eval_deriv,
Real &dE_dr
) const {
dE_dr = 0.0;
core::Real const d( std::sqrt( dis2 ) );
Real const &die = coulomb().die();
Real const C0( 322.0637 );
// choose dielectric
Real fdie, ddie_dr( 0.0 );
//std::string const &diefunc( coulomb().dielectric_function() );
if ( dis2 < 1.0 ) {
fdie = die;
ddie_dr = 0.0;
} else if ( !coulomb().no_dis_dep_die() ) { // ddd
/*
if( diefunc.compare("sigmoid") == 0 ){
fdie = coulomb().die_sigmoid( d, eval_deriv, ddie_dr );
} else if( diefunc.compare("warshel") == 0 ){
fdie = coulomb().die_warshel( d, eval_deriv, ddie_dr );
} else {
*/
fdie = die*d;
ddie_dr = die;
//}
} else { // constant
fdie = die;
ddie_dr = 0.0;
}
core::Real e( 0.0 );
if ( dis2 < 1.0 ) {
e = -d+2.0;
} else { //regular
e = 1.0/d;
}
e *= q1*q2*C0;
if ( eval_deriv ) {
core::Real de_dr( 0.0 ); // on Coulomb part without fdie
if ( dis2 < 1.0 ) { //use linear softening at short-distance
de_dr = -q1*q2*C0/fdie;
//dE_dr = de_dr/(d+0.000001); // to prevent from being infinity
dE_dr = de_dr/d; // to prevent from being infinity
} else { // regular
de_dr = -e/d;
dE_dr = ( de_dr/fdie - e*ddie_dr/(fdie*fdie) )/d;
}
}
//std::cout << e << " " << d << " " << fdie << std::endl;
return e/fdie;
}
} // namespace elec
} // namespace scoring
} // namespace core
#endif
| [
"[email protected]"
] | |
063720509896c20416d025d4d36b34d7dbe539d0 | 879a441a5fa00c0c60d68ae1c784f64cd703784d | /src/test-cpp.cpp | aa6b341f3d006a876d6048e847f92ba3b1f336e8 | [] | no_license | mpadge/libfuzzerr | 93bb42d52b5e775bd7691712c8df73f8ab9f6fb3 | 654f87ac1b3766f5ade4d78815844ea0dd73d6a4 | refs/heads/master | 2020-09-21T16:49:43.161109 | 2020-02-24T15:50:36 | 2020-02-24T15:50:36 | 224,855,412 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 222 | cpp | #include "test-cpp.h"
extern "C" int LLVMFuzzerTestOneInput(const int *Data) {
return 0;
}
//' rcpp_test
//' @noRd
// [[Rcpp::export]]
int rcpp_test (Rcpp::IntegerVector input)
{
int out = 0;
return out;
}
| [
"[email protected]"
] | |
3b811c85039935049b2141a251386365548e3152 | 8ac157eda8e6fe4dab420e47da32300e63c62489 | /UVA/893 - Y3K Problem.cpp | 9ef736af1ac44d1c1ff0120a6bc3a857b86c6f39 | [] | no_license | mdskrumi/Online-Judge-Problem-Solutions | f11cc0e577437012c7da7f2ab376fa01638f95f5 | 453e5d5c2464a63bd919fe95bb16f4cc4a1c2513 | refs/heads/master | 2020-09-28T05:29:00.453502 | 2020-08-13T16:00:12 | 2020-08-13T16:00:12 | 226,700,158 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,456 | cpp | #include<bits/stdc++.h>,
#include<ctype.h>
#include<string.h>
#define sf scanf
#define pf printf
#define pb push_back
#define mp make_pair
#define DOS 10000000000
#define nl "\n"
using namespace std;
int getLeapYear(int year){
if ( year%400 == 0)return 1;
else if ( year%100 == 0)return 0;
else if ( year%4 == 0 )return 1;
return 0;
}
int getDaysInYear(int y){
if(getLeapYear(y)){
return 366;
}return 365;
}
int getDaysInMonth(int m , int y){
if(m == 11 || m == 4 || m == 6 || m == 9)
return 30;
if(m == 2 )
return 28 + getLeapYear(y);
return 31;
}
int main(){
int togo, day , month , year;
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
while(sf("%d%d%d%d",&togo,&day,&month,&year) && togo != 0 && year != 0 ){
day+=togo;
for(int i = 1 ; i < month ; i++){
day+=getDaysInMonth(i,year);
}
month = 1;
while(day > getDaysInYear(year)){
day -= getDaysInYear(year);
year++;
}
while(day>getDaysInMonth(month,year)){
day -= getDaysInMonth(month,year);
month++;
if(month>12){
year++;
month = 1;
}
}
cout << day << " " << month << " " << year << nl;
}
return 0;
}
| [
"[email protected]"
] | |
6d2796d92a888d0aa571ec610d8bbabd911e679f | d20cf7de868dfb2c53578a70d0dda21306167d72 | /data/raw/train/student_61/2317/2316/Casuta.cpp | 3a3bf5cc7b37d25b0a1784aa505370b5f536a038 | [] | no_license | bulacu-magda/Alemia | 905a84ca79157fb657eb424e337b0303fd3323bd | 0fd019c4517064d300399feb94dbcb0f467e8d48 | refs/heads/main | 2023-03-01T17:41:08.788500 | 2021-02-05T08:00:35 | 2021-02-05T08:00:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 92 | cpp | #include "Casuta.h"
Casuta::Casuta(int r, int c) :r(r), c(c)
{
}
Casuta::~Casuta()
{
}
| [
"[email protected]"
] | |
2e4ea5e076ab62b13a6bd0195b251f73c6963428 | 9120a9b17d00f41e5af26b66f5b667c02d870df0 | /INCLUDE/owlext/debugex.h | b6d69b6c8055cf24a38ed4a3e86619f05160ea49 | [] | no_license | pierrebestwork/owl | dd77c095abb214a107f17686e6143907bf809930 | 807aa5ab4df9ee9faa35ba6df9a342a62b9bac76 | refs/heads/master | 2023-02-14T02:12:38.490348 | 2020-03-16T16:41:49 | 2020-03-16T16:41:49 | 326,663,704 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,795 | h | /***************************************************************************
OWL Extensions (OWLEXT) Class Library
DebugEx.h
$Revision: 1.1.4.2 $
$Author: jogybl $
$Date: 2009-10-23 10:49:26 $
This header declares several macros for debugging purposes. There are
two general categories: ASSERT and TRACE. So as not to conflict with
OWL's TRACE macros, this module uses CTRACE instead. Below is a run
down on the macros and briefly how they are used:
IFDEBUG(X) X is expanded only for debug builds. Useful for a
parameter that is only ASSERTed on. Eg:
void foo (int IFDEBUG(x))
{
ASSERT (x);
}
VALIDPTR(P) Returns TRUE for valid pointers (not all non-null ptrs
are valid). The release build simply tests for null.
ASSERT(B) if B is false, you get an Abort/Retry/Ignore msgbox.
Retry drops you into the debugger at the point of the
ASSERT statement. For release builds, the entire
overhead for ASSERT is removed (so it better not have
any side-effects).
VERIFY(B) Same as ASSERT except that the expression remains for
release builds. This is ideal for an expression that
has side-effects. Eg: VERIFY(LoadString(...)).
DBGBRK() Embeds a debugger breakpoint.
COMPILE_ASSERT(B) Evaluates a compile-time expression and fails
to compile if B is false. Useful for array size tests
and such. Eg:
COMPILE_ASSERT (ARRAYCOUNT(myTable) == IDX_LAST);
#define ARRAYCOUNT(A) (sizeof(A) / sizeof(A[0]))
Tracing is built using trace groups and trace levels. A trace group
is used to bind common pieces together. For example, a class will
usually define a trace group that each of its methods use for its
trace messages. A trace group is simply a global object. There are
macros for defining one, declaring a group as extern, and setting
the default group for a source file. Each group object has a current
trace level member.
The trace level is an integer that is used as a filter. All trace
messages include a trace level. If the level of the message is <= to
the current trace level for its group, the message will generate
output. By convention, there are three predefined levels: traceError
(level 1), traceWarning (level 5) and traceInfo (level 10). This
allows all traces to be turned off for a group by setting its level
to 0.
The trace levels for all groups in a module (EXE or DLL) are stored in
an INI file by the name of "MODULE.TRC" that resides in the same
directory as the module. This file is read when CTRACE_INIT is called
in that module. The HINSTANCE is needed to locate the BIN directory.
DEFINE_CTRACEGROUP(name,defLevel) Instantiates a trace group object
callled 'name' + 'TraceGroup'. Eg: ListBoxTest would be
ListBoxTestTraceGroup. The defLevel is the level for
which traces will be generated. Typically, the value
traceWarning is used for this. The level in the TRC file
takes precedence.
EXTERN_CTRACEGROUP(name) Declares that a trace group called 'name'
as an extern group.
DEFAULT_CTRACEGROUP(name) Declares that the default trace group for
this file is 'name' (same name as used in DEFINE_ above).
This is required to use CTRACE instead of CTRACEEX (see
below).
CTRACEEX(name,level,(...)) Generates a trace at 'level' for the
trace group labeld 'name'. The syntax is a bit funny
because it was the only way to remove all overhead for
the trace in a non-trace build. Eg:
CTRACEEX (ListBoxTest, traceWarning,
("Bad thing %d", badThing));
CTRACE(level,(...)) Similar to CTRACEEX, except that the group is
the "default" group.
CTRACEEX_IF(b,name,level,(...)) This macro is used for a conditional
trace. If b is true, the result is equivalent to CTRACEEX.
CTRACE_IF(b,level,(...)) Similar to CTRACEEX_IF, but uses the default
trace group.
ASSERT_TRACE(B,(...)) Similar to CTRACE_IF, except that we see the msg
in the assert msgbox and also as if it were a normal trace.
VERIFY_TRACE(B,(...)) Same difference as ASSERT vs. VERIFY
CTRACE_FUNCTIONEX(name,level,f) Declares an object on the stack that
will ouput the function name f in its ctor and again its
dtor. The output would be:
>> Foo
<< Foo
CTRACE_FUNCTION(level,f) Similar to CTRACE_FUNCTIONEX except that it
uses the default trace group.
CTRACE_FUNCTIONEX2(g,level,f,(...)) Similar to CTRACE_FUNCTIONEX except
that we see extra text beyond the entry trace. Eg, if we
said:
CTRACE_FUNCTIONEX2 (group, traceError, "Foo",
("Param1 = %d", wParam));
>> Foo (Param1 = 10)
<< Foo
The CTRACE_FUNCTION macros increment an indent level for traces, so
the output of a callstack might look like this:
>> Foo
Calling Goo(10)...
>> Goo (val = 10)
Goo ran into a problem: i < 10!
<< Goo
<< Foo
This can even work properly if Goo is in a DLL other than Foo! To do
that, peek at (I)TTraceLink below. The general idea is that modules
who wish to cooperate must "link" up their trace objects. There is an
example of this in the SdiTest app which uses DllTest.
There is code in the TApp class that adds "View Trace" to the system
menu of the main window. When selected, it displays a TTraceWindow for
the traces (the default traces go to OutputDebugString). The trace
window can save the trace buffer, set the font, modify the trace levels
on-the-fly, etc.. This is useful for testers who might not have a debug
monitor or DbWin. All of that is built using the functionality provided
by this module--there is no knowledge of any GUI stuff down here other
than MessageBox.
***************************************************************************/
#if !defined (__OWLEXT_DEBUGEX_H)
#define __OWLEXT_DEBUGEX_H
# ifdef _DEBUG
# include <dos.h> // __emit__ prototype for debugger breakpoint
# define IFDBG(X) X
# define IFNDBG(X)
# if !defined(VALIDPTR)
# define VALIDPTR(P) (! IsBadReadPtr ((P), 1)) // more thorough
# endif
# else
# ifndef NDEBUG
# define NDEBUG
# endif
# define IFDBG(X)
# define IFNDBG(X) X
# define VALIDPTR(P) ((P) != 0) // quicker than IsBadReadPtr
# endif
# define IFDEBUG IFDBG
# define IFNDEBUG IFNDBG
# define DBGBRK() IFDEBUG (_OWL_BREAK) // by Yura Bidus 05/31/98
# define VALIDORNULLPTR(P) (!(P) || VALIDPTR(P))
// use COUNTOF(a) insteed, see owl/private/defs.h
# ifndef ARRAYCOUNT
# define ARRAYCOUNT(A) COUNTOF(A)
# endif
// This guy generates a compiler error such as
// 'Array must have at least one element'
// if the boolean condition argument is false:
# define COMPILE_ASSERT(B) typedef char _Assert##__LINE__ [2*(!!(B)) - 1]
# ifdef _DEBUG
// If we don't turn these on, frequent use of ASSERT will fill DGROUP:
//
# pragma option -d // merge duplicate strings ON
# ifndef __WIN32__
# pragma option -dc // constant strings in code segments ON
# endif
# define ASSERT(X) \
( (!(X) && DebugEx::AssertFailure (__FILE__,__LINE__)) \
? DBGBRK() : (void)0 )
# if !defined(VERIFY)
# define VERIFY(X) ASSERT(X)
# endif
# else
# define ASSERT(X) ((void) 0)
# if !defined(VERIFY)
# define VERIFY(X) ((void) (X))
# endif
# endif
//==========================================================================
# define _TRACEMETHOD __stdcall
# define _TRACEMETHODIMP _TRACEMETHOD
# define _TRACEINTF
# define ASSERT_CTRACE(X,msg) ASSERT_CTRACEEX (X, __def, msg)
# define VERIFY_CTRACE(X,msg) VERIFY_CTRACEEX (X, __def, msg)
# ifndef _DEBUG
# define CTRACE_INIT(hInst)
# define DEFINE_CTRACEGROUP(name,level)
# define EXTERN_CTRACEGROUP(name)
# define DEFAULT_CTRACEGROUP(name)
# define DEFINE_DEFAULT_CTRACEGROUP(name,level)
# define EXTERN_DEFAULT_CTRACEGROUP(name)
# define CTRACEEX(name,level,msg)
# define CTRACE(level,msg)
# define CTRACEEX_IF(b,name,level,msg)
# define CTRACE_IF(b,level,msg)
# define CTRACE_FUNCTIONEX(g,level,f)
# define CTRACE_FUNCTIONEX2(g,level,f,p)
# define CTRACE_FUNCTION(level,f)
# define CTRACE_FUNCTION2(level,f,p)
# define ASSERT_CTRACEEX(X,name,msg) ASSERT (X)
# define VERIFY_CTRACEEX(X,name,msg) VERIFY (X)
# else // _DEBUG (look to end of file)
#if !defined(BI_NO_NAMESPACE) || defined(BI_NAMESPACE)
namespace DebugEx {
# define DEBUGEXT DebugEx
#else
# define DEBUGEXT
#endif
// Generic definitions/compiler options (eg. alignment) preceeding the
// definition of classes
//
# include <owl/preclass.h>
# define ASSERT_CTRACEEX(X,name,msg) \
( (!(X) && DEBUGEXT::AssertFailure (__FILE__, __LINE__, \
& CTRACEGROUP(name), \
DEBUGEXT::TraceF msg)) \
? DBGBRK() : (void)0 )
# define VERIFY_CTRACEEX(X,name,msg) \
ASSERT_CTRACEEX(X,name,msg)
# define CTRACE_INIT(hInst) DEBUGEXT::traceLink.Init (hInst)
struct _TRACEINTF ITraceLink;
struct _TRACEINTF ITraceGroup
{
virtual unsigned _TRACEMETHOD Level () = 0;
virtual void _TRACEMETHOD Level (unsigned) = 0;
virtual ITraceLink * _TRACEMETHOD Link () = 0;
virtual const char * _TRACEMETHOD Name () = 0;
virtual ITraceGroup * _TRACEMETHOD Next () = 0;
};
class _TRACEINTF TTraceGroup : public ITraceGroup
{
public:
TTraceGroup (const char *name, unsigned level);
// return true to ignore trace message, false for normal execution.
typedef bool (* TTraceHook) (TTraceGroup *, unsigned level,
const char *msg);
static TTraceHook TraceHook () { return sTraceHook; }
static void TraceHook (TTraceHook fn) { sTraceHook = fn; }
void Trace (unsigned level, const char *msg);
// Group navigation:
//
static TTraceGroup *FirstGroup () { return sFirst; }
TTraceGroup *NextGroup() { return mNext; }
void ReadState (const char * iniFile);
void SaveState (const char * iniFile);
// ITraceGroup interface:
//
virtual unsigned _TRACEMETHODIMP Level ();
virtual void _TRACEMETHODIMP Level (unsigned);
virtual ITraceLink * _TRACEMETHODIMP Link ();
virtual const char * _TRACEMETHODIMP Name ();
virtual ITraceGroup * _TRACEMETHODIMP Next ();
private:
static TTraceGroup * sFirst;
static TTraceHook sTraceHook;
TTraceGroup * mNext;
const char * mName;
unsigned mLevel; // current trace level for group (0 = all)
};
// Mangles the user-visible group name into something less likely to cause
// duplicate symbol errors:
//
# define CTRACEGROUP(name) name##TraceGroup
// Used in a file to declare a trace group. The trace group is a named
// entity that is used to associate common activities. Eg, a class may be
// implemented such that any trace messages it outputs fall into one group
// which may be activated as desired via an INI file. This name can then
// be used in a CTRACEEX statement.
//
# define DEFINE_CTRACEGROUP(name,level) \
DEBUGEXT::TTraceGroup CTRACEGROUP(name) (#name, level);
// Declares an extern trace group. This is used to write traces as a member
// of a group from a file other than the file where DEFINE_CTRACEGROUP(name)
// was used. This name can then be used in a CTRACEEX statement.
//
# define EXTERN_CTRACEGROUP(name) \
extern DEBUGEXT::TTraceGroup CTRACEGROUP(name);
// This macro is used to declare a default trace group for a file. This is
// required to use the simpler CTRACE macro.
//
# define DEFAULT_CTRACEGROUP(name) \
static DEBUGEXT::TTraceGroup & CTRACEGROUP(__def) = CTRACEGROUP(name); \
static void __KillNoUseDefTraceGroupWarning (DEBUGEXT::TTraceGroup &) \
{ __KillNoUseDefTraceGroupWarning (CTRACEGROUP(__def)); }
// This is the typically used macro, where we both DEFINE a new trace group
// and use it as the DEFAULT trace group for this file.
//
# define DEFINE_DEFAULT_CTRACEGROUP(name,level) \
DEFINE_CTRACEGROUP (name, level) \
DEFAULT_CTRACEGROUP (name)
# define EXTERN_DEFAULT_CTRACEGROUP(name) \
EXTERN_CTRACEGROUP (name) \
DEFAULT_CTRACEGROUP (name)
extern const char * __cdecl TraceF (const char *fmt, ...);
enum TTraceLevel // common values used for trace levels (convention only)
{
traceError = 1,
traceWarning = 5,
traceInfo = 10
};
// Examples:
// CTRACEEX (GroupName, 3 /* level */, ("Message"));
// CTRACEEX (GroupName, 2 /* level */, ("Value %d", nValue));
// CTRACE (2 /* level */, ("Default trace message %d", value));
//
# define CTRACEEX(name,level,msg) CTRACEGROUP(name).Trace (level, DEBUGEXT::TraceF msg)
# define CTRACE(level,msg) CTRACEEX (__def, level, msg)
//
// CTRACE_IF (i < 10, traceWarning, ("Value of i (= %d) is too low", i));
//
# define CTRACEEX_IF(b,name,level,msg) \
(!(b) ? (void)0 : CTRACEEX(name,level,msg))
# define CTRACE_IF(b,level,msg) \
CTRACEEX_IF (b, __def, level, msg)
class TTraceFunction
{
public:
TTraceFunction (TTraceGroup &group, unsigned level, const char *name);
TTraceFunction (TTraceGroup &group, unsigned level, const char *name,
const char * params);
~TTraceFunction ();
private:
TTraceGroup & mGroup;
unsigned mLevel;
bool mTracedEntry;
const char * mName;
void DoTrace (char ch, const char * suffix = 0);
};
# define CTRACE_FUNCTIONEX(g,level,f) \
DEBUGEXT::TTraceFunction __traceFunc (CTRACEGROUP(g), level, f)
# define CTRACE_FUNCTIONEX2(g,level,f,p) \
DEBUGEXT::TTraceFunction __traceFunc (CTRACEGROUP(g), level, f,\
DEBUGEXT::TraceF p)
# define CTRACE_FUNCTION(level,f) \
CTRACE_FUNCTIONEX (__def, level, f)
# define CTRACE_FUNCTION2(level,f,p) \
CTRACE_FUNCTIONEX2 (__def, level, f, p)
//--------------------------------------------------------------------------
// In a multimodule system, one module needs to be in charge of tracing.
// To do that, they need to link up with each other. And to do that, one
// module must be designated as the root of the tracing hierarchy. That
// module will be told about all traces in all other modules. It also has
// any global state information that is needed by all modules (such as the
// indent level, active status, etc.).
//
// The root module needs to link up with some of the other modules in the
// system. The easiest way to do that is to call a function in each of
// those modules, passing an ITraceLink* to it:
//
// void Mod1SetTraceLink (ITraceLink * link)
// {
// link->AddChild (& traceLink);
// }
//
// If Mod1 knows about lower level modules, it could initialize them as
// well:
//
// void Mod1SetTraceLink (ITraceLink * link)
// {
// link->AddChild (& traceLink);
//
// Mod2SetTraceLink (& traceLink);
// Mod3SetTraceLink (& traceLink);
// }
//
// This will link Mod2 and Mod3 as children of Mod1 and Mod1 as a child
// of whomever called Mod1SetTraceLink.
//
struct _TRACEINTF ITraceLink
{
virtual bool _TRACEMETHOD Active () = 0;
virtual void _TRACEMETHOD AddChild (ITraceLink *) = 0;
virtual ITraceLink * _TRACEMETHOD FirstChild () = 0;
virtual ITraceGroup * _TRACEMETHOD FirstGroup () = 0;
virtual const char * _TRACEMETHOD Module () = 0;
virtual void _TRACEMETHOD Next (ITraceLink *) = 0;
virtual ITraceLink * _TRACEMETHOD Next () = 0;
virtual void _TRACEMETHOD ReloadTraceLevels () = 0;
virtual void _TRACEMETHOD RemoveChild (ITraceLink *) = 0;
virtual void _TRACEMETHOD Parent (ITraceLink *) = 0;
virtual ITraceLink * _TRACEMETHOD Parent () = 0;
virtual void _TRACEMETHOD SaveTraceLevels () = 0;
virtual void _TRACEMETHOD TraceIncIndent (int inc) = 0; // 1 or -1
virtual int _TRACEMETHOD TraceIndent () = 0;
virtual int _TRACEMETHOD TraceIndentSize () = 0;
virtual void _TRACEMETHOD TraceMessage (const char *, ITraceLink *) = 0;
};
// Don't pass TTraceLink*'s to other modules:
class _TRACEINTF TTraceLink : public ITraceLink
{
public:
TTraceLink ();
~TTraceLink ();
virtual bool _TRACEMETHODIMP Active ();
virtual void _TRACEMETHODIMP AddChild (ITraceLink *);
virtual ITraceLink * _TRACEMETHODIMP FirstChild ();
virtual ITraceGroup * _TRACEMETHODIMP FirstGroup ();
virtual const char * _TRACEMETHODIMP Module ();
virtual void _TRACEMETHODIMP Next (ITraceLink *);
virtual ITraceLink * _TRACEMETHODIMP Next ();
virtual void _TRACEMETHODIMP ReloadTraceLevels ();
virtual void _TRACEMETHODIMP RemoveChild (ITraceLink *);
virtual void _TRACEMETHODIMP Parent (ITraceLink *);
virtual ITraceLink * _TRACEMETHODIMP Parent ();
virtual void _TRACEMETHODIMP SaveTraceLevels ();
virtual void _TRACEMETHODIMP TraceIncIndent (int inc);
virtual int _TRACEMETHODIMP TraceIndent ();
virtual int _TRACEMETHODIMP TraceIndentSize ();
virtual void _TRACEMETHODIMP TraceMessage (const char *msg,
ITraceLink *source = 0);
typedef void (* TTraceProc) (ITraceLink *source, const char *msg);
void Active (bool b) { mActive = b; }
void Init (HINSTANCE);
TTraceProc TraceProc () { return mTraceProc; }
void TraceProc (TTraceProc fn) { mTraceProc =
fn ? fn : DefTrace; }
void TraceIndentSize (int size) { mIndentSize = size; }
private:
TTraceProc mTraceProc;
HINSTANCE mInstance;
ITraceLink * mParent;
ITraceLink * mFirstChild;
ITraceLink * mNext;
bool mActive;
int mIndent;
int mIndentSize;
char mModule [16];
static void DefTrace (ITraceLink *source, const char *msg);
// ==> OutputDebugString
void TraceFileName (char *);
};
extern TTraceLink traceLink;
extern bool __cdecl AssertFailure (const char * file, unsigned line,
TTraceGroup * = 0, const char *msg = 0);
// Generic definitions/compiler options (eg. alignment) following the
// definition of classes
# include <owl/posclass.h>
#if !defined(BI_NO_NAMESPACE) || defined(BI_NAMESPACE)
};
#endif
#if !defined(BI_NO_NAMESPACE) || defined(BI_NAMESPACE)
using namespace DebugEx;
# endif
# endif // _DEBUG
#endif // __DEBUGEX_H
| [
"[email protected]"
] | |
3352f0c7c732a852be2914096277a76d9a4020d3 | 41ba6db2bcfb863db5b8f1824a13a8bf65f85dc8 | /src/interface.cc | f2c514b5678f4b291a217e8cb46f395f98d0f196 | [] | no_license | jmanero/voltaged | 2042df96a52c41e621e57bef7001f79afaaf72ce | 593356a120b4661c70c86753ae34ccfef67300cf | refs/heads/master | 2016-09-05T13:56:36.170813 | 2014-07-01T14:48:30 | 2014-07-01T14:48:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,334 | cc | #include "spi.h"
/**
* Build a new uv_work_t with an SPIBaton
*/
uv_work_t* SPIInterface::create_request(Local<Value> fd, uint8_t operation, Local<Value> callback) {
SPIBaton* baton = new SPIBaton(); // Create Request Baton
baton->error_code = 0;
baton->operation = operation;
baton->fd = fd->ToInt32()->Value();
baton->callback = Persistent<Function>::New(Local<Function>::Cast(callback));
uv_work_t* request = new uv_work_t(); // Create UV Request
request->data = baton;
return request;
}
/**
* Validate `fd` and `callback` before trying to build a request
*/
Handle<Value> SPIInterface::validate_request(Local<Value> fd, Local<Value> callback) {
if (!fd->IsInt32()) return ThrowException(Exception::TypeError(
String::New("File-handle must be an integer")));
if (!callback->IsFunction()) return ThrowException(Exception::TypeError(
String::New("callback must be a function")));
return Undefined();
}
/**
* Handle callbacks from SPIDevice tasks
*/
void SPIInterface::Result(uv_work_t* req) {
HandleScope scope;
SPIBaton* baton = static_cast<SPIBaton*>(req->data);
Handle<Value> argv[] = { Undefined(), Undefined() };
TryCatch try_catch;
switch(baton->operation) {
case SPI_INTERFACE_OPEN:
argv[1] = Int32::New(baton->fd);
delete baton->device; // FREE THE MALLOCS!!
break;
case SPI_INTERFACE_TRANSFER:
case SPI_INTERFACE_CLOSE:
break;
case SPI_INTERFACE_ERROR:
argv[0] = Exception::Error(
String::New(("SPIDevice Error: " + baton->error_message +
" (" + to_string(baton->error_code) + "): " +
strerror(baton->error_code)).c_str()));
break;
default:
argv[0] = Exception::TypeError(
String::New(("Unhandled SPIInterface operation " +
to_string(baton->operation)).c_str()));
}
baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
if (try_catch.HasCaught()) FatalException(try_catch);
// FREE THE MALLOCS!!
baton->callback.Dispose();
delete baton;
delete req;
}
/**
* Enqueue an open task
*/
Handle<Value> SPIInterface::Open(const Arguments& args) {
HandleScope scope;
// Validate and cast arguments
if (!args[0]->IsString()) return ThrowException(Exception::TypeError(
String::New("Device must be a string")));
String::Utf8Value device_(args[0]->ToString());
if (!args[1]->IsNumber()) return ThrowException(Exception::TypeError(
String::New("Mode must be a number")));
uint8_t mode_ = (uint8_t) args[1]->ToUint32()->Value();
if (!args[2]->IsNumber()) return ThrowException(Exception::TypeError(
String::New("WordLength must be a number")));
uint8_t word_ = (uint8_t) args[2]->ToUint32()->Value();
if (!args[3]->IsNumber()) return ThrowException(Exception::TypeError(
String::New("Speed must be a number")));
uint32_t speed_ = args[3]->ToUint32()->Value();
Local<Number> fd = Int32::New(-1);
validate_request(fd, args[4]);
uv_work_t* request = create_request(fd, SPI_INTERFACE_OPEN, args[4]);
SPIBaton* baton = (SPIBaton*)(request->data);
// <sad-hack> Will be freed in Response.
baton->device = (char*)calloc(device_.length(), sizeof(char));
memcpy(baton->device, *device_, device_.length());
// </sad-hack>
baton->mode = mode_;
baton->word = word_;
baton->speed = speed_;
uv_queue_work(uv_default_loop(), request, SPIDevice::open,
(uv_after_work_cb)(SPIInterface::Result));
return scope.Close(Undefined());
}
/**
* Enqueue a transfer task
*/
Handle<Value> SPIInterface::Transfer(const Arguments& args) {
HandleScope scope;
// Validate and cast arguments
if (!args[1]->IsNumber()) return ThrowException(Exception::TypeError(
String::New("WordLength must be a number")));
uint8_t word_ = (uint8_t) args[1]->ToUint32()->Value();
if (!args[2]->IsNumber()) return ThrowException(Exception::TypeError(
String::New("Speed must be a number")));
uint32_t speed_ = args[2]->ToUint32()->Value();
if (!Buffer::HasInstance(args[3])) return ThrowException(Exception::TypeError(
String::New("Send must be a Buffer")));
Local<Object> send_ = args[3]->ToObject();
if (!Buffer::HasInstance(args[4])) return ThrowException(Exception::TypeError(
String::New("Receive must be a Buffer")));
Local<Object>receive_ = args[4]->ToObject();
validate_request(args[0], args[5]);
uv_work_t* request = create_request(args[0], SPI_INTERFACE_TRANSFER, args[5]);
SPIBaton* baton = (SPIBaton*)(request->data);
baton->word = word_;
baton->speed = speed_;
// Export read and write buffers
baton->length = Buffer::Length(send_);
baton->send = (uint8_t*)(Buffer::Data(send_));
baton->receive = (uint8_t*)(Buffer::Data(receive_));
uv_queue_work(uv_default_loop(), request, SPIDevice::transfer,
(uv_after_work_cb)(SPIInterface::Result));
return scope.Close(Undefined());
}
/**
* Enqueue a close task
*/
Handle<Value> SPIInterface::Close(const Arguments& args) {
HandleScope scope;
validate_request(args[0], args[1]);
uv_queue_work(uv_default_loop(),
create_request(args[0], SPI_INTERFACE_CLOSE, args[1]),
SPIDevice::close, (uv_after_work_cb)(SPIInterface::Result));
return scope.Close(Undefined());
}
/**
* Ye Old V8 Init handler
*/
void Init(Handle<Object> target) {
HandleScope scope;
// Export Methods
target->Set(String::NewSymbol("open"),
FunctionTemplate::New(SPIInterface::Open)->GetFunction());
target->Set(String::NewSymbol("transfer"),
FunctionTemplate::New(SPIInterface::Transfer)->GetFunction());
target->Set(String::NewSymbol("close"),
FunctionTemplate::New(SPIInterface::Close)->GetFunction());
// Export constants
Persistent<Object> constants = Persistent<Object>::New(Object::New());
target->Set(String::NewSymbol("CONST"), constants);
constants->Set(String::NewSymbol("SPI_MODE_0"), Integer::New(SPI_MODE_0));
constants->Set(String::NewSymbol("SPI_MODE_1"), Integer::New(SPI_MODE_1));
constants->Set(String::NewSymbol("SPI_MODE_2"), Integer::New(SPI_MODE_2));
constants->Set(String::NewSymbol("SPI_MODE_3"), Integer::New(SPI_MODE_3));
constants->Set(String::NewSymbol("SPI_NO_CS"), Integer::New(SPI_NO_CS));
constants->Set(String::NewSymbol("SPI_CS_HIGH"), Integer::New(SPI_CS_HIGH));
}
/**
* Node JS Black Magic (tm)
*/
NODE_MODULE(SPIInterface, Init);
| [
"[email protected]"
] | |
e59a85013b2efb44622d5b9f4143473af02ec8f6 | 5722258ec3ce781cd5ec13e125d71064a67c41d4 | /java/security/PermissionProxy.h | b1cd0d9462e38942359a3f6de4f5f507fa916358 | [] | no_license | ISTE-SQA/HamsterJNIPP | 7312ef3e37c157b8656aa10f122cbdb510d53c2f | b29096d0baa9d93ec0aa21391b5a11b154928940 | refs/heads/master | 2022-03-19T11:27:03.765328 | 2019-10-24T15:06:26 | 2019-10-24T15:06:26 | 216,854,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,302 | h | #ifndef __java_security_PermissionProxy_H
#define __java_security_PermissionProxy_H
#include <jni.h>
#include <string>
#include "net/sourceforge/jnipp/JBooleanArrayHelper.h"
#include "net/sourceforge/jnipp/JByteArrayHelper.h"
#include "net/sourceforge/jnipp/JCharArrayHelper.h"
#include "net/sourceforge/jnipp/JDoubleArrayHelper.h"
#include "net/sourceforge/jnipp/JFloatArrayHelper.h"
#include "net/sourceforge/jnipp/JIntArrayHelper.h"
#include "net/sourceforge/jnipp/JLongArrayHelper.h"
#include "net/sourceforge/jnipp/JShortArrayHelper.h"
#include "net/sourceforge/jnipp/JStringHelper.h"
#include "net/sourceforge/jnipp/JStringHelperArray.h"
#include "net/sourceforge/jnipp/ProxyArray.h"
// includes for parameter and return type proxy classes
#include "java\lang\ObjectProxyForward.h"
#include "java\security\PermissionCollectionProxyForward.h"
namespace java
{
namespace security
{
class PermissionProxy
{
private:
static std::string className;
static jclass objectClass;
jobject peerObject;
protected:
PermissionProxy(void* unused);
virtual jobject _getPeerObject() const;
public:
static jclass _getObjectClass();
static inline std::string _getClassName()
{
return className;
}
jclass getObjectClass();
operator jobject();
// constructors
PermissionProxy(jobject obj);
PermissionProxy(::net::sourceforge::jnipp::JStringHelper p0);
virtual ~PermissionProxy();
PermissionProxy& operator=(const PermissionProxy& rhs);
// methods
/*
* boolean equals(Object);
*/
jboolean equals(::java::lang::ObjectProxy p0);
/*
* boolean implies(Permission);
*/
jboolean implies(::java::security::PermissionProxy p0);
/*
* int hashCode();
*/
jint hashCode();
/*
* String getActions();
*/
::net::sourceforge::jnipp::JStringHelper getActions();
/*
* String getName();
*/
::net::sourceforge::jnipp::JStringHelper getName();
/*
* String toString();
*/
::net::sourceforge::jnipp::JStringHelper toString();
/*
* PermissionCollection newPermissionCollection();
*/
::java::security::PermissionCollectionProxy newPermissionCollection();
/*
* void checkGuard(Object);
*/
void checkGuard(::java::lang::ObjectProxy p0);
};
}
}
#endif
| [
"[email protected]"
] | |
8aa5d3e97d5198202bad5785a7f3a92409a4f722 | 2771893a93bdf0b9c2d06d78c9099f7c92e92709 | /c++/004-MedianOfTwoSortedArrays.cpp | 4d32481befd031ce067df7002bd038aba3393a2d | [] | no_license | tangzecn/leetcode | 2144ba31727ca6f2c81c537ab41ef4ba400564b6 | 1a5ebb9c036bea4910002a6dfa260804193134b7 | refs/heads/master | 2021-06-08T13:03:33.641424 | 2017-06-07T22:23:00 | 2017-06-07T22:23:00 | 28,834,674 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,271 | cpp | #include<iostream>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size();
if ((n + m) & 1) {
return findMedian(nums1.begin(), nums2.begin(), n, m, (n + m + 1) >> 1);
} else {
return double(findMedian(nums1.begin(), nums2.begin(), n, m, (n + m) >> 1) +
findMedian(nums1.begin(), nums2.begin(), n, m, (n + m + 2) >> 1)) / 2.0;
}
}
int findMedian(vector<int>::iterator num1, vector<int>::iterator num2, int n, int m, int k) {
if (n > m) return findMedian(num2, num1, m, n, k);
else
if (n == 0) return *(num2 + k - 1);
else
if (k == 1) return min(*num1, *num2);
else {
int n1 = (k / 2 <= n) ? k / 2 : n;
int m1 = k - n1;
if ((*(num1 + n1 - 1)) < (*(num2 + m1 - 1))) {
return findMedian(num1 + n1, num2, n - n1, m, k - n1);
} else if ((*(num1 + n1 - 1)) > (*(num2 + m1 - 1))) {
return findMedian(num1, num2 + m1, n, m - m1, k - m1);
} else {
return *(num1 + n1 - 1);
}
}
}
};
int main() {
return 0;
} | [
"[email protected]"
] | |
762bcf7d8a9b819b532899233b1c141ba59a3904 | c7e6081814b6f6ec8f668e88537f1149f18c9517 | /server-code/src/game_comm/gamemap/MapManager.h | d6ec04645463c82fa439b79275c1015a5d8b54b9 | [] | no_license | OrAlien/mmo-server | fd98f5cd392ec33515de4ac3f7a7aca1d1d738ac | ced79a771bdb260ffb11a87a15df52dc99a26dac | refs/heads/master | 2021-01-01T21:28:05.915099 | 2020-01-21T12:10:06 | 2020-01-21T12:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,703 | h | #ifndef MAPMANAGER_H
#define MAPMANAGER_H
#include <unordered_map>
#include "GameMap.h"
// max uint64_t = 1844 6744 0737 0955 1614
// 099999 00 000000000000
struct SceneID
{
static const uint64_t IDZONE_FACTOR = 100000000000ull;
static const uint64_t IDMAP_FACTOR = 100000000000000ull;
SceneID(uint16_t _idZone, uint16_t _idMap, uint32_t _nDynaMapIdx)
: data64(_idMap * IDMAP_FACTOR + _idZone * IDZONE_FACTOR + _nDynaMapIdx)
{
}
SceneID(uint64_t _data64 = 0)
: data64(_data64)
{
}
SceneID(const SceneID& rht)
: data64(rht.data64)
{
}
uint64_t data64;
operator uint64_t() const { return data64; }
bool operator==(const SceneID& rht) const { return data64 == rht.data64; }
bool operator<(const SceneID& rht) const { return data64 < rht.data64; }
uint32_t GetDynaMapIdx() const { return data64 % IDZONE_FACTOR; }
uint16_t GetZoneID() const { return (data64 % IDMAP_FACTOR) / IDZONE_FACTOR; }
uint16_t GetMapID() const { return data64 / IDMAP_FACTOR; }
};
// custom specialization of std::hash can be injected in namespace std
namespace std
{
template<>
struct hash<SceneID>
{
typedef SceneID argument_type;
typedef std::size_t result_type;
result_type operator()(argument_type const& s) const
{
std::hash<uint64_t> hasher;
return hasher(s.data64);
}
};
} // namespace std
class CMapManager
{
public:
CMapManager();
~CMapManager();
bool Init(uint16_t idZone);
void ForEach(const std::function<void(CGameMap*)>& func);
CGameMap* QueryMap(uint16_t idMap);
CMapData* QueryMapData(uint16_t idMapTemplate);
private:
std::unordered_map<uint16_t, CGameMap*> m_vecMap;
std::unordered_map<uint16_t, CMapData*> m_vecMapData;
};
#endif /* MAPMANAGER_H */
| [
"[email protected]"
] | |
73b441a462472969a4fa67572da788122a7309d1 | becdd0a0deef381f68fa7e7dfbbc5e8b0d61a19a | /src/zmq/zmqconfig.h | a6381ccf1540eb8db7f752f4f62e6a5cc388d811 | [
"MIT"
] | permissive | harzcoin/harzcoin | c9f7ac3b460672119b3403e5658d12638e72ee23 | fb2c9d0e079fc4b55b3eb8cc0bfcb873ed1155d9 | refs/heads/master | 2020-03-10T17:53:28.922294 | 2018-04-14T12:27:02 | 2018-04-14T12:27:02 | 129,511,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 543 | h | // Copyright (c) 2014 The Harzcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef HARZCOIN_ZMQ_ZMQCONFIG_H
#define HARZCOIN_ZMQ_ZMQCONFIG_H
#if defined(HAVE_CONFIG_H)
#include "config/harzcoin-config.h"
#endif
#include <stdarg.h>
#include <string>
#if ENABLE_ZMQ
#include <zmq.h>
#endif
#include "primitives/block.h"
#include "primitives/transaction.h"
void zmqError(const char *str);
#endif // HARZCOIN_ZMQ_ZMQCONFIG_H
| [
"[email protected]"
] | |
32399fa9b2286bd70eeee8d6278aa236b1e70625 | e3d3d199635f3c7302a3b5e67d5e735ac76171f7 | /src/skyx/VClouds/Lightning.h | ea37bbd1c8a6502919092fcf71aaa51440d56582 | [] | no_license | blockspacer/codename-ted | ebd6ec2f5f807d2c63ab07d3d8dfc31e3ed6dbdf | a66fe5ada8d1e64bde51d29e9d47df372f39bfa8 | refs/heads/master | 2021-02-14T17:41:54.728158 | 2017-06-01T19:16:47 | 2017-06-01T19:16:47 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 5,023 | h | /*
--------------------------------------------------------------------------------
This source file is part of SkyX.
Visit http://www.paradise-studios.net/products/skyx/
Copyright (C) 2009-2012 Xavier Verguín González <[email protected]>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
--------------------------------------------------------------------------------
*/
#ifndef _SkyX_VClouds_Lightning_H_
#define _SkyX_VClouds_Lightning_H_
#include "../Prerequisites.h"
namespace SkyX { namespace VClouds{
class DllExport Lightning
{
public:
/** Segment struct
*/
struct Segment
{
public:
/** Default constructor
*/
Segment()
: a(Ogre::Vector3())
, b(Ogre::Vector3())
{
}
/** Constructor
@param a_ First segment point (Start)
@param b_ Second segment point (End)
*/
Segment(const Ogre::Vector3& a_, const Ogre::Vector3& b_)
: a(a_)
, b(b_)
{
}
/// Segment start
Ogre::Vector3 a;
/// Segment end
Ogre::Vector3 b;
};
/** Constructor
@param sm Scene manager
@param sn Scene node
@param orig Lighting origin
@param dir Lighting direction
@param l Lighting lenth
@param d Divisions
@param rec Recursivity level
@param tm Time multiplier
@param wm Width multiplier
@param b Bounds
*/
Lightning(Ogre::SceneManager* sm, Ogre::SceneNode* sn, const Ogre::Vector3& orig, const Ogre::Vector3& dir, const Ogre::Real& l,
const Ogre::uint32& d, const Ogre::uint32& rec, const Ogre::Real& tm, const Ogre::Real& wm, const Ogre::Vector2& b = Ogre::Vector2(0,1));
/** Destructor
*/
~Lightning();
/** Create
*/
void create();
/** Remove
*/
void remove();
/** Update
@param timeSinceLastFrame Time since last frame
*/
void update(Ogre::Real timeSinceLastFrame);
/** Get ray direction
@return Ray direction
*/
inline const Ogre::Vector3& getDirection() const
{
return mDirection;
}
/** Get ray length
@return Ray length
*/
inline const Ogre::Real& getLength() const
{
return mLength;
}
/** Get lightning intensity
@return Lightning intensity
*/
inline const Ogre::Real& getIntensity() const
{
return mIntensity;
}
/** Get billboard set
@return Billboard set
*/
inline Ogre::BillboardSet* getBillboardSet() const
{
return mBillboardSet;
}
/** Get scene node
@return Scene node
*/
inline Ogre::SceneNode* getSceneNode() const
{
return mSceneNode;
}
/** Has the ray finished?
@return true if the ray has finished, false otherwise
*/
inline const bool& isFinished() const
{
return mFinished;
}
/** Update render queue group
@param rqg Render queue group
@remarks Only for internal use. Use VClouds::setRenderQueueGroups(...) instead.
*/
void _updateRenderQueueGroup(const Ogre::uint8& rqg);
private:
/** Update data
@param alpha Alpha
@param currentPos Current position
@param parentTime Parent time
*/
void _updateData(const Ogre::Real& alpha, const Ogre::Real& currentPos, const Ogre::Real& parentTime);
/// Ray origin
Ogre::Vector3 mOrigin;
/// Ray direction
Ogre::Vector3 mDirection;
/// Ray length
Ogre::Real mLength;
/// Real ray length (total segments length amount)
Ogre::Real mRealLength;
/// Number of divisions
Ogre::uint32 mDivisions;
/// Recursivity level
Ogre::uint32 mRecursivity;
/// Width multiplier
Ogre::Real mWidthMultiplier;
/// Ray bounds (for internal visual calculations)
Ogre::Vector2 mBounds;
/// Angle range (Little values -> Less derivations, bigger values -> More derivations)
Ogre::Vector2 mAngleRange;
/// Current elapsed time
Ogre::Real mTime;
/// Global time multiplier
Ogre::Real mTimeMultiplier;
/// Per step time multipliers
Ogre::Vector3 mTimeMultipliers;
/// Lightning intensity
Ogre::Real mIntensity;
/// Segments
std::vector<Segment> mSegments;
/// Children lightnings
std::vector<Lightning*> mChildren;
/// Billboard set
Ogre::BillboardSet* mBillboardSet;
/// Scene manager
Ogre::SceneManager* mSceneManager;
/// Scene node
Ogre::SceneNode* mSceneNode;
/// Has been create() already called?
bool mCreated;
/// Has the ray finished?
bool mFinished;
};
}}
#endif | [
"[email protected]"
] | |
afe3d549175f871010f21aacaa173810f7fec9c8 | fa7f77f470995a4bba077d0ce837e61ba545015c | /libs/pugg/Kernel.h | 7673cbdfcb031e7a8e80ec9888e7d4a98dce813d | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | d3cod3/ofxVisualProgramming | b0d73c7e334c78a90d3dd7e73a8d9e03da38e05a | f152893238cffa070da69c54324b770f07ddeddb | refs/heads/master | 2023-04-06T10:20:29.050546 | 2023-01-24T16:51:11 | 2023-01-24T16:51:11 | 137,724,379 | 154 | 19 | MIT | 2023-09-11T18:56:05 | 2018-06-18T07:56:31 | C++ | UTF-8 | C++ | false | false | 4,102 | h | // Copyright Tunc Bahcecioglu 2009 - 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <string>
#include <map>
#include <vector>
#include "Driver.h"
#include "Plugin.h"
namespace pugg {
class Kernel;
namespace detail {
template <class K, class V>
void delete_all_values(std::map<K,V>& map) {
for (typename std::map<K,V>::iterator iter = map.begin(); iter != map.end(); ++iter) {
delete iter->second;
}
}
template <class V>
void delete_all_values(std::vector<V>& vec) {
for (typename std::vector<V>::iterator iter = vec.begin(); iter != vec.end(); ++iter) {
delete *iter;
}
}
class Server
{
public:
Server(std::string name, int min_driver_version) : _name(name), _min_driver_version(min_driver_version) {}
~Server() {delete_all_values(_drivers);}
std::string name() {return _name;}
int min_driver_version() {return _min_driver_version;}
std::map<std::string, Driver*>& drivers() {return _drivers;}
void clear()
{
delete_all_values(_drivers);
}
private:
std::string _name;
int _min_driver_version;
std::map<std::string, Driver*> _drivers;
};
}
class Kernel
{
public:
virtual ~Kernel()
{
pugg::detail::delete_all_values(_servers);
pugg::detail::delete_all_values(_plugins);
}
void add_server(std::string name, int min_driver_version )
{
_servers[name] = new pugg::detail::Server(name, min_driver_version);
}
bool add_driver(pugg::Driver* driver)
{
if (! driver) return false;
pugg::detail::Server* server = _get_server(driver->server_name());
if (! server) return false;
if (server->min_driver_version() > driver->version()) return false;
server->drivers()[driver->name()] = driver;
return true;
}
template <class DriverType>
DriverType* get_driver(const std::string& server_name, const std::string& name)
{
pugg::detail::Server* server = _get_server(server_name);
if (! server) return NULL;
std::map<std::string,pugg::Driver*>::iterator driver_iter = server->drivers().find(name);
if (driver_iter == server->drivers().end()) return NULL;
return static_cast<DriverType*>(driver_iter->second);
}
template <class DriverType>
std::vector<DriverType*> get_all_drivers(const std::string& server_name)
{
std::vector<DriverType*> drivers;
pugg::detail::Server* server = _get_server(server_name);
if (! server) return drivers;
for (std::map<std::string, pugg::Driver*>::iterator iter = server->drivers().begin(); iter != server->drivers().end(); ++iter) {
drivers.push_back(static_cast<DriverType*>(iter->second));
}
return drivers;
}
bool load_plugin(const std::string& filename)
{
pugg::detail::Plugin* plugin = new pugg::detail::Plugin();
if (plugin->load(filename)) {
plugin->register_plugin(this);
_plugins.push_back(plugin);
return true;
} else {
delete plugin;
return false;
}
}
void clear_drivers()
{
for (std::map<std::string,pugg::detail::Server*>::iterator iter = _servers.begin(); iter != _servers.end(); ++iter) {
iter->second->clear();
}
}
void clear()
{
pugg::detail::delete_all_values(_servers);
pugg::detail::delete_all_values(_plugins);
}
protected:
std::map<std::string,pugg::detail::Server*> _servers;
std::vector<pugg::detail::Plugin*> _plugins;
pugg::detail::Server* _get_server(const std::string& name)
{
std::map<std::string,pugg::detail::Server*>::iterator server_iter = _servers.find(name);
if (server_iter == _servers.end())
return NULL;
else
return server_iter->second;
}
};
}
| [
"[email protected]"
] | |
485520089064f5307bb029bfe47dbd03b76c169e | 2f78e134c5b55c816fa8ee939f54bde4918696a5 | /code/3rdparty/hk410/include/common/hkserialize/version/hkObjectUpdateTracker.h | 70b5c3bb1808f0c5fa74d10e3ba15338014861b0 | [] | no_license | narayanr7/HeavenlySword | b53afa6a7a6c344e9a139279fbbd74bfbe70350c | a255b26020933e2336f024558fefcdddb48038b2 | refs/heads/master | 2022-08-23T01:32:46.029376 | 2020-05-26T04:45:56 | 2020-05-26T04:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,719 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2006 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_SERIALIZE_OBJECT_UPDATE_TRACKER_H
#define HK_SERIALIZE_OBJECT_UPDATE_TRACKER_H
/// Interface used by the versioning system.
/// The hkObjectUpdateTracker is used to track memory allocations,
/// and addition/deletion/replacement of objects when versioning
/// is performed.
class hkObjectUpdateTracker : public hkReferencedObject
{
public:
//
// Memory
//
/// An allocation has been made. Track it with the rest of the allocations.
virtual void addAllocation(void* p) = 0;
/// An chunk allocation has been made. Track it with the rest of the allocations.
virtual void addChunk(void* p, int n, HK_MEMORY_CLASS c) = 0;
//
// Inter object
//
/// Notify that there is a pointer at fromWhere which points to the given object.
/// The 'fromWhere' pointer is patched to point to the new object.
virtual void objectPointedBy( void* object, void* fromWhere ) = 0;
/// Notify that an object is to be replaced.
/// All pointers to the old object are patched to point to the new object.
/// If newObject has a vtable, a finish function is added.
virtual void replaceObject( void* oldObject, void* newObject, const hkClass* newClass ) = 0;
//
// Finish functions
//
/// Notify that the object requires a finish function.
virtual void addFinish( void* newObject, const char* className ) = 0;
/// Remove a finish function from an object.
/// Typically because it has been copied by the version function.
virtual void removeFinish( void* oldObject ) = 0;
};
#endif // HK_SERIALIZE_OBJECT_UPDATE_TRACKER_H
/*
* Havok SDK - PUBLIC RELEASE, BUILD(#20060902)
*
* Confidential Information of Havok. (C) Copyright 1999-2006
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available from [email protected].
*
*/
| [
"[email protected]"
] | |
762dd1d04e6ffe3af8eb1997a1fb7e1711091198 | 599153c3b43f65e603d5ace2fdac954e66f187af | /vijos/2003.cpp | 8bc90cca3708ad41b78bbe2bd03234d06836e8a4 | [] | no_license | davidzyc/oi | d7c538df5520f36afc9f652fed6862f2658e5a3e | 88cfea0d3ce62a7ecd176a4285bbfeac419d6360 | refs/heads/master | 2021-05-12T11:49:26.147403 | 2019-10-25T14:18:03 | 2019-10-25T14:18:03 | 117,396,742 | 0 | 1 | null | 2018-01-14T12:22:38 | 2018-01-14T02:54:50 | C++ | UTF-8 | C++ | false | false | 605 | cpp | #include<cstdio>
#include<iostream>
#include<cstring>
#define MAXN 100005
#define MAXM 100005
#define MAXLEN 11
using namespace std;
int main(){
int n, m, td, ts, ans = 0;
int sd[MAXN];
char s[MAXN][MAXLEN];
cin >> n >> m;
for(int i=0; i<n; i++){
// scanf("%d %s", &sd[i], &s[i]);
cin >> sd[i] >> s[i];
if(sd[i] == 0) sd[i] = -1;
}
for(int i=0; i<m; i++){
// scanf("%d %d", &td, &ts);
cin >> td >> ts;
if(td == 0) td = -1;
ans += n + (ts % n) * td * sd[ans] * (-1);
ans %= n;
// cout << ans << " " << s[ans] << endl;
}
cout << s[ans];
return 0;
}
| [
"[email protected]"
] | |
c3683b2ba5e4d63940b4ad5cb6abce8e73879ca2 | 2a60eb5064dcc45824fe7a1ea073c35647c5407f | /src/modules/voxel/BiomeManager.h | 1d153719c630e18cf541358df9326f354efcfa58 | [] | no_license | Victorique-GOSICK/engine | a20627a34191c4cdcd6f71acb7970e9176c55214 | a7828cfc610530080dafb70c5664794bde2aaac7 | refs/heads/master | 2021-07-20T00:04:28.543152 | 2017-10-27T18:42:29 | 2017-10-27T18:42:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,146 | h | /**
* @file
*/
#pragma once
#include "core/Trace.h"
#include "Biome.h"
#include "TreeContext.h"
#include <glm/glm.hpp>
namespace core {
class Random;
}
namespace voxel {
class Region;
enum class ZoneType {
City,
Max
};
/**
* @brief A zone with a special meaning that might have influence on terrain generation.
*/
class Zone {
private:
glm::ivec3 _pos;
float _radius;
ZoneType _type;
public:
Zone(const glm::ivec3& pos, float radius, ZoneType type);
const glm::ivec3& pos() const;
float radius() const;
ZoneType type() const;
};
inline ZoneType Zone::type() const {
return _type;
}
inline const glm::ivec3& Zone::pos() const {
return _pos;
}
inline float Zone::radius() const {
return _radius;
}
class BiomeManager {
private:
std::vector<Biome*> _bioms;
std::vector<Zone*> _zones[int(ZoneType::Max)];
const Biome* _defaultBiome = nullptr;
void distributePointsInRegion(const char *type, const Region& region, std::vector<glm::vec2>& positions, core::Random& random, int border, float distribution) const;
public:
BiomeManager();
~BiomeManager();
static const float MinCityHeight;
void shutdown();
bool init(const std::string& luaString);
Biome* addBiome(int lower, int upper, float humidity, float temperature, VoxelType type, bool underGround = false);
// this lookup must be really really fast - it is executed once per generated voxel
// iterating in y direction is fastest, because the last biome is cached on a per-thread-basis
inline Voxel getVoxel(const glm::ivec3& pos, bool underground = false) const {
core_trace_scoped(BiomeGetVoxel);
const Biome* biome = getBiome(pos, underground);
return biome->voxel();
}
inline Voxel getVoxel(int x, int y, int z, bool underground = false) const {
return getVoxel(glm::ivec3(x, y, z), underground);
}
bool hasCactus(const glm::ivec3& pos) const;
bool hasTrees(const glm::ivec3& pos) const;
bool hasCity(const glm::ivec3& pos) const;
bool hasClouds(const glm::ivec3& pos) const;
bool hasPlants(const glm::ivec3& pos) const;
void addZone(const glm::ivec3& pos, float radius, ZoneType type);
const Zone* getZone(const glm::ivec3& pos, ZoneType type) const;
const Zone* getZone(const glm::ivec2& pos, ZoneType type) const;
int getCityDensity(const glm::ivec2& pos) const;
float getCityMultiplier(const glm::ivec2& pos, int* targetHeight = nullptr) const;
void getTreeTypes(const Region& region, std::vector<TreeType>& treeTypes) const;
void getTreePositions(const Region& region, std::vector<glm::vec2>& positions, core::Random& random, int border) const;
void getPlantPositions(const Region& region, std::vector<glm::vec2>& positions, core::Random& random, int border) const;
void getCloudPositions(const Region& region, std::vector<glm::vec2>& positions, core::Random& random, int border) const;
/**
* @return Humidity noise in the range [0-1]
*/
float getHumidity(int x, int z) const;
/**
* @return Temperature noise in the range [0-1]
*/
float getTemperature(int x, int z) const;
void setDefaultBiome(const Biome* biome);
const Biome* getBiome(const glm::ivec3& pos, bool underground = false) const;
};
}
| [
"[email protected]"
] | |
c4884b9a5889f454c7cd2f9c797d2315ed63240a | 5e6e1ea98b9aef59237bbf955b2ce3be4d45a030 | /Source/EMOS/Public/EMOS.h | fcc7c77650b46bfc6414a0751cd6f84f2b129126 | [] | no_license | PettyTyrant/EMOS | 245625ff16f6d04efeb06ac19318edfa6d8906ab | 2b0d11f18e1fb301b1e59ef7645ded57fbb1286c | refs/heads/master | 2020-09-29T00:05:37.448644 | 2019-12-10T15:29:00 | 2019-12-10T15:29:00 | 226,898,578 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"
class FEMOSModule : public IModuleInterface
{
public:
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
};
| [
"[email protected]"
] | |
1d94950ab33c5f7f363efa8bf74a6da3389f51c8 | ac7f42629767beb880e858b7ddfdfa13ea2d9dc8 | /level_traverse/main.cpp | 89bf1f1a29af4334dad85e4f59e22a6d8069a24d | [] | no_license | Mooonside/Leetcode | d6a7adca8f447d7af31672be82975f143a120a1a | 4cf1e3cf5d5f79391d7e8cf7916fcc2c744b7c2e | refs/heads/master | 2021-01-01T16:11:41.536091 | 2017-08-26T04:05:47 | 2017-08-26T04:05:47 | 95,767,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 558 | cpp | #include <iostream>
using namespace std;
int main() {
int *parent,*lchild,*rchild;
int len;
cin>>len;
lchild = new int[len+1];
rchild = new int[len+1];
parent = new int[len+1];
for(int i=0;i<=len;i++){
parent[i] = -1;
lchild[i] = 0;
rchild[i] = 0;
}
int p,l,r;
while(cin>>p>>l>>r){
lchild[p] = l;
rchild[p] = r;
parent[l] = p;
parent[r] = p;
}
int root = 1;
while(parent[root]!=-1){
root = parent[root];
}
cout<<root<<endl;
} | [
"[email protected]"
] |
Subsets and Splits