blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
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 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fc3e0e16dac590bb8524bf8bd66d7da47ca75776 | 1b7bc0c8810624c79e1dade01bb63177058f1a28 | /Voltron/Source/UnitTests/DataStructures/Trees/SuffixTrie_tests.cpp | 16374322e559f3766849a4c9d6f1f274860d0a93 | [
"MIT"
] | permissive | ernestyalumni/HrdwCCppCUDA | 61f123359fb585f279a32a19ba64dfdb60a4f66f | ad067fd4e605c230ea87bdc36cc38341e681a1e0 | refs/heads/master | 2023-07-21T06:00:51.881770 | 2023-04-26T13:58:57 | 2023-04-26T13:58:57 | 109,069,731 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,032 | cpp | #include "DataStructures/Trees/SuffixTrie.h"
#include <boost/test/unit_test.hpp>
using namespace DataStructures::Trees::Tries::SuffixTries;
BOOST_AUTO_TEST_SUITE(DataStructures)
BOOST_AUTO_TEST_SUITE(Trees)
BOOST_AUTO_TEST_SUITE(Tries)
BOOST_AUTO_TEST_SUITE(SuffixTrie_tests)
BOOST_AUTO_TEST_SUITE(ExpertIO_tests)
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(SuffixTrieConstructsWithString)
{
ExpertIO::SuffixTrie st {"babc"};
BOOST_TEST(true);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(ContainsFindsSubstringForSuffixTrie)
{
{
ExpertIO::SuffixTrie st {"babc"};
BOOST_TEST(st.contains("abc"));
}
{
ExpertIO::SuffixTrie st {"test"};
BOOST_TEST(st.contains("t"));
BOOST_TEST(st.contains("st"));
BOOST_TEST(st.contains("est"));
BOOST_TEST(st.contains("test"));
BOOST_TEST(!st.contains("tes"));
}
{
ExpertIO::SuffixTrie st {"invisible"};
BOOST_TEST(st.contains("e"));
BOOST_TEST(st.contains("le"));
BOOST_TEST(st.contains("ble"));
BOOST_TEST(st.contains("ible"));
BOOST_TEST(st.contains("sible"));
BOOST_TEST(st.contains("isible"));
BOOST_TEST(st.contains("visible"));
BOOST_TEST(st.contains("nvisible"));
BOOST_TEST(st.contains("invisible"));
BOOST_TEST(!st.contains("nvisibl"));
}
{
ExpertIO::SuffixTrie st {"1234556789"};
BOOST_TEST(st.contains("9"));
BOOST_TEST(st.contains("89"));
BOOST_TEST(st.contains("789"));
BOOST_TEST(st.contains("6789"));
BOOST_TEST(st.contains("56789"));
BOOST_TEST(!st.contains("456789"));
BOOST_TEST(!st.contains("3456789"));
BOOST_TEST(!st.contains("23456789"));
BOOST_TEST(!st.contains("123456789"));
BOOST_TEST(!st.contains("45567"));
}
{
ExpertIO::SuffixTrie st {"testtest"};
BOOST_TEST(st.contains("t"));
BOOST_TEST(st.contains("st"));
BOOST_TEST(st.contains("est"));
BOOST_TEST(st.contains("test"));
BOOST_TEST(st.contains("ttest"));
BOOST_TEST(st.contains("sttest"));
BOOST_TEST(st.contains("esttest"));
BOOST_TEST(st.contains("testtest"));
BOOST_TEST(!st.contains("tt"));
}
{
ExpertIO::SuffixTrie st {"ttttttttt"};
BOOST_TEST(st.contains("t"));
BOOST_TEST(st.contains("tt"));
BOOST_TEST(st.contains("ttt"));
BOOST_TEST(st.contains("tttt"));
BOOST_TEST(st.contains("ttttt"));
BOOST_TEST(st.contains("tttttt"));
BOOST_TEST(st.contains("ttttttt"));
BOOST_TEST(st.contains("tttttttt"));
BOOST_TEST(st.contains("ttttttttt"));
BOOST_TEST(!st.contains("vvv"));
}
}
BOOST_AUTO_TEST_SUITE_END() // ExpertIO_tests
BOOST_AUTO_TEST_SUITE_END() // SuffixTrie_tests
BOOST_AUTO_TEST_SUITE_END() // Tries
BOOST_AUTO_TEST_SUITE_END() // Trees
BOOST_AUTO_TEST_SUITE_END() // DataStructures
| [
"ernestyalumni@gmail.com"
] | ernestyalumni@gmail.com |
65c05019b2ef2a8c16c944fe535336989506409f | 63876d01ccee25cec402431e02f0f24f06b4b3a4 | /ch01_getting_started/exe/ex_01_04.cc | d2348704d43073e63e495c59e0cdac557dd26389 | [] | no_license | christyjohn/cpp_primer | af6f89d06f5048e05d703cf7cc10ffc98c362ac0 | f3352520fde9bf3094a48653e9513964ee100cb5 | refs/heads/master | 2021-04-21T11:46:57.263207 | 2020-03-31T14:06:15 | 2020-03-31T14:06:15 | 249,777,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 257 | cc | #include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cout << "Enter two numbers" << std::endl;
std::cin >> v1 >> v2;
std::cout << "The produt of " << v1 << " and " << v2
<< " is " << v1 * v2 << std::endl;
return 0;
} | [
"christyjohn.crz@gmail.com"
] | christyjohn.crz@gmail.com |
d50d2f7b3779570cb4bff481bf6ed0a83808f780 | 47c3da6a94aa6039bd9cccf30a5424843c955eb0 | /Ones.cpp | 360c492111a010fee678979531fd904f1dc85da4 | [] | no_license | colinmrees/PE129 | 6eccf42b4de5657d9d39bb62c3094c9264249932 | e4e10c18f936c2ae1b018f1ab46b7c51268774e7 | refs/heads/master | 2021-05-05T03:11:18.111547 | 2018-02-01T07:29:12 | 2018-02-01T07:29:12 | 119,791,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,848 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define lint __uint128_t
int intlog2 ( lint val) {
if (val == 0)
return 0;
if (val == 1)
return 0;
int ret = 0;
while (val > 1) {
val >>= 1;
ret++;
}
return ret;
}
lint intpow2 ( int val ){
lint ret = 1;
while( val-- )
ret*=2;
return ret;
}
/****
*Calulates a vector of all possible whole divisors of the totient using the array of all primes, p.
*/
void allFactors ( lint t, int* p, vector<lint>& trials ){
vector<lint> each;
vector<lint>::iterator it;
lint eachProduct;
double maxfactor = sqrt((double)t);
for (int i = 0; p[i]<= maxfactor; ++i ){ //iterate over all primes
eachProduct = 1;
while ( t%p[i] == 0 ){
t=t/p[i];
eachProduct *= p[i];
vector<lint> temp;
temp.resize(trials.size());
transform(trials.begin(),trials.end(),temp.begin(),bind1st(multiplies<lint>(),eachProduct));
int size1 = each.size();
each.insert(each.end(), temp.begin(), temp.end());
if( size1 )
inplace_merge(each.begin(), each.begin()+size1, each.end());
}
int size2 = trials.size();
trials.insert(trials.end(), each.begin(), each.end());
inplace_merge(trials.begin(), trials.begin()+size2, trials.end());
each.clear();
}
if( t != 1 ){
vector<lint> temp;
temp.resize(trials.size());
transform(trials.begin(),trials.end(),temp.begin(),bind1st(multiplies<lint>(),t));
int size2 = trials.size();
trials.insert(trials.end(), temp.begin(), temp.end());
inplace_merge(trials.begin(), trials.begin()+size2, trials.end());
}
}
/****
* Uses the Euler Product Formula to calculate the totient function of n, using the array of all primes, P.
*/
lint ePF( lint n, int* p){
lint totient = n;
double maxfactor = sqrt((double)n);
//cout << "Debug: " << maxfactor << endl;
for (int i = 0; p[i]<= maxfactor; ++i ){ //iterate over all primes
//cout << "Debug: " << i << " " << p[i] << endl;
if ( n%p[i] == 0 ){
totient = totient/p[i]*(p[i]-1);
}
while ( n%p[i] == 0 ){
n=n/p[i];
}
}
if( n != 1 ){
totient = totient/n*(n-1);
}
return totient;
}
/****
* Uses the sieve of Eratosthenes algorithm to calculate all primes less than m
*/
void primes(int m, int* p, bool* sieve ){
for( int i = 2; i < m; ++i )
sieve[i-2]=1;
int x=0;
for( int i = 2; i < m; ++i ){
if (sieve[i-2]){
p[x]=i;
x++;
for( lint j = (lint)i*i; j < m; j=j+i )
sieve[j-2] = 0;
}
}
//cout << x << endl; //used to determine value of x
}
/****
* Calculates the smallest integer comprised of repeating 1s, R(k), which is a multiple of input n
*/
int main( int argc, char** argv ){
//Calculate Primes
int m = int(sqrt(9e13)); //looking for all primes less than m
int num = 632759; //1.3*m/(log(m)-1); //number of primes less than m.
int *p = new int[num];
bool *sieve = new bool[m-2];
primes(m, p, sieve);
delete sieve;
//Input and iterate over all records
char in[40]; lint input;
cin >> in;
int records = atoi(in);
int total = 0;
for (int r = 0; r < records; ++r){
cin >> in;
input = atol(in); //n
if ( input < 1 || input %5 == 0 || input % 2 == 0) { //Catch invalid inputs
cout << 0 << endl;
} else {
//Calculate the totient of n*9 and create a vector containing all whole divisors of the totient
vector<lint> trials;
trials.push_back(1);
lint totient = ePF(input*9, p);
allFactors ( totient, p, trials );
lint k = 0; // R(k)%n
//Pre-calculate the values needed to calculate R(k) in modulo n
int numPre = 80; //number of powers of 2 to pre-calculate in modulo
lint mul[numPre]; lint add[numPre];
mul[0] = 10; add[0] = 1;
for( int i = 1; i < numPre; ++i){
mul[i] = (mul[i-1]*mul[i-1])%input;
add[i] = (add[i-1]*mul[i-1]+add[i-1])%input;
}
//iterate over all divisors of the tortient, and for each calculate R(k)%n from the previous and check if it is 0
lint tinput = 0;
lint last = 0;
lint compare;
for ( vector<lint>::iterator it = trials.begin()+1; it != trials.end(); ++it){ //iterate over all trials
if( input == 1 ){
cout << 1 << endl;
break;
}
tinput = *it-last;
last = *it;
lint copInput = tinput;
for( int i = 0; copInput > 0; ++i ){ //increase R(k) in increments of 10^2^i
if( copInput % 2 ){
k=(k*mul[i]+add[i])%input;
}
copInput /= 2;
if (i >= numPre ){
cerr << "Error: Increase NumPre" << endl;
break;
}
}
if( k == 0 ){
cout << (long)*it << endl; //if the solution is found, output the value of the successful trial
break;
}
}
}
}
delete p;
}
| [
"cmrees@gmail.com"
] | cmrees@gmail.com |
18d354cb289310595a7e9c9071b21d9cf6b82f2e | cd64cca3d9e72e4ef0273e32b0f2d852ddabdadf | /ElementAppearingMoreThan25PercentInSortedArray/ElementAppearingMoreThan25PercentInSortedArray/main.cpp | 84e0426b89d0663fc3df23996c1bb53a365d99ed | [] | no_license | stereotype13/LeetCodePractice | 48f4471a5e0b4d890ac31760f399f91173e197d8 | 1151084f16485c1ac0d5fadd6b533c0fb350a50b | refs/heads/master | 2020-11-25T03:34:57.825558 | 2020-03-09T21:33:02 | 2020-03-09T21:33:02 | 228,477,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,202 | cpp | /*
Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time.
Return that integer.
Example 1:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Constraints:
1 <= arr.length <= 10^4
0 <= arr[i] <= 10^5
*/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
int findSpecialInteger(vector<int>& arr) {
unordered_map<int, int> frequencies;
for (const auto& i : arr)
frequencies[i]++;
auto& p = *max_element(frequencies.begin(), frequencies.end(), [](const auto& p1, const auto& p2) {
return p1.second < p2.second;
});
return p.first;
}
};
class Solution2 {
public:
int findSpecialInteger(vector<int>& arr) {
if (arr.size() == 1)
return arr[0];
int count = 1;
for (int i = 1; i < (int)arr.size(); ++i) {
if (arr[i] == arr[i - 1]) {
++count;
if (count / 4.0 > 0.25)
return arr[i];
continue;
}
count = 1;
}
return -1;
}
};
int main() {
Solution2 solution;
vector<int> input1{ 1,2,2,6,6,6,6,7,10 };
cout << solution.findSpecialInteger(input1) << endl;
cin.get();
return 0;
} | [
"rhodel3@gatech.edu"
] | rhodel3@gatech.edu |
55bc2f3ec4af350954b06b24a9924ea6de4ffd84 | e0387cf8f45d3e2b7ea3788b299f195a621708a8 | /Source/Sable/Core/Bank/Library.cpp | be2c984cd6513b36a15b555f60daa2836ffd85f5 | [] | no_license | ClementVidal/sable.sable | eea0e822d90739269e35bed20805a2789b5fbc81 | 0ec2cd03867a4673472c1bc7b071a3f16b55fb1b | refs/heads/master | 2021-01-13T01:28:54.070144 | 2013-10-15T15:21:49 | 2013-10-15T15:21:49 | 39,085,785 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,859 | cpp | #include <Sable\Core\Bank\Library.h>
IMPLEMENT_MANAGED_CLASS1( Sable, CBankLibrary, CPersistentArchive )
using namespace Sable;
CBankLibrary::CBankLibrary( )
{
m_NextFreeId = 0;
m_CurrentBank = NULL;
m_IsStoring = FALSE;
}
CBankLibrary::~CBankLibrary()
{
}
Int64 CBankLibrary::GetIDFromObject( CManagedObject* obj ) const
{
UInt32 addr = (UInt32) obj;
if( m_ObjectToID.HasItem( obj ) )
return m_ObjectToID.GetItem( obj );
return -1;
}
CManagedObject* CBankLibrary::GetObjectFromID( Int64 id ) const
{
if( m_IDToObject.HasItem( id ) )
return m_IDToObject.GetItem( id );
return NULL;
}
Void CBankLibrary::AddObject( CManagedObject* obj, Int64 id )
{
DebugAssert( obj );
DebugAssert( m_ObjectToID.HasItem( obj ) == FALSE );
m_ObjectToID.AddItem( obj, id );
m_IDToObject.AddItem( id, obj );
Int64 bankId = id;
bankId >>= 32;
CBank* b = FindBank( (HashValue)bankId );
if( b )
m_CurrentBank = b;
m_CurrentBank->GetArchive().AddObjectWithoutLibraryLookup( obj, id );
}
Int64 CBankLibrary::AcquirePointerID( CManagedObject* obj )
{
DebugAssert( m_ObjectToID.HasItem( obj ) == FALSE );
Int64 i = -1;
CBank* b = FindBank( obj );
if( b )
m_CurrentBank = b;
DebugAssert( m_CurrentBank );
Int64 msb = m_CurrentBank->GetId();
Int64 lsb = m_NextFreeId;
i = msb;
i <<= 32;
i |= lsb;
m_NextFreeId++;
return i;
}
CBank* CBankLibrary::FindBank( HashValue bankId ) const
{
BankTable::Iterator it;
ForEachItem( it, m_BankTable )
{
if( (*it)->GetId() == bankId )
return (*it);
}
return NULL;
}
CBank* CBankLibrary::FindBank( CManagedObject* obj ) const
{
BankTable::Iterator it;
ForEachItem( it, m_BankTable )
{
if( (*it)->HasObject( obj ) )
return (*it);
}
return NULL;
}
CBank* CBankLibrary::GetBank( String name ) const
{
BankTable::Iterator it;
ForEachItem( it, m_BankTable )
{
if( StringCompare( (*it)->GetName(), name ) == 0 )
return *it;
}
return NULL;
}
Bool CBankLibrary::Save()
{
BankTable::Iterator it;
m_IsStoring = TRUE;
ForEachItem( it, m_BankTable )
{
(*it)->Open( nAccesMode_Write );
}
ForEachItem( it, m_BankTable )
{
(*it)->Save( );
}
return TRUE;
}
Bool CBankLibrary::Load()
{
BankTable::Iterator it;
m_IsStoring = FALSE;
ForEachItem( it, m_BankTable )
{
if( !(*it)->Open( nAccesMode_Read ) )
return FALSE;
}
ForEachItem( it, m_BankTable )
{
(*it)->Load( );
}
return TRUE;
}
/**
Add a new bank to this library.
TODO: Check if a bank with the given path is not already loaded
*/
Bool CBankLibrary::AddBank( const CFilePath& path )
{
CBank* b = NEWOBJ( CBank, () );
b->SetFilePath( path );
b->SetLibrary( this );
m_BankTable.AddItemAtEnd( b );
return TRUE;
} | [
"clement.vidal@lam.fr"
] | clement.vidal@lam.fr |
92eb660652ef629ec7b1172c832e03a55f013971 | 45fc787fe73d9a64b6757da1abfa1237acfa34de | /arduino/illuminate_led/illuminate_led.ino | c454cb06facc0f29d81d20a5451983f588ef2b3c | [] | no_license | keiji/adk-handson | eff7b9e81d9d63dec663e70a4c1cbce080f20832 | b701ae5c8ed0719302605ae47330751393a49a1d | refs/heads/master | 2016-08-06T17:11:56.252620 | 2013-01-18T23:39:43 | 2013-01-18T23:41:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 245 | ino | #define PIN_LED 13
void setup() {
Serial.begin(115200);
pinMode(PIN_LED, OUTPUT);
}
int light = 0;
int p = 1;
void loop() {
light += p;
if (light == 0 || light == 255) {
p *= -1;
}
delay(10);
analogWrite(PIN_LED, light);
}
| [
"keiji_ariyama@c-lis.co.jp"
] | keiji_ariyama@c-lis.co.jp |
b68a1a8f30611453a584b845dfc47c5a5d0ada9e | 375b9785b16c0a64beb58aac0c2c605b2197d566 | /riscv-sim/src/PeriodicTimeout.cpp | 1ad629ca0b955041e7daef0e5a4662260aaa360f | [] | no_license | linwj130013/riscv-console | 51a67f6ee53f36ebe369ac5459aa931e297aef6f | 2110e388e34320f09a81a26891cbdeab12c548cc | refs/heads/main | 2023-02-18T09:48:08.845556 | 2021-01-19T19:02:29 | 2021-01-19T19:02:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,578 | cpp |
#include "PeriodicTimeout.h"
#include <cstdint>
/*
int CTimeout::SecondsUntilDeadline(struct timeval deadline){
struct timeval CurrentTime;
gettimeofday(&CurrentTime, nullptr);
return ((deadline.tv_sec * 1000 + deadline.tv_usec / 1000) - (CurrentTime.tv_sec * 1000 + CurrentTime.tv_usec / 1000)) / 1000;
};
int CTimeout::MiliSecondsUntilDeadline(struct timeval deadline){
struct timeval CurrentTime;
gettimeofday(&CurrentTime, nullptr);
return ((deadline.tv_sec * 1000 + deadline.tv_usec / 1000) - (CurrentTime.tv_sec * 1000 + CurrentTime.tv_usec / 1000));
};
*/
CPeriodicTimeout::CPeriodicTimeout(int periodms){
gettimeofday(&DNextExpectedTimeout, nullptr);
if(0 >= periodms){
DTimeoutInterval = 1000;
}
else{
DTimeoutInterval = periodms;
}
}
int CPeriodicTimeout::MiliSecondsUntilDeadline(){
struct timeval CurrentTime;
int64_t TimeDelta;
gettimeofday(&CurrentTime, nullptr);
TimeDelta = (DNextExpectedTimeout.tv_sec * 1000 + DNextExpectedTimeout.tv_usec / 1000) - (CurrentTime.tv_sec * 1000 + CurrentTime.tv_usec / 1000);
while(0 >= TimeDelta){
DNextExpectedTimeout.tv_usec += DTimeoutInterval * 1000;
if(1000000 <= DNextExpectedTimeout.tv_usec){
DNextExpectedTimeout.tv_usec %= 1000000;
DNextExpectedTimeout.tv_sec++;
}
TimeDelta = (DNextExpectedTimeout.tv_sec * 1000 + DNextExpectedTimeout.tv_usec / 1000) - (CurrentTime.tv_sec * 1000 + CurrentTime.tv_usec / 1000);
}
return TimeDelta;
}
| [
"cjnitta@gmail.com"
] | cjnitta@gmail.com |
5c01091bfc37af24ad98fcbc16ce8c24cb6e895c | a5051d65ab1eeec604fcb565742eb8837077439d | /off/把数组排成最小的数.cpp | 2b9dc9ac5197eeb715d298aed94aab17497675c0 | [] | no_license | Aspiration1314/Off | 81b3d02fa37bfb28321604f4f22a412816a42884 | 39705aed537e95520e7c2b59e4d6e3dd54d8e010 | refs/heads/master | 2020-04-30T02:26:00.849937 | 2019-03-19T16:56:59 | 2019-03-19T16:56:59 | 176,559,243 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 727 | cpp | /*思路:通过字符串解决大数问题,然后通过自定义的字符串比较规则,对字符串排序*/
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
if (numbers.size()<1)
return string();
string result;
vector<string> numberString;
for (int i = 0; i<numbers.size(); i++)
{
stringstream ss;
ss << numbers[i];
string s = ss.str();
numberString.push_back(s);
}
sort(numberString.begin(), numberString.end(), Compare);
for (int i = 0; i<numberString.size(); i++)
result.append(numberString[i]);
return result;
}
static bool Compare(const string &str1, const string &str2)
{
string s1 = str1 + str2;
string s2 = str2 + str1;
return s1<s2;
}
};
| [
"1114544658@qq.com"
] | 1114544658@qq.com |
89b1e9f84bbbeee65c0d182132d672fabd94f080 | ad2bf55f50be16c3e2bdd3e49fef5f570224f371 | /Basic/Mang/Mang 1 chieu/300. Tim phan tu lon nhat va nho nhat.cpp | 5fda716af0cf9de5767d25a2af4c7ecd51cad8f1 | [] | no_license | GibOreh/CodeC | 31f1b79b6f5c741fecc0031f508b7b96eafc1844 | b45fd8ae9ae6e720c9c5dfc07c23c52f2f85c5d5 | refs/heads/master | 2022-11-24T09:55:50.111087 | 2020-08-02T05:54:31 | 2020-08-02T05:54:31 | 284,399,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 367 | cpp | #include <stdio.h>
void in(int x[],int n){
for(int i=0 ; i<n ; i++){
scanf("%d",&x[i]);
}
}
void check(int x[],int n){
int max=x[0],min=x[0];
for(int i=0 ; i<n ; i++){
if(max < x[i])
max = x[i];
if(min > x[i])
min = x[i];
}
printf("%d ",max);
printf("%d",min);
}
int main(){
int x[20],n;
scanf("%d",&n);
in(x,n);
check(x,n);
return 0;
}
| [
"vuonghung2308@gmail.com"
] | vuonghung2308@gmail.com |
4d38f056a8b3a3d7a3c2f21e593e1314449967b4 | 1b7616e325dbf6c2f591b34a35246d37c078dbbf | /scanner.cpp | 9f9df36eb6beb7267cb813667bd1813570ab541f | [] | no_license | SefikMehmedovic/CS4280-P4 | cd0fd7773d2ac0e5afe17a77e5e1a1e8dfff3d44 | 2c16ad1b48e7a0045468c64861c2caf3fd25de1d | refs/heads/master | 2020-04-13T01:10:33.878061 | 2018-12-23T06:05:50 | 2018-12-23T06:05:50 | 162,866,429 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,483 | cpp | //scanner.cpp
#include <string>
#include <cctype>
#include <cstddef>
#include <iostream>
#include <cstdlib>
#include "scanner.h"
#include "token.h"
using namespace std;
//From token.h
int token_index;
int current_index;
int line_index;
vector <string> file_string;
static int comment_flag;
//function to read in from file input
void read_file(istream &in)
{
populate_operator_map();
populate_keyword_map();
string input_line;
current_index = 0;
Token token;
int counter = 0;
//get line until EOF
while (getline(in, input_line))
{
current_index = 0;
filter(input_line);
if (input_line.length() > 0)
{
file_string.push_back(input_line);
counter++;
}
}
}
int filter(string &input_string)
{
if (current_index >= input_string.length())
return 0;
string filtered_string;
char current_ch;
const char SPACE = ' ';
char prev_ch = ' ';
//go through each char
for (int counter = current_index; counter < input_string.length(); counter++)
{
current_ch = input_string.at(counter);
if (counter > 0)
prev_ch = input_string.at(counter - 1);
if (current_ch == COMMENT_DELIM)
{
filtered_string.push_back(SPACE);
comment_flag = !comment_flag;
}
else if (!comment_flag)
{
//check for space
if (isspace(current_ch))
{
if (!isspace(prev_ch))
filtered_string.push_back(current_ch);
}
else if (is_valid_ch(current_ch) == -1)
{
//check for char
cout << "Error: \'" << current_ch <<
"\' is not a valid character.\n";
exit(EXIT_FAILURE);
}
else
{
filtered_string.push_back(current_ch);
}
}
current_index++;
}
string whitespaces = " \t\f\v\n\r";
size_t trailing_whitespace_index =
filtered_string.find_last_not_of(whitespaces);
if (trailing_whitespace_index != string::npos)
{
filtered_string.erase(trailing_whitespace_index + 1);
}
else
{
bool all_spaces_flag = true;
for (int i = 0; i < filtered_string.length(); i++)
{
if (filtered_string.at(i) != SPACE)
{
all_spaces_flag = false;
break;
}
}
if (all_spaces_flag)
filtered_string.assign("");
}
input_string.assign(filtered_string);
return current_index;
}
//check if the input is not an operator or digit or char
int is_valid_ch(char ch)
{
if (!is_operator(ch) && !isdigit(ch) & !isalpha(ch))
return -1;
else
return 0;
}
//get current line
string get_string()
{
return file_string[line_index];
}
//----------------------------------------------------
int scanner(Token &token)
{
string input_string = get_string();
if (token_index == input_string.length())
{
line_index++;
token_index = 0;
if (line_index < file_string.size())
input_string = file_string[line_index];
else
{
token.desc = "EOF";
token.ID = EOFtk;
token.line_number = (line_index - 1);
return 1;
}
}
token.line_number = (line_index + 1);
int current_state = 0;
int next_state;
int next_col;
string token_desc;
char next_char;
const char SPACE = ' ';
while (token_index <= input_string.length())
{
if (token_index < input_string.length())
next_char = input_string.at(token_index);
else
next_char = SPACE;
next_col = get_column(next_char);
next_state = FSA_TABLE[current_state][next_col];
if (next_state < 0)
{
current_state = 0;
error_output(next_state, input_string);
cout << input_string.substr(0, token_index + 1) << "\n";
cout << string(token_index, SPACE) << "^\n";
token_index++;
exit(EXIT_FAILURE);
}
else if (next_state > FINAL_STATES)
{
token.desc = token_desc;
switch (next_state)
{
case IDENTIFIER_FINAL_STATE:
if (is_keyword(token) != -1)
{
token.ID = KEYWORDtk;
token.desc.assign(token_desc);
}
else
{
token.ID = ID_tk;
token.desc.assign("ID_tk " + token_desc);
}
break;
case INTEGER_FINAL_STATE:
token.ID = INT_tk;
token.desc.assign("INT_tk " + token_desc);
break;
case OPERATOR_FINAL_STATE:
token.ID = OPtk;
get_operator(token);
token.desc.assign(token_desc);
break;
}
return 0;
}
current_state = next_state;
token_index++;
if (!isspace(next_char))
token_desc.push_back(next_char);
}
return -1;
}
//--------------------------------------------------
//get the column with the input
int get_column(char ch)
{
if (isalpha(ch))
{
//check if input is lower case
if (islower(ch))
return 0; //return 0 for lower
else
return 1; //return 1 for upper
}
else if (isdigit(ch))
return 2; //return 2 for digit
else if (isspace(ch))
return 3; //return 3 for space
else if (is_operator(ch))
return 5; //return 5 for operatort=
else
return -1; //does not exisit
}
//output error
void error_output(int state, string input_string)
{
cout << "Scanner error: Line " << line_index << ": ";
//print error
if (state == ERROR_STATE_UPPERCASE)
{
cout << "All tokens must be lower case \n";
}
else if (state == ERROR_STATE_INTEGER)
{
cout << "All integer tokens must only be numbers\n";
}
}
| [
"sefikm10@gmail.com"
] | sefikm10@gmail.com |
b44763de55dad5d2d2465116f1de48f19f19bdb9 | b9e46960a43d2a735f9170b97852d097c743f142 | /src/helpers.cc | d97cb2188decca7cb45a27a1fae050c46e616f88 | [
"MIT"
] | permissive | tunamako/cs426-shell | 9151ec70d298ccdb2ef2d3b10567457b6a0035f9 | b9b17bccc2fd4e9f2d4e03b2268cf7d7e1ebd2f6 | refs/heads/master | 2021-08-11T13:38:54.959523 | 2017-11-13T20:17:58 | 2017-11-13T20:17:58 | 108,306,895 | 0 | 0 | null | 2017-10-26T01:21:21 | 2017-10-25T18:06:40 | C++ | UTF-8 | C++ | false | false | 2,109 | cc | #include "helpers.h"
#include <sstream>
using namespace std;
void ErrorCheckExit(bool condition, string message) {
if(condition) {
perror(message.c_str());
exit(1);
}
}
void ErrorCheck(bool condition, string message) {
if(condition)
perror(message.c_str());
}
//Some info on stringstreams from
//https://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings
vector<string> splitStr(string aString, char delimiter) {
vector<string> ret;
stringstream ss(aString);
string temp;
while (getline(ss, temp, delimiter))
ret.push_back(temp);
return ret;
}
string getEnv(string varname) {
extern char **environ;
int i = 0;
char *next = environ[i];
while(next){
if(string(next).substr(0,varname.size()) == varname)
return string(next).substr(varname.size() + 1, strlen(next));
next = environ[i++];
}
return "";
}
string getPwd() {
char temp[4096];
ErrorCheckExit(getcwd(temp, 4096) == NULL, "getcwd");
return string(temp);
}
char **convertVector(vector<string> &aVector) {
char **ret = new char*[aVector.size()];
for(uint i = 0; i < aVector.size(); i++) {
int strsize = aVector[i].size();
char *temp = strdup(aVector[i].c_str());
ret[i] = new char[strsize];
strncpy(ret[i], temp, strsize);
ret[i][strsize] = 0;
}
ret[aVector.size()] = NULL;
return ret;
}
string findBin(string cmd) {
struct stat buf;
if(stat(cmd.c_str(), &buf) == 0)
return cmd;
string executable;
vector<string> pathdirs = splitStr(getEnv("PATH"),':');
for(auto dir : pathdirs) {
executable = dir + "/" + cmd;
if(stat(executable.c_str(), &buf) == 0)
return executable;
}
return "";
}
//Getting the index of the iterator on return is from:
//https://stackoverflow.com/questions/24997910/get-index-in-vector-from-reverse-iterator
int getLastPositionOf(vector<string> &input, string delims) {
vector<string>::reverse_iterator iter = input.rbegin();
while(iter != input.rend()) {
for(auto op : delims) {
string temp(1, op);
if(*iter == temp)
return distance(input.begin(), iter.base()) - 1;
}
*iter++;
}
return -1;
} | [
"inedibledelicacies@gmail.com"
] | inedibledelicacies@gmail.com |
352ad87dc44b5689ecb0615591c65dfdb14cfca3 | 0d2deffa50a1596fbc5c4b04b7235932c0f6a695 | /src/qt/rpcconsole.cpp | f4be39dd95b27a8b75735b7296304c121b58a19a | [
"MIT"
] | permissive | cjcoingit/cjcoingitrepo | 031cf3f3abdb07cfcfc5aa5d6d93916ff58e2b1a | edbf67c2bfd9050862334f32f9a1922c684857b2 | refs/heads/master | 2021-01-18T23:34:52.463067 | 2017-04-10T18:28:41 | 2017-04-10T18:28:41 | 87,119,204 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 14,607 | cpp | #include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include "guiutil.h"
#include <QTime>
#include <QTimer>
#include <QThread>
#include <QTextEdit>
#include <QKeyEvent>
#include <QUrl>
#include <QScrollBar>
#include <openssl/crypto.h>
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_SCROLLBACK = 50;
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}
};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor: public QObject
{
Q_OBJECT
public slots:
void start();
void request(const QString &command);
signals:
void reply(int category, const QString &command);
};
#include "rpcconsole.moc"
void RPCExecutor::start()
{
// Nothing to do
}
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
{
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
foreach(char ch, strCommand)
{
switch(state)
{
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case ' ': case '\n': case '\t':
if(state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
switch(state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
std::vector<std::string> args;
if(!parseCommandLine(args, command.toStdString()))
{
emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if(args.empty())
return; // Nothing to do
try
{
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
}
catch (json_spirit::Object& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
}
catch (std::exception& e)
{
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget *parent) :
QDialog(parent),
ui(new Ui::RPCConsole),
historyPtr(0)
{
ui->setupUi(this);
#ifndef Q_OS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
ui->showCLOptionsButton->setIcon(QIcon(":/icons/options"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// set OpenSSL version label
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
startExecutor();
clear();
}
RPCConsole::~RPCConsole()
{
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch(key)
{
case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if(obj == ui->lineEdit)
{
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if(obj == ui->messagesWidget && (
(!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
{
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Subscribe to information, replies, messages, errors
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
setNumConnections(model->getNumConnections());
ui->isTestNet->setChecked(model->isTestNet());
setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers());
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Monospace; font-size: 12px; } "
"td.cmd-request { color: #093d76; } "
"td.cmd-error { color: red; } "
"b { color: #093d76; } "
);
message(CMD_REPLY, (tr("Welcome to the Cryptojournal RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")), true);
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
ui->numberOfConnections->setText(QString::number(count));
}
void RPCConsole::setNumBlocks(int count, int countOfPeers)
{
ui->numberOfBlocks->setText(QString::number(count));
ui->totalBlocks->setText(QString::number(countOfPeers));
if(clientModel)
{
// If there is no current number available display N/A instead of 0, which can't ever be true
ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers()));
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if(!cmd.isEmpty())
{
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Truncate history from current position
history.erase(history.begin() + historyPtr, history.end());
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread* thread = new QThread;
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(thread);
// Notify executor when thread started (in executor thread)
connect(thread, SIGNAL(started()), executor, SLOT(start()));
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if(ui->tabWidget->widget(index) == ui->tab_console)
{
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_showCLOptionsButton_clicked()
{
GUIUtil::HelpMessageBox help;
help.exec();
}
void RPCConsole::showTab_Debug()
{
ui->tabWidget->setCurrentIndex(1);
this->show();
}
| [
"cryptojournalcoin@gmail.com"
] | cryptojournalcoin@gmail.com |
457e5a00286a2e33c212329c3cc4c2a6d3666f28 | bf46ead26b9550c92c1f4cb81ff0bb553471ce8f | /src/test/scriptnum_tests.cpp | cd3279003fd7488a3794f396f9d5a73dfcb5f87f | [
"MIT"
] | permissive | HondaisCoin/hondaiscoinmn | afeadfa0a34c6b5aafb2f5f89f7d1b36a77a2ee3 | 5b159940ee12ff8886ef21498dfddffb4ac76b1a | refs/heads/master | 2020-08-29T03:44:24.444315 | 2019-10-27T20:59:52 | 2019-10-27T20:59:52 | 217,913,441 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,466 | cpp | // Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "scriptnum10.h"
#include "script/script.h"
#include "test/test_hondaiscoinmn.h"
#include <boost/test/unit_test.hpp>
#include <limits.h>
#include <stdint.h>
BOOST_FIXTURE_TEST_SUITE(scriptnum_tests, BasicTestingSetup)
static const int64_t values[] = \
{ 0, 1, CHAR_MIN, CHAR_MAX, UCHAR_MAX, SHRT_MIN, USHRT_MAX, INT_MIN, INT_MAX, UINT_MAX, LONG_MIN, LONG_MAX };
static const int64_t offsets[] = { 1, 0x79, 0x80, 0x81, 0xFF, 0x7FFF, 0x8000, 0xFFFF, 0x10000};
static bool verify(const CScriptNum10& bignum, const CScriptNum& scriptnum)
{
return bignum.getvch() == scriptnum.getvch() && bignum.getint() == scriptnum.getint();
}
static void CheckCreateVch(const int64_t& num)
{
CScriptNum10 bignum(num);
CScriptNum scriptnum(num);
BOOST_CHECK(verify(bignum, scriptnum));
std::vector<unsigned char> vch = bignum.getvch();
CScriptNum10 bignum2(bignum.getvch(), false);
vch = scriptnum.getvch();
CScriptNum scriptnum2(scriptnum.getvch(), false);
BOOST_CHECK(verify(bignum2, scriptnum2));
CScriptNum10 bignum3(scriptnum2.getvch(), false);
CScriptNum scriptnum3(bignum2.getvch(), false);
BOOST_CHECK(verify(bignum3, scriptnum3));
}
static void CheckCreateInt(const int64_t& num)
{
CScriptNum10 bignum(num);
CScriptNum scriptnum(num);
BOOST_CHECK(verify(bignum, scriptnum));
BOOST_CHECK(verify(CScriptNum10(bignum.getint()), CScriptNum(scriptnum.getint())));
BOOST_CHECK(verify(CScriptNum10(scriptnum.getint()), CScriptNum(bignum.getint())));
BOOST_CHECK(verify(CScriptNum10(CScriptNum10(scriptnum.getint()).getint()), CScriptNum(CScriptNum(bignum.getint()).getint())));
}
static void CheckAdd(const int64_t& num1, const int64_t& num2)
{
const CScriptNum10 bignum1(num1);
const CScriptNum10 bignum2(num2);
const CScriptNum scriptnum1(num1);
const CScriptNum scriptnum2(num2);
CScriptNum10 bignum3(num1);
CScriptNum10 bignum4(num1);
CScriptNum scriptnum3(num1);
CScriptNum scriptnum4(num1);
// int64_t overflow is undefined.
bool invalid = (((num2 > 0) && (num1 > (std::numeric_limits<int64_t>::max() - num2))) ||
((num2 < 0) && (num1 < (std::numeric_limits<int64_t>::min() - num2))));
if (!invalid)
{
BOOST_CHECK(verify(bignum1 + bignum2, scriptnum1 + scriptnum2));
BOOST_CHECK(verify(bignum1 + bignum2, scriptnum1 + num2));
BOOST_CHECK(verify(bignum1 + bignum2, scriptnum2 + num1));
}
}
static void CheckNegate(const int64_t& num)
{
const CScriptNum10 bignum(num);
const CScriptNum scriptnum(num);
// -INT64_MIN is undefined
if (num != std::numeric_limits<int64_t>::min())
BOOST_CHECK(verify(-bignum, -scriptnum));
}
static void CheckSubtract(const int64_t& num1, const int64_t& num2)
{
const CScriptNum10 bignum1(num1);
const CScriptNum10 bignum2(num2);
const CScriptNum scriptnum1(num1);
const CScriptNum scriptnum2(num2);
bool invalid = false;
// int64_t overflow is undefined.
invalid = ((num2 > 0 && num1 < std::numeric_limits<int64_t>::min() + num2) ||
(num2 < 0 && num1 > std::numeric_limits<int64_t>::max() + num2));
if (!invalid)
{
BOOST_CHECK(verify(bignum1 - bignum2, scriptnum1 - scriptnum2));
BOOST_CHECK(verify(bignum1 - bignum2, scriptnum1 - num2));
}
invalid = ((num1 > 0 && num2 < std::numeric_limits<int64_t>::min() + num1) ||
(num1 < 0 && num2 > std::numeric_limits<int64_t>::max() + num1));
if (!invalid)
{
BOOST_CHECK(verify(bignum2 - bignum1, scriptnum2 - scriptnum1));
BOOST_CHECK(verify(bignum2 - bignum1, scriptnum2 - num1));
}
}
static void CheckCompare(const int64_t& num1, const int64_t& num2)
{
const CScriptNum10 bignum1(num1);
const CScriptNum10 bignum2(num2);
const CScriptNum scriptnum1(num1);
const CScriptNum scriptnum2(num2);
BOOST_CHECK((bignum1 == bignum1) == (scriptnum1 == scriptnum1));
BOOST_CHECK((bignum1 != bignum1) == (scriptnum1 != scriptnum1));
BOOST_CHECK((bignum1 < bignum1) == (scriptnum1 < scriptnum1));
BOOST_CHECK((bignum1 > bignum1) == (scriptnum1 > scriptnum1));
BOOST_CHECK((bignum1 >= bignum1) == (scriptnum1 >= scriptnum1));
BOOST_CHECK((bignum1 <= bignum1) == (scriptnum1 <= scriptnum1));
BOOST_CHECK((bignum1 == bignum1) == (scriptnum1 == num1));
BOOST_CHECK((bignum1 != bignum1) == (scriptnum1 != num1));
BOOST_CHECK((bignum1 < bignum1) == (scriptnum1 < num1));
BOOST_CHECK((bignum1 > bignum1) == (scriptnum1 > num1));
BOOST_CHECK((bignum1 >= bignum1) == (scriptnum1 >= num1));
BOOST_CHECK((bignum1 <= bignum1) == (scriptnum1 <= num1));
BOOST_CHECK((bignum1 == bignum2) == (scriptnum1 == scriptnum2));
BOOST_CHECK((bignum1 != bignum2) == (scriptnum1 != scriptnum2));
BOOST_CHECK((bignum1 < bignum2) == (scriptnum1 < scriptnum2));
BOOST_CHECK((bignum1 > bignum2) == (scriptnum1 > scriptnum2));
BOOST_CHECK((bignum1 >= bignum2) == (scriptnum1 >= scriptnum2));
BOOST_CHECK((bignum1 <= bignum2) == (scriptnum1 <= scriptnum2));
BOOST_CHECK((bignum1 == bignum2) == (scriptnum1 == num2));
BOOST_CHECK((bignum1 != bignum2) == (scriptnum1 != num2));
BOOST_CHECK((bignum1 < bignum2) == (scriptnum1 < num2));
BOOST_CHECK((bignum1 > bignum2) == (scriptnum1 > num2));
BOOST_CHECK((bignum1 >= bignum2) == (scriptnum1 >= num2));
BOOST_CHECK((bignum1 <= bignum2) == (scriptnum1 <= num2));
}
static void RunCreate(const int64_t& num)
{
CheckCreateInt(num);
CScriptNum scriptnum(num);
if (scriptnum.getvch().size() <= CScriptNum::nDefaultMaxNumSize)
CheckCreateVch(num);
else
{
BOOST_CHECK_THROW (CheckCreateVch(num), scriptnum10_error);
}
}
static void RunOperators(const int64_t& num1, const int64_t& num2)
{
CheckAdd(num1, num2);
CheckSubtract(num1, num2);
CheckNegate(num1);
CheckCompare(num1, num2);
}
BOOST_AUTO_TEST_CASE(creation)
{
for(size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i)
{
for(size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j)
{
RunCreate(values[i]);
RunCreate(values[i] + offsets[j]);
RunCreate(values[i] - offsets[j]);
}
}
}
BOOST_AUTO_TEST_CASE(operators)
{
for(size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i)
{
for(size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j)
{
RunOperators(values[i], values[i]);
RunOperators(values[i], -values[i]);
RunOperators(values[i], values[j]);
RunOperators(values[i], -values[j]);
RunOperators(values[i] + values[j], values[j]);
RunOperators(values[i] + values[j], -values[j]);
RunOperators(values[i] - values[j], values[j]);
RunOperators(values[i] - values[j], -values[j]);
RunOperators(values[i] + values[j], values[i] + values[j]);
RunOperators(values[i] + values[j], values[i] - values[j]);
RunOperators(values[i] - values[j], values[i] + values[j]);
RunOperators(values[i] - values[j], values[i] - values[j]);
}
}
}
BOOST_AUTO_TEST_SUITE_END()
| [
"you@example.com"
] | you@example.com |
23ae1f3f7df14117187ddb2546c3a6fbe4ce3c23 | 3329ff94ba44f5a575b5398985a33aa948b5f944 | /0.00705/uniform/lagrangian/sprayCloud/sprayCloudOutputProperties | 516a5217550fbdbe61cee3dccd105f34ada42faf | [] | no_license | zlsherl/SKPS_simple | 38cfac333dd65ed752e34c9f00b555d4255d2efc | 0de13926915af0c7eaf1904fe57a8149a7741ba1 | refs/heads/main | 2023-05-26T20:03:42.391527 | 2021-06-12T10:24:09 | 2021-06-12T10:24:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,509 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2012 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "0.00705/uniform/lagrangian/sprayCloud";
object sprayCloudOutputProperties;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
injectionModel
{
model1
{
volumeTotal 0.00874187;
massInjected 5.99558e-06;
nInjections 28110;
parcelsAddedTotal 11078;
timeStep0 0.00705;
}
}
patchInteractionModel
{
escapedParcels 0;
escapedMass 0;
standardWallInteraction
{
nEscape 3 ( 1 ( 0 ) 1 ( 0 ) 1 ( 0 ) );
massEscape 3 ( 1 ( 0 ) 1 ( 0 ) 1 ( 0 ) );
nStick 3 ( 1 ( 0 ) 1 ( 0 ) 1 ( 0 ) );
massStick 3 ( 1 ( 0 ) 1 ( 0 ) 1 ( 0 ) );
}
}
phaseChangeModel
{
mass 5.99558e-06;
}
// ************************************************************************* //
| [
"krystek.pietrzak@gmail.com"
] | krystek.pietrzak@gmail.com | |
a275a727e51948d50ec6e498e17f1d3c6ff32e27 | adfa317ce1bae691174309d7b361950b07ba5ca8 | /src/ParabolicBoxDomainPdeSystemModifier.hpp | c5936c4cc42c0830729301123c5f50fca2692740 | [] | no_license | CJohnsonMathSys/ChemChaste | 34a121a14a0e62dbb61e735a0c9bb5581652c403 | ca9308628948baf758b7a864b0269c6e6bf29325 | refs/heads/main | 2023-02-22T20:21:50.778557 | 2021-01-27T12:34:00 | 2021-01-27T12:34:00 | 307,725,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,982 | hpp | #ifndef PARABOLICBOXDOMAINPDESYSTEMMODIFIER_HPP_
#define PARABOLICBOXDOMAINPDESYSTEMMODIFIER_HPP_
#include "InhomogenousParabolicPdeForCoupledOdeSystem_templated.hpp"
#include "AbstractBoxDomainPdeSystemModifier.hpp"
#include "AbstractPdeSystemModifier.hpp"
#include "BoundaryConditionsContainer.hpp"
#include "AbstractIvpOdeSolver.hpp"
#include "AbstractOdeSystemForCoupledPdeSystem.hpp"
#include "InhomogenousCoupledPdeOdeCoupledCellSolver.hpp"
#include "AbstractOdeSystemForCoupledPdeSystem.hpp"
#include "InhomogenousCoupledPdeOdeSolver_templated.hpp"
#include "ChemicalDomainFieldForCellCoupling.hpp"
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
class ParabolicBoxDomainPdeSystemModifier : public AbstractBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>
{
protected:
bool mConditionsInterpolated = false;
public:
ParabolicBoxDomainPdeSystemModifier(ChemicalDomainFieldForCellCoupling<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>* p_domain_field,
boost::shared_ptr<ChasteCuboid<SPACE_DIM> > pMeshCuboid=boost::shared_ptr<ChasteCuboid<SPACE_DIM> >(),
double stepSize=1.0,
Vec solution=nullptr);
/**
* Destructor.
*/
virtual ~ParabolicBoxDomainPdeSystemModifier();
/**
* Overridden UpdateAtEndOfTimeStep() method.
*
* Specifies what to do in the simulation at the end of each time step.
*
* @param rCellPopulation reference to the cell population
*/
virtual void UpdateAtEndOfTimeStep(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation);
/**
* Overridden SetupSolve() method.
*
* Specifies what to do in the simulation before the start of the time loop.
*
* @param rCellPopulation reference to the cell population
* @param outputDirectory the output directory, relative to where Chaste output is stored
*/
virtual void SetupSolve(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation, std::string outputDirectory);
/**
* Helper method to construct the boundary conditions container for the PDE.
*
* @param rCellPopulation reference to the cell population
*
* @return the full boundary conditions container
*/
virtual boost::shared_ptr<BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> > ConstructBoundaryConditionsContainer(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation);
/**
* Helper method to initialise the PDE solution using the CellData.
*
* Here we assume a homogeneous initial consition.
*
* @param rCellPopulation reference to the cell population
*/
void SetupInitialSolutionVector(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation);
/**
* Overridden OutputSimulationModifierParameters() method.
* Output any simulation modifier parameters to file.
*
* @param rParamsFile the file stream to which the parameters are output
*/
void OutputSimulationModifierParameters(out_stream& rParamsFile);
void SetPdeDimension(unsigned pdeDim);
unsigned GetPdeDimension();
//void SetNodalInitialConditions(std::vector<double> init_nodal_conditions);
//std::vector<double> GetNodalInitialConditions();
//void SetCellInitialConditions(std::vector<double> init_cell_conditions);
//std::vector<double> GetCellInitialConditions();
};
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::ParabolicBoxDomainPdeSystemModifier(
ChemicalDomainFieldForCellCoupling<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>* p_domain_field,
boost::shared_ptr<ChasteCuboid<SPACE_DIM> > pMeshCuboid,
double stepSize,
Vec solution)
: AbstractBoxDomainPdeSystemModifier<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>(p_domain_field,
pMeshCuboid,
stepSize,
solution)
{
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::~ParabolicBoxDomainPdeSystemModifier()
{
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::UpdateAtEndOfTimeStep(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation)
{
//std::cout<<"ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::UpdateAtEndOfTimeStep - start"<<std::endl;
// Set up boundary conditions, comes from the rCellPopulation rather than the constructor
boost::shared_ptr<BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> > p_bcc = ConstructBoundaryConditionsContainer(rCellPopulation);
this->UpdateCellPdeElementMap(rCellPopulation);
// When using a PDE mesh which doesn't coincide with the cells, we must set up the source terms before solving the PDE.
// Pass in already updated CellPdeElementMap to speed up finding cells.
// this line shoudl be fine for the pOdeSystem
this->SetUpSourceTermsForAveragedSourcePde(this->mpFeMesh, &this->mCellPdeElementMap);
InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> solver(
this->mpFeMesh,
this->mpCoupledDomainField->ReturnSharedPtrPdeSystem().get(),
this->mpCoupledDomainField->ReturnSharedPtrBoundaryConditionsContainer().get(),
rCellPopulation,
this->mpCoupledDomainField->GetNodalOdeSystems(),
this->mpCoupledDomainField->GetNodalOdeSolvers(),
mConditionsInterpolated
);
///\todo Investigate more than one PDE time step per spatial step
SimulationTime* p_simulation_time = SimulationTime::Instance();
double current_time = p_simulation_time->GetTime();
double dt = p_simulation_time->GetTimeStep();
// solver is calling the LinearParabolicSystemWithCOupledOdeSystemSolver
solver.SetTimes(current_time,current_time + dt);
solver.SetTimeStep(dt);
// Use previous solution as the initial condition
Vec previous_solution = this->mSolution;
solver.SetInitialCondition(previous_solution);
// Note that the linear solver creates a vector, so we have to keep a handle on the old one
// in order to destroy it
this->mSolution = solver.Solve();
PetscTools::Destroy(previous_solution);
this->UpdateCellData(rCellPopulation);
mConditionsInterpolated = true;
//std::cout<<"ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::UpdateAtEndOfTimeStep - end"<<std::endl;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::SetupSolve(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation, std::string outputDirectory)
{
//std::cout<<"ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM>::SetupSolve - start"<<std::endl;
AbstractBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::SetupSolve(rCellPopulation,outputDirectory);
// Copy the cell data to mSolution (this is the initial condition)
SetupInitialSolutionVector(rCellPopulation);
// Output the initial conditions on FeMesh
this->UpdateAtEndOfOutputTimeStep(rCellPopulation);
//std::cout<<"ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM>::SetupSolve - end"<<std::endl;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM> // why does this take in a cell population? if() is true, shrinks the box onto the tissue (cellpopulation) here makes no difference
boost::shared_ptr<BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> > ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::ConstructBoundaryConditionsContainer(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation)
{
boost::shared_ptr<BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> > p_bcc(new BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>(false)); // false implies not to delete previous conditions but there shouldn't be any
if (!this->mSetBcsOnBoxBoundary)
{
EXCEPTION("Boundary conditions cannot yet be set on the cell population boundary for a ParabolicBoxDomainPdeSystemModifier");
}
else // Apply BC at boundary nodes of box domain FE mesh
{
p_bcc = this->mpCoupledDomainField -> ReturnSharedPtrBoundaryConditionsContainer();//ChemicalDomainFieldForCellCoupling<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::ReturnSharedPtrBoundaryConditionsContainer();
}
return p_bcc;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::SetupInitialSolutionVector(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation)
{
// set up the initial conditions for the pde mesh
// set up cell initial conditions
for (typename AbstractCellPopulation<SPACE_DIM>::Iterator cell_iter = rCellPopulation.Begin();
cell_iter != rCellPopulation.End();
++cell_iter)
{
CellPropertyCollection& prop_collection = cell_iter->rGetCellPropertyCollection();
if (prop_collection.HasProperty<ChemicalCellProperty>())
{
// the cell has it's own concentration vector that may be related to the domain
boost::shared_ptr<ChemicalCellProperty> property = boost::static_pointer_cast<ChemicalCellProperty>(prop_collection.GetPropertiesType<ChemicalCellProperty>().GetProperty());
std::vector<std::string> cell_species_names = property -> GetStateVariableRegister() -> GetStateVariableRegisterVector();
for(unsigned name_index=0; name_index<cell_species_names.size();name_index++)
{
cell_iter->GetCellData()->SetItem(cell_species_names[name_index], property -> GetCellConcentrationByIndex(name_index));
}
}
else
{
// assume zero concentration in cell, set up for all species in the PROBLEM_DIM, that is species diffusing through the domain
std::vector<double> initial_conditions(PROBLEM_DIM,0.0);
std::vector<std::string> domain_species_names = this->mpCoupledDomainField -> GetDomainStateVariableRegister() -> GetStateVariableRegisterVector();
for(unsigned name_index=0; name_index<domain_species_names.size();name_index++)
{
cell_iter->GetCellData()->SetItem(domain_species_names[name_index], 0.0);
}
}
}
// set pde serialised nodal initial conditions from domain layer
// Initialise mSolution
this->mSolution = PetscTools::CreateVec(this->mpCoupledDomainField -> GetInitialNodeConditions());
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::OutputSimulationModifierParameters(out_stream& rParamsFile)
{
// No parameters to output, so just call method on direct parent class
AbstractBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::OutputSimulationModifierParameters(rParamsFile);
}
#endif /*PARABOLICBOXDOMAINPDESYSTEMMODIFIER_HPP_*/
| [
"c.johnson.6@warwick.ac.uk"
] | c.johnson.6@warwick.ac.uk |
49807796d63581e6a2d97fe635a8cf72098b75f6 | e4f59a3b3a7eda4d1bc00050d76fc8bce1cf093f | /code/Spikes/timer_example_alex/timer_example_alex.ino | 663a0dae2b0fd6f1b643a82a1e88d137e1e45ea8 | [] | no_license | AlexanderNahr/arduino_team_PMES_WS2016 | 03ed37906254cae01adef7d83d787368806a837c | 691d8cb0f4df41bc46ac00b6936949804e428fb7 | refs/heads/master | 2021-01-12T09:55:09.534469 | 2017-03-10T22:39:41 | 2017-03-10T22:39:41 | 76,298,477 | 2 | 3 | null | 2017-03-11T11:53:47 | 2016-12-12T21:48:56 | C++ | UTF-8 | C++ | false | false | 12,311 | ino | /********************************************NOTE********************************************************************
* Statt Pin 13 habe ich pin A2 zur Tonausgabe verwendet.
********************************************************************************************************************/
/****************************************************************************************************************//**
* \file displayTest_Aufgabe1.8
* \brief Uebung 1, Aufgabe 8
* \author Alexander Nahrwold
* \date 2.11.2016
/****************************************************************************************************************/
/*
* Plan:
* - 1 second interrupt for traffic light
* - ADC done interrupt
* - main loop will
* -- count seconds and switch lights on/off
* -- check ADC done flage periodically and store value (not necessarily required)
* -- after both checks are done display will be printed with local, updated values
*
* Source:
* - ADC Interrupt: http://www.glennsweeney.com/tutorials/interrupt-driven-analog-conversion-with-an-atmega328p
* - Arduino timed interrupts: http://playground.arduino.cc/Code/Timer1
* - Timed Interrupts: http://www.instructables.com/id/Arduino-Timer-Interrupts/step2/Structuring-Timer-Interrupts/
/****************************************************************************************************************/
// Include Files
#include <LiquidCrystal.h> //!< include LCD functions:
#include "pitches.h" //!< for
/****************************************************************************************************************/
// Global Variables
int RS_pin = 3; //!< LCD RS pin connects to pin3
int E_pin = 4; //!< LCD E pin connects to pin4
int DB4_pin = 6; //!< LCD DB4 pin connects to pin6
int DB5_pin = 7; //!< LCD DB5 pin connects to pin7
int DB6_pin = 8; //!< LCD DB6 pin connects to pin8
int DB7_pin = 9; //!< LCD DB7 pin connects to pin9
LiquidCrystal lcd( RS_pin, E_pin, DB4_pin, DB5_pin, DB6_pin, DB7_pin); //!< define the LCD screen
int analogValue = -1; //!< global variable, stores the result from analog pin
int g_ledPin1 = 10; //!< red
int g_ledPin2 = 11; //!< yellow
int g_ledPin3 = 12; //!< green
int g_speakerPin = 13; //!< pin associated with the speaker
int toggle1 = 0; //!< interrupt toggler
int g_traffic_light_counter = 0; //!< counter for ISR to control traffic light
/****************************************************************************************************************/
// function declaration
void SwitchTrafficLight( int light_color );
int ButtonCheck( int adc_count, char* button_clicked_buffer, int buffer_size );
void SetupTimer1( void );
/****************************************************************************************************************/
// constants
#define RED_LIGHT 0
#define YELLOW_LIGHT 1
#define GREEN_LIGHT 2
#define RED_LIGHT_TIME 0 //!< start time red light
#define YELLOW_LIGHT_1_TIME 5 //!< start time yellow light
#define GREEN_LIGHT_TIME 8 //!< start time green light
#define YELLOW_LIGHT_2_TIME 9 //!< start time yello light
#define MAX_TIME 9 //!< overflow time
#define RED_FREQUENCY 100 //!< frequency for speaker in Hz
#define GREEN_FREQUENCY 400 //!< frequency for speaker in Hz
#define ONE_SECOND 1000
#define THREE_SECONDS 3*ONE_SECOND
#define FIVE_SECONDS 5*ONE_SECOND
// references ADC counts for button clicks
#define BUTTON_1 1 //!< ADC count button 1/S1 click
#define BUTTON_2 242 //!< ADC count button 2/S2 click
#define BUTTON_3 473 //!< ADC count button 3/S3 click
#define BUTTON_4 679 //!< ADC count button 4/S4 click
#define BUTTON_5 831 //!< ADC count button 5/S5 click
#define NO_BUTTONS 1023 //!< ADC count no buttons clicked
#define BTN_ADC_TOLERANCE 50 //!< tolerance for ADC counts for button click
#define FAILURE -1
#define SUCCESS 0
#define DISPLAY_LINE_1 0 //!< display line 1
#define DISPLAY_LINE_2 1 //!< display line 2
#define DISPLAY_LINE_3 2 //!< display line 3
#define DISPLAY_LINE_4 3 //!< display line 4
#define DISPLAY_BEGIN 0 //!< display begin
#define DISPLAY_END 19 //!< display end
/****************************************************************************************************************//*
* \brief setup function
/****************************************************************************************************************/
void setup()
{
// LCD has 4 lines with 20 chars
lcd.begin(20, 4);
lcd.print("system ready");
// set ledPin as output
pinMode( g_ledPin1, OUTPUT );
pinMode( g_ledPin2, OUTPUT );
pinMode( g_ledPin3, OUTPUT );
//pinMode( g_speakerPin, OUTPUT );
SwitchTrafficLight( RED_LIGHT );
tone( A2, RED_FREQUENCY );
g_traffic_light_counter = 0;
SetupTimer1( ); // TIMER_EXAMPLE - setup timer here
}
// Interrupts
/****************************************************************************************************************//**
* \brief interupt service routine for timer 1 - TIMER_EXAMPLE
* attach timer 1 comparision to interrupt vector table
* -> THIS WILL BE EXECUTED everytime timer1 interrupt is triggered
* \source http://www.instructables.com/id/Arduino-Timer-Interrupts/step2/Structuring-Timer-Interrupts/
/****************************************************************************************************************/
ISR( TIMER1_COMPA_vect )
{
g_traffic_light_counter++;
if( g_traffic_light_counter > MAX_TIME )
{
g_traffic_light_counter = 0;
}
}
/****************************************************************************************************************//*
* \brief main loop
/****************************************************************************************************************/
void loop()
{
delay( 100 );
static char button_print[ 100 ] = "No Button";
static char light_print[ 100 ] = "red";
static int current_light = -1; //!< identifies the current light
// implement your code here:
lcd.clear( );
// DISPLAY LINE 1 ///////////////////////////////////////////////////////
// read and print analog button value
lcd.print( "Analog 0: " );
analogValue = analogRead( A0 );
lcd.print( analogValue );
// DISPLAY LINE 2 ///////////////////////////////////////////////////////
// determine which button is clicked
int clicked_button = ButtonCheck( analogValue,
button_print,
sizeof( button_print ) );
// when button 1 is pressed, leave RED_LIGHT phase
// REMEMBER: IF BUTTONS ARE NOT CONNECTED, IT WILL LOOK LIKE BUTTON 1
// IS ACTIVE
if( clicked_button == BUTTON_1
&& current_light == RED_LIGHT)
{
g_traffic_light_counter = YELLOW_LIGHT_1_TIME;
}
// print results
lcd.setCursor( DISPLAY_BEGIN, DISPLAY_LINE_2 );
lcd.print( button_print );
// DISPLAY LINE 3 ///////////////////////////////////////////////////////
switch( g_traffic_light_counter ) // TIMER_EXAMPLE
{
case RED_LIGHT_TIME:
current_light = RED_LIGHT;
SwitchTrafficLight( current_light );
strcpy( light_print, "red");
tone( A2, RED_FREQUENCY );
break;
case YELLOW_LIGHT_1_TIME:
noTone( A2 );
current_light = YELLOW_LIGHT;
SwitchTrafficLight( current_light );
strcpy( light_print, "yellow");
break;
case GREEN_LIGHT_TIME:
current_light = GREEN_LIGHT;
SwitchTrafficLight( current_light );
strcpy( light_print, "green");
tone( A2, GREEN_FREQUENCY);
break;
case YELLOW_LIGHT_2_TIME:
noTone( A2 );
current_light = YELLOW_LIGHT;
SwitchTrafficLight( current_light );
strcpy( light_print, "yellow");
break;
default:
break;
}
lcd.setCursor( DISPLAY_BEGIN, DISPLAY_LINE_3 );
lcd.print( light_print );
// wait for 100 ms (reduces display flickering)
delay( 100 );
}
/****************************************************************************************************************//**
* \brief switches traffic light
* \param light_color color of light you want to switch
/****************************************************************************************************************/
void SwitchTrafficLight( int light_color )
{
switch( light_color )
{
case RED_LIGHT:
digitalWrite(g_ledPin1, HIGH);
digitalWrite(g_ledPin2, LOW);
digitalWrite(g_ledPin3, LOW);
break;
case YELLOW_LIGHT:
digitalWrite(g_ledPin1, LOW);
digitalWrite(g_ledPin2, HIGH);
digitalWrite(g_ledPin3, LOW);
break;
case GREEN_LIGHT:
digitalWrite(g_ledPin1, LOW);
digitalWrite(g_ledPin2, LOW);
digitalWrite(g_ledPin3, HIGH);
break;
default:
break;
}
}
/****************************************************************************************************************//*
* \brief checks which button is clicked on S-Trike experimentation board
* \param adc_count ADC value returned by analog read function
* \param button_clicked output: char array with string description of button
* \return return the reference value for button click
/****************************************************************************************************************/
int ButtonCheck( int adc_count, char* button_clicked_buffer, int buffer_size )
{
int return_value = FAILURE;
#define MIN_STRING_SIZE 100
strncpy( button_clicked_buffer, "Not Set.", buffer_size );
if( buffer_size >= MIN_STRING_SIZE )
{
if( adc_count >= 0 )
{
/*
* assume adc_count=250
* adc_count_plus = 300
* adc_count_mius = 200
* BUTTON_2=242
*/
int adc_count_plus = adc_count + BTN_ADC_TOLERANCE;
int adc_count_minus = adc_count - BTN_ADC_TOLERANCE;
if( adc_count_plus > BUTTON_1 && adc_count_minus < BUTTON_1)
{
strncpy( button_clicked_buffer, "Button: 1", buffer_size );
return_value = BUTTON_1;
}
else if( adc_count_plus > BUTTON_2 && adc_count_minus < BUTTON_2)
{
strncpy( button_clicked_buffer, "Button: 2", buffer_size );
return_value = BUTTON_2;
}
else if( adc_count_plus > BUTTON_3 && adc_count_minus < BUTTON_3)
{
strncpy( button_clicked_buffer, "Button: 3", buffer_size );
return_value = BUTTON_3;
}
else if( adc_count_plus > BUTTON_4 && adc_count_minus < BUTTON_4)
{
strncpy( button_clicked_buffer, "Button: 4", buffer_size );
return_value = BUTTON_4;
}
else if( adc_count_plus > BUTTON_5 && adc_count_minus < BUTTON_5)
{
strncpy( button_clicked_buffer, "Button: 5", buffer_size);
return_value = BUTTON_5;
}
else
{
strncpy( button_clicked_buffer, "No Button.", buffer_size );
return_value = NO_BUTTONS;
}
}
}
return( return_value );
}
/****************************************************************************************************************//**
* \brief setup timer 1 for Compare Match (CTC) with 1 sec resolution - TIMER_EXAMPLE
* \details modified from \source to accomodate 256 prescaler and 8MHz clk
* \source http://www.instructables.com/id/Arduino-Timer-Interrupts/step2/Structuring-Timer-Interrupts/
/****************************************************************************************************************/
void SetupTimer1( void )
{
cli(); // stop interrupts
// set timer1 interrupt at 1Hz
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
TCNT1 = 0; // initialize counter value to 0
// set compare match register for 1hz increments
OCR1A = 31249; // = (8*10^6) / (1*256) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 256 prescaler
TCCR1B |= (1 << CS12);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei(); // allow interrupts
}
| [
"alexnahr@gmail.com"
] | alexnahr@gmail.com |
81b50e9261d1acbc2d278add0930fe56fcfd8a49 | d00270bfa470bd6b040f5001b745a2d57a526ab5 | /Hacker Rank/sock-merchant.cpp | ccd91f9136340043a1f17d42c8f2db02736be61a | [] | no_license | williamchanrico/competitive-programming | fcec67b3c7c338ebd250bdfc33627a26afe44ab4 | 6290e9f7ebd5063b0341c8068a321d2044a2ad63 | refs/heads/master | 2021-01-22T23:15:32.561571 | 2020-10-17T12:16:44 | 2020-10-17T12:16:44 | 85,616,873 | 2 | 4 | null | 2019-08-11T14:49:18 | 2017-03-20T19:20:11 | C++ | UTF-8 | C++ | false | false | 409 | cpp | #include <algorithm>
#include <cstdio>
#include <map>
int main()
{
int N;
scanf("%d", &N);
int arr[110];
std::map<int, int> m;
for (int a = 0; a < N; a++) {
scanf("%d", &arr[a]);
++m[arr[a]];
}
std::sort(arr, arr + N);
int ans = 0;
for (auto it = m.begin(); it != m.end(); it++) {
ans += (int)(it->second / 2);
}
printf("%d\n", ans);
}
| [
"williamchanrico@gmail.com"
] | williamchanrico@gmail.com |
894e4508ed06492948dfefee20540c3cc4ec40e3 | 1afdb4bce52b84572782b9a33a52bbd4000d784e | /learn/STL/iterator_bidirectional.cpp | 53be426731d7c7f2ea93c74b36a779a5ce53039e | [] | no_license | manishsurolia/C-Plus-Plus | 4eaeffaa9d020efdef5fe1c423a2a482ba1a9699 | 7991d9a0d911b376fc984cd60d96c9b869301d1d | refs/heads/main | 2023-04-14T19:36:31.259053 | 2021-05-06T13:06:55 | 2021-05-06T13:06:55 | 363,832,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 952 | cpp | /*
* The second kind of iterator is bidirectional.
*
* We can increment it, decrement it, but we can't add a value to the iterator.
*
* itr++ // allowed
* itr-- //allowed
*
* itr = itr + 5; // Not allowed.
* itr = itr - 5; // Not allowed.
* if (itr1 < itr2) // Not allowed.
*
* Below are the containers, which provide bi-directional container.
* List, set/multiset, map/multimap.
*
* Linked list, we know that the nodes of a list is scattered in memory. So, we
* can;t do above operations.
* set/multiset, map/multimap, are created with the use of binary tree.
* so again, above mentioned operations are not allowed on iterators.
*/
#include <iostream>
#include <set>
int main(int argc, char **argv)
{
std :: set <int> myset = {10, 30, 20, 40};
for (std::set <int> :: iterator itr = myset.begin(); itr != myset.end();
itr++) {
std::cout <<*itr << " ";
}
std::cout<<std::endl;
return 0;
}
| [
"manishsurolia@gmail.com"
] | manishsurolia@gmail.com |
cac5e4e7183bc95963e3b43c3e6dbdb21dd19aa8 | 8ac157eda8e6fe4dab420e47da32300e63c62489 | /Toph/Jenia's Homework.cpp | d177875acb3c029ef7051cb93ecd60621d2290ad | [] | 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,878 | cpp | #include<bits/stdc++.h>
#include<ctype.h>
#include<string.h>
#include<stdio.h>
#define TAKING freopen("input.txt" , "r" , stdin);
#define MAKING freopen("output.txt","w" , stdout);
#define ll long long
#define sf scanf
#define pf printf
#define pb push_back
#define mp make_pair
#define nl "\n"
#define BOLT ios_base::sync_with_stdio(0)
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define fi first
#define se second
#define sz(v) (int)(v).size()
#define REMOVE_ALL(str , c) str.erase(remove(str.begin(), str.end(), c), str.end())
#define PIE acos(-1)
using namespace std;
inline int ini(){int n;cin >> n;return n;}
inline ll inl(){ll n;cin >> n;return n;}
inline double ind(){double n;cin >> n;return n;}
inline string ins(){string n;cin >> n;return n;}
inline string insl(){string n;getline(cin,n);return n;}
inline int string_to_int(string s){int n;stringstream ss;ss << s;ss >> n;return n;} // Same for double and long long
inline string int_to_string(int n){string s;stringstream ss;ss << n;ss >> s;return s;} // Same for double and long long
inline long long string_to_Long_Long(string s){ll res = 0;for(int i = 0 ; i < s.size() ; i++){res = res*10 + (s[i]-'0');}return res;}
typedef vector <int> vi;
typedef pair <int,long long> pii;
int main(){
BOLT;
int t = ini();
while(t--){
cout << setprecision(16) << fixed ;
double a = ind();
cout << a - (sqrt(a)/2)*(sqrt(a)/2)*PIE << " " << 2*PIE*(sqrt(a)/2) << nl;
}
return 0;
}
| [
"mdskrumi@gmail.com"
] | mdskrumi@gmail.com |
7d36990c18124d01302e0327c973e846a40bff0f | 792fbf91f3da85c65db3b99a3f881e0686a19a7e | /IMApp/IMApp/TestApi.cpp | 6dc08cae3c0667dec2aae5738c271dce019aa8c7 | [] | no_license | wannianhong/txWindowsIMDemo | 17e652c5384e70a69f2ced747495ee946ce4416c | e9d70d1194ffe0ca747a729d3585d8b3108db24f | refs/heads/master | 2020-11-29T06:02:42.080324 | 2019-12-25T04:35:20 | 2019-12-25T04:35:20 | 230,039,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,646 | cpp | #include "TestApi.h"
#include "json.h"
#include "IMWnd.h"
#include <time.h>
//批量发送
void Test_TIMMsgBatchSend()
{
//构造消息文本元素
Json::Value json_value_elem;
json_value_elem[kTIMElemType] = TIMElemType::kTIMElem_Text;
json_value_elem[kTIMTextElemContent] = "this is batch send msgs";
//构造消息
Json::Value json_value_msg;
json_value_msg[kTIMMsgSender] = CIMWnd::GetInst().login_id;
json_value_msg[kTIMMsgClientTime] = time(NULL);
json_value_msg[kTIMMsgServerTime] = time(NULL);
json_value_msg[kTIMMsgElemArray].append(json_value_elem);
// 构造批量发送ID数组列表
Json::Value json_value_ids(Json::arrayValue);
json_value_ids.append("user2");
json_value_ids.append("user3");
// 构造批量发送接口参数
Json::Value json_value_batchsend;
json_value_batchsend[kTIMMsgBatchSendParamIdentifierArray] = json_value_ids;
json_value_batchsend[kTIMMsgBatchSendParamMsg] = json_value_msg;
int ret = TIMMsgBatchSend(json_value_batchsend.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) {
if (code != ERR_SUCC) { // 批量发送成功
CIMWnd::GetInst().Logf("TESTAPI", kTIMLog_Error, "TIMMsgBatchSend cb code:%u desc:%s", code, desc);
return;
}
Json::Value json_result;
Json::Reader reader;
if (!reader.parse(json_param, json_result)) {
CIMWnd::GetInst().Logf("TESTAPI", kTIMLog_Error, "TIMMsgBatchSend result parse Failure!%s",reader.getFormattedErrorMessages().c_str());
return;
}
for (Json::ArrayIndex i = 0; i < json_result.size(); i++) {
Json::Value& res = json_result[i];
std::string id = res[kTIMMsgBatchSendResultIdentifier].asString();
int sub_code = res[kTIMMsgBatchSendResultCode].asInt();
std::string sub_desc = res[kTIMMsgBatchSendResultDesc].asString();
if (code != ERR_SUCC) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMMsgBatchSend to id:%s Failure! code:%u desc:%s", id.c_str(), sub_code, sub_desc.c_str());
}
else {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "TIMMsgBatchSend to id:%s Success!", id.c_str());
}
}
}, nullptr);
if (TIM_SUCC != ret) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMMsgBatchSend Failure!ret %d", ret);
}
}
void Test_MsgFind() {
Json::Value json_msg_locator; // 一条消息对应一个消息定位符(精准定位)
json_msg_locator[kTIMMsgLocatorIsRevoked] = false; //消息是否被撤回
json_msg_locator[kTIMMsgLocatorTime] = 123; //填入消息的时间
json_msg_locator[kTIMMsgLocatorSeq] = 1;
json_msg_locator[kTIMMsgLocatorIsSelf] = false;
json_msg_locator[kTIMMsgLocatorRand] = 12345678;
Json::Value json_msg_locators;
json_msg_locators.append(json_msg_locator);
TIMMsgFindByMsgLocatorList("user2", kTIMConv_C2C, json_msg_locators.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) {
if (code != ERR_SUCC) {
CIMWnd::GetInst().Logf("TESTAPI", kTIMLog_Error, "TIMMsgBatchSend cb code:%u desc:%s", code, desc);
return;
}
}, nullptr);
}
void Test_MsgImport() {
Json::Value json_value_elem; //构造消息文本元素
json_value_elem[kTIMElemType] = TIMElemType::kTIMElem_Text;
json_value_elem[kTIMTextElemContent] = "this is import msg";
Json::Value json_value_msg; //构造消息
json_value_msg[kTIMMsgSender] = CIMWnd::GetInst().login_id;
json_value_msg[kTIMMsgClientTime] = time(NULL);
json_value_msg[kTIMMsgServerTime] = time(NULL);
json_value_msg[kTIMMsgElemArray].append(json_value_elem);
Json::Value json_value_msgs; //消息数组
json_value_msgs.append(json_value_msg);
TIMMsgImportMsgList("user3", kTIMConv_C2C, json_value_msgs.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) {
if (code != ERR_SUCC) {
CIMWnd::GetInst().Logf("TESTAPI", kTIMLog_Error, "TIMMsgBatchSend cb code:%u desc:%s", code, desc);
return;
}
}, nullptr);
}
void Test_MsgDelete() {
Json::Value json_value_msg(Json::objectValue);
Json::Value json_value_msgdelete;
json_value_msgdelete[kTIMMsgDeleteParamIsRamble] = false;
json_value_msgdelete[kTIMMsgDeleteParamMsg] = json_value_msg;
TIMMsgDelete("user2", kTIMConv_C2C, json_value_msgdelete.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) {
if (code != ERR_SUCC) {
CIMWnd::GetInst().Logf("TESTAPI", kTIMLog_Error, "TIMMsgBatchSend cb code:%u desc:%s", code, desc);
return;
}
}, nullptr);
}
void Test_SetGroupInfo() {
//*修改群组名称和群通知
Json::Value json_value_setgroupinfo;
json_value_setgroupinfo[kTIMGroupModifyInfoParamGroupId] = "first group id";
json_value_setgroupinfo[kTIMGroupModifyInfoParamModifyFlag] = kTIMGroupModifyInfoFlag_Name | kTIMGroupModifyInfoFlag_Notification;
json_value_setgroupinfo[kTIMGroupModifyInfoParamGroupName] = "first group name to other name";
json_value_setgroupinfo[kTIMGroupModifyInfoParamNotification] = "first group notification";
//*/
/* 修改群主
Json::Value json_value_setgroupinfo;
json_value_setgroupinfo[kTIMGroupModifyInfoParamGroupId] = "first group id";
json_value_setgroupinfo[kTIMGroupModifyInfoParamModifyFlag] = kTIMGroupModifyInfoFlag_Owner;
json_value_setgroupinfo[kTIMGroupModifyInfoParamOwner] = "user2";
//*/
int ret = TIMGroupModifyGroupInfo(json_value_setgroupinfo.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) {
if (code != ERR_SUCC) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupModifyGroupInfo cb code:%u desc:%s", code, desc);
return;
}
}, nullptr);
if (TIM_SUCC != ret) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupSetGroupInfo Failure!ret %d", ret);
}
}
void Test_SetGroupMemberInfo() {
// 设置 成员为管理员
Json::Value json_value_setgroupmeminfo;
json_value_setgroupmeminfo[kTIMGroupModifyMemberInfoParamGroupId] = "third group id";
json_value_setgroupmeminfo[kTIMGroupModifyMemberInfoParamIdentifier] = "user2";
json_value_setgroupmeminfo[kTIMGroupModifyMemberInfoParamModifyFlag] = kTIMGroupMemberModifyFlag_MemberRole | kTIMGroupMemberModifyFlag_NameCard;
json_value_setgroupmeminfo[kTIMGroupModifyMemberInfoParamMemberRole] = kTIMMemberRole_Admin;
json_value_setgroupmeminfo[kTIMGroupModifyMemberInfoParamNameCard] = "change name card";
int ret = TIMGroupModifyMemberInfo(json_value_setgroupmeminfo.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) {
if (code != ERR_SUCC) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupSetMemberInfo cb code:%u desc:%s", code, desc);
return;
}
}, nullptr);
if (TIM_SUCC != ret) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupSetMemberInfo Failure!ret %d", ret);
}
}
// 获取未决信息 并处理
void Test_GroupGetPendencyList() {
Json::Value get_pendency_option;
get_pendency_option[kTIMGroupPendencyOptionStartTime] = 0;
get_pendency_option[kTIMGroupPendencyOptionMaxLimited] = 0;
int ret = TIMGroupGetPendencyList(get_pendency_option.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) {
if (code != ERR_SUCC) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupGetPendencyList cb code:%u desc:%s", code, desc);
return;
}
Json::Value group_pendency_result;
Json::Reader reader;
if (!reader.parse(json_param, group_pendency_result)) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupGetPendencyList Json Parse Failure!%s", reader.getFormattedErrorMessages().c_str());
return;
}
Json::Value& group_pendency_array = group_pendency_result[kTIMGroupPendencyResultPendencyArray];
for (Json::ArrayIndex i = 0; i < group_pendency_array.size(); i++) {
/* 上报未决消息已读
uint64_t timestamp = group_pendency_array[i][kTIMGroupPendencyAddTime].asUInt64();
int ret = TIMGroupReportPendencyReaded(timestamp, [](int32_t code, const char* desc, const char* json_param, const void* user_data) {
if (code != ERR_SUCC) { //
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupHandlePendency cb code:%u desc:%s", code, desc);
return;
}
}, nullptr);
if (TIM_SUCC != ret) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupHandlePendency Failure!ret %d", ret);
}
//*/
//* 处理 每一个pendency 为accept
Json::Value pendency; //构造 GroupPendency
Json::Value handle_pendency;
handle_pendency[kTIMGroupHandlePendencyParamIsAccept] = true;
handle_pendency[kTIMGroupHandlePendencyParamHandleMsg] = "I accept this pendency";
handle_pendency[kTIMGroupHandlePendencyParamPendency] = pendency;
int ret = TIMGroupHandlePendency(handle_pendency.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) {
if (code != ERR_SUCC) { //
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupHandlePendency cb code:%u desc:%s", code, desc);
return;
}
}, nullptr);
if (TIM_SUCC != ret) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupHandlePendency Failure!ret %d", ret);
}
//*/
}
// HandlePendency
}, nullptr);
if (TIM_SUCC != ret) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupGetPendencyList Failure!ret %d", ret);
}
}
void Test_GetMsgList()
{
Json::Value json_elem(Json::objectValue);
json_elem[kTIMElemType] = 0;
json_elem[kTIMTextElemContent] = "2";
Json::Value json_elem_array(Json::arrayValue);
json_elem_array.append(json_elem);
Json::Value json_msg(Json::objectValue);
json_msg[kTIMMsgClientTime] = 1652039330;
json_msg[kTIMMsgConvId] = "user2";
json_msg[kTIMMsgConvType] = 1;
json_msg[kTIMMsgElemArray] = json_elem_array;
json_msg[kTIMMsgIsFormSelf] = true;
json_msg[kTIMMsgIsRead] = true;
json_msg[kTIMMsgRand] = 3984852732LL;
json_msg[kTIMMsgSender] = "user1";
json_msg[kTIMMsgSeq] = 1;
json_msg[kTIMMsgServerTime] = 1652039330;
json_msg[kTIMMsgStatus] = 2;
Json::Value json_msgget_param;
json_msgget_param[kTIMMsgGetMsgListParamLastMsg] = json_msg;
json_msgget_param[kTIMMsgGetMsgListParamIsRamble] = false;
json_msgget_param[kTIMMsgGetMsgListParamIsForward] = false;
json_msgget_param[kTIMMsgGetMsgListParamCount] = 100;
std::string json = json_msgget_param.toStyledString();
int ret = TIMMsgGetMsgList("user2", kTIMConv_C2C, json.c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "TIMMsgGetMsgList cb code:%u desc:%s", code, desc);
}, nullptr);
}
//****************** 好友关系链接口使用**********************/
void TestFriendshipGetProfileList() {
Json::Value json_get_profile_list_param;
json_get_profile_list_param[kTIMFriendShipGetProfileListParamForceUpdate] = false;
json_get_profile_list_param[kTIMFriendShipGetProfileListParamIdentifierArray].append("user1");
json_get_profile_list_param[kTIMFriendShipGetProfileListParamIdentifierArray].append("user2");
json_get_profile_list_param[kTIMFriendShipGetProfileListParamIdentifierArray].append("user4");
TIMProfileGetUserProfileList(json_get_profile_list_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "GetProfileList cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestFriendshipModifySelfProfile() {
Json::Value modify_item;
modify_item[kTIMUserProfileItemNickName] = "change my nick name"; // 修改昵称
modify_item[kTIMUserProfileItemGender] = kTIMGenderType_Female; // 修改性别
modify_item[kTIMUserProfileItemAddPermission] = kTIMProfileAddPermission_NeedConfirm; // 修改添加好友权限
Json::Value json_user_profile_item_custom;
json_user_profile_item_custom[kTIMUserProfileCustemStringInfoKey] = "Str";
json_user_profile_item_custom[kTIMUserProfileCustemStringInfoValue] = "my define data";
modify_item[kTIMUserProfileItemCustomStringArray].append(json_user_profile_item_custom);
int ret = TIMProfileModifySelfUserProfile(modify_item.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "GetProfileList cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestFriendshipGetFriendProfileList() {
int ret = TIMFriendshipGetFriendProfileList([](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "GetProfileList cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestFriendshipAddFriend() {
Json::Value json_add_friend_param;
json_add_friend_param[kTIMFriendshipAddFriendParamIdentifier] = "user4";
json_add_friend_param[kTIMFriendshipAddFriendParamFriendType] = FriendTypeBoth;
json_add_friend_param[kTIMFriendshipAddFriendParamAddSource] = "Windows";
json_add_friend_param[kTIMFriendshipAddFriendParamAddWording] = "I am Iron Man";
int ret = TIMFriendshipAddFriend(json_add_friend_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, " cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipDeleteFriend() {
Json::Value json_delete_friend_param;
json_delete_friend_param[kTIMFriendshipDeleteFriendParamIdentifierArray].append("user4");
json_delete_friend_param[kTIMFriendshipDeleteFriendParamFriendType] = FriendTypeBoth;
int ret = TIMFriendshipDeleteFriend(json_delete_friend_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipGetPendencyList() {
Json::Value json_get_pendency_list_param;
json_get_pendency_list_param[kTIMFriendshipGetPendencyListParamType] = FriendPendencyTypeBoth;
json_get_pendency_list_param[kTIMFriendshipGetPendencyListParamStartSeq] = 0;
int ret = TIMFriendshipGetPendencyList(json_get_pendency_list_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipReportPendencyReaded() {
uint64_t time_stamp = 1563026447;
int ret = TIMFriendshipReportPendencyReaded(time_stamp, [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipDeletePendency() {
Json::Value json_delete_pendency_param;
json_delete_pendency_param[kTIMFriendshipDeletePendencyParamType] = FriendPendencyTypeSendOut;
json_delete_pendency_param[kTIMFriendshipDeletePendencyParamIdentifierArray].append("user4");
int ret = TIMFriendshipDeletePendency(json_delete_pendency_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipHandleFriendAddRequest() {
Json::Value json_handle_friend_add_param;
json_handle_friend_add_param[kTIMFriendResponeIdentifier] = "user1";
json_handle_friend_add_param[kTIMFriendResponeAction] = ResponseActionAgreeAndAdd;
json_handle_friend_add_param[kTIMFriendResponeRemark] = "I am Captain China";
json_handle_friend_add_param[kTIMFriendResponeGroupName] = "schoolmate";
int ret = TIMFriendshipHandleFriendAddRequest(json_handle_friend_add_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipModifyFriendProfile() {
Json::Value json_modify_friend_profile_item;
json_modify_friend_profile_item[kTIMFriendProfileItemRemark] = "xxxx yyyy"; // 修改备注
json_modify_friend_profile_item[kTIMFriendProfileItemGroupNameArray].append("group1"); // 修改好友所在分组
json_modify_friend_profile_item[kTIMFriendProfileItemGroupNameArray].append("group2");
Json::Value json_modify_friend_profilie_custom;
json_modify_friend_profilie_custom[kTIMFriendProfileCustemStringInfoKey] = "Str";
json_modify_friend_profilie_custom[kTIMFriendProfileCustemStringInfoValue] = "this is changed value";
json_modify_friend_profile_item[kTIMFriendProfileItemCustomStringArray].append(json_modify_friend_profilie_custom);
Json::Value json_modify_friend_info_param;
json_modify_friend_info_param[kTIMFriendshipModifyFriendProfileParamIdentifier] = "user4";
json_modify_friend_info_param[kTIMFriendshipModifyFriendProfileParamItem] = json_modify_friend_profile_item;
int ret = TIMFriendshipModifyFriendProfile(json_modify_friend_info_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipCheckFriendType() {
Json::Value json_check_friend_list_param;
json_check_friend_list_param[kTIMFriendshipCheckFriendTypeParamCheckType] = FriendTypeBoth;
json_check_friend_list_param[kTIMFriendshipCheckFriendTypeParamIdentifierArray].append("user4");
int ret = TIMFriendshipCheckFriendType(json_check_friend_list_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipCreateFriendGroup() {
Json::Value json_create_friend_group_param;
json_create_friend_group_param[kTIMFriendshipCreateFriendGroupParamNameArray].append("Group123");
json_create_friend_group_param[kTIMFriendshipCreateFriendGroupParamNameArray].append("Group321");
json_create_friend_group_param[kTIMFriendshipCreateFriendGroupParamIdentifierArray].append("user4");
json_create_friend_group_param[kTIMFriendshipCreateFriendGroupParamIdentifierArray].append("user10");
int ret = TIMFriendshipCreateFriendGroup(json_create_friend_group_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipGetFriendGroupList() {
Json::Value json_get_friend_group_list_param;
json_get_friend_group_list_param.append("Group123");
//json_get_friend_group_list_param.append("Group1");
//json_get_friend_group_list_param.append("Group2");
int ret = TIMFriendshipGetFriendGroupList(json_get_friend_group_list_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipModifyFriendGroup() {
Json::Value json_modify_friend_group_param;
json_modify_friend_group_param[kTIMFriendshipModifyFriendGroupParamName] = "Group123";
json_modify_friend_group_param[kTIMFriendshipModifyFriendGroupParamNewName] = "GroupNewName";
json_modify_friend_group_param[kTIMFriendshipModifyFriendGroupParamDeleteIdentifierArray].append("user4");
json_modify_friend_group_param[kTIMFriendshipModifyFriendGroupParamAddIdentifierArray].append("user9");
json_modify_friend_group_param[kTIMFriendshipModifyFriendGroupParamAddIdentifierArray].append("user5");
int ret = TIMFriendshipModifyFriendGroup(json_modify_friend_group_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipDeleteFriendGroup() {
Json::Value json_delete_friend_group_param;
json_delete_friend_group_param.append("GroupNewName");
int ret = TIMFriendshipDeleteFriendGroup(json_delete_friend_group_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipAddToBlackList() {
Json::Value json_add_to_blacklist_param;
json_add_to_blacklist_param.append("user5");
json_add_to_blacklist_param.append("user10");
int ret = TIMFriendshipAddToBlackList(json_add_to_blacklist_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipGetBlackList() {
int ret = TIMFriendshipGetBlackList([](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
void TestTIMFriendshipDeleteFromBlackList() {
Json::Value json_delete_from_blacklist_param;
json_delete_from_blacklist_param.append("user5");
json_delete_from_blacklist_param.append("user10");
int ret = TIMFriendshipDeleteFromBlackList(json_delete_from_blacklist_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) {
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc);
CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params);
}, nullptr);
}
// 此函数用于测试各个API功能
void TestApi() {
const void* user_data = nullptr;
Json::Value modify_item;
//TestFriendshipGetProfileList();
//TestFriendshipModifySelfProfile();
//TestTIMFriendshipDeleteFriend();
//TestFriendshipAddFriend();
//TestFriendshipGetFriendProfileList();
TestTIMFriendshipModifyFriendProfile();
//TestTIMFriendshipGetPendencyList();
//TestTIMFriendshipReportPendencyReaded();
//TestTIMFriendshipDeletePendency();
//TestTIMFriendshipHandleFriendAddRequest();
//TestTIMFriendshipCheckFriendType();
//TestTIMFriendshipCreateFriendGroup();
//TestTIMFriendshipGetFriendGroupList();
//TestTIMFriendshipModifyFriendGroup();
//TestTIMFriendshipDeleteFriendGroup();
//TestTIMFriendshipAddToBlackList();
//TestTIMFriendshipGetBlackList();
//TestTIMFriendshipDeleteFromBlackList();
//TIMSetRecvNewMsgCallback(RecvNewMsgCallback, user_data);
//Test_MsgImport();
//Json::Value identifiers(Json::arrayValue);
//...
// Json::Value customs(Json::arrayValue);
//...
// Json::Value option;
//option[kTIMGroupMemberGetInfoOptionInfoFlag] = kTIMGroupMemberInfoFlag_None;
//option[kTIMGroupMemberGetInfoOptionRoleFlag] = kTIMGroupMemberRoleFlag_All;
//option[kTIMGroupMemberGetInfoOptionCustomArray] = customs;
//Json::Value getmeminfo_opt;
//getmeminfo_opt[kTIMGroupGetMemberInfoListParamGroupId] = groupid;
//getmeminfo_opt[kTIMGroupGetMemberInfoListParamIdentifierArray] = identifiers;
//getmeminfo_opt[kTIMGroupGetMemberInfoListParamOption] = option;
//getmeminfo_opt[kTIMGroupGetMemberInfoListParamNextSeq] = 0;
//int ret = TIMGroupGetMemberInfoList(getmeminfo_opt.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) {
//}, this);
//Test_GetMsgList();
} | [
"97548471@qq.com"
] | 97548471@qq.com |
b5b2092bc5acebcfc8ca728bd5eb339655720b6a | a0ebf3f7218a7599ae603ad42b5810b85502b3f8 | /DataStructures.Tests/polynomial_test.cpp | 5b314821de73dafd926b2298727e601f8d860309 | [] | no_license | drussell33/Data-Structures-With-Tests | 381cdc2ececd2d210b3fd8de9d349e707ab4819b | 570c8ff25d979dc16910a1652b4658dac8931d67 | refs/heads/main | 2023-08-30T02:47:21.426698 | 2021-11-10T21:57:47 | 2021-11-10T21:57:47 | 426,788,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,161 | cpp | #include "pch.h"
#include "CppUnitTest.h"
#include "adt_exception.hpp"
#include "crt_check_memory.hpp"
#include "polynomial.hpp"
using namespace data_structures;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace data_structures_tests
{
TEST_CLASS(T14_Polynomial_Test)
{
public:
TEST_METHOD(PolynomialAddSameNumberCoefficients)
{
const CrtCheckMemory check;
// 60x^4 + 50x^3 + 40x^2 + 30^x + 20
const double coefficients_of_polynomial_1[]{ 20.0, 30.0, 40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
// 6x^4 + 7x^3 + 8x^2 + 9^x + 10
const double coefficients_of_polynomial_2[]{ 10.0, 9.0, 8.0, 7.0, 6.0 };
const Polynomial<double> polynomial_2{ coefficients_of_polynomial_2, 5 };
const Polynomial<double> your_answer = polynomial_1 + polynomial_2;
const double coefficients_of_answer[] = { 30.0, 39.0, 48.0, 57.0, 66.0 };
const Polynomial<double> correct_answer(coefficients_of_answer, 5);
Assert::IsTrue(correct_answer == your_answer);
}
TEST_METHOD(PolynomialSubtractSameNumberCoefficients)
{
const CrtCheckMemory check;
const double coefficients_of_polynomial_1[]{ 20.0, 30.0, 40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
double coefficients_of_polynomial_2[]{ 10.0, 9.0, 8.0, 7.0, 6.0 };
const Polynomial<double> polynomial_2{ coefficients_of_polynomial_2, 5 };
const auto your_answer{ polynomial_1 - polynomial_2 };
double coefficients_of_answer[]{ 10.0, 21.0, 32.0, 43.0, 54.0 };
const Polynomial<double> correct_answer{ coefficients_of_answer, 5 };
Assert::IsTrue(correct_answer == your_answer);
}
TEST_METHOD(PolynomialAddDifferentNumberCoefficients_LeftLarger)
{
const CrtCheckMemory check;
// 60x^4 + 50x^3 + 40x^2 + 30^x + 20
const double coefficients_of_polynomial_1[]{ 20.0, 30.0, 40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
// 6x^3 + 7x^2 + 8x + 9
const double coefficients_of_polynomial_2[]{ 9.0, 8.0, 7.0, 6.0 };
const Polynomial<double> polynomial_2{ coefficients_of_polynomial_2, 4 };
const auto your_answer{ polynomial_1 + polynomial_2 };
const double coefficients_of_answer[]{ 29.0, 38.0, 47.0, 56.0, 60.0 };
const Polynomial<double> correct_answer{ coefficients_of_answer, 5 };
Assert::IsTrue(correct_answer == your_answer);
}
TEST_METHOD(PolynomialAddDifferentNumberCoefficients_RightLarger)
{
const CrtCheckMemory check;
// 6x^3 + 7x^2 + 8x + 9
const double coefficients_of_polynomial_1[]{ 9.0, 8.0, 7.0, 6.0 };
const Polynomial<double> polynomial_1(coefficients_of_polynomial_1, 4);
// 60x^4 + 50x^3 + 40x^2 + 30^x + 20
const double coefficients_of_polynomial_2[]{ 20.0, 30.0, 40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_2{ coefficients_of_polynomial_2, 5 };
const auto your_answer{ polynomial_1 + polynomial_2 };
const double coefficients_of_answer[]{ 29.0, 38.0, 47.0, 56.0, 60.0 };
const Polynomial<double> correct_answer{ coefficients_of_answer, 5 };
Assert::IsTrue(correct_answer == your_answer);
}
TEST_METHOD(PolynomialSubtractDifferentNumberCoefficients_LeftLarger)
{
const CrtCheckMemory check;
const double coefficients_of_polynomial_1[]{ 20.0, 30.0, 40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
const double coefficients_of_polynomial_2[]{ 9.0, 8.0, 7.0, 6.0 };
const Polynomial<double> polynomial_2{ coefficients_of_polynomial_2, 4 };
const auto your_answer{ polynomial_1 - polynomial_2 };
const double coefficients_of_answer[]{ 11.0, 22.0, 33.0, 44.0, 60.0 };
const Polynomial<double> correct_answer{ coefficients_of_answer, 5 };
Assert::IsTrue(correct_answer == your_answer);
}
TEST_METHOD(PolynomialSubtractDifferentNumberCoefficients_RightLarger)
{
const CrtCheckMemory check;
const double coefficients_of_polynomial_1[4] = { 9.0, 8.0, 7.0, 6.0 };
const Polynomial<double> polynomial_1(coefficients_of_polynomial_1, 4);
const double coefficients_of_polynomial_2[5] = { 20.0, 30.0, 40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_2(coefficients_of_polynomial_2, 5);
const auto your_answer = polynomial_1 - polynomial_2;
const double coefficients_of_answer[5] = { -11.0, -22.0, -33.0, -44.0, 60.0 };
const Polynomial<double> correct_answer(coefficients_of_answer, 5);
Assert::IsTrue(correct_answer == your_answer);
}
TEST_METHOD(PolynomialAddNegativeNumbers)
{
CrtCheckMemory check;
const double coefficients_of_polynomial_1[]{ -20.0, 30.0, -40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
const double coefficients_of_polynomial_2[]{ 9.0, -8.0, 7.0, -6.0 };
const Polynomial<double> polynomial_2{ coefficients_of_polynomial_2, 4 };
const auto your_answer{ polynomial_1 + polynomial_2 };
double coefficients_of_answer[]{ -11.0, 22.0, -33.0, 44.0, 60.0 };
const Polynomial<double> correct_answer{ coefficients_of_answer, 5 };
Assert::IsTrue(correct_answer == your_answer);
}
TEST_METHOD(PolynomialSubtractNegativeNumbers)
{
const CrtCheckMemory check;
const double coefficients_of_polynomial_1[]{ -20.0, 30.0, -40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
const double coefficients_of_polynomial_2[]{ 9.0, -8.0, 7.0, -6.0 };
const Polynomial<double> polynomial_2{ coefficients_of_polynomial_2, 4 };
const auto your_answer{ polynomial_1 - polynomial_2 };
const double coefficients_of_answer[]{ -29.0, 38.0, -47.0, 56.0, 60.0 };
const Polynomial<double> correct_answer{ coefficients_of_answer, 5 };
Assert::IsTrue(correct_answer == your_answer);
}
TEST_METHOD(PolynomialAssignmentOperator)
{
const CrtCheckMemory check;
const double coefficients_of_polynomial_1[]{ -20.0, 30.0, -40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
const auto polynomial_2{ polynomial_1 };
Assert::IsTrue(polynomial_1 == polynomial_2);
}
TEST_METHOD(PolynomialConstructorandAssignmentOperator)
{
const CrtCheckMemory check;
// 60x^4 + 50x^3 + 40x^2 + 30^x + 20
const double coefficients_of_polynomial_1[]{ 20.0, 30.0, 40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
const Polynomial<double> your_answer = polynomial_1;
const double coefficients_of_answer[] = { 20.0, 30.0, 40.0, 50.0, 60.0 };
const Polynomial<double> correct_answer(coefficients_of_answer, 5);
Assert::IsTrue(correct_answer == your_answer);
}
TEST_METHOD(PolynomialNumberofCoefficientsReturnTest)
{
const CrtCheckMemory check;
// 60x^4 + 50x^3 + 40x^2 + 30^x + 20
const double coefficients_of_polynomial_1[]{ 20.0, 30.0, 40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
const Polynomial<double> your_answer = polynomial_1;
Assert::IsTrue(your_answer.NumberOfCoefficients() == 5);
}
TEST_METHOD(PolynomialMoveTest)
{
const CrtCheckMemory check;
{
const double coefficients_of_polynomial_1[]{ 20.0, 30.0, 40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
Polynomial<double> polynomial_moved(std::move(polynomial_1));
}
}
TEST_METHOD(PolynomialAddNegativeNumbersAndTestNumberOfCoefficients)
{
CrtCheckMemory check;
const double coefficients_of_polynomial_1[]{ -20.0, 30.0, -40.0, 50.0, 60.0 };
const Polynomial<double> polynomial_1{ coefficients_of_polynomial_1, 5 };
const double coefficients_of_polynomial_2[]{ 9.0, -8.0, 7.0, -6.0 };
const Polynomial<double> polynomial_2{ coefficients_of_polynomial_2, 4 };
const auto your_answer{ polynomial_1 + polynomial_2 };
double coefficients_of_answer[]{ -11.0, 22.0, -33.0, 44.0, 60.0 };
const Polynomial<double> correct_answer{ coefficients_of_answer, 5 };
Assert::IsTrue(your_answer.NumberOfCoefficients() == 5);
}
};
;
} | [
"drussell19@wou.edu"
] | drussell19@wou.edu |
c197ac5b165f9b326c97c46212509d191f83b1aa | a164f47a067c044161360e7f3d29e6ce42a5c557 | /inc/MusicLoader.hpp | 38870cfad46489a24dd107ababf57a639b49d6fc | [
"Apache-2.0"
] | permissive | Xwilarg/RhythmParadise | d437c33e1417d12b616e163516a375e37b466ae0 | a29558a47127e1ad29b3fc2d7fff0df6f844fbb4 | refs/heads/master | 2020-09-12T15:02:39.827345 | 2019-12-01T00:55:30 | 2019-12-01T00:55:30 | 222,460,585 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | hpp | #pragma once
#ifdef _WIN32
#pragma comment(lib, "irrKlang.lib")
#endif
# include <irrKlang.h>
# include <string>
namespace rhythm
{
class MusicLoader final
{
public:
MusicLoader() = delete;
~MusicLoader() noexcept;
static bool LoadMusic(const std::string& path) noexcept;
static void PlayMusic() noexcept;
static void StopMusic() noexcept;
static void SetMusicVolume(float value) noexcept;
// value is the position of the music between 0 and 1
static void SetMusicPosition(float value) noexcept;
// return a value between 0 and 1
static float GetMusicPosition() noexcept;
// return the number of ms elapsed
static int GetMusicPositionIsMs() noexcept;
private:
static irrklang::ISoundEngine* _engine;
static irrklang::ISound* _music;
static std::string _path;
};
} | [
"xwilarg@yahoo.fr"
] | xwilarg@yahoo.fr |
9534275d39d6da0c9002f20fb3a99d0296301b82 | 7ed5234fa370e40aea99b6ea1e547500cf771780 | /EasyHLS_RTSP/main.cpp | f64d5446e421eb7e2a76ec6e5c8ac853749af8ef | [] | no_license | ntvis/EasyHLS | 63979e5b911eaef70639968dac01fe5aa5507ee2 | 65c9b17c8badc831eb645c893d4c62e22c4711fa | refs/heads/master | 2021-01-15T19:35:13.687040 | 2015-08-12T06:46:42 | 2015-08-12T06:46:42 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,056 | cpp | /*
Copyright (c) 2013-2014 EasyDarwin.ORG. All rights reserved.
Github: https://github.com/EasyDarwin
WEChat: EasyDarwin
Website: http://www.EasyDarwin.org
*/
#define _CRTDBG_MAP_ALLOC
#include <stdio.h>
#include "EasyHLSAPI.h"
#include "EasyRTSPClientAPI.h"
#include <windows.h>
#define RTSPURL "rtsp://admin:admin@192.168.1.108/"
#define PLAYLIST_CAPACITY 4
#define ALLOW_CACHE false
#define M3U8_VERSION 3
#define TARGET_DURATION 4
#define HLS_ROOT_DIR "./"
#define HLS_SESSION_NAME "rtsp"
#define HTTP_ROOT_URL "http://www.easydarwin.org/easyhls/"
Easy_HLS_Handle fHlsHandle = 0;
Easy_RTSP_Handle fNVSHandle = 0;
/* NVSource从RTSPClient获取数据后回调给上层 */
int Easy_APICALL __NVSourceCallBack( int _chid, int *_chPtr, int _mediatype, char *pbuf, RTSP_FRAME_INFO *frameinfo)
{
if (NULL != frameinfo)
{
if (frameinfo->height==1088) frameinfo->height=1080;
else if (frameinfo->height==544) frameinfo->height=540;
}
if(NULL == fHlsHandle) return -1;
if (_mediatype == MEDIA_TYPE_VIDEO)
{
printf("Get %s Video Len:%d tm:%d rtp:%d\n",frameinfo->type==FRAMETYPE_I?"I":"P", frameinfo->length, frameinfo->timestamp_sec, frameinfo->rtptimestamp);
unsigned int uiFrameType = 0;
if (frameinfo->type == FRAMETYPE_I)
{
uiFrameType = TS_TYPE_PES_VIDEO_I_FRAME;
}
else
{
uiFrameType = TS_TYPE_PES_VIDEO_P_FRAME;
}
EasyHLS_VideoMux(fHlsHandle, uiFrameType, (unsigned char*)pbuf, frameinfo->length, frameinfo->rtptimestamp, frameinfo->rtptimestamp, frameinfo->rtptimestamp);
}
else if (_mediatype == MEDIA_TYPE_AUDIO)
{
printf("Get Audio Len:%d tm:%d rtp:%d\n", frameinfo->length, frameinfo->timestamp_sec, frameinfo->rtptimestamp);
// 暂时不对音频进行处理
}
else if (_mediatype == MEDIA_TYPE_EVENT)
{
if (NULL == pbuf && NULL == frameinfo)
{
printf("Connecting:%s ...\n", RTSPURL);
}
else if (NULL!=frameinfo && frameinfo->type==0xF1)
{
printf("Lose Packet:%s ...\n", RTSPURL);
}
}
return 0;
}
int main()
{
//创建NVSource
EasyRTSP_Init(&fNVSHandle);
if (NULL == fNVSHandle) return 0;
unsigned int mediaType = MEDIA_TYPE_VIDEO;
//mediaType |= MEDIA_TYPE_AUDIO; //换为NVSource, 屏蔽声音
//设置数据回调处理
EasyRTSP_SetCallback(fNVSHandle, __NVSourceCallBack);
//打开RTSP流
EasyRTSP_OpenStream(fNVSHandle, 0, RTSPURL, RTP_OVER_TCP, mediaType, 0, 0, NULL, 1000, 0);
//创建EasyHLS Session
fHlsHandle = EasyHLS_Session_Create(PLAYLIST_CAPACITY, ALLOW_CACHE, M3U8_VERSION);
char subDir[64] = { 0 };
sprintf(subDir,"%s/",HLS_SESSION_NAME);
EasyHLS_ResetStreamCache(fHlsHandle, HLS_ROOT_DIR, subDir, HLS_SESSION_NAME, TARGET_DURATION);
printf("HLS URL:%s%s/%s.m3u8", HTTP_ROOT_URL, HLS_SESSION_NAME, HLS_SESSION_NAME);
while(1)
{
Sleep(10);
};
EasyHLS_Session_Release(fHlsHandle);
fHlsHandle = 0;
EasyRTSP_CloseStream(fNVSHandle);
EasyRTSP_Deinit(&fNVSHandle);
fNVSHandle = NULL;
return 0;
} | [
"mysunpany@gmail.com"
] | mysunpany@gmail.com |
b820dde45cf4236704686c4f45893c5d433ead37 | c7a771dc8763f5f8803385ec0830d2fe484fcf88 | /utility/MsgQueue.hpp | 198aba34af7a9d37ba9e07e8d2b024f6e0c74f41 | [] | no_license | aralehuan/QtDemo | 1af39465be372e9d7f835ec6fd3a80ab2250d8ad | 79a619661cb37546717e39989e693940e1a2fe25 | refs/heads/master | 2021-05-26T00:58:29.152006 | 2020-06-11T10:44:41 | 2020-06-11T10:44:41 | 253,991,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,719 | hpp | #ifndef _MSG_QUEUE_H_
#define _MSG_QUEUE_H_
#include "concurrentqueue.h"
#define MSG_MAX_LEN 65535
/*
消息包队列(先进先出)
支持多线程
lixiaoming 2020-02-04
*/
class MsgQueue
{
public:
struct Item
{
int type;
uint16_t len;
void* data = nullptr;
size_t offset;
~Item()
{
if (data)
free(data);
}
};
public:
~MsgQueue()
{
exit = true;
}
void Exit()
{
exit=true;
}
//写入1条消息
bool Push(int type, uint16_t len, const void* data, size_t dataoffset)
{
auto item = new Item;
if (!item)
{
printf("alloc failed\n");
return false;
}
item->offset = dataoffset/(1024*1024);
item->type = type;
item->len = len;
item->data = malloc(len);
if (!item->data)
goto FAILED;
memcpy(item->data, data, len);
while (!mItemQueue.enqueue(item) && (!exit));
return true;
FAILED:
if (item)
delete item;
return false;
}
//读取一定数量的消息
//返回值:消息数量
size_t Pop(Item** ppItem, size_t nItemMaxNum)
{
auto nItemNum = mItemQueue.try_dequeue_bulk(ppItem, nItemMaxNum);
return nItemNum;
}
//释放消息内存
void Free(Item** ppItem, size_t nItemNum)
{
for (size_t i = 0; i < nItemNum; ++i)
delete ppItem[i];
}
protected:
bool exit=false;
struct MyTraits : public moodycamel::ConcurrentQueueDefaultTraits
{
static const size_t BLOCK_SIZE = 256;//每次分配一块内存,内存可以存放BLOCK_SIZE个元素
static const size_t MAX_SUBQUEUE_SIZE = 512*1024;//总共存多少元素,实际数量为(MAX_SUBQUEUE_SIZE+BLOCK_SIZE-1)/BLOCK_SIZE*BLOCK_SIZE;即整数个BLOCK_SIZE
};
moodycamel::ConcurrentQueue<Item*, MyTraits> mItemQueue;
};
#endif
| [
"411635116@qq.com"
] | 411635116@qq.com |
81b0dae78ca5454b0c051ff1c2b295c40d047885 | b22f93e45064cf15aa25000af2990f112af48421 | /src/qt/test/uritests.cpp | 2b8b8046b025f5b78b7b93ad9e47c180655b2777 | [
"MIT"
] | permissive | regtable/netcoin-2 | 5e9056fd3fc27654e6632df1cdf5f7343e1db8b9 | 026f272d174e53df9276ad7029945969edbd6afe | refs/heads/master | 2020-03-08T01:06:52.075379 | 2017-12-29T10:03:13 | 2017-12-29T10:03:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,842 | cpp | #include "uritests.h"
#include "../guiutil.h"
#include "../walletmodel.h"
#include <QUrl>
void URITests::uriTests()
{
SendCoinsRecipient rv;
QUrl uri;
uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-dontexist="));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?dontexist="));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 0);
uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?label=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString("Wikipedia Example Address"));
QVERIFY(rv.amount == 0);
uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=0.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100000);
uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100100000);
uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=100&label=Wikipedia Example"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.amount == 10000000000LL);
QVERIFY(rv.label == QString("Wikipedia Example"));
uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(GUIUtil::parseBitcoinURI("netcoin://LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address", &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
// We currently don't implement the message parameter (ok, yea, we break spec...)
uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-message=Wikipedia Example Address"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000.0&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
}
| [
"kosextertioner@yahoo.com"
] | kosextertioner@yahoo.com |
e3f483a5ce60eee11b217794213e1088096612a5 | 30dd9ff200f97b525b069577471d23387b23970b | /src/sensing/driver/velodyne/velodyne_laserscan/include/velodyne_laserscan/VelodyneLaserScan.h | 32280b2b1dc1b1da790257676d0a1267877a587e | [
"BSD-3-Clause"
] | permissive | ColleyLi/AutowareArchitectureProposal | cd544ef913e3c49852d385883c3e3ee5b518b1b8 | 80ac2a8823d342e5a1e34703dbde27e8e9b5cd98 | refs/heads/master | 2022-04-18T01:41:53.649137 | 2020-04-21T12:18:58 | 2020-04-21T12:18:58 | 257,659,506 | 2 | 0 | Apache-2.0 | 2020-04-21T17:03:50 | 2020-04-21T17:03:49 | null | UTF-8 | C++ | false | false | 2,573 | h | // Copyright (C) 2018, 2019 Kevin Hallenbeck, Joshua Whitley
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of {copyright_holder} nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef VELODYNELASERSCAN_H
#define VELODYNELASERSCAN_H
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/PointCloud2.h>
#include <boost/thread/lock_guard.hpp>
#include <boost/thread/mutex.hpp>
#include <dynamic_reconfigure/server.h>
#include <velodyne_laserscan/VelodyneLaserScanConfig.h>
namespace velodyne_laserscan
{
class VelodyneLaserScan
{
public:
VelodyneLaserScan(ros::NodeHandle & nh, ros::NodeHandle & nh_priv);
private:
boost::mutex connect_mutex_;
void connectCb();
void recvCallback(const sensor_msgs::PointCloud2ConstPtr & msg);
ros::NodeHandle nh_;
ros::Subscriber sub_;
ros::Publisher pub_;
VelodyneLaserScanConfig cfg_;
dynamic_reconfigure::Server<VelodyneLaserScanConfig> srv_;
void reconfig(VelodyneLaserScanConfig & config, uint32_t level);
unsigned int ring_count_;
};
} // namespace velodyne_laserscan
#endif // VELODYNELASERSCAN_H | [
"yukky.saito@gmail.com"
] | yukky.saito@gmail.com |
5c809e4f70337c289cd127fcc38f16ff89e22cde | 2005da53aca39bddd2514ba0d75a8b5e65415391 | /Effects/13_pacman.h | 9902f933ded1c2befbd5c6df914036fd4af0e7e6 | [] | no_license | Dovgalyuk/LedTable_emulator | 9612b7595dd636ddf0627e19177b6a30ba97045e | 261ac1b4c22ab9f4b70d428329c6a3b8988b6ac8 | refs/heads/master | 2020-12-02T03:27:44.264454 | 2019-12-30T13:08:46 | 2019-12-30T13:08:46 | 230,872,319 | 0 | 0 | null | 2019-12-30T07:48:07 | 2019-12-30T07:48:07 | null | UTF-8 | C++ | false | false | 3,260 | h | #pragma once
#include "Effects/effect.h"
#define PACMAN_W 10
#define PACMAN_H 10
static const uint32_t pacman1[PACMAN_W*PACMAN_H] PROGMEM = {
0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000,
0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000,
0x000000, 0xffff00, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000,
0xffff00, 0xffff00, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00,
0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00,
0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00,
0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00,
0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000,
0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000,
0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000,
};
static const uint32_t pacman2[PACMAN_W*PACMAN_H] PROGMEM = {
0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000,
0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000,
0x000000, 0xffff00, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000,
0xffff00, 0xffff00, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000,
0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000,
0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000,
0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000,
0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000,
0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000,
0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000,
};
class Pacman : public Effect
{
public:
Pacman() {}
void on_init()
{
phase = 0;
}
void on_update()
{
fader(255);
CRGB c(255, 255, 255);
for (int i = PACMAN_W - phase ; i < WIDTH ; i += 4)
{
setPixColor(i, PACMAN_H / 2 - 1, c);
setPixColor(i + 1, PACMAN_H / 2 - 1, c);
setPixColor(i, PACMAN_H / 2, c);
setPixColor(i + 1, PACMAN_H / 2, c);
}
drawSprite(0, 0, PACMAN_W, PACMAN_H, phase / 2 ? pacman1 : pacman2);
phase = (phase + 1) % 4;
}
private:
static void drawSprite(int x, int y, int w, int h, const uint32_t *spr)
{
for (int i = 0 ; i < w ; ++i)
{
for (int j = 0 ; j < h ; ++j)
{
int v = pgm_read_dword(spr + i + j * w);
if (v)
setPixColor(x + i, y + j, CRGB(v));
}
}
}
private:
int phase;
};
| [
"pavel.dovgaluk@gmail.com"
] | pavel.dovgaluk@gmail.com |
e31be0253ab44b174f872e3a16544589c43267d5 | 529ffc32bdfb6779c36fac274096db5855c98ef7 | /binary search tree/find no of rotation by bs method.cpp | 8c005bcb164bf8e5ab9a46b11b60df1ae82c399f | [] | no_license | rajukumar2152/Dtastructure-Algorithm | c2bc7442ff36d5a9ca1d5298f8d1b1acc178f8b2 | 545a28aeba3be3495ec73b9c8876997b8ccb313d | refs/heads/master | 2023-07-08T15:39:12.168944 | 2021-08-05T19:59:41 | 2021-08-05T19:59:41 | 373,874,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | cpp |
///raju kumar sahi chak raha hain
#include<iostream>
using namespace std;
int k ;
void binrysearch(int a[], int s, int e , int num ){
int mid = s+(e-s)/2;
if (a[mid]==num){
cout << "NUMBER IS FOUND at index ->";
cout<<mid<<endl ;
int k=mid;
cout<<k<<"kbs ";
return;
}
if (num <a[mid]){
binrysearch(a, s, mid-1, num);
}
if (num >a[mid]){
binrysearch(a,mid+1, e, num );
}
}
int main()
{
int a[]= {1,2,3,12,13,45,65,85};
binrysearch(a,0,7,12);
cout<<k<<"raju klsmks";
return 0;
} | [
"rajukumar2152chd@gmail.com"
] | rajukumar2152chd@gmail.com |
af4a4903fa6f9fadc6fcf0c8e72b22f08aeea755 | 45ce394ca1fc18194f7ed9dc1d3a7bfcb5d7fb99 | /Codeforces/818A.cpp | ddc230ffd71c90511745e4de535e077390780ae2 | [] | no_license | lethanhtam1604/MyAPCodes | 4bd34c19538ebd7271dde9b9cd6100cad7893e77 | d2528cda1ef8051839067a0bc05294bc34b357ea | refs/heads/master | 2021-01-23T16:26:06.383769 | 2018-02-10T12:46:10 | 2018-02-10T12:46:10 | 93,297,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | cpp | #include <iostream>
#include <stdio.h>
#include <vector>
#include <math.h>
#include <unordered_map>
#include <string>
#include <algorithm>
using namespace std;
int main() {
#ifndef ONLINE_JUDGE
freopen("/Users/TamLe/Documents/Input.txt", "rt", stdin);
#endif
long long n,k;
scanf("%I64d %I64d", &n, &k);
long long a = (n/2)/(k+1);
long long b = k*a;
long long c = n-(a+b);
printf("%I64d %I64d %I64d\n", a, b, c);
}
| [
"thanhtam.le@citynow.vn"
] | thanhtam.le@citynow.vn |
bf34390ec108c2ee0e4d6636f797992525b40991 | 770a91809c9859913f844f941d098b39635922fa | /sensors/SensorPca9685Led.h | a094a09f2404a74d39ec2fa23e659c8e0d7d66ed | [] | no_license | janjurca/NodeManager | 3439c952545f07c28a384980f1a549c0792a049d | 86364487f2dda1e3deddaa223c96c41d4655fd4e | refs/heads/master | 2023-08-04T11:06:18.024742 | 2021-09-13T19:48:48 | 2021-09-13T19:48:48 | 388,770,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,016 | h | /*
* The MySensors Arduino library handles the wireless radio link and protocol
* between your home built sensors/actuators and HA controller of choice.
* The sensors forms a self healing radio network with optional repeaters. Each
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
* network topology allowing messages to be routed to nodes.
*
* Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
* Copyright (C) 2013-2017 Sensnology AB
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
*
* Documentation: http://www.mysensors.org
* Support Forum: http://forum.mysensors.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*/
#ifndef SensorPca9685Led_h
#define SensorPca9685Led_h
/*
SensorPca9685Led
*/
#include <math.h>
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
class SensorPca9685Led {
protected:
Adafruit_PWMServoDriver* _pca9685;
bool _ownPca9685 = false;
uint8_t _i2c_addr = 0xFF;
int _pwm_ch = 0;
int _target_color = 0;
int _start_color = 0;
int _cur_color = 0;
unsigned long _start_time = 0;
int _status = OFF;
int _easing = EASE_LINEAR;
int _duration = 1000;
int _step_duration = 100;
public:
enum _easing_list {
EASE_LINEAR = 0,
EASE_INSINE = 1,
EASE_OUTSINE = 2,
EASE_INOUTSINE = 3
};
SensorPca9685Led(int channel = 0,uint8_t i2c_addr = 0x40, Adafruit_PWMServoDriver* pca9685 = NULL) {
_i2c_addr = i2c_addr;
_pwm_ch = channel;
// only create new ServoDriver if no one exists
if (pca9685 == NULL) {
_pca9685 = new Adafruit_PWMServoDriver(_i2c_addr);
_ownPca9685 = true;
} else {
_pca9685 = pca9685;
_ownPca9685 = false;
}
};
// setter/getter
void setEasing(int value) {
_easing = value;
};
void setDuration(int value) {
_duration = value;
};
void setStepDuration(int value) {
_step_duration = value;
};
// define what to do during setup
void onSetup() {
//only initialize PCA9685, if its ours
if (_ownPca9685) {
_pca9685->reset();
_pca9685->begin();
_pca9685->setPWMFreq(1600); // This is the maximum PWM frequency
_pca9685->setPWM(_pwm_ch, 0, 0); //set LED OFF; TODO: set all LED off
}
};
// set the LED value
void setVal(int value) {
// load fader with target colors 12bit (4095)
_target_color = value;
// load fader with start colors;
_start_color = _cur_color;
// load fader with start time
unsigned long current_time = millis();
_start_time = current_time;
debug(PSTR(LOG_SENSOR "_pwm_ch=%d _target_color=%d _start_color=%d\n"),_pwm_ch,_target_color,_start_color);
};
// set the LED value as HEX-String
void setValHex(String hexstring) {
//scale from 8bit to 12bit and call setVal
this->setVal((strtoul( hexstring.c_str(), NULL, 16) * 4095./255.));
};
// set the LED value as Percentage
void setValPercentage(int percentage) {
//scale from 100% to 12bit and call setVal
this->setVal(percentage * 4095./100.);
};
// get the LED value
int getVal() {
return _target_color;
};
// get the LED value as Percentage
int getValPercentage() {
return (_target_color * 100./4095.);
};
// get the LED value as Hex-String (8-bit)
String getValHex() {
return String((_target_color * 255./4095.),HEX);
};
void faderInc() {
int delta = 0;
unsigned long current_step = 0;
unsigned long current_time = millis();
//do nothing if start_time is smaller than current time OR if color already set
//TODO: Handle current_time resp millis() overflow
if ((current_time < _start_time) || (_target_color == _cur_color) ) return;
//fade within _duration
if((_start_time + _duration) > current_time) {
// calculate the delta between the target value and the current
delta = _target_color - _start_color;
//calculate current timestep for this fader
current_step = current_time - _start_time;
// calculate the smooth transition
_cur_color = (int)(_getEasing(current_step,_start_color,delta,_duration));
} else {
_cur_color = _target_color;
}
// write to the PWM output
_pca9685->setPWM(_pwm_ch, 0, _cur_color);
//makes fading very slow; only uncomment if necessary
// debug(PSTR(LOG_SENSOR "_pwm_ch=%d _target_color=%d _start_color=%d _start_time=%d current_time=%d current_step=%d _duration=%d value=%d\n"),_pwm_ch,_target_color,_start_color,_start_time,current_time,current_step,_duration,_cur_color);
};
// for smooth transitions. t: current time, b: beginning value, c: change in value, d: duration
float _getEasing(float t, float b, float c, float d) {
if (_easing == EASE_INSINE) return -c * cos(t/d * (M_PI/2)) + c + b;
else if (_easing == EASE_OUTSINE) return c * sin(t/d * (M_PI/2)) + b;
else if (_easing == EASE_INOUTSINE) return -c/2 * (cos(M_PI*t/d) - 1) + b;
else return c*t/d + b;
};
};
#endif | [
"noreply@github.com"
] | janjurca.noreply@github.com |
49222ff90b271d830a72611c852dab8f9e8c412d | 6260bd86db2e7a4ca329f0fb00aa57fc2720316d | /Pattern_C.cpp | 2040693b3b954c02d76b8c91d93f784678430f0b | [] | no_license | Raushankumar143/A-to-Z-Pattren | 58a5f495250cd24932c6ef729665b95c93b053a7 | 50c01f9e25f3fc42e9d9d171986c3cbcc953e730 | refs/heads/master | 2022-11-24T07:28:27.667252 | 2020-07-30T08:54:04 | 2020-07-30T08:54:04 | 283,718,068 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 381 | cpp | #include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter size:";
cin>>n;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==0||i==n-1||j==0)
{
cout<<"*";
}else{
cout<<" ";
}
}
cout<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | Raushankumar143.noreply@github.com |
c3c1229f72a9077abb3e285c4d049b3a2260ee98 | 0ee479c186a0b7b025d8847cb67235bd1b980ec9 | /Pi_semaforo_rtos/Pi_semaforo_rtos.ino | afaaba1aaf5b94dfb2a62887cbea82fbe6407bf1 | [] | no_license | gervasiogesse/Projeto-Integrador | 2c1a09d2079feca353b9f52901ea4ab7a1abbe8e | 186b6f4c98817e5511022e43f3e7d4de297d7c09 | refs/heads/master | 2020-09-14T06:38:29.520197 | 2019-12-18T01:39:03 | 2019-12-18T01:39:03 | 223,052,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,140 | ino | /*
* Autores: Gervasio Gesse Junior
* Iris menezes Barbosa
* Titulo: Projeto Integrador 6 bimestre Univesp Polo Jandira
* Data: 23 de Novembro de 2019
* Resumo: Semáforo com intervalo de tempo variável com
* sinalização sonora para ficlitar a travessia deficientes
* visuais e pessoas com mobilidade reduzida.
*/
#include <Arduino_FreeRTOS.h>
#include <semphr.h>
#include "string.h"
#include <SoftwareSerial.h>
//Define a saida para os leds
const int vermelho = 4;
const int amarelo = 5;
const int verde = 6;
const int p_vermelho = 7;
const int p_verde = 8;
const int botao = 2;
const int buzzer = 3;
//Define os pinos para a serial
SoftwareSerial mySerial(10, 11); // RX, TX
// Define a estrutura do semaforo
SemaphoreHandle_t xSerialSemaphore;
// Define buffer
char bufferPC[64] = {'\0'};
char bufferBT[64] = {'\0'};
// Define o tempo em segundos para os estados do semaforo
int t_vermelho = 10, t_amarelo = 10, t_verde = 10;
// Define as tasks
void TaskBlink( void *pvParameters );
void TaskSemaforoPrincipal( void *pvParameters );
void TaskComSerial( void *pvParameters );
void TaskBluetoothSerial( void *pvParameters );
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
mySerial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB, on LEONARDO, MICRO, YUN, and other 32u4 based boards.
}
if ( xSerialSemaphore == NULL ) // Verifica se o semaforo existe e se não existir cria
{
xSerialSemaphore = xSemaphoreCreateMutex(); // Cria um semaforo mutex
if ( ( xSerialSemaphore ) != NULL )
xSemaphoreGive( ( xSerialSemaphore ) ); // Libera o semaforo
}
if ( xSerialSemaphore != NULL )
{
//Cria as tasks de comunicacao
xTaskCreate(TaskComSerial, "ComSerial", 128, NULL, 2, NULL );
xTaskCreate(TaskBluetoothSerial, "BluetoothSerial", 128, NULL, 2, NULL );
}
else
{
Serial.println("**** Erro ao criar semaforo!");
}
// Now set up two tasks to run independently.
xTaskCreate(
TaskBlink
, (const portCHAR *)"Blink" // A name just for humans
, 128 // This stack size can be checked & adjusted by reading the Stack Highwater
, NULL
, 2 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
, NULL );
xTaskCreate(
TaskSemaforoPrincipal
, (const portCHAR *) "SemaforoPrincipal"
, 128 // Stack size
, NULL
, 2 // Priority
, NULL );
}
void loop() {
//Em branco. Tudo é feito pelas tasks do SO
}
/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/
void TaskBlink(void *pvParameters) // Task blink para teste.
{
(void) pvParameters;
// inicializa digital LED_BUILTIN interno no pino 13 como output.
pinMode(LED_BUILTIN, OUTPUT);
pinMode(botao, INPUT_PULLUP);
for (;;) // A Task shall never return or exit.
{
if(digitalRead(botao) == 0){
t_vermelho = 40;
digitalWrite(LED_BUILTIN, HIGH);
} else{
digitalWrite(LED_BUILTIN, HIGH); // liga o led interno
vTaskDelay( 200 / portTICK_PERIOD_MS ); // aguarda um segundo
digitalWrite(LED_BUILTIN, LOW); // desliga o led interno
vTaskDelay( 1800 / portTICK_PERIOD_MS ); // aguarda um segundo
}
}
}
void TaskComSerial(void *pvParameters)
{
(void) pvParameters;
char caractere;
int i=0;
for (;;)
{
//Trocar portMAX_DELAY por ( TickType_t ) 5 para ticks e deposi desistir
if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE )
{
// Enquanto receber algo pela serial
while(Serial.available() > 0) {
// Lê byte da serial PC
caractere = Serial.read();
// Serial.print("Recebi: ");
// Serial.println(caractere);
// Concatena valores
bufferPC[i] = caractere;
i++;
bufferPC[i]= '\0';
// Aguarda buffer serial ler próximo caractere
vTaskDelay(1);
}
i=0;
if(bufferBT[0] != '\0'){
Serial.println(bufferBT);
if(strncmp(bufferBT, "+DISC:SUCCESS", 13) == 0){
Serial.println("DesConectado");
}
if(strncmp(bufferBT, "OK", 2) == 0){
Serial.println("Conectado");
t_vermelho = 40;
}
}
bufferBT[0] = '\0';
xSemaphoreGive( xSerialSemaphore );
}
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void TaskBluetoothSerial(void *pvParameters)
{
(void) pvParameters;
char caractere;
int i=0;
for (;;)
{
//Trocar portMAX_DELAY por ( TickType_t ) 5 para ticks e deposi desistir
if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE )
{
// Enquanto receber algo pela serial
while(mySerial.available() > 0) {
// Lê byte da serial
caractere = mySerial.read();
Serial.print("Recebi BT: ");
Serial.println(caractere);
// Concatena valores
bufferBT[i] = caractere;
i++;
bufferBT[i]= '\0';
// Aguarda buffer serial ler próximo caractere
vTaskDelay(1);
}
i=0;
if(bufferPC[0] != '\0'){
mySerial.println(bufferPC);
Serial.println(bufferPC);
}
bufferPC[0] = '\0';
xSemaphoreGive( xSerialSemaphore );
}
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void TaskSemaforoPrincipal(void *pvParameters) // Task blink para teste.
{
(void) pvParameters;
// inicializa os pinos do leds que representam os estados.
pinMode(verde, OUTPUT);
pinMode(amarelo, OUTPUT);
pinMode(vermelho, OUTPUT);
pinMode(p_vermelho, OUTPUT);
pinMode(p_verde, OUTPUT);
pinMode(buzzer, OUTPUT);
int qtd=0;
for (;;) // A Task shall never return or exit.
{
digitalWrite(vermelho, LOW);
digitalWrite(verde, HIGH); // liga o led verde para carro
digitalWrite(p_vermelho, HIGH); //liga o led vermelho para pedestres
digitalWrite(p_verde, LOW);
vTaskDelay( t_verde * 1000 / portTICK_PERIOD_MS ); // Tempo do estado aberto carro
digitalWrite(verde, LOW);
digitalWrite(amarelo, HIGH);
vTaskDelay( t_amarelo * 1000 / portTICK_PERIOD_MS ); // Tempo do estado amarelo carro
digitalWrite(amarelo, LOW);
digitalWrite(p_vermelho, LOW);
digitalWrite(vermelho, HIGH);
digitalWrite(p_verde, HIGH);
qtd = (t_vermelho - 5)/2;
while(qtd > 0){
digitalWrite(buzzer, HIGH);
vTaskDelay( 1 * 500 / portTICK_PERIOD_MS );
digitalWrite(buzzer, LOW);
vTaskDelay( 2 * 1500 / portTICK_PERIOD_MS );
qtd = qtd - 1;
}
digitalWrite(p_verde, LOW);
for(int i=0; i < 5; i++){
digitalWrite(buzzer, HIGH);
digitalWrite(p_vermelho, HIGH);
vTaskDelay( 1 * 1000 / portTICK_PERIOD_MS );
digitalWrite(buzzer, LOW);
digitalWrite(p_vermelho, LOW);
vTaskDelay( 1 * 1000 / portTICK_PERIOD_MS );
}
// vTaskDelay( t_vermelho * 1000 / portTICK_PERIOD_MS ); // Tempo do estado vermelho carro
// Desliga flag
t_vermelho = 10;
}
}
| [
"gervasio.81@gmail.com"
] | gervasio.81@gmail.com |
ed7bc8e083c12884fded08dd6edf49f934cfca2a | aa049fc9c45ab0ee44a4f68ce456972fac36705f | /client/TxClient/withdraw.h | ad9aaab93dc28b5e8715752c2ad2626568ea6e71 | [] | no_license | yudi-matsuzake/tx | 3fca86912594a0a339d009ca561c93b9df6daef9 | 5cf42f096bff1ed228ab93011e0dc329601d708a | refs/heads/master | 2021-01-21T21:14:39.476972 | 2017-06-07T16:53:13 | 2017-06-07T16:53:13 | 92,320,591 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 400 | h | #ifndef WITHDRAW_H
#define WITHDRAW_H
#include <QString>
#include <QJsonObject>
class Withdraw
{
public:
Withdraw();
Withdraw(const int& account_id, const double& value, const QString& withdraw_method);
bool write(QJsonObject& json) const;
bool read(QJsonObject& json);
private:
static const QString JSON_TYPE;
int account_id;
double value;
QString withdraw_method;
};
#endif // WITHDRAW_H
| [
"paulor@alunos.utfpr.edu.br"
] | paulor@alunos.utfpr.edu.br |
e691de82570ec69293a0f4ccec8d311a9c5051d3 | fe2362eda423bb3574b651c21ebacbd6a1a9ac2a | /VTK-7.1.1/Views/Core/vtkDataRepresentation.cxx | bc3746092f4b461b34d9d4b4b89a62bb85fa672f | [
"BSD-3-Clause"
] | permissive | likewatchk/python-pcl | 1c09c6b3e9de0acbe2f88ac36a858fe4b27cfaaf | 2a66797719f1b5af7d6a0d0893f697b3786db461 | refs/heads/master | 2023-01-04T06:17:19.652585 | 2020-10-15T21:26:58 | 2020-10-15T21:26:58 | 262,235,188 | 0 | 0 | NOASSERTION | 2020-05-08T05:29:02 | 2020-05-08T05:29:01 | null | UTF-8 | C++ | false | false | 13,677 | cxx | /*=========================================================================
Program: Visualization Toolkit
Module: vtkDataRepresentation.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkDataRepresentation.h"
#include "vtkAlgorithmOutput.h"
#include "vtkAnnotationLayers.h"
#include "vtkAnnotationLink.h"
#include "vtkCommand.h"
#include "vtkConvertSelectionDomain.h"
#include "vtkDataObject.h"
#include "vtkDataSet.h"
#include "vtkDemandDrivenPipeline.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include "vtkTrivialProducer.h"
#include <map>
//---------------------------------------------------------------------------
// vtkDataRepresentation::Internals
//---------------------------------------------------------------------------
class vtkDataRepresentation::Internals {
public:
// This is a cache of shallow copies of inputs provided for convenience.
// It is a map from (port index, connection index) to (original input data port, shallow copy port).
// NOTE: The original input data port pointer is not reference counted, so it should
// not be assumed to be a valid pointer. It is only used for pointer comparison.
std::map<std::pair<int, int>,
std::pair<vtkAlgorithmOutput*, vtkSmartPointer<vtkTrivialProducer> > >
InputInternal;
// This is a cache of vtkConvertSelectionDomain filters provided for convenience.
// It is a map from (port index, connection index) to convert selection domain filter.
std::map<std::pair<int, int>, vtkSmartPointer<vtkConvertSelectionDomain> >
ConvertDomainInternal;
};
//---------------------------------------------------------------------------
// vtkDataRepresentation::Command
//----------------------------------------------------------------------------
class vtkDataRepresentation::Command : public vtkCommand
{
public:
static Command* New() { return new Command(); }
void Execute(vtkObject *caller, unsigned long eventId,
void *callData) VTK_OVERRIDE
{
if (this->Target)
{
this->Target->ProcessEvents(caller, eventId, callData);
}
}
void SetTarget(vtkDataRepresentation* t)
{
this->Target = t;
}
private:
Command() { this->Target = 0; }
vtkDataRepresentation* Target;
};
//----------------------------------------------------------------------------
// vtkDataRepresentation
//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkDataRepresentation);
vtkCxxSetObjectMacro(vtkDataRepresentation,
AnnotationLinkInternal, vtkAnnotationLink);
vtkCxxSetObjectMacro(vtkDataRepresentation, SelectionArrayNames, vtkStringArray);
//----------------------------------------------------------------------------
vtkTrivialProducer* vtkDataRepresentation::GetInternalInput(int port, int conn)
{
return this->Implementation->InputInternal[
std::pair<int, int>(port, conn)].second.GetPointer();
}
//----------------------------------------------------------------------------
void vtkDataRepresentation::SetInternalInput(int port, int conn,
vtkTrivialProducer* producer)
{
this->Implementation->InputInternal[std::pair<int, int>(port, conn)] =
std::pair<vtkAlgorithmOutput*, vtkSmartPointer<vtkTrivialProducer> >(
this->GetInputConnection(port, conn), producer);
}
//----------------------------------------------------------------------------
vtkDataRepresentation::vtkDataRepresentation()
{
this->Implementation = new vtkDataRepresentation::Internals();
// Listen to event indicating that the algorithm is done executing.
// We may need to clear the data object cache after execution.
this->Observer = Command::New();
this->AddObserver(vtkCommand::EndEvent, this->Observer);
this->Selectable = true;
this->SelectionArrayNames = vtkStringArray::New();
this->SelectionType = vtkSelectionNode::INDICES;
this->AnnotationLinkInternal = vtkAnnotationLink::New();
this->SetNumberOfOutputPorts(0);
}
//----------------------------------------------------------------------------
vtkDataRepresentation::~vtkDataRepresentation()
{
delete this->Implementation;
this->Observer->Delete();
this->SetSelectionArrayNames(0);
this->SetAnnotationLinkInternal(0);
}
//----------------------------------------------------------------------------
void vtkDataRepresentation::SetAnnotationLink(vtkAnnotationLink* link)
{
this->SetAnnotationLinkInternal(link);
}
//----------------------------------------------------------------------------
void vtkDataRepresentation::ProcessEvents(vtkObject *caller, unsigned long eventId, void *vtkNotUsed(callData))
{
// After the algorithm executes, if the release data flag is on,
// clear the input shallow copy cache.
if (caller == this && eventId == vtkCommand::EndEvent)
{
// Release input data if requested.
for (int i = 0; i < this->GetNumberOfInputPorts(); ++i)
{
for (int j = 0; j < this->GetNumberOfInputConnections(i); ++j)
{
vtkInformation* inInfo = this->GetExecutive()->GetInputInformation(i, j);
vtkDataObject* dataObject = inInfo->Get(vtkDataObject::DATA_OBJECT());
if (dataObject && (dataObject->GetGlobalReleaseDataFlag() ||
inInfo->Get(vtkDemandDrivenPipeline::RELEASE_DATA())))
{
std::pair<int, int> p(i, j);
this->Implementation->InputInternal.erase(p);
this->Implementation->ConvertDomainInternal.erase(p);
}
}
}
}
}
//----------------------------------------------------------------------------
vtkAlgorithmOutput* vtkDataRepresentation::GetInternalOutputPort(int port, int conn)
{
if (port >= this->GetNumberOfInputPorts() ||
conn >= this->GetNumberOfInputConnections(port))
{
vtkErrorMacro("Port " << port << ", connection "
<< conn << " is not defined on this representation.");
return 0;
}
// The cached shallow copy is out of date when the input data object
// changed, or the shallow copy modified time is less than the
// input modified time.
std::pair<int, int> p(port, conn);
vtkAlgorithmOutput* input = this->GetInputConnection(port, conn);
vtkDataObject* inputDObj = this->GetInputDataObject(port, conn);
if (this->Implementation->InputInternal.find(p) ==
this->Implementation->InputInternal.end() ||
this->Implementation->InputInternal[p].first != input ||
this->Implementation->InputInternal[p].second->GetMTime() < inputDObj->GetMTime())
{
this->Implementation->InputInternal[p].first = input;
vtkDataObject* copy = inputDObj->NewInstance();
copy->ShallowCopy(inputDObj);
vtkTrivialProducer* tp = vtkTrivialProducer::New();
tp->SetOutput(copy);
copy->Delete();
this->Implementation->InputInternal[p].second = tp;
tp->Delete();
}
return this->Implementation->InputInternal[p].second->GetOutputPort();
}
//----------------------------------------------------------------------------
vtkAlgorithmOutput* vtkDataRepresentation::GetInternalAnnotationOutputPort(
int port, int conn)
{
if (port >= this->GetNumberOfInputPorts() ||
conn >= this->GetNumberOfInputConnections(port))
{
vtkErrorMacro("Port " << port << ", connection "
<< conn << " is not defined on this representation.");
return 0;
}
// Create a new filter in the cache if necessary.
std::pair<int, int> p(port, conn);
if (this->Implementation->ConvertDomainInternal.find(p) ==
this->Implementation->ConvertDomainInternal.end())
{
this->Implementation->ConvertDomainInternal[p] =
vtkSmartPointer<vtkConvertSelectionDomain>::New();
}
// Set up the inputs to the cached filter.
vtkConvertSelectionDomain* domain = this->Implementation->ConvertDomainInternal[p];
domain->SetInputConnection(0,
this->GetAnnotationLink()->GetOutputPort(0));
domain->SetInputConnection(1,
this->GetAnnotationLink()->GetOutputPort(1));
domain->SetInputConnection(2,
this->GetInternalOutputPort(port, conn));
// Output port 0 of the convert domain filter is the linked
// annotation(s) (the vtkAnnotationLayers object).
return domain->GetOutputPort();
}
//----------------------------------------------------------------------------
vtkAlgorithmOutput* vtkDataRepresentation::GetInternalSelectionOutputPort(
int port, int conn)
{
// First make sure the convert domain filter is up to date.
if (!this->GetInternalAnnotationOutputPort(port, conn))
{
return 0;
}
// Output port 1 of the convert domain filter is the current selection
// that was contained in the linked annotation.
std::pair<int, int> p(port, conn);
if (this->Implementation->ConvertDomainInternal.find(p) !=
this->Implementation->ConvertDomainInternal.end())
{
return this->Implementation->ConvertDomainInternal[p]->GetOutputPort(1);
}
return NULL;
}
//----------------------------------------------------------------------------
void vtkDataRepresentation::Select(
vtkView* view, vtkSelection* selection, bool extend)
{
if (this->Selectable)
{
vtkSelection* converted = this->ConvertSelection(view, selection);
if (converted)
{
this->UpdateSelection(converted, extend);
if (converted != selection)
{
converted->Delete();
}
}
}
}
//----------------------------------------------------------------------------
vtkSelection* vtkDataRepresentation::ConvertSelection(
vtkView* vtkNotUsed(view), vtkSelection* selection)
{
return selection;
}
//----------------------------------------------------------------------------
void vtkDataRepresentation::UpdateSelection(vtkSelection* selection, bool extend)
{
if (extend)
{
selection->Union(this->AnnotationLinkInternal->GetCurrentSelection());
}
this->AnnotationLinkInternal->SetCurrentSelection(selection);
this->InvokeEvent(vtkCommand::SelectionChangedEvent, reinterpret_cast<void*>(selection));
}
//----------------------------------------------------------------------------
void vtkDataRepresentation::Annotate(
vtkView* view, vtkAnnotationLayers* annotations, bool extend)
{
vtkAnnotationLayers* converted = this->ConvertAnnotations(view, annotations);
if (converted)
{
this->UpdateAnnotations(converted, extend);
if (converted != annotations)
{
converted->Delete();
}
}
}
//----------------------------------------------------------------------------
vtkAnnotationLayers* vtkDataRepresentation::ConvertAnnotations(
vtkView* vtkNotUsed(view), vtkAnnotationLayers* annotations)
{
return annotations;
}
//----------------------------------------------------------------------------
void vtkDataRepresentation::UpdateAnnotations(vtkAnnotationLayers* annotations, bool extend)
{
if (extend)
{
// Append the annotations to the existing set of annotations on the link
vtkAnnotationLayers* currentAnnotations = this->AnnotationLinkInternal->GetAnnotationLayers();
for(unsigned int i=0; i<annotations->GetNumberOfAnnotations(); ++i)
{
currentAnnotations->AddAnnotation(annotations->GetAnnotation(i));
}
this->InvokeEvent(vtkCommand::AnnotationChangedEvent, reinterpret_cast<void*>(currentAnnotations));
}
else
{
this->AnnotationLinkInternal->SetAnnotationLayers(annotations);
this->InvokeEvent(vtkCommand::AnnotationChangedEvent, reinterpret_cast<void*>(annotations));
}
}
//----------------------------------------------------------------------------
void vtkDataRepresentation::SetSelectionArrayName(const char* name)
{
if (!this->SelectionArrayNames)
{
this->SelectionArrayNames = vtkStringArray::New();
}
this->SelectionArrayNames->Initialize();
this->SelectionArrayNames->InsertNextValue(name);
}
//----------------------------------------------------------------------------
const char* vtkDataRepresentation::GetSelectionArrayName()
{
if (this->SelectionArrayNames &&
this->SelectionArrayNames->GetNumberOfTuples() > 0)
{
return this->SelectionArrayNames->GetValue(0);
}
return 0;
}
//----------------------------------------------------------------------------
void vtkDataRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "AnnotationLink: " << (this->AnnotationLinkInternal ? "" : "(null)") << endl;
if (this->AnnotationLinkInternal)
{
this->AnnotationLinkInternal->PrintSelf(os, indent.GetNextIndent());
}
os << indent << "Selectable: " << this->Selectable << endl;
os << indent << "SelectionType: " << this->SelectionType << endl;
os << indent << "SelectionArrayNames: " << (this->SelectionArrayNames ? "" : "(null)") << endl;
if (this->SelectionArrayNames)
{
this->SelectionArrayNames->PrintSelf(os, indent.GetNextIndent());
}
}
| [
"likewatchk@gmail.com"
] | likewatchk@gmail.com |
bca4be2272a4e895b122e7a049507646263ab59a | da659b9c71a3c89a71f1639669da93e315edb198 | /Compactador-Huffman/comdeshuff/tcell.h | 98f4cf84a77116aec493647d2ec346b18d4c6a41 | [] | no_license | amg1127/PROGRAMAS-DA-FACULDADE | 941b732f1abc1c2b8859dd2b8f1ce5e580183153 | 48efcdb52e6a165d6980406909b3501212c0d2c4 | refs/heads/master | 2020-05-17T19:56:39.930515 | 2020-02-17T11:55:04 | 2020-02-17T11:55:04 | 183,930,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,674 | h | class TCell {
private:
int _id;
int _weight;
char _character;
TCell *_parent;
TCell *_son0;
TCell *_son1;
bool _hasSons;
std::string _pathToSon (TCell *);
template <typename SWPTYPE>
inline void swapvar (SWPTYPE &v1, SWPTYPE &v2) { SWPTYPE aux; aux=v1; v1=v2; v2=aux; }
public:
TCell (TCell * = NULL);
~TCell ();
int id (void);
void setId (int);
char character (void);
void setCharacter (char);
int weight ();
void setWeight (int);
int distanceToRoot (void);
int maxDistanceToSons (void);
bool isRoot (void);
bool hasSons (void);
void killSons (void);
void makeSons (void);
TCell *son0 (void);
TCell *son1 (void);
TCell *son (int);
TCell *parent (void);
TCell *root (void);
TCell *findSonByWeight (int);
TCell *findSonById (int);
TCell *findSonByCharacter (char);
TCell *findSonByPath (std::string);
TCell *self (void);
std::string pathFromRootToMe (void);
std::string pathToSon (TCell &);
std::string pathToSon (TCell *);
bool isSonOf (TCell &);
bool isSonOf (TCell *);
bool isParentOf (TCell &);
bool isParentOf (TCell *);
void swap (TCell &, bool = false);
void swap (TCell *, bool = false);
void copyFrom (TCell &, bool = false);
void copyFrom (TCell *, bool = false);
void copyTo (TCell &, bool = false);
void copyTo (TCell *, bool = false);
std::string dump (int = 0);
};
| [
"amg1127@5465fe1f-e9f4-4a51-a9b0-42098c041c11"
] | amg1127@5465fe1f-e9f4-4a51-a9b0-42098c041c11 |
f466f3f46c747c7cf2cc4a2a55c61133767947a6 | 719bcf0ec862bed0416c6a4d78ef03f1191f608b | /01.计算机基础知识/05.设计模式/04.行为型模式/08.访问者模式/c++/ComputerPart.h | ef0c52d40d0aaf80ad7b529c40f8d0cfc154a8bd | [] | no_license | cleveryuan777/C-background-development-interview-experience | d16e73efd08d020e3db2b7c3f718394b1806f2b3 | 48c1f22ea431a36288b73bc53e8573f828eed88c | refs/heads/main | 2023-06-14T05:04:55.013084 | 2021-04-04T14:19:56 | 2021-04-04T14:19:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | h | #pragma once
class ComputerPartVisitor;
class ComputerPart
{
public:
ComputerPart();
virtual void accept(ComputerPartVisitor* computerPartVisitor) = 0;
virtual ~ComputerPart();
};
| [
"jackster@163.com"
] | jackster@163.com |
6b051b551d2e3aa7abe399710d0706d2748df7eb | 4cd434f48bf76da03503130cb3e9d8611a29a659 | /iTrace/CinematicCamera.cpp | ef9ee7b22502c3b7c107db646b011d6f7f4053c1 | [
"MIT"
] | permissive | Ruixel/iTrace | 39d593856f89664d9c42e570369af146e2098713 | 07e31bb60acba03bc6523986233f16191c502682 | refs/heads/master | 2022-12-22T13:44:10.535266 | 2020-10-01T22:43:41 | 2020-10-01T22:43:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,035 | cpp | #include "CinematicCamera.h"
#include <unordered_map>
#include "CommandPusher.h"
#include <iostream>
namespace iTrace {
namespace Rendering {
std::unordered_map<std::string, KeyFrame> KeyFrames;
std::unordered_map<std::string, Animation> Animations;
Animation* PlayingAnimation = nullptr;
std::vector<std::string> KeyFrameCommand(std::vector<std::string> Input)
{
auto ParseInterpolationMode = [](std::string& Text) {
if (Text == "linear") {
return InterpolationMode::LINEAR;
}
else if (Text == "sine") {
return InterpolationMode::SINE;
}
else {
return InterpolationMode::NONE;
}
};
if (Input.size() == 0) {
return { "Not enough data provided for keyframe command" };
}
if (Input[0] == ">help") {
//todo: write help text (probably needs to be pretty long)
return { "temporary help text" };
}
if (Input.size() < 2) {
return { "Not enough data provided for keyframe command" };
}
if (Input[0] == "add") {
if (Input.size() < 4) {
return { "Not enough data provided for keyframe command" };
}
std::string& Name = Input[1];
if (KeyFrames.find(Name) == KeyFrames.end()) {
KeyFrame ToAddKeyFrame;
ToAddKeyFrame.FirstHalf = ParseInterpolationMode(Input[2]);
ToAddKeyFrame.SecondHalf = ParseInterpolationMode(Input[3]);
if (ToAddKeyFrame.FirstHalf == NONE || ToAddKeyFrame.SecondHalf == NONE) {
return { "incorrect interpolation mode has been used", "available modes are: linear and sine" };
}
ToAddKeyFrame.Position = std::any_cast<Vector3f>(GetGlobalCommandPusher().GivenConstantData["camera_pos"]);
ToAddKeyFrame.Rotation = glm::mod(std::any_cast<Vector3f>(GetGlobalCommandPusher().GivenConstantData["camera_rot"]),360.f);
ToAddKeyFrame.Fov = std::any_cast<float>(GetGlobalCommandPusher().GivenConstantData["camera_fov"]);
KeyFrames[Name] = ToAddKeyFrame;
return { "Added keyframe: " + Name };
}
else {
return { "There is already a keyframe with the name: " + Name,
"if you wish to modify this keyframe, use 'keyframe modify [...]' instead" };
}
}
else if (Input[0] == "remove") {
std::string& Name = Input[1];
if (KeyFrames.find(Name) == KeyFrames.end()) {
return { "Could not find keyframe called: " + Name };
}
else {
KeyFrames.erase(Name);
}
}
else if (Input[0] == "modify") {
if (Input.size() < 4) {
return { "Not enough data provided for keyframe command" };
}
std::string& Name = Input[1];
if (KeyFrames.find(Name) == KeyFrames.end()) {
return { "Could not find keyframe called: " + Name };
}
}
else {
return { Input[0] + " is not a correct syntax for the keyframe command, see keyframe >help" };
}
return std::vector<std::string>();
}
std::vector<std::string> AnimationCommand(std::vector<std::string> Input)
{
if (Input.size() < 1) {
return { "Not enough data provided for animation command" };
}
if (Input[0] == ">help") {
return { "temporary help text" };
}
if (Input[0] == "add") {
if (Input.size() < 2) {
return { "Not enough data provided for animation command" };
}
auto& Name = Input[1];
Animation ToAddAnimation;
if (Animations.find(Name) == Animations.end()) {
//parse keyframes + keyframe timings
for (int i = 0; i < (Input.size() - 2) / 2; i++) {
auto& KeyFrameName = Input[i * 2 + 2];
float KeyFrameTiming;
AnimationKeyFrame AnimationKeyFrame;
if (KeyFrames.find(KeyFrameName) == KeyFrames.end()) {
return { "No keyframe with the name: " + KeyFrameName };
}
if (Core::SafeParseFloat(Input[i * 2 + 3], KeyFrameTiming)) {
auto& KeyFrame = KeyFrames[KeyFrameName];
AnimationKeyFrame = KeyFrame;
AnimationKeyFrame.Time = ToAddAnimation.LatestTime + KeyFrameTiming;
}
else {
return { "Failed to parse timing: " + Input[i * 2 + 3] };
}
ToAddAnimation.KeyFrames.push_back(AnimationKeyFrame);
ToAddAnimation.LatestTime += KeyFrameTiming;
}
Animations[Name] = ToAddAnimation;
return { "Added animation: " + Name };
}
else {
return { "There already exists an animation called: " + Name };
}
}
else if (Input[0] == "play") {
if (Input.size() < 2) {
return { "Not enough data provided for animation command" };
}
auto& Name = Input[1];
if (Animations.find(Name) == Animations.end()) {
return { "No animation called: " + Name };
}
else {
PlayingAnimation = &Animations[Name];
//ideally integrate some kind of safety here to ensure you cannot remove
//a playing animation
return { "Now playing animation: " + Name };
}
}
}
bool PollAnimation(Camera& Camera, Window& Window)
{
if (PlayingAnimation == nullptr) {
return false;
}
else {
PlayingAnimation->TimeInAnimation += Window.GetFrameTime();
if (PlayingAnimation->TimeInAnimation >= PlayingAnimation->LatestTime) {
PlayingAnimation->TimeInAnimation = 0.0;
PlayingAnimation->ActiveKeyFrame = 0;
PlayingAnimation = nullptr;
return false;
}
//begin by interpolating only the positions!
while (PlayingAnimation->TimeInAnimation >= PlayingAnimation->KeyFrames[PlayingAnimation->ActiveKeyFrame].Time) {
PlayingAnimation->ActiveKeyFrame++;
}
if (PlayingAnimation->ActiveKeyFrame == 0) {
Camera.Position = PlayingAnimation->KeyFrames[0].Position;
Camera.Rotation = PlayingAnimation->KeyFrames[0].Rotation;
Camera.fov = PlayingAnimation->KeyFrames[0].Fov;
Camera.Project = glm::perspective(glm::radians(Camera.fov), float(Window.GetResolution().x) / float(Window.GetResolution().y), Camera.znear, Camera.zfar);
}
else {
int KeyFrameIdx = PlayingAnimation->ActiveKeyFrame;
auto& CurrentKeyFrame = PlayingAnimation->KeyFrames[KeyFrameIdx - 1];
auto& NextKeyFrame = PlayingAnimation->KeyFrames[KeyFrameIdx];
float Interpolation = (PlayingAnimation->TimeInAnimation - CurrentKeyFrame.Time) / (NextKeyFrame.Time - CurrentKeyFrame.Time);
//for now, linear!
Interpolation = 1.0 - (sin(Interpolation * 3.14159265 + 1.570796) * 0.5 + 0.5);
Camera.Position = glm::mix(CurrentKeyFrame.Position, NextKeyFrame.Position, Interpolation);
Camera.fov = glm::mix(CurrentKeyFrame.Fov, NextKeyFrame.Fov, Interpolation);
auto MixRotation = [](float a, float b, float interp) {
float dist = abs(a - b);
if (dist > 180.0) {
//we need to use the different direction!
//one of our angles needs to be converted!
if (a > 180.0 && b < 180.0) {
//here we use an example, a is 350 degrees,
//and b is 10 degrees
//here b should be converted to 370 degrees,
//and then it should be interpolated
b = b + 360.0;
return glm::mod(glm::mix(a, b, interp), 360.f);
}
else {
//here we use an example, a is 10 degrees,
//and b is 350 degrees
//here a should be converted to 370 degrees,
//and then it should be interpolated
a = a + 360.0;
return glm::mod(glm::mix(a, b, interp), 360.f);
}
}
else {
return glm::mix(a, b, interp);
}
};
Camera.Rotation = Vector3f(
MixRotation(CurrentKeyFrame.Rotation.x, NextKeyFrame.Rotation.x, Interpolation),
MixRotation(CurrentKeyFrame.Rotation.y, NextKeyFrame.Rotation.y, Interpolation),
MixRotation(CurrentKeyFrame.Rotation.z, NextKeyFrame.Rotation.z, Interpolation)
);
Camera.Project = glm::perspective(glm::radians(Camera.fov), float(Window.GetResolution().x) / float(Window.GetResolution().y), Camera.znear, Camera.zfar);
}
return true;
}
}
}
} | [
"420iblazeitcopswontfindme@gmail.com"
] | 420iblazeitcopswontfindme@gmail.com |
6c19f429bb84e5bfc1f4e2d9e989c38712c7ec90 | dfb83f9e1d2a64e719c3d61004b25650f372f5a2 | /src/compiler/simplified-lowering.h | 19b98109671f18d0c6f7b0c0ae8b4237d24df1df | [] | no_license | kingland/v8-MinGW | 8ae0a89ebe9ad022bd88612f7e38398cfd50287e | 83c03915b0005faf60a517b7fe1938c08dd44d18 | refs/heads/master | 2021-01-10T08:27:14.667611 | 2015-10-01T04:17:59 | 2015-10-01T04:17:59 | 43,477,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,392 | h | // Copyright 2014 the V8 project 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 V8_COMPILER_SIMPLIFIED_LOWERING_H_
#define V8_COMPILER_SIMPLIFIED_LOWERING_H_
#include "compiler/graph-reducer.h"
#include "compiler/js-graph.h"
#include "compiler/lowering-builder.h"
#include "compiler/machine-operator.h"
#include "compiler/node.h"
#include "compiler/simplified-operator.h"
namespace v8 {
namespace internal {
namespace compiler {
class SimplifiedLowering : public LoweringBuilder {
public:
explicit SimplifiedLowering(JSGraph* jsgraph,
SourcePositionTable* source_positions)
: LoweringBuilder(jsgraph->graph(), source_positions),
jsgraph_(jsgraph),
machine_(jsgraph->zone()) {}
virtual ~SimplifiedLowering() {}
void LowerAllNodes();
virtual void Lower(Node* node);
void LowerChange(Node* node, Node* effect, Node* control);
// TODO(titzer): These are exposed for direct testing. Use a friend class.
void DoLoadField(Node* node);
void DoStoreField(Node* node);
void DoLoadElement(Node* node);
void DoStoreElement(Node* node);
private:
JSGraph* jsgraph_;
MachineOperatorBuilder machine_;
Node* SmiTag(Node* node);
Node* IsTagged(Node* node);
Node* Untag(Node* node);
Node* OffsetMinusTagConstant(int32_t offset);
Node* ComputeIndex(const ElementAccess& access, Node* index);
void DoChangeTaggedToUI32(Node* node, Node* effect, Node* control,
bool is_signed);
void DoChangeUI32ToTagged(Node* node, Node* effect, Node* control,
bool is_signed);
void DoChangeTaggedToFloat64(Node* node, Node* effect, Node* control);
void DoChangeFloat64ToTagged(Node* node, Node* effect, Node* control);
void DoChangeBoolToBit(Node* node, Node* effect, Node* control);
void DoChangeBitToBool(Node* node, Node* effect, Node* control);
friend class RepresentationSelector;
Zone* zone() { return jsgraph_->zone(); }
JSGraph* jsgraph() { return jsgraph_; }
Graph* graph() { return jsgraph()->graph(); }
CommonOperatorBuilder* common() { return jsgraph()->common(); }
MachineOperatorBuilder* machine() { return &machine_; }
};
} // namespace compiler
} // namespace internal
} // namespace v8
#endif // V8_COMPILER_SIMPLIFIED_LOWERING_H_
| [
"sarayu.noo@gmail.com"
] | sarayu.noo@gmail.com |
c8979234267967df51c34d1f6320764989876a01 | 6054718314d0c98d8c8e8296e9f331fcb114ffae | /RenderToScreen.cpp | 3abe799f889dede59ddf38d1ea530685a8eeb8d6 | [
"MIT"
] | permissive | paleahn/ROIW_based-Raytracer | b00e21276f7a5aa496047fc801afaf006017d8d0 | 70499e2a4a0f1d12a4ca18909819026dbf2ac49e | refs/heads/master | 2022-04-23T18:52:23.846410 | 2020-04-25T16:21:55 | 2020-04-25T16:21:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,356 | cpp | #include "RenderToScreen.h"
#include "Logger.h"
#include <cstdint>
union color
{
struct
{
uint8_t b, g, r, a;
};
uint8_t data[4];
};
#pragma region WINDOW DISPLAY
//base code for window display provided Tommi Lipponen
#define WIN32_LEAN_AND_MEAN 1
#include <Windows.h>
#include <stdio.h>
struct RenderTarget {
HDC device;
int width;
int height;
unsigned *data;
BITMAPINFO info;
RenderTarget(HDC givenDevice, int width, int height)
: device(givenDevice), width(width), height(height), data(nullptr)
{
data = new unsigned[unsigned int(width * height)];
info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth = width;
info.bmiHeader.biHeight = height;
info.bmiHeader.biPlanes = 1;
info.bmiHeader.biBitCount = 32;
info.bmiHeader.biCompression = BI_RGB;
}
~RenderTarget() { delete[] data; }
inline int size() const {
return width * height;
}
void clear(unsigned color) {
const int count = size();
for (int i = 0; i < count; i++) {
data[i] = color;
}
}
inline void pixel(int x, int y, unsigned color) {
data[y * width + x] = color;
}
void present() {
StretchDIBits(device,
0, 0, width, height,
0, 0, width, height,
data, &info,
DIB_RGB_COLORS, SRCCOPY);
}
};
static unsigned
makeColor(unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha)
{
unsigned result = 0;
if (alpha > 0)
{
result |= ((unsigned)red << 16);
result |= ((unsigned)green << 8);
result |= ((unsigned)blue << 0);
result |= ((unsigned)alpha << 24);
}
return result;
}
static LRESULT CALLBACK
Win32DefaultProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
switch (message) {
case WM_CLOSE: { PostQuitMessage(0); } break;
default: { return DefWindowProcA(window, message, wparam, lparam); } break;
}
return 0;
}
#pragma endregion
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0L;
default:
return DefWindowProcW(hWnd, message, wParam, lParam);
}
}
RenderToScreen::RenderToScreen(color *image, size_t width, size_t height, const char *title) : width(width), height(height), rt(nullptr), title(title)
{
const char *const myclass = "minimalWindowClass";
WNDCLASSEXA wc = {};
wc.cbSize = sizeof(wc);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = DefWindowProc;
wc.hInstance = GetModuleHandle(0);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszClassName = myclass;
if (RegisterClassExA(&wc))
{
DWORD window_style = (WS_OVERLAPPEDWINDOW & ~(WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
RECT rc = { 0, 0, width, height };
if (!AdjustWindowRect(&rc, window_style, FALSE))
{
Logger::LogError("Couldn't show the image : window rect adjustment failed!");
return;
}
HWND windowHandleA = CreateWindowExA(0, wc.lpszClassName,
title, window_style, CW_USEDEFAULT, CW_USEDEFAULT,
rc.right - rc.left, rc.bottom - rc.top, 0, 0, GetModuleHandle(NULL), NULL);
if (!windowHandleA) { Logger::LogError("Couldn't show the image : window handle creation was unsuccessful!"); return; }
ShowWindow(windowHandleA, SW_SHOW);
if (windowHandleA)
{
HDC device = GetDC(windowHandleA);
rt = new RenderTarget(device, width, height);
rt->clear(makeColor(0x00,0x00,0x00,0xff));
} else
{
Logger::LogError("Couldn't show the image : Couldn't create the window!");
}
} else
{
Logger::LogError("Couldn't show the image : Could not register window class!");
}
}
RenderToScreen::~RenderToScreen()
{
delete rt;
}
void RenderToScreen::handleMessagesBlocking()
{
MSG msg;
while(GetMessage(&msg, 0, 0, 0))
{
if (msg.message == WM_QUIT) { return; }
TranslateMessage(&msg);
DispatchMessage(&msg);
rt->present();
}
}
void RenderToScreen::updateImage(color *image)
{
if (rt == nullptr) return;
for (size_t y = 0; y < height; y++)
for (size_t x = 0; x < width; x++)
{
color ¤tColor = image[y * width + x];
rt->pixel(x, y, makeColor(currentColor.r, currentColor.g, currentColor.b, currentColor.a));
}
rt->present();
}
| [
"clepirelli@gmail.com"
] | clepirelli@gmail.com |
9914d119815417fe48f668f1b5ed2d527a44dd6c | c45ed46065d8b78dac0dd7df1c95b944f34d1033 | /TC-SRM-576-div1-256/xhk.cpp | 48d9ed3bf6e404793f85e3035da26df51d3081be | [] | no_license | yzq986/cntt2016-hw1 | ed65a6b7ad3dfe86a4ff01df05b8fc4b7329685e | 12e799467888a0b3c99ae117cce84e8842d92337 | refs/heads/master | 2021-01-17T11:27:32.270012 | 2017-01-26T03:23:22 | 2017-01-26T03:23:22 | 84,036,200 | 0 | 0 | null | 2017-03-06T06:04:12 | 2017-03-06T06:04:12 | null | UTF-8 | C++ | false | false | 3,388 | cpp | // BEGIN CUT HERE
// END CUT HERE
#line 5 "ArcadeManao.cpp"
#include<bits/stdc++.h>
using namespace std;
int n,m,sx,sy;
int a[110][110],fa[10010];
int id(int x,int y)
{return (x-1)*m+y;
}
int find(int i)
{return fa[i]==i?i:fa[i]=find(fa[i]);
}
class ArcadeManao
{ public:
int shortestLadder(vector <string> level, int coinRow, int coinColumn)
{ int i,j,p,fx,fy;
n=level.size();
m=level[0].length();
sx=coinRow;
sy=coinColumn;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
a[i][j]=(level[i-1][j-1]=='X'?1:0);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
fa[id(i,j)]=id(i,j);
for(i=1;i<=n;i++)
for(j=1;j<m;j++)
if(a[i][j] && a[i][j+1])
{ fx=find(id(i,j));
fy=find(id(i,j+1));
if(fx!=fy)
fa[fx]=fy;
}
for(p=1;p<=n;p++)
{ if(find(id(n,1))==find(id(sx,sy))) return p-1;
for(j=1;j<=m;j++)
for(i=1;i+p<=n;i++)
{ if(!a[i][j] || !a[i+p][j]) continue;
fx=find(id(i,j));
fy=find(id(i+p,j));
if(fx!=fy) fa[fx]=fy;
}
}
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"XXXX....",
"...X.XXX",
"XXX..X..",
"......X.",
"XXXXXXXX"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 4; int Arg3 = 2; verify_case(0, Arg3, shortestLadder(Arg0, Arg1, Arg2)); }
void test_case_1() { string Arr0[] = {"XXXX",
"...X",
"XXXX"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 1; int Arg3 = 1; verify_case(1, Arg3, shortestLadder(Arg0, Arg1, Arg2)); }
void test_case_2() { string Arr0[] = {"..X..",
".X.X.",
"X...X",
".X.X.",
"..X..",
"XXXXX"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 3; int Arg3 = 4; verify_case(2, Arg3, shortestLadder(Arg0, Arg1, Arg2)); }
void test_case_3() { string Arr0[] = {"X"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 1; int Arg3 = 0; verify_case(3, Arg3, shortestLadder(Arg0, Arg1, Arg2)); }
void test_case_4() { string Arr0[] = {"XXXXXXXXXX",
"...X......",
"XXX.......",
"X.....XXXX",
"..XXXXX..X",
".........X",
".........X",
"XXXXXXXXXX"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 1; int Arg3 = 2; verify_case(4, Arg3, shortestLadder(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{ ArcadeManao ___test;
___test.run_test(-1);
return 0;
}
// END CUT HERE
| [
"noreply@github.com"
] | yzq986.noreply@github.com |
c2e54c22d8ac1eacc6eb7b461133b6f1164c1580 | 95033e45e9abcc2316ed8c2cf4b7c5077beacd62 | /core/osd/ClockDevice.h | 04d51ce35ec2e758da5097d1827a39a2de27a8d3 | [] | no_license | zeromus/bliss32 | 5083ae05298962cf55d77396f1ad0a4a68e96e33 | 7a41f9d051c7e2ead21b4b1ed009935449b17d16 | refs/heads/master | 2016-09-01T18:02:18.309718 | 2015-06-17T22:12:06 | 2015-06-17T22:12:06 | 5,157,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 247 | h |
#ifndef CLOCKDEVICE_H
#define CLOCKDEVICE_H
#include "types.h"
#include "Device.h"
class ClockDevice : public Device
{
public:
virtual INT64 getTickFrequency() = 0;
virtual INT64 getTick() = 0;
};
#endif
| [
"zeromus@zeromus.org"
] | zeromus@zeromus.org |
19ac5e384467acbcc86d92914909e001e00a65ca | 40d5773ad01d383dc6f03b293859925e87711810 | /factory/factory2.h | a1e146939735716007e14edd9aec2121a49732ac | [] | no_license | luoyouchun/DesignPatten | 3bc2f0a89fc995b87b0d7369ccc5aee51c2efe0d | fc3f7e0756c5868dc100f908a6c75143cc8f1666 | refs/heads/master | 2020-04-17T10:18:12.047018 | 2019-01-31T09:15:46 | 2019-01-31T09:15:46 | 166,495,963 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,171 | h | #pragma once
#include <map>
#include <string>
#include <functional>
#include <memory>
template<typename P>
struct factory2
{
template<typename T>
struct register_t
{
register_t(const std::string& key)
{
factory2::get().map_.emplace(key, ®ister_t<T>::create);
}
inline static P* create() { return new T; }
};
inline P* produce(const std::string& key)
{
if (map_.find(key) == map_.end())
throw std::invalid_argument("the product key is not exist!");
return map_[key]();
}
std::unique_ptr<P> produce_unique(const std::string& key)
{
return std::unique_ptr<P>(produce(key));
}
std::shared_ptr<P> produce_shared(const std::string& key)
{
return std::shared_ptr<P>(produce(key));
}
typedef P*(*FunPtr)();
inline static factory2& get()
{
static factory2 instance;
return instance;
}
private:
factory2() {};
factory2(const factory2&) = delete;
factory2(factory2&&) = delete;
std::map<std::string, FunPtr> map_;
};
#define REGISTER_PRODUCT_VNAME(T) reg_product_##T##_
#define REGISTER_PRODUCT(T, key) static factory2<T>::register_t<T> REGISTER_PRODUCT_VNAME(T)(key); | [
"chinaluo_007@163.com"
] | chinaluo_007@163.com |
e72a2c65edf89f10ad353e538bcb233101f954e6 | d2dd6b45c6e6ac4fcc0f7aa34bc044615d3f42ce | /src/para/thread/thread_pool_test.cc | 7257a608d6c97c6b7868b92844b0bbd6dfa1229e | [
"MIT"
] | permissive | wzheng21/libpara | 50c92eed7f323d055871a7c30646c6bae21fcee7 | 25598bf4ba2407d4f9af50a2e9a49a6b5658fafe | refs/heads/main | 2023-06-05T04:06:49.149237 | 2021-06-19T00:30:26 | 2021-06-19T00:30:26 | 343,213,140 | 0 | 0 | MIT | 2021-06-19T00:30:27 | 2021-02-28T20:58:10 | C++ | UTF-8 | C++ | false | false | 527 | cc | // Copyright (c) 2021
// Authors: Weixiong (Victor) Zheng
// All rights reserved
//
// SPDX-License-Identifier: MIT
#include "para/thread/thread_pool.h"
#include "para/base/time.h"
#include "para/testing/testing.h"
#include "glog/logging.h"
namespace para {
TEST(SimpleThreadPool, Basic) {
SimpleThreadPool pool(2);
for (int i = 1; i <= 5; ++i) {
pool.Submit([i](){
LOG(INFO) << "Sleep, Thread " << i;
SleepForSeconds(1.);
LOG(INFO) << "Wake up, Thread " << i;
});
}
}
} // namespace para
| [
"zwxne2010@gmail.com"
] | zwxne2010@gmail.com |
cc2b95e4cd0e3d00ce662e4723d3e07de8caa6f3 | 577491f76e130d0fc757f011834691c6aa635051 | /Sources/Devices/Instance.cpp | 2cb63e0471429ae04e8346e632af47ed0a6538fa | [
"MIT"
] | permissive | opencollective/Acid | e627b082046e0148aaf7e2a8667fdd22df34235b | 0e1ed9605c4cddb89f92c2daeaa70ec512ce23f3 | refs/heads/master | 2023-08-26T13:26:36.840191 | 2019-09-21T05:30:22 | 2019-09-21T05:30:22 | 210,002,966 | 0 | 1 | null | 2019-09-21T14:51:39 | 2019-09-21T14:51:38 | null | UTF-8 | C++ | false | false | 6,913 | cpp | #include "Instance.hpp"
#include "Graphics/Graphics.hpp"
#include "Window.hpp"
#if !defined(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)
#define VK_EXT_DEBUG_UTILS_EXTENSION_NAME "VK_EXT_debug_utils"
#endif
namespace acid {
const std::vector<const char *> Instance::ValidationLayers = {"VK_LAYER_LUNARG_standard_validation"}; // "VK_LAYER_RENDERDOC_Capture"
const std::vector<const char *> Instance::InstanceExtensions = {VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME};
const std::vector<const char *> Instance::DeviceExtensions = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; // VK_AMD_SHADER_IMAGE_LOAD_STORE_LOD_EXTENSION_NAME,
// VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME, VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME
VKAPI_ATTR VkBool32 VKAPI_CALL CallbackDebug(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode,
const char *pLayerPrefix, const char *pMessage, void *pUserData) {
Log::Error(pMessage, '\n');
return static_cast<VkBool32>(false);
}
VkResult Instance::FvkCreateDebugReportCallbackEXT(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator,
VkDebugReportCallbackEXT *pCallback) {
auto func = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"));
if (func) {
return func(instance, pCreateInfo, pAllocator, pCallback);
}
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
void Instance::FvkDestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks *pAllocator) {
auto func = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"));
if (func) {
func(instance, callback, pAllocator);
}
}
void Instance::FvkCmdPushDescriptorSetKHR(VkDevice device, VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t set,
uint32_t descriptorWriteCount, const VkWriteDescriptorSet *pDescriptorWrites) {
auto func = reinterpret_cast<PFN_vkCmdPushDescriptorSetKHR>(vkGetDeviceProcAddr(device, "vkCmdPushDescriptorSetKHR"));
if (func) {
func(commandBuffer, pipelineBindPoint, layout, set, descriptorWriteCount, pDescriptorWrites);
}
}
uint32_t Instance::FindMemoryTypeIndex(const VkPhysicalDeviceMemoryProperties *deviceMemoryProperties, const VkMemoryRequirements *memoryRequirements,
const VkMemoryPropertyFlags &requiredProperties) {
for (uint32_t i = 0; i < deviceMemoryProperties->memoryTypeCount; ++i) {
if (memoryRequirements->memoryTypeBits & (1 << i)) {
if ((deviceMemoryProperties->memoryTypes[i].propertyFlags & requiredProperties) == requiredProperties) {
return i;
}
}
}
throw std::runtime_error("Couldn't find a proper memory type");
}
Instance::Instance() {
SetupLayers();
SetupExtensions();
CreateInstance();
CreateDebugCallback();
}
Instance::~Instance() {
FvkDestroyDebugReportCallbackEXT(m_instance, m_debugReportCallback, nullptr);
vkDestroyInstance(m_instance, nullptr);
}
void Instance::SetupLayers() {
uint32_t instanceLayerPropertyCount;
vkEnumerateInstanceLayerProperties(&instanceLayerPropertyCount, nullptr);
std::vector<VkLayerProperties> instanceLayerProperties(instanceLayerPropertyCount);
vkEnumerateInstanceLayerProperties(&instanceLayerPropertyCount, instanceLayerProperties.data());
#if defined(ACID_DEBUG)
LogVulkanLayers(instanceLayerProperties);
#endif
// Sets up the layers.
#if defined(ACID_DEBUG) && !defined(ACID_BUILD_MACOS)
for (const auto &layerName : ValidationLayers) {
bool layerFound = false;
for (const auto &layerProperties : instanceLayerProperties) {
if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
Log::Error("Vulkan validation layer not found: ", std::quoted(layerName), '\n');
continue;
}
m_instanceLayers.emplace_back(layerName);
}
#endif
for (const auto &layerName : DeviceExtensions) {
m_deviceExtensions.emplace_back(layerName);
}
}
void Instance::SetupExtensions() {
// Sets up the extensions.
auto [extensions, extensionsCount] = Window::Get()->GetInstanceExtensions();
for (uint32_t i = 0; i < extensionsCount; i++) {
m_instanceExtensions.emplace_back(extensions[i]);
}
for (const auto &instanceExtension : InstanceExtensions) {
m_instanceExtensions.emplace_back(instanceExtension);
}
#if defined(ACID_DEBUG) && !defined(ACID_BUILD_MACOS)
m_instanceExtensions.emplace_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
m_instanceExtensions.emplace_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
#endif
}
void Instance::CreateInstance() {
const auto &engineVersion = Engine::Get()->GetVersion();
//const auto &appVersion = Engine::Get()->GetApp()->GetVersion();
//const auto &appName = Engine::Get()->GetApp()->GetName();
VkApplicationInfo applicationInfo = {};
applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
//applicationInfo.pApplicationName = appName.c_str();
//applicationInfo.applicationVersion = VK_MAKE_VERSION(appVersion.m_major, appVersion.m_minor, appVersion.m_patch);
applicationInfo.pEngineName = "Acid";
applicationInfo.engineVersion = VK_MAKE_VERSION(engineVersion.m_major, engineVersion.m_minor, engineVersion.m_patch);
applicationInfo.apiVersion = VK_MAKE_VERSION(1, 1, 0);
VkInstanceCreateInfo instanceCreateInfo = {};
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pApplicationInfo = &applicationInfo;
instanceCreateInfo.enabledLayerCount = static_cast<uint32_t>(m_instanceLayers.size());
instanceCreateInfo.ppEnabledLayerNames = m_instanceLayers.data();
instanceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(m_instanceExtensions.size());
instanceCreateInfo.ppEnabledExtensionNames = m_instanceExtensions.data();
Graphics::CheckVk(vkCreateInstance(&instanceCreateInfo, nullptr, &m_instance));
}
void Instance::CreateDebugCallback() {
#if defined(ACID_DEBUG) && !defined(ACID_BUILD_MACOS)
VkDebugReportCallbackCreateInfoEXT debugReportCallbackCreateInfo = {};
debugReportCallbackCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
debugReportCallbackCreateInfo.pNext = nullptr;
debugReportCallbackCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
debugReportCallbackCreateInfo.pfnCallback = &CallbackDebug;
debugReportCallbackCreateInfo.pUserData = nullptr;
Graphics::CheckVk(FvkCreateDebugReportCallbackEXT(m_instance, &debugReportCallbackCreateInfo, nullptr, &m_debugReportCallback));
#endif
}
void Instance::LogVulkanLayers(const std::vector<VkLayerProperties> &layerProperties) {
Log::Out("Instance Layers: ");
for (const auto &layer : layerProperties) {
Log::Out(layer.layerName, ", ");
}
Log::Out("\n\n");
}
}
| [
"mattparks5855@gmail.com"
] | mattparks5855@gmail.com |
27596d2634f0d9efd956d0a48f022a7ceb563be5 | f6f0be9108ba516d0f49e009ffe525814c6f0c95 | /test/graph/checking_bipartiteness_online_test.cpp | 94b29046a79bb35626b011646ab44200615b5241 | [] | no_license | PauloMiranda98/Competitive-Programming-Notebook | fe07a318c50c147cc3939dfde9034fe3de5056d9 | 54af0a8dcefdeb5505538a3716855db62bcdc716 | refs/heads/master | 2023-08-02T04:36:52.830218 | 2023-07-31T00:21:04 | 2023-07-31T00:21:04 | 242,273,238 | 20 | 4 | null | 2021-07-08T19:21:44 | 2020-02-22T03:30:13 | C++ | UTF-8 | C++ | false | false | 130 | cpp | #include "../../code/graph/floyd_warshall.h"
void test(){
//No tests yet, then I'll add
}
int main() {
test();
return 0;
}
| [
"paulomirandamss12@gmail.com"
] | paulomirandamss12@gmail.com |
5605b06bcb526fea47c7520deb241382ef612c4c | a4c8533710e295ecf4726c618c1a02760d888613 | /02_Build/01_Compile/01_Tasking_4p3/ctc/include.stl/stl/_rope.h | 2313f7ebacb1b15989fa6433940d9c41d75eb3b3 | [] | no_license | miaozhendaoren/K2SAR_EMS | ee42a1918cf45fbbbb24b0c8a128951d14eeee67 | 787d17cfa2c9a3ef89743dce1778f0087de32254 | refs/heads/master | 2021-01-17T23:05:04.505435 | 2015-12-22T14:39:24 | 2015-12-22T14:39:24 | 49,954,845 | 1 | 0 | null | 2016-01-19T13:35:48 | 2016-01-19T13:35:48 | null | UTF-8 | C++ | false | false | 80,854 | h |
/*
*
* Copyright (c) 1996,1997
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1997
* Moscow Center for SPARC Technology
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
/* NOTE: This is an internal header file, included by other STL headers.
* You should not attempt to use it directly.
*/
// rope<_CharT,_Alloc> is a sequence of _CharT.
// Ropes appear to be mutable, but update operations
// really copy enough of the data structure to leave the original
// valid. Thus ropes can be logically copied by just copying
// a pointer value.
#ifndef _STLP_INTERNAL_ROPE_H
#define _STLP_INTERNAL_ROPE_H
#ifndef _STLP_INTERNAL_ALGOBASE_H
# include <stl/_algobase.h>
#endif
#if !defined (_STLP_USE_NO_IOSTREAMS) && !defined (_STLP_INTERNAL_IOSFWD)
# include <stl/_iosfwd.h>
#endif
#ifndef _STLP_INTERNAL_ALLOC_H
# include <stl/_alloc.h>
#endif
#ifndef _STLP_INTERNAL_ITERATOR_H
# include <stl/_iterator.h>
#endif
#ifndef _STLP_INTERNAL_ALGO_H
# include <stl/_algo.h>
#endif
#ifndef _STLP_INTERNAL_FUNCTION_BASE_H
# include <stl/_function_base.h>
#endif
#ifndef _STLP_INTERNAL_NUMERIC_H
# include <stl/_numeric.h>
#endif
#ifndef _STLP_INTERNAL_HASH_FUN_H
# include <stl/_hash_fun.h>
#endif
#ifndef _STLP_CHAR_TRAITS_H
# include <stl/char_traits.h>
#endif
#ifndef _STLP_INTERNAL_THREADS_H
# include <stl/_threads.h>
#endif
#ifdef _STLP_SGI_THREADS
# include <mutex.h>
#endif
#ifndef _STLP_DONT_SUPPORT_REBIND_MEMBER_TEMPLATE
# define _STLP_CREATE_ALLOCATOR(__atype,__a, _Tp) (_Alloc_traits<_Tp,__atype>::create_allocator(__a))
#else
# define _STLP_CREATE_ALLOCATOR(__atype,__a, _Tp) __stl_alloc_create(__a,(_Tp*)0)
#endif
_STLP_BEGIN_NAMESPACE
// First a lot of forward declarations. The standard seems to require
// much stricter "declaration before use" than many of the implementations
// that preceded it.
template<class _CharT, _STLP_DFL_TMPL_PARAM(_Alloc, allocator<_CharT>) > class rope;
template<class _CharT, class _Alloc> struct _Rope_RopeConcatenation;
template<class _CharT, class _Alloc> struct _Rope_RopeRep;
template<class _CharT, class _Alloc> struct _Rope_RopeLeaf;
template<class _CharT, class _Alloc> struct _Rope_RopeFunction;
template<class _CharT, class _Alloc> struct _Rope_RopeSubstring;
template<class _CharT, class _Alloc> class _Rope_iterator;
template<class _CharT, class _Alloc> class _Rope_const_iterator;
template<class _CharT, class _Alloc> class _Rope_char_ref_proxy;
template<class _CharT, class _Alloc> class _Rope_char_ptr_proxy;
_STLP_MOVE_TO_PRIV_NAMESPACE
template <class _CharT>
struct _BasicCharType { typedef __false_type _Ret; };
_STLP_TEMPLATE_NULL
struct _BasicCharType<char> { typedef __true_type _Ret; };
#ifdef _STLP_HAS_WCHAR_T
_STLP_TEMPLATE_NULL
struct _BasicCharType<wchar_t> { typedef __true_type _Ret; };
#endif
// Some helpers, so we can use the power algorithm on ropes.
// See below for why this isn't local to the implementation.
// This uses a nonstandard refcount convention.
// The result has refcount 0.
template<class _CharT, class _Alloc>
struct _Rope_Concat_fn
: public binary_function<rope<_CharT,_Alloc>, rope<_CharT,_Alloc>,
rope<_CharT,_Alloc> > {
rope<_CharT,_Alloc> operator() (const rope<_CharT,_Alloc>& __x,
const rope<_CharT,_Alloc>& __y) {
return __x + __y;
}
};
template <class _CharT, class _Alloc>
inline
rope<_CharT,_Alloc>
__identity_element(_Rope_Concat_fn<_CharT, _Alloc>)
{ return rope<_CharT,_Alloc>(); }
_STLP_MOVE_TO_STD_NAMESPACE
// Store an eos
template <class _CharT>
inline void _S_construct_null_aux(_CharT *__p, const __true_type&)
{ *__p = 0; }
template <class _CharT>
inline void _S_construct_null_aux(_CharT *__p, const __false_type&)
{ _STLP_STD::_Construct(__p); }
template <class _CharT>
inline void _S_construct_null(_CharT *__p) {
typedef typename _IsIntegral<_CharT>::_Ret _Char_Is_Integral;
_S_construct_null_aux(__p, _Char_Is_Integral());
}
// char_producers are logically functions that generate a section of
// a string. These can be converted to ropes. The resulting rope
// invokes the char_producer on demand. This allows, for example,
// files to be viewed as ropes without reading the entire file.
template <class _CharT>
class char_producer {
public:
virtual ~char_producer() {}
virtual void operator()(size_t __start_pos, size_t __len,
_CharT* __buffer) = 0;
// Buffer should really be an arbitrary output iterator.
// That way we could flatten directly into an ostream, etc.
// This is thoroughly impossible, since iterator types don't
// have runtime descriptions.
};
// Sequence buffers:
//
// Sequence must provide an append operation that appends an
// array to the sequence. Sequence buffers are useful only if
// appending an entire array is cheaper than appending element by element.
// This is true for many string representations.
// This should perhaps inherit from ostream<sequence::value_type>
// and be implemented correspondingly, so that they can be used
// for formatted. For the sake of portability, we don't do this yet.
//
// For now, sequence buffers behave as output iterators. But they also
// behave a little like basic_ostringstream<sequence::value_type> and a
// little like containers.
template<class _Sequence
# if !(defined (_STLP_NON_TYPE_TMPL_PARAM_BUG) || \
defined ( _STLP_NO_DEFAULT_NON_TYPE_PARAM ))
, size_t _Buf_sz = 100
# if defined(__sgi) && !defined(__GNUC__)
# define __TYPEDEF_WORKAROUND
,class _V = typename _Sequence::value_type
# endif /* __sgi */
# endif /* _STLP_NON_TYPE_TMPL_PARAM_BUG */
>
// The 3rd parameter works around a common compiler bug.
class sequence_buffer : public iterator <output_iterator_tag, void, void, void, void> {
public:
# ifndef __TYPEDEF_WORKAROUND
typedef typename _Sequence::value_type value_type;
typedef sequence_buffer<_Sequence
# if !(defined (_STLP_NON_TYPE_TMPL_PARAM_BUG) || \
defined ( _STLP_NO_DEFAULT_NON_TYPE_PARAM ))
, _Buf_sz
> _Self;
# else /* _STLP_NON_TYPE_TMPL_PARAM_BUG */
> _Self;
enum { _Buf_sz = 100};
# endif /* _STLP_NON_TYPE_TMPL_PARAM_BUG */
// # endif
# else /* __TYPEDEF_WORKAROUND */
typedef _V value_type;
typedef sequence_buffer<_Sequence, _Buf_sz, _V> _Self;
# endif /* __TYPEDEF_WORKAROUND */
protected:
_Sequence* _M_prefix;
value_type _M_buffer[_Buf_sz];
size_t _M_buf_count;
public:
void flush() {
_M_prefix->append(_M_buffer, _M_buffer + _M_buf_count);
_M_buf_count = 0;
}
~sequence_buffer() { flush(); }
sequence_buffer() : _M_prefix(0), _M_buf_count(0) {}
sequence_buffer(const _Self& __x) {
_M_prefix = __x._M_prefix;
_M_buf_count = __x._M_buf_count;
_STLP_STD::copy(__x._M_buffer, __x._M_buffer + __x._M_buf_count, _M_buffer);
}
sequence_buffer(_Self& __x) {
__x.flush();
_M_prefix = __x._M_prefix;
_M_buf_count = 0;
}
sequence_buffer(_Sequence& __s) : _M_prefix(&__s), _M_buf_count(0) {}
_Self& operator= (_Self& __x) {
__x.flush();
_M_prefix = __x._M_prefix;
_M_buf_count = 0;
return *this;
}
_Self& operator= (const _Self& __x) {
_M_prefix = __x._M_prefix;
_M_buf_count = __x._M_buf_count;
_STLP_STD::copy(__x._M_buffer, __x._M_buffer + __x._M_buf_count, _M_buffer);
return *this;
}
void push_back(value_type __x) {
if (_M_buf_count < _Buf_sz) {
_M_buffer[_M_buf_count] = __x;
++_M_buf_count;
} else {
flush();
_M_buffer[0] = __x;
_M_buf_count = 1;
}
}
void append(const value_type *__s, size_t __len) {
if (__len + _M_buf_count <= _Buf_sz) {
size_t __i = _M_buf_count;
size_t __j = 0;
for (; __j < __len; __i++, __j++) {
_M_buffer[__i] = __s[__j];
}
_M_buf_count += __len;
} else if (0 == _M_buf_count) {
_M_prefix->append(__s, __s + __len);
} else {
flush();
append(__s, __len);
}
}
_Self& write(const value_type *__s, size_t __len) {
append(__s, __len);
return *this;
}
_Self& put(value_type __x) {
push_back(__x);
return *this;
}
_Self& operator=(const value_type& __rhs) {
push_back(__rhs);
return *this;
}
_Self& operator*() { return *this; }
_Self& operator++() { return *this; }
_Self& operator++(int) { return *this; }
};
// The following should be treated as private, at least for now.
template<class _CharT>
class _Rope_char_consumer {
#if !defined (_STLP_MEMBER_TEMPLATES)
public:
//Without member templates we have to use run-time parameterization.
// The symmetry with char_producer is accidental and temporary.
virtual ~_Rope_char_consumer() {}
virtual bool operator()(const _CharT* __buffer, size_t __len) = 0;
#endif
};
//
// What follows should really be local to rope. Unfortunately,
// that doesn't work, since it makes it impossible to define generic
// equality on rope iterators. According to the draft standard, the
// template parameters for such an equality operator cannot be inferred
// from the occurence of a member class as a parameter.
// (SGI compilers in fact allow this, but the __result wouldn't be
// portable.)
// Similarly, some of the static member functions are member functions
// only to avoid polluting the global namespace, and to circumvent
// restrictions on type inference for template functions.
//
//
// The internal data structure for representing a rope. This is
// private to the implementation. A rope is really just a pointer
// to one of these.
//
// A few basic functions for manipulating this data structure
// are members of _RopeRep. Most of the more complex algorithms
// are implemented as rope members.
//
// Some of the static member functions of _RopeRep have identically
// named functions in rope that simply invoke the _RopeRep versions.
//
template<class _CharT, class _Alloc>
struct _Rope_RopeRep
: public _Refcount_Base
{
typedef _Rope_RopeRep<_CharT, _Alloc> _Self;
public:
//
// GAB: 11/09/05
//
// "__ROPE_DEPTH_SIZE" is set to one more then the "__ROPE_MAX_DEPTH".
// This was originally just an addition of "__ROPE_MAX_DEPTH + 1"
// but this addition causes the sunpro compiler to complain about
// multiple declarations during the initialization of "_S_min_len".
// Changed to be a fixed value and the sunpro compiler appears to
// be happy???
//
# define __ROPE_MAX_DEPTH 45
# define __ROPE_DEPTH_SIZE 46 // __ROPE_MAX_DEPTH + 1
enum { _S_max_rope_depth = __ROPE_MAX_DEPTH };
enum _Tag {_S_leaf, _S_concat, _S_substringfn, _S_function};
// Apparently needed by VC++
// The data fields of leaves are allocated with some
// extra space, to accomodate future growth and for basic
// character types, to hold a trailing eos character.
enum { _S_alloc_granularity = 8 };
_Tag _M_tag:8;
bool _M_is_balanced:8;
_STLP_FORCE_ALLOCATORS(_CharT, _Alloc)
typedef _Alloc allocator_type;
allocator_type get_allocator() const { return allocator_type(_M_size); }
unsigned char _M_depth;
_CharT* _STLP_VOLATILE _M_c_string;
_STLP_PRIV _STLP_alloc_proxy<size_t, _CharT, allocator_type> _M_size;
#ifdef _STLP_NO_ARROW_OPERATOR
_Rope_RopeRep() : _Refcount_Base(1), _M_size(allocator_type(), 0) {
# if defined (_STLP_CHECK_RUNTIME_COMPATIBILITY)
_STLP_CHECK_RUNTIME_COMPATIBILITY();
# endif
}
#endif
/* Flattened version of string, if needed. */
/* typically 0. */
/* If it's not 0, then the memory is owned */
/* by this node. */
/* In the case of a leaf, this may point to */
/* the same memory as the data field. */
_Rope_RopeRep(_Tag __t, unsigned char __d, bool __b, size_t _p_size,
allocator_type __a) :
_Refcount_Base(1),
_M_tag(__t), _M_is_balanced(__b), _M_depth(__d), _M_c_string(0), _M_size(__a, _p_size) {
#if defined (_STLP_CHECK_RUNTIME_COMPATIBILITY)
_STLP_CHECK_RUNTIME_COMPATIBILITY();
#endif
}
typedef _STLP_TYPENAME _STLP_PRIV _BasicCharType<_CharT>::_Ret _IsBasicCharType;
#if 0
/* Please tell why this code is necessary if you uncomment it.
* Problem with it is that rope implementation expect that _S_rounded_up_size(n)
* returns a size > n in order to store the terminating null charater. When
* instanciation type is not a char or wchar_t this is not guaranty resulting in
* memory overrun.
*/
static size_t _S_rounded_up_size_aux(size_t __n, __true_type const& /*_IsBasicCharType*/) {
// Allow slop for in-place expansion.
return (__n + _S_alloc_granularity) & ~(_S_alloc_granularity - 1);
}
static size_t _S_rounded_up_size_aux(size_t __n, __false_type const& /*_IsBasicCharType*/) {
// Allow slop for in-place expansion.
return (__n + _S_alloc_granularity - 1) & ~(_S_alloc_granularity - 1);
}
#endif
// fbp : moved from RopeLeaf
static size_t _S_rounded_up_size(size_t __n)
//{ return _S_rounded_up_size_aux(__n, _IsBasicCharType()); }
{ return (__n + _S_alloc_granularity) & ~(_S_alloc_granularity - 1); }
static void _S_free_string( _CharT* __s, size_t __len,
allocator_type __a) {
_STLP_STD::_Destroy_Range(__s, __s + __len);
// This has to be a static member, so this gets a bit messy
# ifndef _STLP_DONT_SUPPORT_REBIND_MEMBER_TEMPLATE
__a.deallocate(__s, _S_rounded_up_size(__len)); //*ty 03/24/2001 - restored not to use __stl_alloc_rebind() since it is not defined under _STLP_MEMBER_TEMPLATE_CLASSES
# else
__stl_alloc_rebind (__a, (_CharT*)0).deallocate(__s, _S_rounded_up_size(__len));
# endif
}
// Deallocate data section of a leaf.
// This shouldn't be a member function.
// But its hard to do anything else at the
// moment, because it's templatized w.r.t.
// an allocator.
// Does nothing if __GC is defined.
void _M_free_c_string();
void _M_free_tree();
// Deallocate t. Assumes t is not 0.
void _M_unref_nonnil() {
if (_M_decr() == 0) _M_free_tree();
}
void _M_ref_nonnil() {
_M_incr();
}
static void _S_unref(_Self* __t) {
if (0 != __t) {
__t->_M_unref_nonnil();
}
}
static void _S_ref(_Self* __t) {
if (0 != __t) __t->_M_incr();
}
//static void _S_free_if_unref(_Self* __t) {
// if (0 != __t && 0 == __t->_M_ref_count) __t->_M_free_tree();
//}
};
template<class _CharT, class _Alloc>
struct _Rope_RopeLeaf : public _Rope_RopeRep<_CharT,_Alloc> {
public:
_CharT* _M_data; /* Not necessarily 0 terminated. */
/* The allocated size is */
/* _S_rounded_up_size(size), except */
/* in the GC case, in which it */
/* doesn't matter. */
private:
typedef _Rope_RopeRep<_CharT,_Alloc> _RopeRep;
typedef typename _RopeRep::_IsBasicCharType _IsBasicCharType;
void _M_init(__true_type const& /*_IsBasicCharType*/) {
this->_M_c_string = _M_data;
}
void _M_init(__false_type const& /*_IsBasicCharType*/) {}
public:
_STLP_FORCE_ALLOCATORS(_CharT, _Alloc)
typedef typename _RopeRep::allocator_type allocator_type;
_Rope_RopeLeaf( _CharT* __d, size_t _p_size, allocator_type __a)
: _Rope_RopeRep<_CharT,_Alloc>(_RopeRep::_S_leaf, 0, true, _p_size, __a),
_M_data(__d) {
_STLP_ASSERT(_p_size > 0)
_M_init(_IsBasicCharType());
}
# ifdef _STLP_NO_ARROW_OPERATOR
_Rope_RopeLeaf() {}
_Rope_RopeLeaf(const _Rope_RopeLeaf<_CharT, _Alloc>& ) {}
# endif
// The constructor assumes that d has been allocated with
// the proper allocator and the properly padded size.
// In contrast, the destructor deallocates the data:
~_Rope_RopeLeaf() {
if (_M_data != this->_M_c_string) {
this->_M_free_c_string();
}
_RopeRep::_S_free_string(_M_data, this->_M_size._M_data, this->get_allocator());
}
};
template<class _CharT, class _Alloc>
struct _Rope_RopeConcatenation : public _Rope_RopeRep<_CharT, _Alloc> {
private:
typedef _Rope_RopeRep<_CharT,_Alloc> _RopeRep;
public:
_RopeRep* _M_left;
_RopeRep* _M_right;
_STLP_FORCE_ALLOCATORS(_CharT, _Alloc)
typedef typename _RopeRep::allocator_type allocator_type;
_Rope_RopeConcatenation(_RopeRep* __l, _RopeRep* __r, allocator_type __a)
: _Rope_RopeRep<_CharT,_Alloc>(_RopeRep::_S_concat,
(max)(__l->_M_depth, __r->_M_depth) + 1, false,
__l->_M_size._M_data + __r->_M_size._M_data, __a), _M_left(__l), _M_right(__r)
{}
# ifdef _STLP_NO_ARROW_OPERATOR
_Rope_RopeConcatenation() {}
_Rope_RopeConcatenation(const _Rope_RopeConcatenation<_CharT, _Alloc>&) {}
# endif
~_Rope_RopeConcatenation() {
this->_M_free_c_string();
_M_left->_M_unref_nonnil();
_M_right->_M_unref_nonnil();
}
};
template <class _CharT, class _Alloc>
struct _Rope_RopeFunction : public _Rope_RopeRep<_CharT, _Alloc> {
private:
typedef _Rope_RopeRep<_CharT,_Alloc> _RopeRep;
public:
char_producer<_CharT>* _M_fn;
/*
* Char_producer is owned by the
* rope and should be explicitly
* deleted when the rope becomes
* inaccessible.
*/
bool _M_delete_when_done;
_STLP_FORCE_ALLOCATORS(_CharT, _Alloc)
typedef typename _Rope_RopeRep<_CharT,_Alloc>::allocator_type allocator_type;
# ifdef _STLP_NO_ARROW_OPERATOR
_Rope_RopeFunction() {}
_Rope_RopeFunction(const _Rope_RopeFunction<_CharT, _Alloc>& ) {}
# endif
_Rope_RopeFunction(char_producer<_CharT>* __f, size_t _p_size,
bool __d, allocator_type __a)
: _Rope_RopeRep<_CharT,_Alloc>(_RopeRep::_S_function, 0, true, _p_size, __a), _M_fn(__f)
, _M_delete_when_done(__d)
{ _STLP_ASSERT(_p_size > 0) }
~_Rope_RopeFunction() {
this->_M_free_c_string();
if (_M_delete_when_done) {
delete _M_fn;
}
}
};
/*
* Substring results are usually represented using just
* concatenation nodes. But in the case of very long flat ropes
* or ropes with a functional representation that isn't practical.
* In that case, we represent the __result as a special case of
* RopeFunction, whose char_producer points back to the rope itself.
* In all cases except repeated substring operations and
* deallocation, we treat the __result as a RopeFunction.
*/
template<class _CharT, class _Alloc>
struct _Rope_RopeSubstring : public char_producer<_CharT>, public _Rope_RopeFunction<_CharT,_Alloc> {
public:
// XXX this whole class should be rewritten.
typedef _Rope_RopeRep<_CharT,_Alloc> _RopeRep;
_RopeRep *_M_base; // not 0
size_t _M_start;
/* virtual */ void operator()(size_t __start_pos, size_t __req_len,
_CharT* __buffer) {
typedef _Rope_RopeFunction<_CharT,_Alloc> _RopeFunction;
typedef _Rope_RopeLeaf<_CharT,_Alloc> _RopeLeaf;
switch (_M_base->_M_tag) {
case _RopeRep::_S_function:
case _RopeRep::_S_substringfn:
{
char_producer<_CharT>* __fn =
__STATIC_CAST(_RopeFunction*, _M_base)->_M_fn;
_STLP_ASSERT(__start_pos + __req_len <= this->_M_size._M_data)
_STLP_ASSERT(_M_start + this->_M_size._M_data <= _M_base->_M_size._M_data)
(*__fn)(__start_pos + _M_start, __req_len, __buffer);
}
break;
case _RopeRep::_S_leaf:
{
_CharT* __s =
__STATIC_CAST(_RopeLeaf*, _M_base)->_M_data;
_STLP_PRIV __ucopy_n(__s + __start_pos + _M_start, __req_len, __buffer);
}
break;
default:
_STLP_ASSERT(false)
;
}
}
_STLP_FORCE_ALLOCATORS(_CharT, _Alloc)
typedef typename _RopeRep::allocator_type allocator_type;
_Rope_RopeSubstring(_RopeRep* __b, size_t __s, size_t __l, allocator_type __a)
: _Rope_RopeFunction<_CharT,_Alloc>(this, __l, false, __a),
_M_base(__b), _M_start(__s) {
_STLP_ASSERT(__l > 0)
_STLP_ASSERT(__s + __l <= __b->_M_size._M_data)
_M_base->_M_ref_nonnil();
this->_M_tag = _RopeRep::_S_substringfn;
}
virtual ~_Rope_RopeSubstring()
{ _M_base->_M_unref_nonnil(); }
};
/*
* Self-destructing pointers to Rope_rep.
* These are not conventional smart pointers. Their
* only purpose in life is to ensure that unref is called
* on the pointer either at normal exit or if an exception
* is raised. It is the caller's responsibility to
* adjust reference counts when these pointers are initialized
* or assigned to. (This convention significantly reduces
* the number of potentially expensive reference count
* updates.)
*/
template<class _CharT, class _Alloc>
struct _Rope_self_destruct_ptr {
_Rope_RopeRep<_CharT,_Alloc>* _M_ptr;
~_Rope_self_destruct_ptr()
{ _Rope_RopeRep<_CharT,_Alloc>::_S_unref(_M_ptr); }
# ifdef _STLP_USE_EXCEPTIONS
_Rope_self_destruct_ptr() : _M_ptr(0) {}
# else
_Rope_self_destruct_ptr() {}
# endif
_Rope_self_destruct_ptr(_Rope_RopeRep<_CharT,_Alloc>* __p) : _M_ptr(__p) {}
_Rope_RopeRep<_CharT,_Alloc>& operator*() { return *_M_ptr; }
_Rope_RopeRep<_CharT,_Alloc>* operator->() { return _M_ptr; }
operator _Rope_RopeRep<_CharT,_Alloc>*() { return _M_ptr; }
_Rope_self_destruct_ptr<_CharT, _Alloc>&
operator= (_Rope_RopeRep<_CharT,_Alloc>* __x)
{ _M_ptr = __x; return *this; }
};
/*
* Dereferencing a nonconst iterator has to return something
* that behaves almost like a reference. It's not possible to
* return an actual reference since assignment requires extra
* work. And we would get into the same problems as with the
* CD2 version of basic_string.
*/
template<class _CharT, class _Alloc>
class _Rope_char_ref_proxy {
typedef _Rope_char_ref_proxy<_CharT, _Alloc> _Self;
friend class rope<_CharT,_Alloc>;
friend class _Rope_iterator<_CharT,_Alloc>;
friend class _Rope_char_ptr_proxy<_CharT,_Alloc>;
typedef _Rope_self_destruct_ptr<_CharT,_Alloc> _Self_destruct_ptr;
typedef _Rope_RopeRep<_CharT,_Alloc> _RopeRep;
typedef rope<_CharT,_Alloc> _My_rope;
size_t _M_pos;
_CharT _M_current;
bool _M_current_valid;
_My_rope* _M_root; // The whole rope.
public:
_Rope_char_ref_proxy(_My_rope* __r, size_t __p) :
_M_pos(__p), _M_current_valid(false), _M_root(__r) {}
_Rope_char_ref_proxy(const _Self& __x) :
_M_pos(__x._M_pos), _M_current_valid(false), _M_root(__x._M_root) {}
// Don't preserve cache if the reference can outlive the
// expression. We claim that's not possible without calling
// a copy constructor or generating reference to a proxy
// reference. We declare the latter to have undefined semantics.
_Rope_char_ref_proxy(_My_rope* __r, size_t __p, _CharT __c)
: _M_pos(__p), _M_current(__c), _M_current_valid(true), _M_root(__r) {}
inline operator _CharT () const;
_Self& operator= (_CharT __c);
_Rope_char_ptr_proxy<_CharT, _Alloc> operator& () const;
_Self& operator= (const _Self& __c) {
return operator=((_CharT)__c);
}
};
#ifdef _STLP_FUNCTION_TMPL_PARTIAL_ORDER
template<class _CharT, class __Alloc>
inline void swap(_Rope_char_ref_proxy <_CharT, __Alloc > __a,
_Rope_char_ref_proxy <_CharT, __Alloc > __b) {
_CharT __tmp = __a;
__a = __b;
__b = __tmp;
}
#else
// There is no really acceptable way to handle this. The default
// definition of swap doesn't work for proxy references.
// It can't really be made to work, even with ugly hacks, since
// the only unusual operation it uses is the copy constructor, which
// is needed for other purposes. We provide a macro for
// full specializations, and instantiate the most common case.
# define _ROPE_SWAP_SPECIALIZATION(_CharT, __Alloc) \
inline void swap(_Rope_char_ref_proxy <_CharT, __Alloc > __a, \
_Rope_char_ref_proxy <_CharT, __Alloc > __b) { \
_CharT __tmp = __a; \
__a = __b; \
__b = __tmp; \
}
_ROPE_SWAP_SPECIALIZATION(char, allocator<char>)
# ifndef _STLP_NO_WCHAR_T
_ROPE_SWAP_SPECIALIZATION(wchar_t, allocator<wchar_t>)
# endif
#endif /* !_STLP_FUNCTION_TMPL_PARTIAL_ORDER */
template<class _CharT, class _Alloc>
class _Rope_char_ptr_proxy {
// XXX this class should be rewritten.
public:
typedef _Rope_char_ptr_proxy<_CharT, _Alloc> _Self;
friend class _Rope_char_ref_proxy<_CharT,_Alloc>;
size_t _M_pos;
rope<_CharT,_Alloc>* _M_root; // The whole rope.
_Rope_char_ptr_proxy(const _Rope_char_ref_proxy<_CharT,_Alloc>& __x)
: _M_pos(__x._M_pos), _M_root(__x._M_root) {}
_Rope_char_ptr_proxy(const _Self& __x)
: _M_pos(__x._M_pos), _M_root(__x._M_root) {}
_Rope_char_ptr_proxy() {}
_Rope_char_ptr_proxy(_CharT* __x) : _M_pos(0), _M_root(0) {
_STLP_ASSERT(0 == __x)
}
_Self& operator= (const _Self& __x) {
_M_pos = __x._M_pos;
_M_root = __x._M_root;
return *this;
}
_Rope_char_ref_proxy<_CharT,_Alloc> operator*() const {
return _Rope_char_ref_proxy<_CharT,_Alloc>(_M_root, _M_pos);
}
};
/*
* Rope iterators:
* Unlike in the C version, we cache only part of the stack
* for rope iterators, since they must be efficiently copyable.
* When we run out of cache, we have to reconstruct the iterator
* value.
* Pointers from iterators are not included in reference counts.
* Iterators are assumed to be thread private. Ropes can
* be shared.
*/
template<class _CharT, class _Alloc>
class _Rope_iterator_base
/* : public random_access_iterator<_CharT, ptrdiff_t> */
{
friend class rope<_CharT,_Alloc>;
typedef _Rope_iterator_base<_CharT, _Alloc> _Self;
typedef _Rope_RopeConcatenation<_CharT,_Alloc> _RopeConcat;
public:
typedef _Rope_RopeRep<_CharT,_Alloc> _RopeRep;
enum { _S_path_cache_len = 4 }; // Must be <= 9 because of _M_path_direction.
enum { _S_iterator_buf_len = 15 };
size_t _M_current_pos;
// The whole rope.
_RopeRep* _M_root;
// Starting position for current leaf
size_t _M_leaf_pos;
// Buffer possibly containing current char.
_CharT* _M_buf_start;
// Pointer to current char in buffer, != 0 ==> buffer valid.
_CharT* _M_buf_ptr;
// One past __last valid char in buffer.
_CharT* _M_buf_end;
// What follows is the path cache. We go out of our
// way to make this compact.
// Path_end contains the bottom section of the path from
// the root to the current leaf.
struct {
# if defined (__BORLANDC__) && (__BORLANDC__ < 0x560)
_RopeRep const*_M_data[4];
# else
_RopeRep const*_M_data[_S_path_cache_len];
# endif
} _M_path_end;
// Last valid __pos in path_end;
// _M_path_end[0] ... _M_path_end[_M_leaf_index-1]
// point to concatenation nodes.
int _M_leaf_index;
// (_M_path_directions >> __i) & 1 is 1
// if we got from _M_path_end[leaf_index - __i - 1]
// to _M_path_end[leaf_index - __i] by going to the
// __right. Assumes path_cache_len <= 9.
unsigned char _M_path_directions;
// Short buffer for surrounding chars.
// This is useful primarily for
// RopeFunctions. We put the buffer
// here to avoid locking in the
// multithreaded case.
// The cached path is generally assumed to be valid
// only if the buffer is valid.
struct {
# if defined (__BORLANDC__) && (__BORLANDC__ < 0x560)
_CharT _M_data[15];
# else
_CharT _M_data[_S_iterator_buf_len];
# endif
} _M_tmp_buf;
// Set buffer contents given path cache.
static void _S_setbuf(_Rope_iterator_base<_CharT, _Alloc>& __x);
// Set buffer contents and path cache.
static void _S_setcache(_Rope_iterator_base<_CharT, _Alloc>& __x);
// As above, but assumes path cache is valid for previous posn.
static void _S_setcache_for_incr(_Rope_iterator_base<_CharT, _Alloc>& __x);
_Rope_iterator_base() {}
_Rope_iterator_base(_RopeRep* __root, size_t __pos)
: _M_current_pos(__pos),_M_root(__root), _M_buf_ptr(0) {}
void _M_incr(size_t __n);
void _M_decr(size_t __n);
public:
size_t index() const { return _M_current_pos; }
private:
void _M_copy_buf(const _Self& __x) {
_M_tmp_buf = __x._M_tmp_buf;
if (__x._M_buf_start == __x._M_tmp_buf._M_data) {
_M_buf_start = _M_tmp_buf._M_data;
_M_buf_end = _M_buf_start + (__x._M_buf_end - __x._M_buf_start);
_M_buf_ptr = _M_buf_start + (__x._M_buf_ptr - __x._M_buf_start);
} else {
_M_buf_end = __x._M_buf_end;
}
}
public:
_Rope_iterator_base(const _Self& __x) :
_M_current_pos(__x._M_current_pos),
_M_root(__x._M_root),
_M_leaf_pos( __x._M_leaf_pos ),
_M_buf_start(__x._M_buf_start),
_M_buf_ptr(__x._M_buf_ptr),
_M_path_end(__x._M_path_end),
_M_leaf_index(__x._M_leaf_index),
_M_path_directions(__x._M_path_directions)
{
if (0 != __x._M_buf_ptr) {
_M_copy_buf(__x);
}
}
_Self& operator = (const _Self& __x)
{
_M_current_pos = __x._M_current_pos;
_M_root = __x._M_root;
_M_buf_start = __x._M_buf_start;
_M_buf_ptr = __x._M_buf_ptr;
_M_path_end = __x._M_path_end;
_M_leaf_index = __x._M_leaf_index;
_M_path_directions = __x._M_path_directions;
_M_leaf_pos = __x._M_leaf_pos;
if (0 != __x._M_buf_ptr) {
_M_copy_buf(__x);
}
return *this;
}
};
template<class _CharT, class _Alloc> class _Rope_iterator;
template<class _CharT, class _Alloc>
class _Rope_const_iterator : public _Rope_iterator_base<_CharT,_Alloc> {
friend class rope<_CharT,_Alloc>;
typedef _Rope_const_iterator<_CharT, _Alloc> _Self;
typedef _Rope_iterator_base<_CharT,_Alloc> _Base;
// protected:
public:
# ifndef _STLP_HAS_NO_NAMESPACES
typedef _Rope_RopeRep<_CharT,_Alloc> _RopeRep;
// The one from the base class may not be directly visible.
# endif
_Rope_const_iterator(const _RopeRep* __root, size_t __pos):
_Rope_iterator_base<_CharT,_Alloc>(__CONST_CAST(_RopeRep*,__root), __pos)
// Only nonconst iterators modify root ref count
{}
public:
typedef _CharT reference; // Really a value. Returning a reference
// Would be a mess, since it would have
// to be included in refcount.
typedef const _CharT* pointer;
typedef _CharT value_type;
typedef ptrdiff_t difference_type;
typedef random_access_iterator_tag iterator_category;
public:
_Rope_const_iterator() {}
_Rope_const_iterator(const _Self& __x) :
_Rope_iterator_base<_CharT,_Alloc>(__x) { }
_Rope_const_iterator(const _Rope_iterator<_CharT,_Alloc>& __x):
_Rope_iterator_base<_CharT,_Alloc>(__x) {}
_Rope_const_iterator(const rope<_CharT,_Alloc>& __r, size_t __pos) :
_Rope_iterator_base<_CharT,_Alloc>(__r._M_tree_ptr._M_data, __pos) {}
_Self& operator= (const _Self& __x) {
_Base::operator=(__x);
return *this;
}
reference operator*() {
if (0 == this->_M_buf_ptr)
#if !defined (__DMC__)
_S_setcache(*this);
#else
{ _Rope_iterator_base<_CharT, _Alloc>* __x = this; _S_setcache(*__x); }
#endif
return *(this->_M_buf_ptr);
}
_Self& operator++()
{
if ( this->_M_buf_ptr != 0 ) {
_CharT *__next = this->_M_buf_ptr + 1;
if ( __next < this->_M_buf_end ) {
this->_M_buf_ptr = __next;
++this->_M_current_pos;
return *this;
}
}
this->_M_incr(1);
return *this;
}
_Self& operator+=(ptrdiff_t __n) {
if (__n >= 0) {
this->_M_incr(__n);
} else {
this->_M_decr(-__n);
}
return *this;
}
_Self& operator--() {
this->_M_decr(1);
return *this;
}
_Self& operator-=(ptrdiff_t __n) {
if (__n >= 0) {
this->_M_decr(__n);
} else {
this->_M_incr(-__n);
}
return *this;
}
_Self operator++(int) {
size_t __old_pos = this->_M_current_pos;
this->_M_incr(1);
return _Rope_const_iterator<_CharT,_Alloc>(this->_M_root, __old_pos);
// This makes a subsequent dereference expensive.
// Perhaps we should instead copy the iterator
// if it has a valid cache?
}
_Self operator--(int) {
size_t __old_pos = this->_M_current_pos;
this->_M_decr(1);
return _Rope_const_iterator<_CharT,_Alloc>(this->_M_root, __old_pos);
}
inline reference operator[](size_t __n);
};
template<class _CharT, class _Alloc>
class _Rope_iterator : public _Rope_iterator_base<_CharT,_Alloc> {
friend class rope<_CharT,_Alloc>;
typedef _Rope_iterator<_CharT, _Alloc> _Self;
typedef _Rope_iterator_base<_CharT,_Alloc> _Base;
typedef _Rope_RopeRep<_CharT,_Alloc> _RopeRep;
public:
rope<_CharT,_Alloc>* _M_root_rope;
// root is treated as a cached version of this,
// and is used to detect changes to the underlying
// rope.
// Root is included in the reference count.
// This is necessary so that we can detect changes reliably.
// Unfortunately, it requires careful bookkeeping for the
// nonGC case.
_Rope_iterator(rope<_CharT,_Alloc>* __r, size_t __pos);
void _M_check();
public:
typedef _Rope_char_ref_proxy<_CharT,_Alloc> reference;
typedef _Rope_char_ref_proxy<_CharT,_Alloc>* pointer;
typedef _CharT value_type;
typedef ptrdiff_t difference_type;
typedef random_access_iterator_tag iterator_category;
public:
~_Rope_iterator() { //*TY 5/6/00 - added dtor to balance reference count
_RopeRep::_S_unref(this->_M_root);
}
rope<_CharT,_Alloc>& container() { return *_M_root_rope; }
_Rope_iterator() {
this->_M_root = 0; // Needed for reference counting.
}
_Rope_iterator(const _Self& __x) :
_Rope_iterator_base<_CharT,_Alloc>(__x) {
_M_root_rope = __x._M_root_rope;
_RopeRep::_S_ref(this->_M_root);
}
_Rope_iterator(rope<_CharT,_Alloc>& __r, size_t __pos);
_Self& operator= (const _Self& __x) {
_RopeRep* __old = this->_M_root;
_RopeRep::_S_ref(__x._M_root);
_Base::operator=(__x);
_M_root_rope = __x._M_root_rope;
_RopeRep::_S_unref(__old);
return *this;
}
reference operator*() {
_M_check();
if (0 == this->_M_buf_ptr) {
return reference(_M_root_rope, this->_M_current_pos);
} else {
return reference(_M_root_rope, this->_M_current_pos, *(this->_M_buf_ptr));
}
}
_Self& operator++() {
this->_M_incr(1);
return *this;
}
_Self& operator+=(ptrdiff_t __n) {
if (__n >= 0) {
this->_M_incr(__n);
} else {
this->_M_decr(-__n);
}
return *this;
}
_Self& operator--() {
this->_M_decr(1);
return *this;
}
_Self& operator-=(ptrdiff_t __n) {
if (__n >= 0) {
this->_M_decr(__n);
} else {
this->_M_incr(-__n);
}
return *this;
}
_Self operator++(int) {
size_t __old_pos = this->_M_current_pos;
this->_M_incr(1);
return _Self(_M_root_rope, __old_pos);
}
_Self operator--(int) {
size_t __old_pos = this->_M_current_pos;
this->_M_decr(1);
return _Self(_M_root_rope, __old_pos);
}
reference operator[](ptrdiff_t __n) {
return reference(_M_root_rope, this->_M_current_pos + __n);
}
};
# ifdef _STLP_USE_OLD_HP_ITERATOR_QUERIES
template <class _CharT, class _Alloc>
inline random_access_iterator_tag
iterator_category(const _Rope_iterator<_CharT,_Alloc>&) { return random_access_iterator_tag();}
template <class _CharT, class _Alloc>
inline _CharT* value_type(const _Rope_iterator<_CharT,_Alloc>&) { return 0; }
template <class _CharT, class _Alloc>
inline ptrdiff_t* distance_type(const _Rope_iterator<_CharT,_Alloc>&) { return 0; }
template <class _CharT, class _Alloc>
inline random_access_iterator_tag
iterator_category(const _Rope_const_iterator<_CharT,_Alloc>&) { return random_access_iterator_tag(); }
template <class _CharT, class _Alloc>
inline _CharT* value_type(const _Rope_const_iterator<_CharT,_Alloc>&) { return 0; }
template <class _CharT, class _Alloc>
inline ptrdiff_t* distance_type(const _Rope_const_iterator<_CharT,_Alloc>&) { return 0; }
#endif /* _STLP_USE_OLD_HP_ITERATOR_QUERIES */
template <class _CharT, class _Alloc, class _CharConsumer>
bool _S_apply_to_pieces(_CharConsumer& __c,
_Rope_RopeRep<_CharT, _Alloc> *__r,
size_t __begin, size_t __end);
// begin and end are assumed to be in range.
template <class _CharT, class _Alloc>
class rope
#if defined (_STLP_USE_PARTIAL_SPEC_WORKAROUND)
: public __stlport_class<rope<_CharT, _Alloc> >
#endif
{
typedef rope<_CharT,_Alloc> _Self;
public:
typedef _CharT value_type;
typedef ptrdiff_t difference_type;
typedef size_t size_type;
typedef _CharT const_reference;
typedef const _CharT* const_pointer;
typedef _Rope_iterator<_CharT,_Alloc> iterator;
typedef _Rope_const_iterator<_CharT,_Alloc> const_iterator;
typedef _Rope_char_ref_proxy<_CharT,_Alloc> reference;
typedef _Rope_char_ptr_proxy<_CharT,_Alloc> pointer;
friend class _Rope_iterator<_CharT,_Alloc>;
friend class _Rope_const_iterator<_CharT,_Alloc>;
friend struct _Rope_RopeRep<_CharT,_Alloc>;
friend class _Rope_iterator_base<_CharT,_Alloc>;
friend class _Rope_char_ptr_proxy<_CharT,_Alloc>;
friend class _Rope_char_ref_proxy<_CharT,_Alloc>;
friend struct _Rope_RopeSubstring<_CharT,_Alloc>;
_STLP_DECLARE_RANDOM_ACCESS_REVERSE_ITERATORS;
protected:
typedef _CharT* _Cstrptr;
static _CharT _S_empty_c_str[1];
enum { _S_copy_max = 23 };
// For strings shorter than _S_copy_max, we copy to
// concatenate.
typedef _Rope_RopeRep<_CharT, _Alloc> _RopeRep;
typedef typename _RopeRep::_IsBasicCharType _IsBasicCharType;
public:
_STLP_FORCE_ALLOCATORS(_CharT, _Alloc)
typedef _Alloc allocator_type;
public:
// The only data member of a rope:
_STLP_PRIV _STLP_alloc_proxy<_RopeRep*, _CharT, allocator_type> _M_tree_ptr;
public:
allocator_type get_allocator() const { return allocator_type(_M_tree_ptr); }
public:
typedef _Rope_RopeConcatenation<_CharT,_Alloc> _RopeConcatenation;
typedef _Rope_RopeLeaf<_CharT,_Alloc> _RopeLeaf;
typedef _Rope_RopeFunction<_CharT,_Alloc> _RopeFunction;
typedef _Rope_RopeSubstring<_CharT,_Alloc> _RopeSubstring;
// Retrieve a character at the indicated position.
static _CharT _S_fetch(_RopeRep* __r, size_type __pos);
// Obtain a pointer to the character at the indicated position.
// The pointer can be used to change the character.
// If such a pointer cannot be produced, as is frequently the
// case, 0 is returned instead.
// (Returns nonzero only if all nodes in the path have a refcount
// of 1.)
static _CharT* _S_fetch_ptr(_RopeRep* __r, size_type __pos);
static void _S_unref(_RopeRep* __t) {
_RopeRep::_S_unref(__t);
}
static void _S_ref(_RopeRep* __t) {
_RopeRep::_S_ref(__t);
}
typedef _Rope_self_destruct_ptr<_CharT,_Alloc> _Self_destruct_ptr;
// _Result is counted in refcount.
static _RopeRep* _S_substring(_RopeRep* __base,
size_t __start, size_t __endp1);
static _RopeRep* _S_concat_char_iter(_RopeRep* __r,
const _CharT* __iter, size_t __slen);
// Concatenate rope and char ptr, copying __s.
// Should really take an arbitrary iterator.
// Result is counted in refcount.
static _RopeRep* _S_destr_concat_char_iter(_RopeRep* __r,
const _CharT* __iter, size_t __slen);
// As above, but one reference to __r is about to be
// destroyed. Thus the pieces may be recycled if all
// relevent reference counts are 1.
// General concatenation on _RopeRep. _Result
// has refcount of 1. Adjusts argument refcounts.
static _RopeRep* _S_concat_rep(_RopeRep* __left, _RopeRep* __right);
public:
#if defined (_STLP_MEMBER_TEMPLATES)
template <class _CharConsumer>
#else
typedef _Rope_char_consumer<_CharT> _CharConsumer;
#endif
void apply_to_pieces(size_t __begin, size_t __end,
_CharConsumer& __c) const
{ _S_apply_to_pieces(__c, _M_tree_ptr._M_data, __begin, __end); }
protected:
static size_t _S_rounded_up_size(size_t __n)
{ return _RopeRep::_S_rounded_up_size(__n); }
// Allocate and construct a RopeLeaf using the supplied allocator
// Takes ownership of s instead of copying.
static _RopeLeaf* _S_new_RopeLeaf(_CharT *__s,
size_t _p_size, allocator_type __a) {
_RopeLeaf* __space = _STLP_CREATE_ALLOCATOR(allocator_type, __a,
_RopeLeaf).allocate(1);
_STLP_TRY {
new(__space) _RopeLeaf(__s, _p_size, __a);
}
_STLP_UNWIND(_STLP_CREATE_ALLOCATOR(allocator_type,__a,
_RopeLeaf).deallocate(__space, 1))
return __space;
}
static _RopeConcatenation* _S_new_RopeConcatenation(_RopeRep* __left, _RopeRep* __right,
allocator_type __a) {
_RopeConcatenation* __space = _STLP_CREATE_ALLOCATOR(allocator_type, __a,
_RopeConcatenation).allocate(1);
return new(__space) _RopeConcatenation(__left, __right, __a);
}
static _RopeFunction* _S_new_RopeFunction(char_producer<_CharT>* __f,
size_t _p_size, bool __d, allocator_type __a) {
_RopeFunction* __space = _STLP_CREATE_ALLOCATOR(allocator_type, __a,
_RopeFunction).allocate(1);
return new(__space) _RopeFunction(__f, _p_size, __d, __a);
}
static _RopeSubstring* _S_new_RopeSubstring(_Rope_RopeRep<_CharT,_Alloc>* __b, size_t __s,
size_t __l, allocator_type __a) {
_RopeSubstring* __space = _STLP_CREATE_ALLOCATOR(allocator_type, __a,
_RopeSubstring).allocate(1);
return new(__space) _RopeSubstring(__b, __s, __l, __a);
}
static
_RopeLeaf* _S_RopeLeaf_from_unowned_char_ptr(const _CharT *__s,
size_t _p_size, allocator_type __a) {
if (0 == _p_size) return 0;
_CharT* __buf = _STLP_CREATE_ALLOCATOR(allocator_type,__a, _CharT).allocate(_S_rounded_up_size(_p_size));
_STLP_PRIV __ucopy_n(__s, _p_size, __buf);
_S_construct_null(__buf + _p_size);
_STLP_TRY {
return _S_new_RopeLeaf(__buf, _p_size, __a);
}
_STLP_UNWIND(_RopeRep::_S_free_string(__buf, _p_size, __a))
_STLP_RET_AFTER_THROW(0)
}
// Concatenation of nonempty strings.
// Always builds a concatenation node.
// Rebalances if the result is too deep.
// Result has refcount 1.
// Does not increment left and right ref counts even though
// they are referenced.
static _RopeRep*
_S_tree_concat(_RopeRep* __left, _RopeRep* __right);
// Concatenation helper functions
static _RopeLeaf*
_S_leaf_concat_char_iter(_RopeLeaf* __r,
const _CharT* __iter, size_t __slen);
// Concatenate by copying leaf.
// should take an arbitrary iterator
// result has refcount 1.
static _RopeLeaf* _S_destr_leaf_concat_char_iter
(_RopeLeaf* __r, const _CharT* __iter, size_t __slen);
// A version that potentially clobbers __r if __r->_M_ref_count == 1.
// A helper function for exponentiating strings.
// This uses a nonstandard refcount convention.
// The result has refcount 0.
typedef _STLP_PRIV _Rope_Concat_fn<_CharT,_Alloc> _Concat_fn;
#if !defined (__GNUC__) || (__GNUC__ < 3)
friend _Concat_fn;
#else
friend struct _STLP_PRIV _Rope_Concat_fn<_CharT,_Alloc>;
#endif
public:
static size_t _S_char_ptr_len(const _CharT* __s) {
return char_traits<_CharT>::length(__s);
}
public: /* for operators */
rope(_RopeRep* __t, const allocator_type& __a = allocator_type())
: _M_tree_ptr(__a, __t) { }
private:
// Copy __r to the _CharT buffer.
// Returns __buffer + __r->_M_size._M_data.
// Assumes that buffer is uninitialized.
static _CharT* _S_flatten(_RopeRep* __r, _CharT* __buffer);
// Again, with explicit starting position and length.
// Assumes that buffer is uninitialized.
static _CharT* _S_flatten(_RopeRep* __r,
size_t __start, size_t __len,
_CharT* __buffer);
// fbp : HP aCC prohibits access to protected min_len from within static methods ( ?? )
public:
static const unsigned long _S_min_len[__ROPE_DEPTH_SIZE];
protected:
static bool _S_is_balanced(_RopeRep* __r)
{ return (__r->_M_size._M_data >= _S_min_len[__r->_M_depth]); }
static bool _S_is_almost_balanced(_RopeRep* __r) {
return (__r->_M_depth == 0 ||
__r->_M_size._M_data >= _S_min_len[__r->_M_depth - 1]);
}
static bool _S_is_roughly_balanced(_RopeRep* __r) {
return (__r->_M_depth <= 1 ||
__r->_M_size._M_data >= _S_min_len[__r->_M_depth - 2]);
}
// Assumes the result is not empty.
static _RopeRep* _S_concat_and_set_balanced(_RopeRep* __left,
_RopeRep* __right) {
_RopeRep* __result = _S_concat_rep(__left, __right);
if (_S_is_balanced(__result)) __result->_M_is_balanced = true;
return __result;
}
// The basic rebalancing operation. Logically copies the
// rope. The result has refcount of 1. The client will
// usually decrement the reference count of __r.
// The result is within height 2 of balanced by the above
// definition.
static _RopeRep* _S_balance(_RopeRep* __r);
// Add all unbalanced subtrees to the forest of balanceed trees.
// Used only by balance.
static void _S_add_to_forest(_RopeRep*__r, _RopeRep** __forest);
// Add __r to forest, assuming __r is already balanced.
static void _S_add_leaf_to_forest(_RopeRep* __r, _RopeRep** __forest);
#ifdef _STLP_DEBUG
// Print to stdout, exposing structure
static void _S_dump(_RopeRep* __r, int __indent = 0);
#endif
// Return -1, 0, or 1 if __x < __y, __x == __y, or __x > __y resp.
static int _S_compare(const _RopeRep* __x, const _RopeRep* __y);
void _STLP_FUNCTION_THROWS _M_throw_out_of_range() const;
void _M_reset(_RopeRep* __r) {
//if (__r != _M_tree_ptr._M_data) {
_S_unref(_M_tree_ptr._M_data);
_M_tree_ptr._M_data = __r;
//}
}
public:
bool empty() const { return 0 == _M_tree_ptr._M_data; }
// Comparison member function. This is public only for those
// clients that need a ternary comparison. Others
// should use the comparison operators below.
int compare(const _Self& __y) const {
return _S_compare(_M_tree_ptr._M_data, __y._M_tree_ptr._M_data);
}
rope(const _CharT* __s, const allocator_type& __a = allocator_type())
: _M_tree_ptr(__a, _S_RopeLeaf_from_unowned_char_ptr(__s, _S_char_ptr_len(__s),__a))
{}
rope(const _CharT* __s, size_t __len,
const allocator_type& __a = allocator_type())
: _M_tree_ptr(__a, (_S_RopeLeaf_from_unowned_char_ptr(__s, __len, __a)))
{}
// Should perhaps be templatized with respect to the iterator type
// and use Sequence_buffer. (It should perhaps use sequence_buffer
// even now.)
rope(const _CharT *__s, const _CharT *__e,
const allocator_type& __a = allocator_type())
: _M_tree_ptr(__a, _S_RopeLeaf_from_unowned_char_ptr(__s, __e - __s, __a))
{}
rope(const const_iterator& __s, const const_iterator& __e,
const allocator_type& __a = allocator_type())
: _M_tree_ptr(__a, _S_substring(__s._M_root, __s._M_current_pos,
__e._M_current_pos))
{}
rope(const iterator& __s, const iterator& __e,
const allocator_type& __a = allocator_type())
: _M_tree_ptr(__a, _S_substring(__s._M_root, __s._M_current_pos,
__e._M_current_pos))
{}
rope(_CharT __c, const allocator_type& __a = allocator_type())
: _M_tree_ptr(__a, (_RopeRep*)0) {
_CharT* __buf = _M_tree_ptr.allocate(_S_rounded_up_size(1));
_Copy_Construct(__buf, __c);
_S_construct_null(__buf + 1);
_STLP_TRY {
_M_tree_ptr._M_data = _S_new_RopeLeaf(__buf, 1, __a);
}
_STLP_UNWIND(_RopeRep::_S_free_string(__buf, 1, __a))
}
rope(size_t __n, _CharT __c,
const allocator_type& __a = allocator_type()):
_M_tree_ptr(__a, (_RopeRep*)0) {
if (0 == __n)
return;
rope<_CharT,_Alloc> __result;
# define __exponentiate_threshold size_t(32)
_RopeRep* __remainder;
rope<_CharT,_Alloc> __remainder_rope;
// gcc-2.7.2 bugs
typedef _STLP_PRIV _Rope_Concat_fn<_CharT,_Alloc> _Concat_fn;
size_t __exponent = __n / __exponentiate_threshold;
size_t __rest = __n % __exponentiate_threshold;
if (0 == __rest) {
__remainder = 0;
} else {
_CharT* __rest_buffer = _M_tree_ptr.allocate(_S_rounded_up_size(__rest));
uninitialized_fill_n(__rest_buffer, __rest, __c);
_S_construct_null(__rest_buffer + __rest);
_STLP_TRY {
__remainder = _S_new_RopeLeaf(__rest_buffer, __rest, __a);
}
_STLP_UNWIND(_RopeRep::_S_free_string(__rest_buffer, __rest, __a))
}
__remainder_rope._M_tree_ptr._M_data = __remainder;
if (__exponent != 0) {
_CharT* __base_buffer = _M_tree_ptr.allocate(_S_rounded_up_size(__exponentiate_threshold));
_RopeLeaf* __base_leaf;
rope<_CharT,_Alloc> __base_rope;
uninitialized_fill_n(__base_buffer, __exponentiate_threshold, __c);
_S_construct_null(__base_buffer + __exponentiate_threshold);
_STLP_TRY {
__base_leaf = _S_new_RopeLeaf(__base_buffer,
__exponentiate_threshold, __a);
}
_STLP_UNWIND(_RopeRep::_S_free_string(__base_buffer,
__exponentiate_threshold, __a))
__base_rope._M_tree_ptr._M_data = __base_leaf;
if (1 == __exponent) {
__result = __base_rope;
// One each for base_rope and __result
//_STLP_ASSERT(2 == __result._M_tree_ptr._M_data->_M_ref_count)
} else {
__result = _STLP_PRIV __power(__base_rope, __exponent, _Concat_fn());
}
if (0 != __remainder) {
__result += __remainder_rope;
}
} else {
__result = __remainder_rope;
}
_M_tree_ptr._M_data = __result._M_tree_ptr._M_data;
_M_tree_ptr._M_data->_M_ref_nonnil();
# undef __exponentiate_threshold
}
rope(const allocator_type& __a = allocator_type())
: _M_tree_ptr(__a, (_RopeRep*)0) {}
// Construct a rope from a function that can compute its members
rope(char_producer<_CharT> *__fn, size_t __len, bool __delete_fn,
const allocator_type& __a = allocator_type())
: _M_tree_ptr(__a, (_RopeRep*)0) {
_M_tree_ptr._M_data = (0 == __len) ?
0 : _S_new_RopeFunction(__fn, __len, __delete_fn, __a);
}
rope(const _Self& __x)
: _M_tree_ptr(__x._M_tree_ptr, __x._M_tree_ptr._M_data) {
_S_ref(_M_tree_ptr._M_data);
}
#if !defined (_STLP_NO_MOVE_SEMANTIC)
rope(__move_source<_Self> __src)
: _M_tree_ptr(__src.get()._M_tree_ptr, __src.get()._M_tree_ptr._M_data) {
__src.get()._M_tree_ptr._M_data = 0;
}
#endif
~rope() {
_S_unref(_M_tree_ptr._M_data);
}
_Self& operator=(const _Self& __x) {
_STLP_ASSERT(get_allocator() == __x.get_allocator())
_S_ref(__x._M_tree_ptr._M_data);
_M_reset(__x._M_tree_ptr._M_data);
return *this;
}
void clear() {
_S_unref(_M_tree_ptr._M_data);
_M_tree_ptr._M_data = 0;
}
void push_back(_CharT __x) {
_M_reset(_S_destr_concat_char_iter(_M_tree_ptr._M_data, &__x, 1));
}
void pop_back() {
_RopeRep* __old = _M_tree_ptr._M_data;
_M_tree_ptr._M_data =
_S_substring(_M_tree_ptr._M_data, 0, _M_tree_ptr._M_data->_M_size._M_data - 1);
_S_unref(__old);
}
_CharT back() const {
return _S_fetch(_M_tree_ptr._M_data, _M_tree_ptr._M_data->_M_size._M_data - 1);
}
void push_front(_CharT __x) {
_RopeRep* __old = _M_tree_ptr._M_data;
_RopeRep* __left =
_S_RopeLeaf_from_unowned_char_ptr(&__x, 1, _M_tree_ptr);
_STLP_TRY {
_M_tree_ptr._M_data = _S_concat_rep(__left, _M_tree_ptr._M_data);
_S_unref(__old);
_S_unref(__left);
}
_STLP_UNWIND(_S_unref(__left))
}
void pop_front() {
_RopeRep* __old = _M_tree_ptr._M_data;
_M_tree_ptr._M_data = _S_substring(_M_tree_ptr._M_data, 1, _M_tree_ptr._M_data->_M_size._M_data);
_S_unref(__old);
}
_CharT front() const {
return _S_fetch(_M_tree_ptr._M_data, 0);
}
void balance() {
_RopeRep* __old = _M_tree_ptr._M_data;
_M_tree_ptr._M_data = _S_balance(_M_tree_ptr._M_data);
_S_unref(__old);
}
void copy(_CharT* __buffer) const {
_STLP_STD::_Destroy_Range(__buffer, __buffer + size());
_S_flatten(_M_tree_ptr._M_data, __buffer);
}
/*
* This is the copy function from the standard, but
* with the arguments reordered to make it consistent with the
* rest of the interface.
* Note that this guaranteed not to compile if the draft standard
* order is assumed.
*/
size_type copy(size_type __pos, size_type __n, _CharT* __buffer) const {
size_t _p_size = size();
size_t __len = (__pos + __n > _p_size? _p_size - __pos : __n);
_STLP_STD::_Destroy_Range(__buffer, __buffer + __len);
_S_flatten(_M_tree_ptr._M_data, __pos, __len, __buffer);
return __len;
}
# ifdef _STLP_DEBUG
// Print to stdout, exposing structure. May be useful for
// performance debugging.
void dump() {
_S_dump(_M_tree_ptr._M_data);
}
# endif
// Convert to 0 terminated string in new allocated memory.
// Embedded 0s in the input do not terminate the copy.
const _CharT* c_str() const;
// As above, but also use the flattened representation as the
// the new rope representation.
const _CharT* replace_with_c_str();
// Reclaim memory for the c_str generated flattened string.
// Intentionally undocumented, since it's hard to say when this
// is safe for multiple threads.
void delete_c_str () {
if (0 == _M_tree_ptr._M_data) return;
if (_RopeRep::_S_leaf == _M_tree_ptr._M_data->_M_tag &&
((_RopeLeaf*)_M_tree_ptr._M_data)->_M_data ==
_M_tree_ptr._M_data->_M_c_string) {
// Representation shared
return;
}
_M_tree_ptr._M_data->_M_free_c_string();
_M_tree_ptr._M_data->_M_c_string = 0;
}
_CharT operator[] (size_type __pos) const {
return _S_fetch(_M_tree_ptr._M_data, __pos);
}
_CharT at(size_type __pos) const {
if (__pos >= size()) _M_throw_out_of_range();
return (*this)[__pos];
}
const_iterator begin() const {
return(const_iterator(_M_tree_ptr._M_data, 0));
}
// An easy way to get a const iterator from a non-const container.
const_iterator const_begin() const {
return(const_iterator(_M_tree_ptr._M_data, 0));
}
const_iterator end() const {
return(const_iterator(_M_tree_ptr._M_data, size()));
}
const_iterator const_end() const {
return(const_iterator(_M_tree_ptr._M_data, size()));
}
size_type size() const {
return(0 == _M_tree_ptr._M_data? 0 : _M_tree_ptr._M_data->_M_size._M_data);
}
size_type length() const {
return size();
}
size_type max_size() const {
return _S_min_len[__ROPE_MAX_DEPTH-1] - 1;
// Guarantees that the result can be sufficiently
// balanced. Longer ropes will probably still work,
// but it's harder to make guarantees.
}
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
const_reverse_iterator const_rbegin() const {
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
const_reverse_iterator const_rend() const {
return const_reverse_iterator(begin());
}
// The symmetric cases are intentionally omitted, since they're presumed
// to be less common, and we don't handle them as well.
// The following should really be templatized.
// The first argument should be an input iterator or
// forward iterator with value_type _CharT.
_Self& append(const _CharT* __iter, size_t __n) {
_M_reset(_S_destr_concat_char_iter(_M_tree_ptr._M_data, __iter, __n));
return *this;
}
_Self& append(const _CharT* __c_string) {
size_t __len = _S_char_ptr_len(__c_string);
append(__c_string, __len);
return *this;
}
_Self& append(const _CharT* __s, const _CharT* __e) {
_M_reset(_S_destr_concat_char_iter(_M_tree_ptr._M_data, __s, __e - __s));
return *this;
}
_Self& append(const_iterator __s, const_iterator __e) {
_STLP_ASSERT(__s._M_root == __e._M_root)
_STLP_ASSERT(get_allocator() == __s._M_root->get_allocator())
_Self_destruct_ptr __appendee(_S_substring(__s._M_root, __s._M_current_pos, __e._M_current_pos));
_M_reset(_S_concat_rep(_M_tree_ptr._M_data, (_RopeRep*)__appendee));
return *this;
}
_Self& append(_CharT __c) {
_M_reset(_S_destr_concat_char_iter(_M_tree_ptr._M_data, &__c, 1));
return *this;
}
_Self& append() { return append(_CharT()); } // XXX why?
_Self& append(const _Self& __y) {
_STLP_ASSERT(__y.get_allocator() == get_allocator())
_M_reset(_S_concat_rep(_M_tree_ptr._M_data, __y._M_tree_ptr._M_data));
return *this;
}
_Self& append(size_t __n, _CharT __c) {
rope<_CharT,_Alloc> __last(__n, __c);
return append(__last);
}
void swap(_Self& __b) {
_M_tree_ptr.swap(__b._M_tree_ptr);
}
#if defined (_STLP_USE_PARTIAL_SPEC_WORKAROUND) && !defined (_STLP_FUNCTION_TMPL_PARTIAL_ORDER)
void _M_swap_workaround(_Self& __x) { swap(__x); }
#endif
protected:
// Result is included in refcount.
static _RopeRep* replace(_RopeRep* __old, size_t __pos1,
size_t __pos2, _RopeRep* __r) {
if (0 == __old) { _S_ref(__r); return __r; }
_Self_destruct_ptr __left(_S_substring(__old, 0, __pos1));
_Self_destruct_ptr __right(_S_substring(__old, __pos2, __old->_M_size._M_data));
_STLP_MPWFIX_TRY //*TY 06/01/2000 -
_RopeRep* __result;
if (0 == __r) {
__result = _S_concat_rep(__left, __right);
} else {
_STLP_ASSERT(__old->get_allocator() == __r->get_allocator())
_Self_destruct_ptr __left_result(_S_concat_rep(__left, __r));
__result = _S_concat_rep(__left_result, __right);
}
return __result;
_STLP_MPWFIX_CATCH //*TY 06/01/2000 -
}
public:
void insert(size_t __p, const _Self& __r) {
if (__p > size()) _M_throw_out_of_range();
_STLP_ASSERT(get_allocator() == __r.get_allocator())
_M_reset(replace(_M_tree_ptr._M_data, __p, __p, __r._M_tree_ptr._M_data));
}
void insert(size_t __p, size_t __n, _CharT __c) {
rope<_CharT,_Alloc> __r(__n,__c);
insert(__p, __r);
}
void insert(size_t __p, const _CharT* __i, size_t __n) {
if (__p > size()) _M_throw_out_of_range();
_Self_destruct_ptr __left(_S_substring(_M_tree_ptr._M_data, 0, __p));
_Self_destruct_ptr __right(_S_substring(_M_tree_ptr._M_data, __p, size()));
_Self_destruct_ptr __left_result(
_S_concat_char_iter(__left, __i, __n));
// _S_ destr_concat_char_iter should be safe here.
// But as it stands it's probably not a win, since __left
// is likely to have additional references.
_M_reset(_S_concat_rep(__left_result, __right));
}
void insert(size_t __p, const _CharT* __c_string) {
insert(__p, __c_string, _S_char_ptr_len(__c_string));
}
void insert(size_t __p, _CharT __c) {
insert(__p, &__c, 1);
}
void insert(size_t __p) {
_CharT __c = _CharT();
insert(__p, &__c, 1);
}
void insert(size_t __p, const _CharT* __i, const _CharT* __j) {
_Self __r(__i, __j);
insert(__p, __r);
}
void insert(size_t __p, const const_iterator& __i,
const const_iterator& __j) {
_Self __r(__i, __j);
insert(__p, __r);
}
void insert(size_t __p, const iterator& __i,
const iterator& __j) {
_Self __r(__i, __j);
insert(__p, __r);
}
// (position, length) versions of replace operations:
void replace(size_t __p, size_t __n, const _Self& __r) {
if (__p > size()) _M_throw_out_of_range();
_M_reset(replace(_M_tree_ptr._M_data, __p, __p + __n, __r._M_tree_ptr._M_data));
}
void replace(size_t __p, size_t __n,
const _CharT* __i, size_t __i_len) {
_Self __r(__i, __i_len);
replace(__p, __n, __r);
}
void replace(size_t __p, size_t __n, _CharT __c) {
_Self __r(__c);
replace(__p, __n, __r);
}
void replace(size_t __p, size_t __n, const _CharT* __c_string) {
_Self __r(__c_string);
replace(__p, __n, __r);
}
void replace(size_t __p, size_t __n,
const _CharT* __i, const _CharT* __j) {
_Self __r(__i, __j);
replace(__p, __n, __r);
}
void replace(size_t __p, size_t __n,
const const_iterator& __i, const const_iterator& __j) {
_Self __r(__i, __j);
replace(__p, __n, __r);
}
void replace(size_t __p, size_t __n,
const iterator& __i, const iterator& __j) {
_Self __r(__i, __j);
replace(__p, __n, __r);
}
// Single character variants:
void replace(size_t __p, _CharT __c) {
if (__p > size()) _M_throw_out_of_range();
iterator __i(this, __p);
*__i = __c;
}
void replace(size_t __p, const _Self& __r) {
replace(__p, 1, __r);
}
void replace(size_t __p, const _CharT* __i, size_t __i_len) {
replace(__p, 1, __i, __i_len);
}
void replace(size_t __p, const _CharT* __c_string) {
replace(__p, 1, __c_string);
}
void replace(size_t __p, const _CharT* __i, const _CharT* __j) {
replace(__p, 1, __i, __j);
}
void replace(size_t __p, const const_iterator& __i,
const const_iterator& __j) {
replace(__p, 1, __i, __j);
}
void replace(size_t __p, const iterator& __i,
const iterator& __j) {
replace(__p, 1, __i, __j);
}
// Erase, (position, size) variant.
void erase(size_t __p, size_t __n) {
if (__p > size()) _M_throw_out_of_range();
_M_reset(replace(_M_tree_ptr._M_data, __p, __p + __n, 0));
}
// Erase, single character
void erase(size_t __p) {
erase(__p, __p + 1);
}
// Insert, iterator variants.
iterator insert(const iterator& __p, const _Self& __r)
{ insert(__p.index(), __r); return __p; }
iterator insert(const iterator& __p, size_t __n, _CharT __c)
{ insert(__p.index(), __n, __c); return __p; }
iterator insert(const iterator& __p, _CharT __c)
{ insert(__p.index(), __c); return __p; }
iterator insert(const iterator& __p )
{ insert(__p.index()); return __p; }
iterator insert(const iterator& __p, const _CharT* c_string)
{ insert(__p.index(), c_string); return __p; }
iterator insert(const iterator& __p, const _CharT* __i, size_t __n)
{ insert(__p.index(), __i, __n); return __p; }
iterator insert(const iterator& __p, const _CharT* __i,
const _CharT* __j)
{ insert(__p.index(), __i, __j); return __p; }
iterator insert(const iterator& __p,
const const_iterator& __i, const const_iterator& __j)
{ insert(__p.index(), __i, __j); return __p; }
iterator insert(const iterator& __p,
const iterator& __i, const iterator& __j)
{ insert(__p.index(), __i, __j); return __p; }
// Replace, range variants.
void replace(const iterator& __p, const iterator& __q,
const _Self& __r)
{ replace(__p.index(), __q.index() - __p.index(), __r); }
void replace(const iterator& __p, const iterator& __q, _CharT __c)
{ replace(__p.index(), __q.index() - __p.index(), __c); }
void replace(const iterator& __p, const iterator& __q,
const _CharT* __c_string)
{ replace(__p.index(), __q.index() - __p.index(), __c_string); }
void replace(const iterator& __p, const iterator& __q,
const _CharT* __i, size_t __n)
{ replace(__p.index(), __q.index() - __p.index(), __i, __n); }
void replace(const iterator& __p, const iterator& __q,
const _CharT* __i, const _CharT* __j)
{ replace(__p.index(), __q.index() - __p.index(), __i, __j); }
void replace(const iterator& __p, const iterator& __q,
const const_iterator& __i, const const_iterator& __j)
{ replace(__p.index(), __q.index() - __p.index(), __i, __j); }
void replace(const iterator& __p, const iterator& __q,
const iterator& __i, const iterator& __j)
{ replace(__p.index(), __q.index() - __p.index(), __i, __j); }
// Replace, iterator variants.
void replace(const iterator& __p, const _Self& __r)
{ replace(__p.index(), __r); }
void replace(const iterator& __p, _CharT __c)
{ replace(__p.index(), __c); }
void replace(const iterator& __p, const _CharT* __c_string)
{ replace(__p.index(), __c_string); }
void replace(const iterator& __p, const _CharT* __i, size_t __n)
{ replace(__p.index(), __i, __n); }
void replace(const iterator& __p, const _CharT* __i, const _CharT* __j)
{ replace(__p.index(), __i, __j); }
void replace(const iterator& __p, const_iterator __i,
const_iterator __j)
{ replace(__p.index(), __i, __j); }
void replace(const iterator& __p, iterator __i, iterator __j)
{ replace(__p.index(), __i, __j); }
// Iterator and range variants of erase
iterator erase(const iterator& __p, const iterator& __q) {
size_t __p_index = __p.index();
erase(__p_index, __q.index() - __p_index);
return iterator(this, __p_index);
}
iterator erase(const iterator& __p) {
size_t __p_index = __p.index();
erase(__p_index, 1);
return iterator(this, __p_index);
}
_Self substr(size_t __start, size_t __len = 1) const {
if (__start > size()) _M_throw_out_of_range();
return rope<_CharT,_Alloc>(_S_substring(_M_tree_ptr._M_data, __start, __start + __len));
}
_Self substr(iterator __start, iterator __end) const {
return rope<_CharT,_Alloc>(_S_substring(_M_tree_ptr._M_data, __start.index(), __end.index()));
}
_Self substr(iterator __start) const {
size_t __pos = __start.index();
return rope<_CharT,_Alloc>(_S_substring(_M_tree_ptr._M_data, __pos, __pos + 1));
}
_Self substr(const_iterator __start, const_iterator __end) const {
// This might eventually take advantage of the cache in the
// iterator.
return rope<_CharT,_Alloc>(_S_substring(_M_tree_ptr._M_data, __start.index(), __end.index()));
}
rope<_CharT,_Alloc> substr(const_iterator __start) {
size_t __pos = __start.index();
return rope<_CharT,_Alloc>(_S_substring(_M_tree_ptr._M_data, __pos, __pos + 1));
}
#include <stl/_string_npos.h>
size_type find(const _Self& __s, size_type __pos = 0) const {
if (__pos >= size())
# ifndef _STLP_OLD_ROPE_SEMANTICS
return npos;
# else
return size();
# endif
size_type __result_pos;
const_iterator __result = _STLP_STD::search(const_begin() + (ptrdiff_t)__pos, const_end(), __s.begin(), __s.end() );
__result_pos = __result.index();
# ifndef _STLP_OLD_ROPE_SEMANTICS
if (__result_pos == size()) __result_pos = npos;
# endif
return __result_pos;
}
size_type find(_CharT __c, size_type __pos = 0) const;
size_type find(const _CharT* __s, size_type __pos = 0) const {
size_type __result_pos;
const_iterator __result = _STLP_STD::search(const_begin() + (ptrdiff_t)__pos, const_end(),
__s, __s + _S_char_ptr_len(__s));
__result_pos = __result.index();
# ifndef _STLP_OLD_ROPE_SEMANTICS
if (__result_pos == size()) __result_pos = npos;
# endif
return __result_pos;
}
iterator mutable_begin() {
return(iterator(this, 0));
}
iterator mutable_end() {
return(iterator(this, size()));
}
reverse_iterator mutable_rbegin() {
return reverse_iterator(mutable_end());
}
reverse_iterator mutable_rend() {
return reverse_iterator(mutable_begin());
}
reference mutable_reference_at(size_type __pos) {
return reference(this, __pos);
}
# ifdef __STD_STUFF
reference operator[] (size_type __pos) {
return reference(this, __pos);
}
reference at(size_type __pos) {
if (__pos >= size()) _M_throw_out_of_range();
return (*this)[__pos];
}
void resize(size_type, _CharT) {}
void resize(size_type) {}
void reserve(size_type = 0) {}
size_type capacity() const {
return max_size();
}
// Stuff below this line is dangerous because it's error prone.
// I would really like to get rid of it.
// copy function with funny arg ordering.
size_type copy(_CharT* __buffer, size_type __n,
size_type __pos = 0) const {
return copy(__pos, __n, __buffer);
}
iterator end() { return mutable_end(); }
iterator begin() { return mutable_begin(); }
reverse_iterator rend() { return mutable_rend(); }
reverse_iterator rbegin() { return mutable_rbegin(); }
# else
const_iterator end() { return const_end(); }
const_iterator begin() { return const_begin(); }
const_reverse_iterator rend() { return const_rend(); }
const_reverse_iterator rbegin() { return const_rbegin(); }
# endif
}; //class rope
#if defined (__GNUC__) && (__GNUC__ == 2) && (__GNUC_MINOR__ == 96)
template <class _CharT, class _Alloc>
const size_t rope<_CharT, _Alloc>::npos = ~(size_t) 0;
#endif
template <class _CharT, class _Alloc>
inline _CharT
_Rope_const_iterator< _CharT, _Alloc>::operator[](size_t __n)
{ return rope<_CharT,_Alloc>::_S_fetch(this->_M_root, this->_M_current_pos + __n); }
template <class _CharT, class _Alloc>
inline bool operator== (const _Rope_const_iterator<_CharT,_Alloc>& __x,
const _Rope_const_iterator<_CharT,_Alloc>& __y) {
return (__x._M_current_pos == __y._M_current_pos &&
__x._M_root == __y._M_root);
}
template <class _CharT, class _Alloc>
inline bool operator< (const _Rope_const_iterator<_CharT,_Alloc>& __x,
const _Rope_const_iterator<_CharT,_Alloc>& __y)
{ return (__x._M_current_pos < __y._M_current_pos); }
#ifdef _STLP_USE_SEPARATE_RELOPS_NAMESPACE
template <class _CharT, class _Alloc>
inline bool operator!= (const _Rope_const_iterator<_CharT,_Alloc>& __x,
const _Rope_const_iterator<_CharT,_Alloc>& __y)
{ return !(__x == __y); }
template <class _CharT, class _Alloc>
inline bool operator> (const _Rope_const_iterator<_CharT,_Alloc>& __x,
const _Rope_const_iterator<_CharT,_Alloc>& __y)
{ return __y < __x; }
template <class _CharT, class _Alloc>
inline bool operator<= (const _Rope_const_iterator<_CharT,_Alloc>& __x,
const _Rope_const_iterator<_CharT,_Alloc>& __y)
{ return !(__y < __x); }
template <class _CharT, class _Alloc>
inline bool operator>= (const _Rope_const_iterator<_CharT,_Alloc>& __x,
const _Rope_const_iterator<_CharT,_Alloc>& __y)
{ return !(__x < __y); }
#endif /* _STLP_USE_SEPARATE_RELOPS_NAMESPACE */
template <class _CharT, class _Alloc>
inline ptrdiff_t operator-(const _Rope_const_iterator<_CharT,_Alloc>& __x,
const _Rope_const_iterator<_CharT,_Alloc>& __y)
{ return (ptrdiff_t)__x._M_current_pos - (ptrdiff_t)__y._M_current_pos; }
#if !defined( __MWERKS__ ) || __MWERKS__ >= 0x2000 // dwa 8/21/97 - "ambiguous access to overloaded function" bug.
template <class _CharT, class _Alloc>
inline _Rope_const_iterator<_CharT,_Alloc>
operator-(const _Rope_const_iterator<_CharT,_Alloc>& __x, ptrdiff_t __n)
{ return _Rope_const_iterator<_CharT,_Alloc>(__x._M_root, __x._M_current_pos - __n); }
# endif
template <class _CharT, class _Alloc>
inline _Rope_const_iterator<_CharT,_Alloc>
operator+(const _Rope_const_iterator<_CharT,_Alloc>& __x, ptrdiff_t __n)
{ return _Rope_const_iterator<_CharT,_Alloc>(__x._M_root, __x._M_current_pos + __n); }
template <class _CharT, class _Alloc>
inline _Rope_const_iterator<_CharT,_Alloc>
operator+(ptrdiff_t __n, const _Rope_const_iterator<_CharT,_Alloc>& __x)
{ return _Rope_const_iterator<_CharT,_Alloc>(__x._M_root, __x._M_current_pos + __n); }
template <class _CharT, class _Alloc>
inline bool operator== (const _Rope_iterator<_CharT,_Alloc>& __x,
const _Rope_iterator<_CharT,_Alloc>& __y) {
return (__x._M_current_pos == __y._M_current_pos &&
__x._M_root_rope == __y._M_root_rope);
}
template <class _CharT, class _Alloc>
inline bool operator< (const _Rope_iterator<_CharT,_Alloc>& __x,
const _Rope_iterator<_CharT,_Alloc>& __y)
{ return (__x._M_current_pos < __y._M_current_pos); }
#if defined (_STLP_USE_SEPARATE_RELOPS_NAMESPACE)
template <class _CharT, class _Alloc>
inline bool operator!= (const _Rope_iterator<_CharT,_Alloc>& __x,
const _Rope_iterator<_CharT,_Alloc>& __y)
{ return !(__x == __y); }
template <class _CharT, class _Alloc>
inline bool operator> (const _Rope_iterator<_CharT,_Alloc>& __x,
const _Rope_iterator<_CharT,_Alloc>& __y)
{ return __y < __x; }
template <class _CharT, class _Alloc>
inline bool operator<= (const _Rope_iterator<_CharT,_Alloc>& __x,
const _Rope_iterator<_CharT,_Alloc>& __y)
{ return !(__y < __x); }
template <class _CharT, class _Alloc>
inline bool operator>= (const _Rope_iterator<_CharT,_Alloc>& __x,
const _Rope_iterator<_CharT,_Alloc>& __y)
{ return !(__x < __y); }
#endif /* _STLP_USE_SEPARATE_RELOPS_NAMESPACE */
template <class _CharT, class _Alloc>
inline ptrdiff_t operator-(const _Rope_iterator<_CharT,_Alloc>& __x,
const _Rope_iterator<_CharT,_Alloc>& __y)
{ return (ptrdiff_t)__x._M_current_pos - (ptrdiff_t)__y._M_current_pos; }
#if !defined( __MWERKS__ ) || __MWERKS__ >= 0x2000 // dwa 8/21/97 - "ambiguous access to overloaded function" bug.
template <class _CharT, class _Alloc>
inline _Rope_iterator<_CharT,_Alloc>
operator-(const _Rope_iterator<_CharT,_Alloc>& __x,
ptrdiff_t __n) {
return _Rope_iterator<_CharT,_Alloc>(__x._M_root_rope, __x._M_current_pos - __n);
}
# endif
template <class _CharT, class _Alloc>
inline _Rope_iterator<_CharT,_Alloc>
operator+(const _Rope_iterator<_CharT,_Alloc>& __x,
ptrdiff_t __n) {
return _Rope_iterator<_CharT,_Alloc>(__x._M_root_rope, __x._M_current_pos + __n);
}
template <class _CharT, class _Alloc>
inline _Rope_iterator<_CharT,_Alloc>
operator+(ptrdiff_t __n, const _Rope_iterator<_CharT,_Alloc>& __x) {
return _Rope_iterator<_CharT,_Alloc>(__x._M_root_rope, __x._M_current_pos + __n);
}
template <class _CharT, class _Alloc>
inline rope<_CharT,_Alloc>
operator+ (const rope<_CharT,_Alloc>& __left,
const rope<_CharT,_Alloc>& __right) {
_STLP_ASSERT(__left.get_allocator() == __right.get_allocator())
return rope<_CharT,_Alloc>(rope<_CharT,_Alloc>::_S_concat_rep(__left._M_tree_ptr._M_data, __right._M_tree_ptr._M_data));
// Inlining this should make it possible to keep __left and __right in registers.
}
template <class _CharT, class _Alloc>
inline rope<_CharT,_Alloc>&
operator+= (rope<_CharT,_Alloc>& __left,
const rope<_CharT,_Alloc>& __right) {
__left.append(__right);
return __left;
}
template <class _CharT, class _Alloc>
inline rope<_CharT,_Alloc>
operator+ (const rope<_CharT,_Alloc>& __left,
const _CharT* __right) {
size_t __rlen = rope<_CharT,_Alloc>::_S_char_ptr_len(__right);
return rope<_CharT,_Alloc>(rope<_CharT,_Alloc>::_S_concat_char_iter(__left._M_tree_ptr._M_data, __right, __rlen));
}
template <class _CharT, class _Alloc>
inline rope<_CharT,_Alloc>&
operator+= (rope<_CharT,_Alloc>& __left,
const _CharT* __right) {
__left.append(__right);
return __left;
}
template <class _CharT, class _Alloc>
inline rope<_CharT,_Alloc>
operator+ (const rope<_CharT,_Alloc>& __left, _CharT __right) {
return rope<_CharT,_Alloc>(rope<_CharT,_Alloc>::_S_concat_char_iter(__left._M_tree_ptr._M_data, &__right, 1));
}
template <class _CharT, class _Alloc>
inline rope<_CharT,_Alloc>&
operator+= (rope<_CharT,_Alloc>& __left, _CharT __right) {
__left.append(__right);
return __left;
}
template <class _CharT, class _Alloc>
inline bool
operator< (const rope<_CharT,_Alloc>& __left,
const rope<_CharT,_Alloc>& __right) {
return __left.compare(__right) < 0;
}
template <class _CharT, class _Alloc>
inline bool
operator== (const rope<_CharT,_Alloc>& __left,
const rope<_CharT,_Alloc>& __right) {
return __left.compare(__right) == 0;
}
#ifdef _STLP_USE_SEPARATE_RELOPS_NAMESPACE
template <class _CharT, class _Alloc>
inline bool
operator!= (const rope<_CharT,_Alloc>& __x, const rope<_CharT,_Alloc>& __y) {
return !(__x == __y);
}
template <class _CharT, class _Alloc>
inline bool
operator> (const rope<_CharT,_Alloc>& __x, const rope<_CharT,_Alloc>& __y) {
return __y < __x;
}
template <class _CharT, class _Alloc>
inline bool
operator<= (const rope<_CharT,_Alloc>& __x, const rope<_CharT,_Alloc>& __y) {
return !(__y < __x);
}
template <class _CharT, class _Alloc>
inline bool
operator>= (const rope<_CharT,_Alloc>& __x, const rope<_CharT,_Alloc>& __y) {
return !(__x < __y);
}
template <class _CharT, class _Alloc>
inline bool operator!= (const _Rope_char_ptr_proxy<_CharT,_Alloc>& __x,
const _Rope_char_ptr_proxy<_CharT,_Alloc>& __y) {
return !(__x == __y);
}
#endif /* _STLP_USE_SEPARATE_RELOPS_NAMESPACE */
template <class _CharT, class _Alloc>
inline bool operator== (const _Rope_char_ptr_proxy<_CharT,_Alloc>& __x,
const _Rope_char_ptr_proxy<_CharT,_Alloc>& __y) {
return (__x._M_pos == __y._M_pos && __x._M_root == __y._M_root);
}
#if !defined (_STLP_USE_NO_IOSTREAMS)
template<class _CharT, class _Traits, class _Alloc>
basic_ostream<_CharT, _Traits>& operator<< (basic_ostream<_CharT, _Traits>& __o,
const rope<_CharT, _Alloc>& __r);
#endif
typedef rope<char, allocator<char> > crope;
#if defined (_STLP_HAS_WCHAR_T)
typedef rope<wchar_t, allocator<wchar_t> > wrope;
#endif
inline crope::reference __mutable_reference_at(crope& __c, size_t __i)
{ return __c.mutable_reference_at(__i); }
#if defined (_STLP_HAS_WCHAR_T)
inline wrope::reference __mutable_reference_at(wrope& __c, size_t __i)
{ return __c.mutable_reference_at(__i); }
#endif
#if defined (_STLP_FUNCTION_TMPL_PARTIAL_ORDER)
template <class _CharT, class _Alloc>
inline void swap(rope<_CharT,_Alloc>& __x, rope<_CharT,_Alloc>& __y)
{ __x.swap(__y); }
#else
inline void swap(crope& __x, crope& __y) { __x.swap(__y); }
# ifdef _STLP_HAS_WCHAR_T // dwa 8/21/97
inline void swap(wrope& __x, wrope& __y) { __x.swap(__y); }
# endif
#endif /* _STLP_FUNCTION_TMPL_PARTIAL_ORDER */
// Hash functions should probably be revisited later:
_STLP_TEMPLATE_NULL struct hash<crope> {
size_t operator()(const crope& __str) const {
size_t _p_size = __str.size();
if (0 == _p_size) return 0;
return 13*__str[0] + 5*__str[_p_size - 1] + _p_size;
}
};
#if defined (_STLP_HAS_WCHAR_T) // dwa 8/21/97
_STLP_TEMPLATE_NULL struct hash<wrope> {
size_t operator()(const wrope& __str) const {
size_t _p_size = __str.size();
if (0 == _p_size) return 0;
return 13*__str[0] + 5*__str[_p_size - 1] + _p_size;
}
};
#endif
#if (!defined (_STLP_MSVC) || (_STLP_MSVC >= 1310))
// I couldn't get this to work with VC++
template<class _CharT,class _Alloc>
# if defined (__DMC__)
extern
# endif
void _Rope_rotate(_Rope_iterator<_CharT, _Alloc> __first,
_Rope_iterator<_CharT, _Alloc> __middle,
_Rope_iterator<_CharT, _Alloc> __last);
inline void rotate(_Rope_iterator<char, allocator<char> > __first,
_Rope_iterator<char, allocator<char> > __middle,
_Rope_iterator<char, allocator<char> > __last)
{ _Rope_rotate(__first, __middle, __last); }
#endif
template <class _CharT, class _Alloc>
inline _Rope_char_ref_proxy<_CharT, _Alloc>::operator _CharT () const {
if (_M_current_valid) {
return _M_current;
} else {
return _My_rope::_S_fetch(_M_root->_M_tree_ptr._M_data, _M_pos);
}
}
#if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION) && !defined (_STLP_NO_MOVE_SEMANTIC)
template <class _CharT, class _Alloc>
struct __move_traits<rope<_CharT, _Alloc> > {
typedef __true_type implemented;
//Completness depends on the allocator:
typedef typename __move_traits<_Alloc>::complete complete;
};
#endif
_STLP_END_NAMESPACE
#if !defined (_STLP_LINK_TIME_INSTANTIATION)
# include <stl/_rope.c>
#endif
#endif /* _STLP_INTERNAL_ROPE_H */
// Local Variables:
// mode:C++
// End:
| [
"331201091@qq.com"
] | 331201091@qq.com |
708e125bf8ce2375b99689d29046aad43647bdf7 | 92ef9ddd14e80aa2f17928985ee700eb5852c785 | /Challenge-ReadSerial-Slave.ino | 591a8c05cf467b4b9d0494d9015f6ddb7a9fa92d | [] | no_license | OmriRaz/Ninja-Challenge-Intel-2019 | 530dee02ae1c1754fcfde50482564010d8736c7b | 94cfe2d5746b37b0614bed6b74ef7386bfa4b6c9 | refs/heads/master | 2021-06-30T10:12:09.193488 | 2021-03-02T14:10:16 | 2021-03-02T14:10:16 | 226,540,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | ino | #include<SoftwareSerial.h>
SoftwareSerial SLAVE(2,3);
String input = "0";
void setup() {
SLAVE.begin(9600);
Serial.begin(9600);
}
void loop() {
while(SLAVE.available() > 0) {
input = SLAVE.read();
Serial.println("Recieved code is: " + input);
}
}
| [
"noreply@github.com"
] | OmriRaz.noreply@github.com |
78673482b3db29f0d28ec6224b57931364ad991e | 941214a73266366edbf48a05971c8c83512bfcda | /MS/directshow/baseclassesvc2017/transip.h | e59199d681e47b72c67c4c385854758769a8c143 | [] | no_license | sjk7/edu | 19c2f570c5addc02dbcb675cb4c37c578ecbb839 | 41842fca23d46b3d7709f40117e26490fd06b22b | refs/heads/master | 2020-06-15T19:37:16.043521 | 2017-11-19T05:48:18 | 2017-11-19T05:48:18 | 75,267,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,578 | h | //------------------------------------------------------------------------------
// File: TransIP.h
//
// Desc: DirectShow base classes - defines classes from which simple
// Transform-In-Place filters may be derived.
//
// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
//
// The difference between this and Transfrm.h is that Transfrm copies the data.
//
// It assumes the filter has one input and one output stream, and has no
// interest in memory management, interface negotiation or anything else.
//
// Derive your class from this, and supply Transform and the media type/format
// negotiation functions. Implement that class, compile and link and
// you're done.
#ifndef __TRANSIP__
#define __TRANSIP__
// ======================================================================
// This is the com object that represents a simple transform filter. It
// supports IBaseFilter, IMediaFilter and two pins through nested interfaces
// ======================================================================
class CTransInPlaceFilter;
// Several of the pin functions call filter functions to do the work,
// so you can often use the pin classes unaltered, just overriding the
// functions in CTransInPlaceFilter. If that's not enough and you want
// to derive your own pin class, override GetPin in the filter to supply
// your own pin classes to the filter.
// ==================================================
// Implements the input pin
// ==================================================
class CTransInPlaceInputPin : public CTransformInputPin
{
protected:
CTransInPlaceFilter * const m_pTIPFilter; // our filter
BOOL m_bReadOnly; // incoming stream is read only
public:
CTransInPlaceInputPin(
__in_opt LPCTSTR pObjectName,
__inout CTransInPlaceFilter *pFilter,
__inout HRESULT *phr,
__in_opt LPCWSTR pName);
// --- IMemInputPin -----
// Provide an enumerator for media types by getting one from downstream
STDMETHODIMP EnumMediaTypes( __deref_out IEnumMediaTypes **ppEnum );
// Say whether media type is acceptable.
HRESULT CheckMediaType(const CMediaType* pmt);
// Return our upstream allocator
STDMETHODIMP GetAllocator(__deref_out IMemAllocator ** ppAllocator);
// get told which allocator the upstream output pin is actually
// going to use.
STDMETHODIMP NotifyAllocator(IMemAllocator * pAllocator,
BOOL bReadOnly);
// Allow the filter to see what allocator we have
// N.B. This does NOT AddRef
IMemAllocator * PeekAllocator() const
{ return m_pAllocator; }
// Pass this on downstream if it ever gets called.
STDMETHODIMP GetAllocatorRequirements(__out ALLOCATOR_PROPERTIES *pProps);
HRESULT CompleteConnect(IPin *pReceivePin);
inline const BOOL ReadOnly() { return m_bReadOnly ; }
}; // CTransInPlaceInputPin
// ==================================================
// Implements the output pin
// ==================================================
class CTransInPlaceOutputPin : public CTransformOutputPin
{
protected:
// m_pFilter points to our CBaseFilter
CTransInPlaceFilter * const m_pTIPFilter;
public:
CTransInPlaceOutputPin(
__in_opt LPCTSTR pObjectName,
__inout CTransInPlaceFilter *pFilter,
__inout HRESULT *phr,
__in_opt LPCWSTR pName);
// --- CBaseOutputPin ------------
// negotiate the allocator and its buffer size/count
// Insists on using our own allocator. (Actually the one upstream of us).
// We don't override this - instead we just agree the default
// then let the upstream filter decide for itself on reconnect
// virtual HRESULT DecideAllocator(IMemInputPin * pPin, IMemAllocator ** pAlloc);
// Provide a media type enumerator. Get it from upstream.
STDMETHODIMP EnumMediaTypes( __deref_out IEnumMediaTypes **ppEnum );
// Say whether media type is acceptable.
HRESULT CheckMediaType(const CMediaType* pmt);
// This just saves the allocator being used on the output pin
// Also called by input pin's GetAllocator()
void SetAllocator(IMemAllocator * pAllocator);
IMemInputPin * ConnectedIMemInputPin()
{ return m_pInputPin; }
// Allow the filter to see what allocator we have
// N.B. This does NOT AddRef
IMemAllocator * PeekAllocator() const
{ return m_pAllocator; }
HRESULT CompleteConnect(IPin *pReceivePin);
}; // CTransInPlaceOutputPin
class AM_NOVTABLE CTransInPlaceFilter : public CTransformFilter
{
public:
// map getpin/getpincount for base enum of pins to owner
// override this to return more specialised pin objects
virtual CBasePin *GetPin(int n);
public:
// Set bModifiesData == false if your derived filter does
// not modify the data samples (for instance it's just copying
// them somewhere else or looking at the timestamps).
CTransInPlaceFilter(__in_opt LPCTSTR, __inout_opt LPUNKNOWN, REFCLSID clsid, __inout HRESULT *,
bool bModifiesData = true);
#ifdef UNICODE
CTransInPlaceFilter(__in_opt LPCSTR, __inout_opt LPUNKNOWN, REFCLSID clsid, __inout HRESULT *,
bool bModifiesData = true);
#endif
// The following are defined to avoid undefined pure virtuals.
// Even if they are never called, they will give linkage warnings/errors
// We override EnumMediaTypes to bypass the transform class enumerator
// which would otherwise call this.
HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType)
{ DbgBreak("CTransInPlaceFilter::GetMediaType should never be called");
return E_UNEXPECTED;
}
// This is called when we actually have to provide our own allocator.
HRESULT DecideBufferSize(IMemAllocator*, __inout ALLOCATOR_PROPERTIES *);
// The functions which call this in CTransform are overridden in this
// class to call CheckInputType with the assumption that the type
// does not change. In Debug builds some calls will be made and
// we just ensure that they do not assert.
HRESULT CheckTransform(const CMediaType *mtIn, const CMediaType *mtOut)
{
return S_OK;
};
// =================================================================
// ----- You may want to override this -----------------------------
// =================================================================
HRESULT CompleteConnect(PIN_DIRECTION dir,IPin *pReceivePin);
// chance to customize the transform process
virtual HRESULT Receive(IMediaSample *pSample);
// =================================================================
// ----- You MUST override these -----------------------------------
// =================================================================
virtual HRESULT Transform(IMediaSample *pSample) PURE;
// this goes in the factory template table to create new instances
// static CCOMObject * CreateInstance(LPUNKNOWN, HRESULT *);
#ifdef PERF
// Override to register performance measurement with a less generic string
// You should do this to avoid confusion with other filters
virtual void RegisterPerfId()
{m_idTransInPlace = MSR_REGISTER(TEXT("TransInPlace"));}
#endif // PERF
// implementation details
protected:
IMediaSample * CTransInPlaceFilter::Copy(IMediaSample *pSource);
#ifdef PERF
int m_idTransInPlace; // performance measuring id
#endif // PERF
bool m_bModifiesData; // Does this filter change the data?
// these hold our input and output pins
friend class CTransInPlaceInputPin;
friend class CTransInPlaceOutputPin;
CTransInPlaceInputPin *InputPin() const
{
return (CTransInPlaceInputPin *)m_pInput;
};
CTransInPlaceOutputPin *OutputPin() const
{
return (CTransInPlaceOutputPin *)m_pOutput;
};
// Helper to see if the input and output types match
BOOL TypesMatch()
{
return InputPin()->CurrentMediaType() ==
OutputPin()->CurrentMediaType();
}
// Are the input and output allocators different?
BOOL UsingDifferentAllocators() const
{
return InputPin()->PeekAllocator() != OutputPin()->PeekAllocator();
}
}; // CTransInPlaceFilter
#endif /* __TRANSIP__ */
| [
"radiowebmasters@gmail.com"
] | radiowebmasters@gmail.com |
e5d151e1755e98bacb494378aa48a8ef08ee98a4 | 019870db548f9dbad19093de581d75686d68d6ca | /src/core/XMLLoadable.cpp | f5cbc46d7241122571d1e3ada66bbc6d2266f727 | [
"WTFPL"
] | permissive | davidhhyq/JVGS | cf8c54f6e557b1b31960cdd11ea03e1713e107f1 | 59be35ed61b355b445b82bf32796c0f229e21b60 | refs/heads/master | 2020-06-17T14:19:03.785109 | 2014-11-12T09:48:17 | 2014-11-12T09:48:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,618 | cpp | #include "XMLLoadable.h"
#include "LogManager.h"
#include "../tinyxml/tinyxml.h"
using namespace std;
namespace jvgs
{
namespace core
{
XMLLoadable::XMLLoadable()
{
}
XMLLoadable::~XMLLoadable()
{
}
void XMLLoadable::queryBoolAttribute(TiXmlElement *element,
const string &attribute, bool *value) const
{
if(element->Attribute(attribute)) {
string str = element->Attribute(attribute.c_str());
if(str == "true")
*value = true;
else if(str == "false")
*value = false;
else
LogManager::getInstance()->error(
"Bool attributes should be true or false.");
}
}
void XMLLoadable::load(TiXmlElement *element)
{
/* First load data from another file. */
if(element->Attribute("filename"))
load(element->Attribute("filename"));
/* Now load the specific data. */
loadData(element);
}
void XMLLoadable::load(const string &fileName)
{
LogManager *logManager = LogManager::getInstance();
TiXmlDocument *document = new TiXmlDocument(fileName);
if(document->LoadFile()) {
load(document->RootElement());
} else {
logManager->warning("Could not load xml document: %s.",
fileName.c_str());
}
delete document;
}
}
}
| [
"jaspervdj@gmail.com"
] | jaspervdj@gmail.com |
cb5da0a2dbaa7f8347be7f0219f53b1ef4f681c0 | 04855d63403efcb5316e3ea11e57128e9f7c5c02 | /mediapipe/calculators/core/flow_limiter_calculator.cc | 6d595e6cd19ae24cee7e6723bc3f2cb91a9b60b2 | [
"Apache-2.0"
] | permissive | Gilgahex/mediapipe | bc49f9d8b7048f24c9fe59c98f68d8b3b6cd863d | c06effd494e8da07488723615522e67ce9783c0a | refs/heads/master | 2021-10-28T07:25:30.760525 | 2020-03-09T01:52:05 | 2020-03-09T01:52:05 | 216,973,960 | 4 | 7 | Apache-2.0 | 2021-10-14T01:29:02 | 2019-10-23T05:19:19 | C++ | UTF-8 | C++ | false | false | 7,454 | cc | // Copyright 2019 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <utility>
#include <vector>
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/port/ret_check.h"
#include "mediapipe/framework/port/status.h"
#include "mediapipe/util/header_util.h"
namespace mediapipe {
// FlowLimiterCalculator is used to limit the number of pipelined processing
// operations in a section of the graph.
//
// Typical topology:
//
// in ->-[FLC]-[foo]-...-[bar]-+->- out
// ^_____________________|
// FINISHED
//
// By connecting the output of the graph section to this calculator's FINISHED
// input with a backwards edge, this allows FLC to keep track of how many
// timestamps are currently being processed.
//
// The limit defaults to 1, and can be overridden with the MAX_IN_FLIGHT side
// packet.
//
// As long as the number of timestamps being processed ("in flight") is below
// the limit, FLC allows input to pass through. When the limit is reached,
// FLC starts dropping input packets, keeping only the most recent. When the
// processing count decreases again, as signaled by the receipt of a packet on
// FINISHED, FLC allows packets to flow again, releasing the most recently
// queued packet, if any.
//
// If there are multiple input streams, packet dropping is synchronized.
//
// IMPORTANT: for each timestamp where FLC forwards a packet (or a set of
// packets, if using multiple data streams), a packet must eventually arrive on
// the FINISHED stream. Dropping packets in the section between FLC and
// FINISHED will make the in-flight count incorrect.
//
// TODO: Remove this comment when graph-level ISH has been removed.
// NOTE: this calculator should always use the ImmediateInputStreamHandler and
// uses it by default. However, if the graph specifies a graph-level
// InputStreamHandler, to override that setting, the InputStreamHandler must
// be explicitly specified as shown below.
//
// Example config:
// node {
// calculator: "FlowLimiterCalculator"
// input_stream: "raw_frames"
// input_stream: "FINISHED:finished"
// input_stream_info: {
// tag_index: 'FINISHED'
// back_edge: true
// }
// input_stream_handler {
// input_stream_handler: 'ImmediateInputStreamHandler'
// }
// output_stream: "gated_frames"
// }
class FlowLimiterCalculator : public CalculatorBase {
public:
static ::mediapipe::Status GetContract(CalculatorContract* cc) {
int num_data_streams = cc->Inputs().NumEntries("");
RET_CHECK_GE(num_data_streams, 1);
RET_CHECK_EQ(cc->Outputs().NumEntries(""), num_data_streams)
<< "Output streams must correspond input streams except for the "
"finish indicator input stream.";
for (int i = 0; i < num_data_streams; ++i) {
cc->Inputs().Get("", i).SetAny();
cc->Outputs().Get("", i).SetSameAs(&(cc->Inputs().Get("", i)));
}
cc->Inputs().Get("FINISHED", 0).SetAny();
if (cc->InputSidePackets().HasTag("MAX_IN_FLIGHT")) {
cc->InputSidePackets().Tag("MAX_IN_FLIGHT").Set<int>();
}
if (cc->Outputs().HasTag("ALLOW")) {
cc->Outputs().Tag("ALLOW").Set<bool>();
}
cc->SetInputStreamHandler("ImmediateInputStreamHandler");
return ::mediapipe::OkStatus();
}
::mediapipe::Status Open(CalculatorContext* cc) final {
finished_id_ = cc->Inputs().GetId("FINISHED", 0);
max_in_flight_ = 1;
if (cc->InputSidePackets().HasTag("MAX_IN_FLIGHT")) {
max_in_flight_ = cc->InputSidePackets().Tag("MAX_IN_FLIGHT").Get<int>();
}
RET_CHECK_GE(max_in_flight_, 1);
num_in_flight_ = 0;
allowed_id_ = cc->Outputs().GetId("ALLOW", 0);
allow_ctr_ts_ = Timestamp(0);
num_data_streams_ = cc->Inputs().NumEntries("");
data_stream_bound_ts_.resize(num_data_streams_);
RET_CHECK_OK(CopyInputHeadersToOutputs(cc->Inputs(), &(cc->Outputs())));
return ::mediapipe::OkStatus();
}
bool Allow() { return num_in_flight_ < max_in_flight_; }
::mediapipe::Status Process(CalculatorContext* cc) final {
bool old_allow = Allow();
Timestamp lowest_incomplete_ts = Timestamp::Done();
// Process FINISHED stream.
if (!cc->Inputs().Get(finished_id_).Value().IsEmpty()) {
RET_CHECK_GT(num_in_flight_, 0)
<< "Received a FINISHED packet, but we had none in flight.";
--num_in_flight_;
}
// Process data streams.
for (int i = 0; i < num_data_streams_; ++i) {
auto& stream = cc->Inputs().Get("", i);
auto& out = cc->Outputs().Get("", i);
Packet& packet = stream.Value();
auto ts = packet.Timestamp();
if (ts.IsRangeValue() && data_stream_bound_ts_[i] <= ts) {
data_stream_bound_ts_[i] = ts + 1;
// Note: it's ok to update the output bound here, before sending the
// packet, because updates are batched during the Process function.
out.SetNextTimestampBound(data_stream_bound_ts_[i]);
}
lowest_incomplete_ts =
std::min(lowest_incomplete_ts, data_stream_bound_ts_[i]);
if (packet.IsEmpty()) {
// If the input stream is closed, close the corresponding output.
if (stream.IsDone() && !out.IsClosed()) {
out.Close();
}
// TODO: if the packet is empty, the ts is unset, and we
// cannot read the timestamp bound, even though we'd like to propagate
// it.
} else if (mediapipe::ContainsKey(pending_ts_, ts)) {
// If we have already sent this timestamp (on another stream), send it
// on this stream too.
out.AddPacket(std::move(packet));
} else if (Allow() && (ts > last_dropped_ts_)) {
// If the in-flight is under the limit, and if we have not already
// dropped this or a later timestamp on another stream, then send
// the packet and add an in-flight timestamp.
out.AddPacket(std::move(packet));
pending_ts_.insert(ts);
++num_in_flight_;
} else {
// Otherwise, we'll drop the packet.
last_dropped_ts_ = std::max(last_dropped_ts_, ts);
}
}
// Remove old pending_ts_ entries.
auto it = std::lower_bound(pending_ts_.begin(), pending_ts_.end(),
lowest_incomplete_ts);
pending_ts_.erase(pending_ts_.begin(), it);
// Update ALLOW signal.
if ((old_allow != Allow()) && allowed_id_.IsValid()) {
cc->Outputs()
.Get(allowed_id_)
.AddPacket(MakePacket<bool>(Allow()).At(++allow_ctr_ts_));
}
return ::mediapipe::OkStatus();
}
private:
std::set<Timestamp> pending_ts_;
Timestamp last_dropped_ts_;
int num_data_streams_;
int num_in_flight_;
int max_in_flight_;
CollectionItemId finished_id_;
CollectionItemId allowed_id_;
Timestamp allow_ctr_ts_;
std::vector<Timestamp> data_stream_bound_ts_;
};
REGISTER_CALCULATOR(FlowLimiterCalculator);
} // namespace mediapipe
| [
"jqtang@google.com"
] | jqtang@google.com |
0c544558fa04ba6f3513a0a955c4688df4d3775a | a4c71e7e8fdd4f1a5595dc765dbd78681b786586 | /libraries/utilities/include/TypeAliases.h | 8e24eb85a2cf4275e63d3104e98890130c236b4e | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | awesomemachinelearning/ELL | 68307c9ed6aa001baab64d23529e22baad643f02 | cb897e3aec148a1e9bd648012b5f53ab9d0dd20c | refs/heads/master | 2020-09-26T10:41:06.841270 | 2019-08-09T22:02:42 | 2019-08-09T22:02:42 | 226,237,954 | 1 | 0 | NOASSERTION | 2019-12-06T03:26:24 | 2019-12-06T03:26:23 | null | UTF-8 | C++ | false | false | 1,161 | h | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: TypeAliases.h (utilities)
// Authors: Kern Handa
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <type_traits>
namespace ell
{
namespace utilities
{
// macOS seems to alias intptr_t to long, which is different from what they
// alias for int32_t and int64_t, which are int and long long,
// respectively. We will now use a custom type to alias to either int32_t
// or int64_t, depending on the value of sizeof(void*). If neither
// int32_t nor int64_t match the width of void*, then we will raise a
// static_assert and fail to compile.
using IntPtrT = std::conditional_t<sizeof(void*) == sizeof(int32_t), int32_t, int64_t>;
static_assert(sizeof(IntPtrT) == sizeof(void*), "Unsupported architecture");
using UIntPtrT = std::make_unsigned_t<IntPtrT>;
static_assert(sizeof(UIntPtrT) == sizeof(void*), "Unsupported architecture");
} // namespace utilities
} // namespace ell
| [
"kerha@microsoft.com"
] | kerha@microsoft.com |
1736d80dfec0aa35a8fcb213f6abe8abcc7d7ddd | 9e02c151f257584592d7374b0045196a3fd2cf53 | /AtCoder/ABC/102/A.cpp | e297acd7049e01fface3292eefcffe07afb84f8d | [] | no_license | robertcal/cpp_competitive_programming | 891c97f315714a6b1fc811f65f6be361eb642ef2 | 0bf5302f1fb2aa8f8ec352d83fa6281f73dec9b5 | refs/heads/master | 2021-12-13T18:12:31.930186 | 2021-09-29T00:24:09 | 2021-09-29T00:24:09 | 173,748,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int N; cin >> N;
if (N % 2 == 0) {
cout << N << endl;
} else {
cout << N * 2 << endl;
}
}
| [
"robertcal900@gmail.com"
] | robertcal900@gmail.com |
1a422115c8460dbad76bf699f522a7f4388eceea | 39185d0b188bf1736fb209a6480e732a31e1cb83 | /project/Shader.cpp | cd99267dd8134c846f9078aeb3caa7ead5a2bc98 | [] | no_license | DaniGodin/MotionBlur | a61f9fd19f9bd5b865729689d7d96c3119d81898 | 89a15760876e71bc29e62b3966cc21c1c3f20057 | refs/heads/master | 2020-05-20T20:57:20.468241 | 2019-07-08T09:28:57 | 2019-07-08T09:28:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,069 | cpp | //
// Created by dany on 03/07/19.
//
#include "Shader.hpp"
Shader::Shader(const char* vertexPath, const char* fragmentPath)
{
// 1. retrieve the vertex/fragment source code from filePath
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
// ensure ifstream objects can throw exceptions:
vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
try
{
// open files
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
// read file's buffer contents into streams
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
// close file handlers
vShaderFile.close();
fShaderFile.close();
// convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (std::ifstream::failure e)
{
std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
}
const char* vShaderCode = vertexCode.c_str();
const char * fShaderCode = fragmentCode.c_str();
// 2. compile shaders
unsigned int vertex, fragment;
// vertex shader
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
// fragment Shader
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
checkCompileErrors(fragment, "FRAGMENT");
// shader Program
ID = glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
checkCompileErrors(ID, "PROGRAM");
// delete the shaders as they're linked into our program now and no longer necessary
glDeleteShader(vertex);
glDeleteShader(fragment);
}
| [
"danielgodin.pro@gmail.com"
] | danielgodin.pro@gmail.com |
9665d519f309d7a075c1d3c027c0e94f1a0ebf3d | f85cfed4ae3c54b5d31b43e10435bb4fc4875d7e | /sc-virt/src/tools/clang/test/OpenMP/critical_codegen.cpp | be749a65f0cb7e42896ef99098c4da514b875417 | [
"NCSA",
"MIT"
] | permissive | archercreat/dta-vs-osc | 2f495f74e0a67d3672c1fc11ecb812d3bc116210 | b39f4d4eb6ffea501025fc3e07622251c2118fe0 | refs/heads/main | 2023-08-01T01:54:05.925289 | 2021-09-05T21:00:35 | 2021-09-05T21:00:35 | 438,047,267 | 1 | 1 | MIT | 2021-12-13T22:45:20 | 2021-12-13T22:45:19 | null | UTF-8 | C++ | false | false | 4,380 | cpp | // RUN: %clang_cc1 -verify -fopenmp -x c++ -emit-llvm %s -fexceptions -fcxx-exceptions -o - | FileCheck %s
// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp -fexceptions -fcxx-exceptions -debug-info-kind=line-tables-only -x c++ -emit-llvm %s -o - | FileCheck %s --check-prefix=TERM_DEBUG
// expected-no-diagnostics
// REQUIRES: x86-registered-target
#ifndef HEADER
#define HEADER
// CHECK: [[IDENT_T_TY:%.+]] = type { i32, i32, i32, i32, i8* }
// CHECK: [[UNNAMED_LOCK:@.+]] = common global [8 x i32] zeroinitializer
// CHECK: [[THE_NAME_LOCK:@.+]] = common global [8 x i32] zeroinitializer
// CHECK: [[THE_NAME_LOCK1:@.+]] = common global [8 x i32] zeroinitializer
// CHECK: define {{.*}}void [[FOO:@.+]]()
void foo() {}
// CHECK-LABEL: @main
// TERM_DEBUG-LABEL: @main
int main() {
// CHECK: [[A_ADDR:%.+]] = alloca i8
char a;
// CHECK: [[GTID:%.+]] = call {{.*}}i32 @__kmpc_global_thread_num([[IDENT_T_TY]]* [[DEFAULT_LOC:@.+]])
// CHECK: call {{.*}}void @__kmpc_critical([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]], [8 x i32]* [[UNNAMED_LOCK]])
// CHECK-NEXT: store i8 2, i8* [[A_ADDR]]
// CHECK-NEXT: call {{.*}}void @__kmpc_end_critical([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]], [8 x i32]* [[UNNAMED_LOCK]])
#pragma omp critical
a = 2;
// CHECK: call {{.*}}void @__kmpc_critical([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]], [8 x i32]* [[THE_NAME_LOCK]])
// CHECK-NEXT: invoke {{.*}}void [[FOO]]()
// CHECK: call {{.*}}void @__kmpc_end_critical([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]], [8 x i32]* [[THE_NAME_LOCK]])
#pragma omp critical(the_name)
foo();
// CHECK: call {{.*}}void @__kmpc_critical_with_hint([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]], [8 x i32]* [[THE_NAME_LOCK1]], i{{64|32}} 23)
// CHECK-NEXT: invoke {{.*}}void [[FOO]]()
// CHECK: call {{.*}}void @__kmpc_end_critical([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]], [8 x i32]* [[THE_NAME_LOCK1]])
#pragma omp critical(the_name1) hint(23)
foo();
// CHECK: call {{.*}}void @__kmpc_critical([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]], [8 x i32]* [[THE_NAME_LOCK]])
// CHECK: br label
// CHECK-NOT: call {{.*}}void @__kmpc_end_critical(
// CHECK: br label
// CHECK-NOT: call {{.*}}void @__kmpc_end_critical(
// CHECK: br label
if (a)
#pragma omp critical(the_name)
while (1)
;
// CHECK: call {{.*}}void [[FOO]]()
foo();
// CHECK-NOT: call void @__kmpc_critical
// CHECK-NOT: call void @__kmpc_end_critical
return a;
}
struct S {
int a;
};
// CHECK-LABEL: critical_ref
void critical_ref(S &s) {
// CHECK: [[S_ADDR:%.+]] = alloca %struct.S*,
// CHECK: [[S_REF:%.+]] = load %struct.S*, %struct.S** [[S_ADDR]],
// CHECK: [[S_A_REF:%.+]] = getelementptr inbounds %struct.S, %struct.S* [[S_REF]], i32 0, i32 0
++s.a;
// CHECK: [[S_REF:%.+]] = load %struct.S*, %struct.S** [[S_ADDR]],
// CHECK: store %struct.S* [[S_REF]], %struct.S** [[S_ADDR:%.+]],
// CHECK: call void @__kmpc_critical(
#pragma omp critical
// CHECK: [[S_REF:%.+]] = load %struct.S*, %struct.S** [[S_ADDR]],
// CHECK: [[S_A_REF:%.+]] = getelementptr inbounds %struct.S, %struct.S* [[S_REF]], i32 0, i32 0
++s.a;
// CHECK: call void @__kmpc_end_critical(
}
// CHECK-LABEL: parallel_critical
// TERM_DEBUG-LABEL: parallel_critical
void parallel_critical() {
#pragma omp parallel
#pragma omp critical
// TERM_DEBUG-NOT: __kmpc_global_thread_num
// TERM_DEBUG: call void @__kmpc_critical({{.+}}), !dbg [[DBG_LOC_START:![0-9]+]]
// TERM_DEBUG: invoke void {{.*}}foo{{.*}}()
// TERM_DEBUG: unwind label %[[TERM_LPAD:.+]],
// TERM_DEBUG-NOT: __kmpc_global_thread_num
// TERM_DEBUG: call void @__kmpc_end_critical({{.+}}), !dbg [[DBG_LOC_END:![0-9]+]]
// TERM_DEBUG: [[TERM_LPAD]]
// TERM_DEBUG: call void @__clang_call_terminate
// TERM_DEBUG: unreachable
foo();
}
// TERM_DEBUG-DAG: [[DBG_LOC_START]] = !DILocation(line: [[@LINE-12]],
// TERM_DEBUG-DAG: [[DBG_LOC_END]] = !DILocation(line: [[@LINE-3]],
#endif
| [
"sebi@quantstamp.com"
] | sebi@quantstamp.com |
d69626decbd3e3c4e8c9ab64007c72e6502ff1c8 | 157bd746d634378cba837618971f59498e03ea16 | /Open_Acidification_pH-stat_arduino/ChangeKp.ino | 7447ea6ef8ef9abbdb3197dcf662bfa0cfd170d6 | [
"MIT"
] | permissive | riggja/Open_Acidification_pH-stat_arduino | 4ba18ae90b241ba03a91d52827f81205e5921d27 | ff3837bc9aac3142b46df043620c1224b9cd8e81 | refs/heads/master | 2022-12-28T07:08:18.469104 | 2020-09-17T00:37:14 | 2020-09-17T00:37:14 | 297,202,121 | 0 | 0 | MIT | 2020-09-21T01:54:36 | 2020-09-21T01:54:35 | null | UTF-8 | C++ | false | false | 1,695 | ino | // ************************************************
// Change Kp value
// ************************************************
void ChangeKp() {
double kp_temp;
kp_temp = Kp;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Kp:"));
lcd.setCursor(0, 1);
lcd.print(kp_temp);
key = NO_KEY;
while (key != '#') {
key = custom_keypad.waitForKey();
switch (key) {
case '1':
kp_temp = kp_temp + 10000;
break;
case '4':
kp_temp = kp_temp - 10000;
break;
case '2':
kp_temp = kp_temp + 1000;
break;
case '5':
kp_temp = kp_temp - 1000;
break;
case '3':
kp_temp = kp_temp + 100;
break;
case '6':
kp_temp = kp_temp - 100;
break;
case 'A':
kp_temp = kp_temp + 10;
break;
case 'B':
kp_temp = kp_temp - 10;
break;
case '7':
kp_temp = kp_temp + 1;
break;
case '*':
kp_temp = kp_temp - 1;
break;
case '8':
kp_temp = kp_temp + 0.1;
break;
case '0':
kp_temp = kp_temp - 0.1;
break;
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Kp:"));
lcd.setCursor(0, 1);
lcd.print(kp_temp, 2);
Serial.print(F("New Kp: "));
Serial.println(kp_temp);
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("New Kp:"));
lcd.print(kp_temp);
lcd.setCursor(0, 1);
lcd.print(F("Keep:1 Discard:2"));
while (key != '2') {
key = custom_keypad.waitForKey();
if (key == '1') {
Kp = kp_temp;
EepromWriteDouble(KP_ADDRESS, Kp);
my_pid.SetTunings(Kp, Ki, Kd);
key = '2';
}
}
}
| [
"noreply@github.com"
] | riggja.noreply@github.com |
037b9c6432e4f5f53e699ca34a5e6df17d654390 | 58e06a9c681c20a9d84b926247c723087331b9f1 | /cse20311/lab1/prog2.cpp | c4322789120e7d3f90f2a694f280852f063e9ae0 | [] | no_license | ericl1ericl/Notre-Dame | 1869a5f2d138d98520471d1838581d4bfdeb5f51 | 0a2f6c371e1bbb54b723d8c2c2c2b1b212922c14 | refs/heads/master | 2021-01-25T04:36:45.670324 | 2018-10-29T20:54:19 | 2018-10-29T20:54:19 | 93,458,868 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 582 | cpp | #include <iostream>
using namespace std;
int main()
{
int td;
cout << "Enter the number of touchdowns scored by the Irish: ";
cin >> td;
int xpt;
cout << "Enter the number of extra points made by the Irish: ";
cin >> xpt;
int fg;
cout << "Enter the number of field goals made by the Irish: ";
cin >> fg;
int s;
cout << "Enter the number of safeties scored by the Irish: ";
cin >> s;
int sum;
sum = td*6 + xpt*1 + fg*3 + s*2;
cout << "The Fighting Irish scored " << sum << " points. Go Irish!"
<< endl;
return 0;
}
// Eric Layne
| [
"elayne@nd.edu"
] | elayne@nd.edu |
520a33eb013975868822fa7c6698f18b9517447c | 2705848da209f2200c651301b25e323e9eeaffbc | /EnergyEfficient_Scheduling_GGA/GroupingGenome.cpp | e4913218582d4bf5234a296b5aa2534a264937dc | [] | no_license | JR8ll/EEBS | a57aa2c1c553761cd761dec61b1f68b5aecb8207 | bd3902ede624e5d19da65f890bdd1f4409a45e8f | refs/heads/main | 2023-02-27T12:27:03.244492 | 2021-02-01T09:17:23 | 2021-02-01T09:17:23 | 334,894,607 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 21,688 | cpp |
#include "GroupingGenome.h"
GroupingGenome::GroupingGenome(){}
GroupingGenome::GroupingGenome(const GroupingGenome &other) {
this->copy((const GroupingGenome *) &other);
}
GroupingGenome::~GroupingGenome(){
int n = this->size();
for(int i = 0; i < n; i++) {
delete this->at(i);
}
}
void GroupingGenome::init() {
destroy();
this->resize(0);
}
void GroupingGenome::destroy() {
int n = this->size();
// Destroys all of the containers
for (int i = 0; i < n; i++) {
if ((*this)[i] != NULL) {
// TODO delete all jobs 23.07.2018
for(unsigned j = 0; j < (*this)[i]->numJobs; j++) {
(*this)[i]->destroy();
}
delete (*this)[i];
}
(*this)[i] = NULL;
}
}
void GroupingGenome::copy(const GroupingGenome *other) {
if (this == other) return;
this->destroy();
int n = other->size();
this->resize(n);
for (int i = 0; i < n; i++) {
(*this)[i] = new Batch(); //new Batch();
(*this)[i]->copy((*other)[i]);
}
}
void GroupingGenome::clean() { // Initialize all Genes (NOT clear()
int n = this->size();
for (int i = 0; i < n; i++) {
(*this)[i]->clear();
}
}
int GroupingGenome::firstEmpty(const bool from_start) {
int n = this->size();
if(from_start) {
for (unsigned i = 0; i < n; i++) {
if(this->at(i)->numJobs == 0) {
return i;
}
}
} else {
for (int i = n-1; i >= 0; i--) {
if(this->at(i)->numJobs == 0) {
return i;
}
}
}
return -1;
}
int GroupingGenome::predecessorOnMachine(int batchIdx){
int n = this->size();
int assignedM = 0;
if(batchIdx > 0 && batchIdx < n) {
assignedM = (int) floor(this->at(batchIdx)->key);
for(int i = batchIdx - 1; i >= 0; i--) {
if(floor(this->at(i)->key) == assignedM) {
return i;
}
}
}
return -1; // no predecessor
}
void GroupingGenome::operator=(const GroupingGenome &other) {
copy((const GroupingGenome *) & other);
}
// Initialization
void GroupingGenome::initializeRandom() {
// ACTUAL INITIALIZATION IS DONE IN ***SOLUTION CLASSES (MOMHLib)
this->clear();
this->resize(Global::problem->n);
for(unsigned i = 0; i < Global::problem->n; i++) {
// do {
// TODO: cur_batch = GARandomInt(0, Global::nJobs - 1);
// } while (!batches[cur_batch].addOrder(&order[i]));
}
}
void GroupingGenome::initializeEDD() {
// ACTUAL INITIALIZATION IS DONE IN ***SOLUTION CLASSES (MOMHLib)
cout << "GroupingGenome::initializeEDD() not implemented!" << endl;
};
void GroupingGenome::initializeTWD(){
// ACTUAL INITIALIZATION IS DONE IN ***SOLUTION CLASSES (MOMHLib)
cout << "GroupingGenome::initializeTWD() not implemented!" << endl;
};
// Mutation
void GroupingGenome::mutShift(const float prob){
cout << "GroupingGenome::mutShift(const float) not implemented." << endl;
}
void GroupingGenome::mutSwap(const float prob){
cout << "GroupingGenome::mutSwap(const float) not implemented." << endl;
}
// Refinement
bool GroupingGenome::shiftJobsForDominance(const int srcBatchIdx, const int dstBatchIdx) {
cout << "GroupingGenome::shiftJobsForDominance is not yet implemented." << endl;
if(srcBatchIdx >= 0 && srcBatchIdx < this->size() && dstBatchIdx >= 0 && dstBatchIdx < this->size() && srcBatchIdx != dstBatchIdx) {
if(this->at(srcBatchIdx)->numJobs <= 0) {
// no Jobs contained in source
return false;
}
}
return false;
}
bool GroupingGenome::shiftJobsTWT(const int srcBatchIdx, const int dstBatchIdx) {
// shift a job from source to destination batch if (assume that dst´s completion <= scr´s completion)
if(srcBatchIdx >= 0 && srcBatchIdx < this->size() && dstBatchIdx >= 0 && dstBatchIdx < this->size() && srcBatchIdx != dstBatchIdx) {
if(this->at(srcBatchIdx)->numJobs > 0 && this->at(srcBatchIdx)->f == (this->at(dstBatchIdx)->f || this->at(dstBatchIdx)->f == 0 && this->at(dstBatchIdx)->freeCapacity > 0)) {
vector<int> jobIds2bShifted;
for(unsigned i = 0; i < this->at(srcBatchIdx)->numJobs; i++) {
jobIds2bShifted.push_back(this->at(srcBatchIdx)->getJob(i).id);
}
// sort jobs by weight
// make_heap(jobIds2bShifted.begin(), jobIds2bShifted.end());
// sort_heap(jobIds2bShifted.begin(), jobIds2bShifted.end(), compareJobWeight);
sort(jobIds2bShifted.begin(), jobIds2bShifted.end(), compareJobWeight);
bool jobsShifted = false;
for(unsigned i = 0; i < jobIds2bShifted.size(); i++) {
if(Global::problem->jobs.getJobByID(jobIds2bShifted[i])->s <= this->at(dstBatchIdx)->freeCapacity) {
if(Global::problem->jobs.getJobByID(jobIds2bShifted[i])->r <= this->at(dstBatchIdx)->r) { // IMPORTANT
// job will not increase the batch´s release time
// capacity available, addJob to dst, eraseJob from src
if(this->at(dstBatchIdx)->addJob(Global::problem->jobs.getJobByID(jobIds2bShifted[i]))) {
this->at(srcBatchIdx)->erase(jobIds2bShifted[i]);
jobsShifted = true;
if(this->at(dstBatchIdx)->freeCapacity <= 0) {
break;
}
}
}
}
}
return jobsShifted;
}
// no Jobs contained in source, incompatible families or no free capacity
return false;
}
// index out of bounds
return false;
}
bool GroupingGenome::shiftJobsEPC(const int srcBatchIdx, const int dstBatchIdx) {
// shift jobs aiming at a decreased EPC => try to shift as many jobs into the destination batch so eventually the source batch can be cleared
if(srcBatchIdx >= 0 && srcBatchIdx < this->size() && dstBatchIdx >= 0 && dstBatchIdx < this->size() && srcBatchIdx != dstBatchIdx) {
if(this->at(srcBatchIdx)->numJobs > 0 && this->at(dstBatchIdx)->numJobs > 0 && this->at(srcBatchIdx)->f == this->at(dstBatchIdx)->f && this->at(dstBatchIdx)->freeCapacity > 0) {
vector<int> jobIds2bShifted;
for(unsigned i = 0; i < this->at(srcBatchIdx)->numJobs; i++) {
jobIds2bShifted.push_back(this->at(srcBatchIdx)->getJob(i).id);
}
// sort jobs by size
// make_heap(jobIds2bShifted.begin(), jobIds2bShifted.end());
//sort_heap(jobIds2bShifted.begin(), jobIds2bShifted.end(), compareJobSize);
sort(jobIds2bShifted.begin(), jobIds2bShifted.end(), compareJobSize);
// shift jobs
bool jobsShifted = false;
for(unsigned i = 0; i < jobIds2bShifted.size(); i++) {
if(Global::problem->jobs.getJobByID(jobIds2bShifted[i])->s <= this->at(dstBatchIdx)->freeCapacity) {
// TODO: conditions to shift a job
// capacity available, addJob to dst, eraseJob from src
if(this->at(dstBatchIdx)->addJob(Global::problem->jobs.getJobByID(jobIds2bShifted[i]))) {
this->at(srcBatchIdx)->erase(jobIds2bShifted[i]);
jobsShifted = true;
if(this->at(dstBatchIdx)->freeCapacity <= 0) {
break;
}
}
}
}
return jobsShifted;
}
// else, no jobs contained in either src or dst, incompatible families or no free capacity
}
// index out of bounds or src eq dst
return false;
}
bool GroupingGenome::shiftJobsTWC(const int srcBatchIdx, const int dstBatchIdx) {
// shift a job from source to destination batch if (assume that dst´s completion <= scr´s completion)
if(srcBatchIdx >= 0 && srcBatchIdx < this->size() && dstBatchIdx >= 0 && dstBatchIdx < this->size() && srcBatchIdx != dstBatchIdx) {
if(this->at(srcBatchIdx)->numJobs > 0 && this->at(srcBatchIdx)->f == (this->at(dstBatchIdx)->f || this->at(dstBatchIdx)->f == 0 && this->at(dstBatchIdx)->freeCapacity > 0)) {
vector<int> jobIds2bShifted;
for(unsigned i = 0; i < this->at(srcBatchIdx)->numJobs; i++) {
jobIds2bShifted.push_back(this->at(srcBatchIdx)->getJob(i).id);
}
// sort jobs by weight
// make_heap(jobIds2bShifted.begin(), jobIds2bShifted.end());
// sort_heap(jobIds2bShifted.begin(), jobIds2bShifted.end(), compareJobWeight);
sort(jobIds2bShifted.begin(), jobIds2bShifted.end(), compareJobWeight);
bool jobsShifted = false;
for(unsigned i = 0; i < jobIds2bShifted.size(); i++) {
if(Global::problem->jobs.getJobByID(jobIds2bShifted[i])->s <= this->at(dstBatchIdx)->freeCapacity) {
if(Global::problem->jobs.getJobByID(jobIds2bShifted[i])->r <= this->at(dstBatchIdx)->r) { // IMPORTANT
// job will not increase the batch´s release time
// capacity available, addJob to dst, eraseJob from src
if(this->at(dstBatchIdx)->addJob(Global::problem->jobs.getJobByID(jobIds2bShifted[i]))) {
this->at(srcBatchIdx)->erase(jobIds2bShifted[i]);
jobsShifted = true;
if(this->at(dstBatchIdx)->freeCapacity <= 0) {
break;
}
}
}
}
}
return jobsShifted;
}
// no Jobs contained in source, incompatible families or no free capacity
return false;
}
// index out of bounds
return false;
}
bool GroupingGenome::swapJobsPossible(const int batchId1, const int jobId1, const int batchId2, const int jobId2) {
if( batchId1 >= 0 && batchId1 <= this->size() && batchId2 >= 0 && batchId2 <= this->size() ) {
if(!this->at(batchId1)->contains(jobId1) || !this->at(batchId2)->contains(jobId2)) {
// batch does not contain the job
return false;
}
else {
// check for matching families and sufficient capacity
return (this->at(batchId1)->f = this->at(batchId2)->f)
&& ( (this->at(batchId1)->freeCapacity + Global::problem->jobs.getJobByID(jobId1)->s) >= Global::problem->jobs.getJobByID(jobId2)->s )
&& ( (this->at(batchId2)->freeCapacity + Global::problem->jobs.getJobByID(jobId2)->s) >= Global::problem->jobs.getJobByID(jobId1)->s );
}
}
// else: index out of bounds
return false;
}
/// sorting
void GroupingGenome::sortBy_r(bool asc) {
if(asc) {
sort(this->begin(), this->end(), GroupingGenome::compareBy_r);
}
else {
sort(this->begin(), this->end(), GroupingGenome::compareBy_r_desc);
}
// TODO update completion times ?
}
void GroupingGenome::sortBy_pLot(bool asc) {
if(asc) {
sort(this->begin(), this->end(), GroupingGenome::compareBy_pLot);
}
else {
sort(this->begin(), this->end(), GroupingGenome::compareBy_pLot_desc);
}
// TODO update completion times ?
}
void GroupingGenome::sortBy_pItem(bool asc){
if(asc) {
sort(this->begin(), this->end(), GroupingGenome::compareBy_pItem);
}
else {
sort(this->begin(), this->end(), GroupingGenome::compareBy_pItem_desc);
}
// TODO update completion times ?
}
void GroupingGenome::sortBy_w(bool asc){
if(asc) {
sort(this->begin(), this->end(), GroupingGenome::compareBy_w);
}
else {
sort(this->begin(), this->end(), GroupingGenome::compareBy_w_desc);
}
// TODO update completion times ?
}
void GroupingGenome::sortBy_wpLot(bool asc) {
if(asc) {
sort(this->begin(), this->end(), GroupingGenome::compareBy_wpLot);
}
else {
sort(this->begin(), this->end(), GroupingGenome::compareBy_wpLot_desc);
}
// TODO update completion times ?
}
void GroupingGenome::sortBy_wpItem(bool asc) {
if(asc) {
sort(this->begin(), this->end(), GroupingGenome::compareBy_wpItem);
}
else {
sort(this->begin(), this->end(), GroupingGenome::compareBy_wpItem_desc);
}
// TODO update completion times ?
}
void GroupingGenome::sortBy_BATCII(int time, double kappa, bool asc) {
// get average p
double avgP = 0; // average processing time
double numJ = 0; // total number of jobs
int bMax = this->size();
for(unsigned i = 0; i < bMax; i++) {
int jMax = this->at(i)->numJobs;
numJ += (double) jMax;
for(unsigned j = 0; j < jMax; j++) {
avgP += (double) this->at(i)->getJob(j).p;
}
}
avgP = avgP / numJ;
if(asc) { // sort ascending
sort(this->begin(), this->end(), CompareBy_BATCII(avgP, time, kappa));
}
else { // sort descending
sort(this->begin(), this->end(), CompareBy_BATCII_desc(avgP, time, kappa));
}
// TODO this->updateCompletionTimes(); ??
}
void GroupingGenome::moveNonEmptyBatchesToFront() {
sort(this->begin(), this->end(), GroupingGenome::compareEmpty);
}
bool GroupingGenome::reinsert(vector<int> &missingJobs) {
set<int> assigned;
vector<int> unins = missingJobs;
assigned.clear();
int iMax = unins.size();
int bMax = this->size();
for(unsigned i = 0; i < iMax; i++) {
// insert first-fit into existing batches
for(unsigned b = 0; b < bMax; b++) {
if (this->at(b)->addJob(Global::problem->jobs.getJobByID(unins[i]))) {
if(this->at(b)->numJobs <= 1) {
this->at(b)->setKey((double) rand() / ((double) RAND_MAX + 1.0) * Global::problem->m);
}
assigned.insert(unins[i]);
break;
}
}
}
return assigned.size() == unins.size();
}
bool GroupingGenome::reinsertTWTEPC_2(vector<int> &missingJobs) {
// TODO: check earliestStart, latestC and update the batches´ values
set<int> assigned;
vector<int> unins = missingJobs;
assigned.clear();
int iMax = unins.size();
int bMax = this->size();
for(unsigned i = 0; i < iMax; i++) {
// insert first-fit into existing batches
for(unsigned b = 0; b < bMax; b++) {
// TODO: check if job.r <= batch.earliestD und job.p <= batch.latestC-batch.earliestStart
if(Global::problem->jobs.getJobByID(unins[i])->r <= this->at(b)->earliestStart && Global::problem->jobs.getJobByID(unins[i])->p <= (this->at(b)->latestC - this->at(b)->earliestStart)) {
if (this->at(b)->addJob(Global::problem->jobs.getJobByID(unins[i]))) {
assigned.insert(unins[i]);
break;
}
}
}
}
return assigned.size() == unins.size();
}
bool GroupingGenome::reinsertTWTEPC_3(vector<int> &missingJobs) {
set<int> assigned;
vector<int> unins = missingJobs;
assigned.clear();
int iMax = unins.size();
int bMax = this->size();
for(unsigned i = 0; i < iMax; i++) {
// insert first-fit into existing batches
for(unsigned b = 0; b < bMax; b++) {
// check if job.r <= batch.earliestD und job.p <= batch.latestC-batch.earliestStart
if(Global::problem->jobs.getJobByID(unins[i])->r <= this->at(b)->r) {
// job´s r does not affect batch´s r
if (this->at(b)->addJob(Global::problem->jobs.getJobByID(unins[i]))) {
assigned.insert(unins[i]);
break;
}
}
}
}
return assigned.size() == unins.size();
}
bool GroupingGenome::reinsertTWCEPC_2(vector<int> &missingJobs) {
// TODO: check earliestStart, latestC and update the batches´ values
set<int> assigned;
vector<int> unins = missingJobs;
assigned.clear();
int iMax = unins.size();
int bMax = this->size();
for(unsigned i = 0; i < iMax; i++) {
// insert first-fit into existing batches
for(unsigned b = 0; b < bMax; b++) {
// TODO: check if job.r <= batch.earliestD und job.p <= batch.latestC-batch.earliestStart
if(Global::problem->jobs.getJobByID(unins[i])->r <= this->at(b)->earliestStart && Global::problem->jobs.getJobByID(unins[i])->p <= (this->at(b)->latestC - this->at(b)->earliestStart)) {
if (this->at(b)->addJob(Global::problem->jobs.getJobByID(unins[i]))) {
assigned.insert(unins[i]);
break;
}
}
}
}
return assigned.size() == unins.size();
}
bool GroupingGenome::reinsertReady(vector<int> &missingJobs){ // reinsert considering ready times
set<int> assigned;
vector<int> unins = missingJobs;
assigned.clear();
int jMax = unins.size();
int bMax = this->size();
// sort job ids by decreasing weight
sort(missingJobs.begin(), missingJobs.end(), compareJobWeight);
for(unsigned i = 0; i < bMax; i++) {
for(unsigned j = 0; j < jMax; j++) {
if(assigned.count(unins[j]) == 0 && this->at(i)->r >= Global::problem->jobs.getJobByID(unins[j])->r || this->at(i)->numJobs == 0) {
// Try to assign a job if 1) it is not yet assigned AND 2) its r is not larger than the batch´s r OR 3) the batch is empty
if(this->at(i)->addJob(Global::problem->jobs.getJobByID(j))) {
// The job is only assigned if the batch´s capacity restriction is met and the families match
assigned.insert(unins[j]);
}
}
}
}
return assigned.size() == unins.size();
}
bool GroupingGenome::reinsertDue(vector<int> &missingJobs){ // reinsert considering due dates
set<int> assigned;
vector<int> unins = missingJobs;
assigned.clear();
int iMax = unins.size();
int bMax = this->size();
int dRestriction;
// sort job ids by decreasing weight
sort(missingJobs.begin(), missingJobs.end(), compareJobWeight);
for(unsigned j = 0; j < iMax; j++) {
for(unsigned i = 0; i < bMax; i++) {
if(this->at(i)->getC() <= 0) {
dRestriction = this->at(i)->latestD;
}
else {
dRestriction = this->at(i)->getC();
}
// at the time of reinsertion the batch is not yet scheduled, therefore put job in if its d is not larger than the latest d of jobs already assigned
if(assigned.count(unins[j]) == 0 && this->at(i)->latestD >= Global::problem->jobs.getJobByID(unins[j])->d || this->at(i)->numJobs == 0) {
// Try to assign a job if 1) it is not yet assigned AND 2) its r is not larger than the batch´s r OR 3) the batch is empty
if(this->at(i)->addJob(Global::problem->jobs.getJobByID(j))) {
// The job is only assigned if the batch´s capacity restriction is met and the families match
assigned.insert(unins[j]);
}
}
}
}
return assigned.size() == unins.size();
}
bool GroupingGenome::reinsertReadyDue(vector<int> &missingJobs){ // reinsert considering ready times and due dates
return false;
}
bool GroupingGenome::reinsertReadyDueWeight(vector<int> &missingJobs){ // reinsert considering ready times, due dates and weight
return false;
}
bool GroupingGenome::reinsertMinDeltaTWT(vector<int> &missingJobs){ // reinsert increasing TWT as little as possible
return false;
}
bool GroupingGenome::reinsertTWT(vector<int> &missingJobs){ // reinsert so that TWT of accepting batch does not increase
std::cout << "GroupingGenome::reinsterTWT(vector<int>) not implemented." << endl;
return false;
}
bool GroupingGenome::reinsertTWC(vector<int> &missingJobs){ // reinsert so that TWT of accepting batch does not increase
std::cout << "GroupingGenome::reinsterTWC(vector<int>) not implemented." << endl;
return false;
}
bool GroupingGenome::reinsertBATC(vector<int> &missingJobs){ // reinsert so the BATC values of utilized batches are not increased
return false;
}
// compare Batches
/// ascending order
bool GroupingGenome::compareBy_r(const Batch* a, const Batch* b) {
if(a->r == b->r) {
return a->id < b->id;
}
else {
return a->r< b->r;
}
}
bool GroupingGenome::compareBy_pLot(const Batch* a, const Batch* b) {
if(a->pLot == b->pLot) {
return a->id < b->id;
}
else {
return a->pLot < b->pLot;
}
}
bool GroupingGenome::compareBy_pItem(const Batch* a, const Batch* b) {
if(a->pItem == b->pItem) {
return a->id < b->id;
}
else {
return a->pItem < b->pItem;
}
}
bool GroupingGenome::compareBy_w(const Batch* a, const Batch* b) {
if(a->w == b->w) {
return a->id < b->id;
}
else {
return a->w < b->w;
}
}
bool GroupingGenome::compareBy_wpLot(const Batch* a, const Batch* b) {
// consider empty batches
if(a->pLot == 0) {
if(b->pLot == 0) {
return a->id < b->id;
} else {
return false; // TODO check
}
}
if(b->pLot == 0) {
return true;
}
if(((double)a->w / (double)a->pLot) == ((double)b->w / (double)b->pLot)) {
return a->id < b->id;
}
else {
return ((double)a->w / (double)a->pLot) < ((double)b->w / (double)b->pLot);
}
}
bool GroupingGenome::compareBy_wpItem(const Batch* a, const Batch* b) {
// consider empty batches
if(a->pLot == 0) {
if(b->pLot == 0) {
return a->id < b->id;
} else {
return false; // TODO check
}
}
if(b->pLot == 0) {
return true;
}
if(((double)a->w / (double)a->pItem) == ((double)b->w / (double)b->pItem)) {
return a->id < b->id;
}
else {
return ((double)a->w / (double)a->pItem) < ((double)b->w / (double)b->pItem);
}
}
bool GroupingGenome::compareEmpty(const Batch* a, const Batch* b) {
if( (a->numJobs > 0 && b->numJobs > 0) || (a->numJobs == 0 && b->numJobs == 0) ) {
return a->id < b->id;
}
else if( b->numJobs > 0) {
return false;
}
return true;
// return true if a is to be placed before b
}
/// descending order
bool GroupingGenome::compareBy_r_desc(const Batch* a, const Batch* b) {
if(a->r == b->r) {
return a->id < b->id;
}
else {
return a->r > b->r;
}
}
bool GroupingGenome::compareBy_pLot_desc(const Batch* a, const Batch* b) {
if(a->pLot == b->pLot) {
return a->id < b->id;
}
else {
return a->pLot > b->pLot;
}
}
bool GroupingGenome::compareBy_pItem_desc(const Batch* a, const Batch* b) {
if(a->pItem == b->pItem) {
return a->id < b->id;
}
else {
return a->pItem > b->pItem;
}
}
bool GroupingGenome::compareBy_w_desc(const Batch* a, const Batch* b) {
if(a->w == b->w) {
return a->id < b->id;
}
else {
return a->w > b->w;
}
}
bool GroupingGenome::compareBy_wpLot_desc(const Batch* a, const Batch* b) {
// consider empty batches
if(a->pLot == 0) {
if(b->pLot == 0) {
return a->id < b->id;
} else {
return false; // TODO check
}
}
if(b->pLot == 0) {
return true;
}
if(((double)a->w / (double)a->pLot) == ((double)b->w / (double)b->pLot)) {
return a->id < b->id;
}
else {
return ((double)a->w / (double)a->pLot) > ((double)b->w / (double)b->pLot);
}
}
bool GroupingGenome::compareBy_wpItem_desc(const Batch* a, const Batch* b) {
// consider empty batches
if(a->pLot == 0) {
if(b->pLot == 0) {
return a->id < b->id;
} else {
return false; // TODO check
}
}
if(b->pLot == 0) {
return true;
}
if(((double)a->w / (double)a->pItem) == ((double)b->w / (double)b->pItem)) {
return a->id < b->id;
}
else {
return ((double)a->w / (double)a->pItem) > ((double)b->w / (double)b->pItem);
}
}
bool compareJobWeight(const int JobIdx1, const int JobIdx2) {
return Global::problem->jobs.getJobByID(JobIdx1)->w > Global::problem->jobs.getJobByID(JobIdx2)->w;
}
bool compareJobSize(const int JobIdx1, const int JobIdx2) {
return Global::problem->jobs.getJobByID(JobIdx1)->s > Global::problem->jobs.getJobByID(JobIdx2)->s;
} | [
"jrocholl@gmx.de"
] | jrocholl@gmx.de |
56d078f0ae59c6912ec3b34f4d5f49b65e32936f | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE590_Free_Memory_Not_on_Heap/s01/CWE590_Free_Memory_Not_on_Heap__delete_array_int_declare_53a.cpp | a1c1b30a02a9a6d0247843407acab9a6aed2d0e3 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 2,733 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_int_declare_53a.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml
Template File: sources-sink-53a.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: declare Data buffer is declared on the stack
* GoodSource: Allocate memory on the heap
* Sink:
* BadSink : Print then free data
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_array_int_declare_53
{
#ifndef OMITBAD
/* bad function declaration */
void badSink_b(int * data);
void bad()
{
int * data;
data = NULL; /* Initialize data */
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
int dataBuffer[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i] = 5;
}
}
data = dataBuffer;
}
badSink_b(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
void goodG2BSink_b(int * data);
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
int * data;
data = NULL; /* Initialize data */
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
int * dataBuffer = new int[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i] = 5;
}
}
data = dataBuffer;
}
goodG2BSink_b(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE590_Free_Memory_Not_on_Heap__delete_array_int_declare_53; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
9228924cb3c36116eed4107f3ddb3e76833b73b4 | f8d1986a121ae1f7448d5af1b58ad12dc60c6bcf | /deep_learning_object_detection/include/velodyne_height_map/heightmap.h | 08ec84c514925f85313f498e6494c752187b0ffa | [] | no_license | Sadaku1993/my_master_thesis_ros | 93d080b5de0bf2d7b47bea0665415bca6fac4aa4 | b60bb0b7822b9308d30f54d72d831e10db468fcc | refs/heads/master | 2020-03-11T07:41:35.225356 | 2018-03-24T06:19:11 | 2018-03-24T06:19:11 | 129,863,849 | 0 | 1 | null | 2018-04-17T07:26:12 | 2018-04-17T07:26:11 | null | UTF-8 | C++ | false | false | 1,959 | h | /* -*- mode: C++ -*- */
/* Copyright (C) 2010 UT-Austin & Austin Robot Technology,
* David Claridge, Michael Quinlan
*
* License: Modified BSD Software License
*/
#ifndef _HEIGHT_MAP_H_
#define _HEIGHT_MAP_H_
#include <ros/ros.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl-1.7/pcl/filters/voxel_grid.h>
namespace velodyne_height_map {
// shorter names for point cloud types in this namespace
// typedef pcl::PointXYZINormal VPoint;
typedef pcl::PointXYZRGBNormal VPoint;
typedef pcl::PointCloud<VPoint> VPointCloud;
class HeightMap
{
public:
/** Constructor
*
* @param node NodeHandle of this instance
* @param private_nh private NodeHandle of this instance
*/
HeightMap(ros::NodeHandle node, ros::NodeHandle private_nh);
~HeightMap();
/** callback to process data input
*
* @param scan vector of input 3D data points
* @param stamp time stamp of data
* @param frame_id data frame of reference
*/
void processData(const VPointCloud::ConstPtr &scan);
private:
void constructFullClouds(const VPointCloud::ConstPtr &scan, unsigned npoints,
size_t &obs_count, size_t &empty_count);
void constructGridClouds(const VPointCloud::ConstPtr &scan, unsigned npoints,
size_t &obs_count, size_t &empty_count);
// Parameters that define the grids and the height threshold
// Can be set via the parameter server
int grid_dim_;
double m_per_cell_;
double height_diff_threshold_;
bool full_clouds_;
// Point clouds generated in processData
VPointCloud obstacle_cloud_;
VPointCloud clear_cloud_;
VPointCloud original_cloud_;
// ROS topics
ros::Subscriber velodyne_scan_;
ros::Publisher obstacle_publisher_;
ros::Publisher clear_publisher_;
ros::Publisher original_publisher_;
};
} // namespace velodyne_height_map
#endif
| [
"ce62001@meiji.ac.jp"
] | ce62001@meiji.ac.jp |
07cdabae9b7c1e1bfb720e23afff04355786c49f | e60849340c8c1a4c50c915c36ce45387e0388032 | /StructureGraphLib/Synthesizer.h | 7b70339b54d14b3766474550b06e45774f015c10 | [] | no_license | BigkoalaZhu/StBl | bb55d013d54052870aeb6982babaf240d14aa0d1 | 0433e1ed92b2e3993fe559709ecbdc218fcf3546 | refs/heads/master | 2021-01-13T00:59:08.416099 | 2015-12-12T02:56:37 | 2015-12-12T02:56:37 | 44,472,750 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,726 | h | #pragma once
#include "StructureGraph.h"
using namespace Structure;
#include "RMF.h"
extern int randomCount;
extern int uniformTriCount;
struct ParameterCoord{
float u, v;
float theta, psi;
float origOffset;
Eigen::Vector3f origPoint;
Eigen::Vector3f origNormal;
Structure::Node * origNode;
ParameterCoord(){ u = v = -1; theta = psi = 0; origOffset = 0; origNode = NULL; }
ParameterCoord(float theta, float psi, float u, float v = 0, float offset = 0, Structure::Node * node = NULL){
this->u = u;
this->v = v;
this->theta = theta;
this->psi = psi;
this->origOffset = offset;
this->origNode = node;
}
bool operator < (const ParameterCoord& other) const{
return (u < other.u);
}
};
static inline QDebug operator<<(QDebug dbg, const ParameterCoord &c){
dbg.nospace() << QString("[ %1, %2] - theta = %3 \tpsi = %4").arg(c.u).arg(c.v).arg(c.theta).arg(c.psi);
return dbg.space();
}
typedef QMap<QString, QMap<QString, QVariant> > SynthData;
struct Synthesizer{
// Generate sample points in the parameter domain
static QVector<ParameterCoord> genPointCoordsCurve( Structure::Curve * curve, const std::vector<Eigen::Vector3f> & points, const std::vector<Eigen::Vector3f> & normals );
static QVector<ParameterCoord> genPointCoordsSheet( Structure::Sheet * sheet, const std::vector<Eigen::Vector3f> & points, const std::vector<Eigen::Vector3f> & normals );
static QVector<ParameterCoord> genFeatureCoords( Structure::Node * node );
static QVector<ParameterCoord> genEdgeCoords( Structure::Node * node );
static QVector<ParameterCoord> genRandomCoords( Structure::Node * node, int samples_count );
static QVector<ParameterCoord> genUniformCoords( Structure::Node * node, float sampling_resolution = -1);
static QVector<ParameterCoord> genRemeshCoords( Structure::Node * node );
static QVector<ParameterCoord> genUniformTrisCoords( Structure::Node * node );
static QVector<ParameterCoord> genSampleCoordsCurve(Structure::Curve * curve, int samplingType = Features | Random);
static QVector<ParameterCoord> genSampleCoordsSheet(Structure::Sheet * sheet, int samplingType = Features | Random);
// Compute the geometry on given samples in the parameter domain
static void sampleGeometryCurve( QVector<ParameterCoord> samples, Structure::Curve * curve, QVector<float> &offsets, QVector<Vec2f> &normals);
static void sampleGeometrySheet( QVector<ParameterCoord> samples, Structure::Sheet * sheet, QVector<float> &offsets, QVector<Vec2f> &normals );
// Preparation
enum SamplingType{ Features = 1, Edges = 2, Random = 4, Uniform = 8, All = 16, AllNonUniform = 32, Remeshing = 64, TriUniform = 128 };
static void prepareSynthesizeCurve( Structure::Curve * curve1, Structure::Curve * curve2, int samplingType, SynthData & output );
static void prepareSynthesizeSheet( Structure::Sheet * sheet1, Structure::Sheet * sheet2, int samplingType, SynthData & output );
// Blend geometries
static void blendGeometryCurves( Structure::Curve * curve, float alpha, const SynthData & data, QVector<Eigen::Vector3f> &points, QVector<Eigen::Vector3f> &normals, bool isApprox);
static void blendGeometrySheets( Structure::Sheet * sheet, float alpha, const SynthData & data, QVector<Eigen::Vector3f> &points, QVector<Eigen::Vector3f> &normals, bool isApprox);
// Reconstruction on given base skeleton
static void reconstructGeometryCurve( Structure::Curve * base_curve, const QVector<ParameterCoord> &in_samples, const QVector<float> &in_offsets,
const QVector<Vec2f> &in_normals, QVector<Eigen::Vector3f> &out_points, QVector<Eigen::Vector3f> &out_normals, bool isApprox);
static void reconstructGeometrySheet( Structure::Sheet * base_sheet, const QVector<ParameterCoord> &in_samples, const QVector<float> &in_offsets,
const QVector<Vec2f> &in_normals, QVector<Eigen::Vector3f> &out_points, QVector<Eigen::Vector3f> &out_normals, bool isApprox);
// Blend skeleton bases
static void blendCurveBases(Structure::Curve * curve1, Structure::Curve * curve2, float alpha);
static void blendSheetBases(Structure::Sheet * sheet1, Structure::Sheet * sheet2, float alpha);
// Helper functions
static RMF consistentFrame( Structure::Curve * curve, Array1D_Vector4d & coords );
// IO
static void saveSynthesisData(Structure::Node *node, QString prefix, SynthData & input);
static int loadSynthesisData(Structure::Node *node, QString prefix, SynthData & output);
static void writeXYZ( QString filename, std::vector<Eigen::Vector3f> points, std::vector<Eigen::Vector3f> normals );
};
Q_DECLARE_METATYPE(Eigen::Vector3f)
Q_DECLARE_METATYPE(QVector<float>)
Q_DECLARE_METATYPE(QVector<Vec2f>)
Q_DECLARE_METATYPE(QVector<Eigen::Vector3f>)
Q_DECLARE_METATYPE(QVector<ParameterCoord>)
| [
"chenyang.chandler.zhu@gmail.com"
] | chenyang.chandler.zhu@gmail.com |
6a13614cd35fde8e2425622356dc85a580d25ead | 2053e0ec782db1f74eba0c210fcc3ab381e7f152 | /leetcode/162.cpp | 6a5bcd28c30b753d1325b1b911f3300f4c2b8736 | [] | no_license | danielsamfdo/codingAlgo | 86d18b0265c4f5edb323d01ac52f24a2b88599d4 | 0a8e5b67d814ddedcb604f4588e6d959c8958c0b | refs/heads/master | 2021-05-15T10:46:18.941263 | 2017-11-01T02:42:40 | 2017-11-01T02:42:40 | 108,208,650 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | cpp | //https://leetcode.com/problems/find-peak-element/
class Solution {
public:
int search(vector<int>& nums, int l, int r) {
if (l == r)
return l;
int mid = (l + r) / 2;
if (nums[mid] > nums[mid + 1])
return search(nums, l, mid);
return search(nums, mid + 1, r);
}
int findPeakElement(vector<int>& nums) {
return search(nums,0,nums.size()-1);
// int l = 0;
// int r = nums.size()-1;
// if(r==1)return 0;
// int res;
// while(l<r){
// int mid= (l+r)/2;
// res = mid;
// if(nums[mid]>nums[mid+1]){
// r=mid;
// }
// else{
// l=mid+1;
// }
// }
// return l;
}
};//https://leetcode.com/problems/find-peak-element/solution/ | [
"danielsamfdo@gmail.com"
] | danielsamfdo@gmail.com |
931b6d161bf8ea675f2d50896cf7b796109823f7 | d613fa2cbc96c5de066248d9dfda9ac43bfe0f69 | /app/src/EditTableController.cpp | 595b7ecd75dda5896cf4db233eba68e038ab6d09 | [] | no_license | alejinjer/utag | bc4b082432c6f2fea323ce2efd85658b31db7d2a | c3abcddd7c8c2a5e89a6fed28c534aa53b55f6d2 | refs/heads/main | 2022-12-31T13:42:11.620722 | 2020-10-23T12:57:34 | 2020-10-23T12:57:34 | 306,637,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | cpp | #include "EditTableController.h"
EditTableController::EditTableController(QTableWidget *parent)
: m_parent(parent)
{
for (int i = 0; i < TAG_COUNT; ++i) {
m_currentFileTags[i] = new QTableWidgetItem("");
m_parent->setItem(i, 0, m_currentFileTags[i]);
}
}
EditTableController::~EditTableController()
{
}
void EditTableController::setCurrentFile(const QVector<QString> &v)
{
for (auto i = 0; i < TAG_COUNT; i++) {
m_currentFileTags[i]->setData(Qt::DisplayRole, v[i + 1]);
}
}
void EditTableController::unsetCurrentFile()
{
for (auto i = 0; i < TAG_COUNT; i++) {
m_currentFileTags[i]->setData(Qt::DisplayRole, "");
}
}
QVector<QTableWidgetItem *> EditTableController::getCurrentFile()
{
return m_currentFileTags;
}
| [
"opiskun@e1r4p8.unit.ua"
] | opiskun@e1r4p8.unit.ua |
b44aee909a850211924f4a503dd11391b4666a0f | b511bb6461363cf84afa52189603bd9d1a11ad34 | /code/twice_integer.cpp | 4f6c7de443c001b58e475604e4b5e46e7f37a203 | [] | no_license | masumr/problem_solve | ec0059479425e49cc4c76a107556972e1c545e89 | 1ad4ec3e27f28f10662c68bbc268eaad9f5a1a9e | refs/heads/master | 2021-01-16T19:07:01.198885 | 2017-08-12T21:21:59 | 2017-08-12T21:21:59 | 100,135,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int i,t,n,j,k;
vector<int>a;
cin>>t;
while(t--)
{
cin>>n;
for(i=0;i<n;i++){
cin>>k;
a.push_back(k);
}
sort(a.begin(),a.end());
int count=0;
for(i=0;i<a.size();i++)
{
int k=2*a[i];
for(j=i+1;j<a.size();j++)
{
if(k==a[j]){
count++;
break;
}
}
}
cout<<count<<endl;
a.clear();
}
}
| [
"masumr455@gmial.com"
] | masumr455@gmial.com |
e908f1eb8661dacd5e95926183ccbe93942b52ee | 35cfa2ac88a962d71905c1a77f76d3fa3c3a6f55 | /Plane.cpp | c59617879d0b858b987fe8b8902270b55fda1851 | [] | no_license | Romain96/M1S2_GN | 31524dd471ac214dde5f44d744cf2d3a34b37ca8 | 9743f634c22035051587dffa917221d6b296ee58 | refs/heads/master | 2021-03-16T11:00:21.236577 | 2018-03-04T22:49:13 | 2018-03-04T22:49:13 | 120,600,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,405 | cpp | /*
* (C) Romain PERRIN
* romain.perrin@etu.unistra.fr
* UFR de Mathématiques-Informatique
* 2018-2019
*/
// glm
#include "glm/glm.hpp"
#include "glm/vec3.hpp"
#include "Plane.h"
//-----------------------------------------------------------------------------
// Constant(s)
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Constructor(s)
//-----------------------------------------------------------------------------
Plane::Plane() :
_eigenvector1(glm::vec3(0.f)),
_eigenvector2(glm::vec3(0.f)),
_eigenvector3(glm::vec3(0.f))
{
// nothing
}
/**
* @brief Plane::Plane constructs a new plane with ACP computed eigenvectors
* @param ev1 eigenvector 1
* @param ev2 eigenvector 2
* @param ev3 eigenvector 3
*/
Plane::Plane(glm::vec3 &ev1, glm::vec3 &ev2, glm::vec3 &ev3) :
_eigenvector1(ev1),
_eigenvector2(ev2),
_eigenvector3(ev3)
{
// nothing
}
//-----------------------------------------------------------------------------
// Getter(s)
//-----------------------------------------------------------------------------
/**
* @brief Plane::getEigenvector1
* @return the first eigenvector
*/
glm::vec3& Plane::getEigenvector1()
{
return _eigenvector1;
}
/**
* @brief Plane::getEigenvector2
* @return the second eigenvector
*/
glm::vec3& Plane::getEigenvector2()
{
return _eigenvector2;
}
/**
* @brief Plane::getEigenvector3
* @return the third eigenvector
*/
glm::vec3& Plane::getEigenvector3()
{
return _eigenvector3;
}
//-----------------------------------------------------------------------------
// Setter(s)
//-----------------------------------------------------------------------------
/**
* @brief Plane::setEigenvector1
* @param ev1 new first eigenvector
*/
void Plane::setEigenvector1(glm::vec3 &ev1)
{
_eigenvector1 = ev1;
}
/**
* @brief Plane::setEigenvector2
* @param ev2 new second eigenvector
*/
void Plane::setEigenvector2(glm::vec3 &ev2)
{
_eigenvector2 = ev2;
}
/**
* @brief Plane::setEigenvector3
* @param ev3 new third eigenvector
*/
void Plane::setEigenvector3(glm::vec3 &ev3)
{
_eigenvector3 = ev3;
}
//-----------------------------------------------------------------------------
// Method(s)
//-----------------------------------------------------------------------------
| [
"romain.perrin@etu.unistra.fr"
] | romain.perrin@etu.unistra.fr |
ea6856858ffbc835cb51e9f4c4e204bde93dac55 | b570f5afc4d9baeaaeb3757f46017a8eeb89d681 | /C++/Text/lib/Header.cpp | ce6c0bbc997fce3ee27463852ad959ffe2206ba8 | [] | no_license | Anat37/akos | b87f7b2e91adb0994ab2741b1ad65e303af87633 | 78f90b062ebf3dac7be241f95efc1b9f41aa20d0 | refs/heads/master | 2020-12-24T19:37:00.703813 | 2016-11-06T18:01:03 | 2016-11-06T18:01:03 | 58,388,351 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,259 | cpp | #include "Header.h"
Header::Header(const T_Args& args, int t_lvl)
{
level = t_lvl;
w_v = args.w_v;
char *tmp_border = new char[w_v+1];
memset(tmp_border, '#', w_v);
tmp_border[w_v] = '\0';
border = T_String(tmp_border);
delete[] tmp_border;
}
T_String Header::begining(T_String tmp, int curr_level)
{
return T_String();
}
T_String Header::ending(T_String tmp, int curr_level)
{
return T_String();
}
void Header::next_level()
{
++level;
}
void Header::prev_level()
{
--level;
}
T_String Header::split_by_words(T_String str, int curr_level)
{
int col = 0,
last_pos = 0,
i = 0;
for(i = 0; str[i]; i++, col++)
{
if ((str[i] == ' ')&&(col<=w_v))
{
last_pos = i;
}
if (col>w_v)
{
if (i-last_pos>w_v)
{
cout<<"word len error!"<<endl;
exit(0);
}else
{
str[last_pos] = '\n';
i = ++last_pos;
col = 0;
}
}
}
if (col>w_v)
{
if (i-last_pos>w_v)
{
cout<<"word len error!"<<endl;
exit(0);
}else
{
str[last_pos] = '\n';
}
}
int last_i = 0;
T_String tmp_str;
int first = 1;
for(int i = 0; str[i]; i++)
{
if (str[i] == '\n')
{
if (first)
{
tmp_str = tmp_str+get_start_indent(str.slice(last_i, i));
first = 0;
}
else
{
tmp_str = tmp_str+T_String('\n')+get_start_indent(str.slice(last_i, i));
}
last_i = i+1;
}
}
if (first)
{
tmp_str = tmp_str+get_start_indent(str.slice(last_i, strlen(str)));
}
else
{
tmp_str = tmp_str+T_String('\n')+get_start_indent(str.slice(last_i, strlen(str)));
}
return border+T_String('\n')+tmp_str+T_String('\n')+border;
}
T_String Header::get_start_indent(T_String str)
{
if (strlen(str)>w_v)
return str;
size_t pos = (w_v-strlen(str))/2;
char *indent_start = new char [pos+2];
memset(indent_start, ' ', pos);
indent_start[pos] = '\0';
T_String str_indent_start(indent_start);
delete[] indent_start;
return str_indent_start+str;
}
void Header::print()
{
T_String ans;
for (size_t i = 0; i<pos; i++)
{
ans = ans + begining(data[i], levels[i]) + split_by_words( data[i], levels[i]) + ending(data[i], levels[i]) + T_String('\n');
}
ans = ans + T_String('\n');
cout << ans;
}
unsigned long int Header::countSymbols()
{
T_String ans;
for (size_t i = 0; i<pos; i++)
{
ans = ans + begining(data[i], levels[i]) + split_by_words( data[i], levels[i]) + ending(data[i], levels[i]) + T_String('\n');
}
ans = ans + T_String('\n');
return strlen(ans);
}
unsigned long int Header::countWords()
{
unsigned long int count = 0;
for (size_t i = 0; i<pos; i++)
{
for(size_t j = 0; j<strlen(data[i]); j++)
{
if ((data[i][j] == ' ')||(data[i][j] == '\n'))
count += 1;
}
}
return count;
} | [
"kozlof9@yandex.ru"
] | kozlof9@yandex.ru |
9d4930a7f256d7941824c2c34fd5ea6c2272d637 | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/Game Programming Gems 5/Section5-Graphics/5.05-GridlessFire_Adabala/pqueue.cpp | 4babdca7db308bbdee2454a06186a16fbbeaa4e5 | [] | no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 1,846 | cpp | /***********************************************
Demo for chapter "Gridless Controllable Fire"
in Games Programming Gems 5.
Author: Neeharika Adabala
Date: August 2004
************************************************/
#include"pqueue.h"
void PQ::PQupheap(float *DistArr,int *FoundArr,int k)const
{
float v;
int j;
//printf("in PQupheap\n");
v=DistArr[k]; DistArr[0] = 999999999999999.0f;
j=FoundArr[k];
while((DistArr[k/2] <= v)&&(k>0)) {
DistArr[k] = DistArr[k/2];
FoundArr[k] = FoundArr[k/2];
k=k/2;
// printf("in PQupheap\n");
}
if (k==0) printf("Distance is %f\n",v);
DistArr[k] = v;
FoundArr[k] = j;
}
void PQ::PQInsert(float distance,int index,float *DistArr,int *FoundArr)
const
{
//printf("in PQInsert\n");
FoundArr[0]=FoundArr[0]+1;
DistArr[FoundArr[0]] = distance;
FoundArr[FoundArr[0]] = index;
PQupheap(DistArr,FoundArr,FoundArr[0]);
}
void PQ::PQdownheap(float *DistArr,int *FoundArr,int k,int index) const
{
int j,N;
float v;
v=DistArr[k];
N = FoundArr[0]; /* tricky patch to maintain the data structure */
FoundArr[0]=index;
while (k <= N/2) {
j=k+k;
if (j < N && DistArr[j] <DistArr[j+1]) j++;
if (v>=DistArr[j]) break;
DistArr[k]=DistArr[j];
FoundArr[k]=FoundArr[j];
k=j;
//printf("in PQdownheap \n");
}
DistArr[k] = v;
FoundArr[k]= index;
FoundArr[0]=N; /* restore data struct */
}
void PQ::PQreplace(float distance,float *DistArr,int *FoundArr,int index)
const
{
//printf("in PQreplace\n");
DistArr[0]=distance;
PQdownheap(DistArr,FoundArr,0,index);
}
| [
"alec.nunn@gmail.com"
] | alec.nunn@gmail.com |
848114d88c4cb77a2e2608983754a0e87ce40d9e | d732c881b57ef5e3c8f8d105b2f2e09b86bcc3fe | /src/module-wx/VType_wxNavigationKeyEvent.cpp | 7865193e75d53c4add497dbeb0ff05fedb77495a | [] | no_license | gura-lang/gurax | 9180861394848fd0be1f8e60322b65a92c4c604d | d9fedbc6e10f38af62c53c1bb8a4734118d14ce4 | refs/heads/master | 2023-09-01T09:15:36.548730 | 2023-09-01T08:49:33 | 2023-09-01T08:49:33 | 160,017,455 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,114 | cpp | //==============================================================================
// VType_wxNavigationKeyEvent.cpp
// Don't edit this file since it's been generated by Generate.gura.
//==============================================================================
#include "stdafx.h"
Gurax_BeginModuleScope(wx)
//------------------------------------------------------------------------------
// Help
//------------------------------------------------------------------------------
static const char* g_docHelp_en = u8R"""(
# Overview
# Predefined Variable
${help.ComposePropertyHelp(wx.NavigationKeyEvent, `en)}
# Operator
# Cast Operation
${help.ComposeConstructorHelp(wx.NavigationKeyEvent, `en)}
${help.ComposeMethodHelp(wx.NavigationKeyEvent, `en)}
)""";
static const char* g_docHelp_ja = u8R"""(
# 概要
# 定数
${help.ComposePropertyHelp(wx.NavigationKeyEvent, `ja)}
# オペレータ
# キャスト
${help.ComposeConstructorHelp(wx.NavigationKeyEvent, `ja)}
${help.ComposeMethodHelp(wx.NavigationKeyEvent, `ja)}
)""";
//------------------------------------------------------------------------------
// Implementation of constructor
//------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Implementation of method
//-----------------------------------------------------------------------------
// wx.NavigationKeyEvent#GetCurrentFocus() {block?}
Gurax_DeclareMethodAlias(wxNavigationKeyEvent, GetCurrentFocus_gurax, "GetCurrentFocus")
{
Declare(VTYPE_wxWindow, Flag::None);
DeclareBlock(BlkOccur::ZeroOrOnce);
}
Gurax_ImplementMethodEx(wxNavigationKeyEvent, GetCurrentFocus_gurax, processor_gurax, argument_gurax)
{
// Target
auto& valueThis_gurax = GetValueThis(argument_gurax);
auto pEntity_gurax = valueThis_gurax.GetEntityPtr();
if (!pEntity_gurax) return Value::nil();
// Function body
return argument_gurax.ReturnValue(processor_gurax, new Value_wxWindow(
pEntity_gurax->GetCurrentFocus()));
}
// wx.NavigationKeyEvent#GetDirection()
Gurax_DeclareMethodAlias(wxNavigationKeyEvent, GetDirection_gurax, "GetDirection")
{
Declare(VTYPE_Bool, Flag::None);
}
Gurax_ImplementMethodEx(wxNavigationKeyEvent, GetDirection_gurax, processor_gurax, argument_gurax)
{
// Target
auto& valueThis_gurax = GetValueThis(argument_gurax);
auto pEntity_gurax = valueThis_gurax.GetEntityPtr();
if (!pEntity_gurax) return Value::nil();
// Function body
bool rtn = pEntity_gurax->GetDirection();
return new Gurax::Value_Bool(rtn);
}
// wx.NavigationKeyEvent#IsFromTab()
Gurax_DeclareMethodAlias(wxNavigationKeyEvent, IsFromTab_gurax, "IsFromTab")
{
Declare(VTYPE_Bool, Flag::None);
}
Gurax_ImplementMethodEx(wxNavigationKeyEvent, IsFromTab_gurax, processor_gurax, argument_gurax)
{
// Target
auto& valueThis_gurax = GetValueThis(argument_gurax);
auto pEntity_gurax = valueThis_gurax.GetEntityPtr();
if (!pEntity_gurax) return Value::nil();
// Function body
bool rtn = pEntity_gurax->IsFromTab();
return new Gurax::Value_Bool(rtn);
}
// wx.NavigationKeyEvent#IsWindowChange()
Gurax_DeclareMethodAlias(wxNavigationKeyEvent, IsWindowChange_gurax, "IsWindowChange")
{
Declare(VTYPE_Bool, Flag::None);
}
Gurax_ImplementMethodEx(wxNavigationKeyEvent, IsWindowChange_gurax, processor_gurax, argument_gurax)
{
// Target
auto& valueThis_gurax = GetValueThis(argument_gurax);
auto pEntity_gurax = valueThis_gurax.GetEntityPtr();
if (!pEntity_gurax) return Value::nil();
// Function body
bool rtn = pEntity_gurax->IsWindowChange();
return new Gurax::Value_Bool(rtn);
}
// wx.NavigationKeyEvent#SetCurrentFocus(currentFocus as wx.Window)
Gurax_DeclareMethodAlias(wxNavigationKeyEvent, SetCurrentFocus_gurax, "SetCurrentFocus")
{
Declare(VTYPE_Nil, Flag::None);
DeclareArg("currentFocus", VTYPE_wxWindow, ArgOccur::Once, ArgFlag::None);
}
Gurax_ImplementMethodEx(wxNavigationKeyEvent, SetCurrentFocus_gurax, processor_gurax, argument_gurax)
{
// Target
auto& valueThis_gurax = GetValueThis(argument_gurax);
auto pEntity_gurax = valueThis_gurax.GetEntityPtr();
if (!pEntity_gurax) return Value::nil();
// Arguments
Gurax::ArgPicker args_gurax(argument_gurax);
Value_wxWindow& value_currentFocus = args_gurax.Pick<Value_wxWindow>();
wxWindow* currentFocus = value_currentFocus.GetEntityPtr();
// Function body
pEntity_gurax->SetCurrentFocus(currentFocus);
return Gurax::Value::nil();
}
// wx.NavigationKeyEvent#SetDirection(direction as Bool)
Gurax_DeclareMethodAlias(wxNavigationKeyEvent, SetDirection_gurax, "SetDirection")
{
Declare(VTYPE_Nil, Flag::None);
DeclareArg("direction", VTYPE_Bool, ArgOccur::Once, ArgFlag::None);
}
Gurax_ImplementMethodEx(wxNavigationKeyEvent, SetDirection_gurax, processor_gurax, argument_gurax)
{
// Target
auto& valueThis_gurax = GetValueThis(argument_gurax);
auto pEntity_gurax = valueThis_gurax.GetEntityPtr();
if (!pEntity_gurax) return Value::nil();
// Arguments
Gurax::ArgPicker args_gurax(argument_gurax);
bool direction = args_gurax.PickBool();
// Function body
pEntity_gurax->SetDirection(direction);
return Gurax::Value::nil();
}
// wx.NavigationKeyEvent#SetFlags(flags as Number)
Gurax_DeclareMethodAlias(wxNavigationKeyEvent, SetFlags_gurax, "SetFlags")
{
Declare(VTYPE_Nil, Flag::None);
DeclareArg("flags", VTYPE_Number, ArgOccur::Once, ArgFlag::None);
}
Gurax_ImplementMethodEx(wxNavigationKeyEvent, SetFlags_gurax, processor_gurax, argument_gurax)
{
// Target
auto& valueThis_gurax = GetValueThis(argument_gurax);
auto pEntity_gurax = valueThis_gurax.GetEntityPtr();
if (!pEntity_gurax) return Value::nil();
// Arguments
Gurax::ArgPicker args_gurax(argument_gurax);
long flags = args_gurax.PickNumber<long>();
// Function body
pEntity_gurax->SetFlags(flags);
return Gurax::Value::nil();
}
// wx.NavigationKeyEvent#SetFromTab(fromTab as Bool)
Gurax_DeclareMethodAlias(wxNavigationKeyEvent, SetFromTab_gurax, "SetFromTab")
{
Declare(VTYPE_Nil, Flag::None);
DeclareArg("fromTab", VTYPE_Bool, ArgOccur::Once, ArgFlag::None);
}
Gurax_ImplementMethodEx(wxNavigationKeyEvent, SetFromTab_gurax, processor_gurax, argument_gurax)
{
// Target
auto& valueThis_gurax = GetValueThis(argument_gurax);
auto pEntity_gurax = valueThis_gurax.GetEntityPtr();
if (!pEntity_gurax) return Value::nil();
// Arguments
Gurax::ArgPicker args_gurax(argument_gurax);
bool fromTab = args_gurax.PickBool();
// Function body
pEntity_gurax->SetFromTab(fromTab);
return Gurax::Value::nil();
}
// wx.NavigationKeyEvent#SetWindowChange(windowChange as Bool)
Gurax_DeclareMethodAlias(wxNavigationKeyEvent, SetWindowChange_gurax, "SetWindowChange")
{
Declare(VTYPE_Nil, Flag::None);
DeclareArg("windowChange", VTYPE_Bool, ArgOccur::Once, ArgFlag::None);
}
Gurax_ImplementMethodEx(wxNavigationKeyEvent, SetWindowChange_gurax, processor_gurax, argument_gurax)
{
// Target
auto& valueThis_gurax = GetValueThis(argument_gurax);
auto pEntity_gurax = valueThis_gurax.GetEntityPtr();
if (!pEntity_gurax) return Value::nil();
// Arguments
Gurax::ArgPicker args_gurax(argument_gurax);
bool windowChange = args_gurax.PickBool();
// Function body
pEntity_gurax->SetWindowChange(windowChange);
return Gurax::Value::nil();
}
//-----------------------------------------------------------------------------
// Implementation of property
//-----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// VType_wxNavigationKeyEvent
//------------------------------------------------------------------------------
VType_wxNavigationKeyEvent VTYPE_wxNavigationKeyEvent("NavigationKeyEvent");
void VType_wxNavigationKeyEvent::DoPrepare(Frame& frameOuter)
{
// Add help
AddHelp(Gurax_Symbol(en), g_docHelp_en);
AddHelp(Gurax_Symbol(ja), g_docHelp_ja);
// Declaration of VType
Declare(VTYPE_wxEvent, Flag::Mutable);
// Assignment of method
Assign(Gurax_CreateMethod(wxNavigationKeyEvent, GetCurrentFocus_gurax));
Assign(Gurax_CreateMethod(wxNavigationKeyEvent, GetDirection_gurax));
Assign(Gurax_CreateMethod(wxNavigationKeyEvent, IsFromTab_gurax));
Assign(Gurax_CreateMethod(wxNavigationKeyEvent, IsWindowChange_gurax));
Assign(Gurax_CreateMethod(wxNavigationKeyEvent, SetCurrentFocus_gurax));
Assign(Gurax_CreateMethod(wxNavigationKeyEvent, SetDirection_gurax));
Assign(Gurax_CreateMethod(wxNavigationKeyEvent, SetFlags_gurax));
Assign(Gurax_CreateMethod(wxNavigationKeyEvent, SetFromTab_gurax));
Assign(Gurax_CreateMethod(wxNavigationKeyEvent, SetWindowChange_gurax));
}
//------------------------------------------------------------------------------
// Value_wxNavigationKeyEvent
//------------------------------------------------------------------------------
VType& Value_wxNavigationKeyEvent::vtype = VTYPE_wxNavigationKeyEvent;
EventValueFactoryDeriv<Value_wxNavigationKeyEvent> Value_wxNavigationKeyEvent::eventValueFactory;
String Value_wxNavigationKeyEvent::ToString(const StringStyle& ss) const
{
return ToStringGeneric(ss, "wx.NavigationKeyEvent");
}
Gurax_EndModuleScope(wx)
| [
"ypsitau@nifty.com"
] | ypsitau@nifty.com |
feb8f93817283ad5a7356cc24b00d6f93afd0618 | 90e6ac97019b3478ff0596eb193af315a7a8bd4a | /IDR(s)/Matrix.h | 3d8274b4615dffcd9603a80881c48c9cd36503c5 | [] | no_license | aggarwal2000/IDR-biortho-NLA4HPC | ab2674e0975778f4310ede4a8391801c5f9fead3 | acd2aa6ed61f487d2be5ba103cfebe8a68d59421 | refs/heads/master | 2023-03-18T08:52:07.186156 | 2021-03-09T15:07:48 | 2021-03-09T15:07:48 | 346,045,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,992 | h | /*!
\file Matrix.h
\brief Definition of classes Dense_Matrix, CSR_Matrix and COO_Matrix
*/
# pragma once
#include<cassert>
#include<cuComplex.h>
#include"location_enums.h"
typedef cuDoubleComplex DoubleComplex;
//! enum class which defines storage order for dense matrices
/**
This enum class defines the order(row/column) in which values are stored in dense matrices
*/
enum class ORDER {
COLUMN_MAJOR, /*!< means that the matrix values are stored in column major order */
ROW_MAJOR /*!< means that the matrix values are stored in row major order */
};
//! Class for Complex Dense Matrices
/*!
This class contains attributes and member functions for complex dense matrix class objects.
*/
class Dense_Matrix {
private:
const int rows; /*!< Number of rows in dense matrix*/
const int cols; /*!< Number of columns in dense matrix */
const int lda; /*!< Leading Dimension of dimension of dense matrix (Usually the number of rows is rounded up to a certain value to give lda.) */
ORDER order = ORDER::COLUMN_MAJOR; /*!< storage order of dense matrix */
CPU_EXISTENCE cpu_exists = CPU_EXISTENCE::NON_EXISTENT; /*!< presence/absence of dense matrix internals(large arrays) in CPU memory*/
GPU_EXISTENCE gpu_exists = GPU_EXISTENCE::NON_EXISTENT; /*!< presence/absence of dense matrix internals(large arrays) in GPU memory*/
DoubleComplex* cpu_values = nullptr; /*!< Pointer storing base address of the array allocated on CPU containing dense matrix's values.
It is equal to nullptr in case no memory is allocated. Note:values on CPU and GPU do not match until they are copied.*/
DoubleComplex* gpu_values = nullptr;/*!< Pointer storing base address of the array allocated on GPU containing dense matrix's values.
It is equal to nullptr in case no memory is allocated. Note:values on CPU and GPU do not match until they are copied.*/
public:
//! Returns number of rows in dense matrix
/*!
\return number of rows in dense matrix
*/
int GetRows() const
{
return rows;
}
//! Returns number of columns in dense matrix
/*!
\return number of columns in dense matrix
*/
int GetCols() const
{
return cols;
}
//! Returns leading dimension of dense matrix
/*!
\return leading dimension of dense matrix
*/
int GetLda() const
{
return lda;
}
//! Returns storage order of dense matrix
/*!
\return order in which values are stored in the dense matrix
*/
ORDER GetOrder() const
{
return order;
}
//! Returns a pointer to the array allocated on CPU which stores the dense matrix values
/*!
\return pointer to the array allocated on CPU which stores the dense matrix values; nullptr in case no such array exists
*/
DoubleComplex* GetCPUValues() const
{
if(ExistsCPU() == true)
return cpu_values;
else
return nullptr;
}
//! Returns a pointer to the array allocated on GPU which stores the dense matrix values
/*!
\return pointer to the array allocated on GPU which stores the dense matrix values; nullptr in case no such array exists
*/
DoubleComplex* GetGPUValues() const
{
if(ExistsGPU() == true)
return gpu_values;
else
return nullptr;
}
//! Takes in a column index and returns a pointer to its starting location on GPU.
/*!
\param[in] col_ind index of the column for which the pointer (to GPU memory) is required
\return pointer to the starting location of the column on GPU memory; nullptr in case no memory is allocated on GPU
*/
DoubleComplex* GetColPtrGPU(const int col_ind) const
{
assert(col_ind < GetCols());
//return &gpu_values[lda * col_ind];
if(ExistsGPU() == true)
return GetGPUValues() + GetLda() * col_ind;
else
return nullptr;
}
//! Takes in a column index and returns a pointer to its starting location on CPU.
/*!
\param[in] col_ind index of the column for which the pointer (to CPU memory) is required
\return pointer to the starting location of the column on CPU memory; nullptr in case no memory is allocated on CPU
*/
DoubleComplex* GetColPtrCPU(const int col_ind) const
{
assert(col_ind < GetCols());
if(ExistsCPU() == true)
return GetCPUValues() + GetLda() * col_ind;
else
return nullptr;
}
//! Takes in a location and returns its GPU memory address
/*!
\param[in] row row index of the element
\param[in] col column index the element
\return pointer(GPU memory address) to the element; nullptr in case no memory is allocated on GPU
*/
DoubleComplex* GetSpecificLocationPtrGPU(const int row, const int col) const
{
//return &gpu_values[row + lda * col];
assert(row < GetRows());
assert(col < GetCols());
if(ExistsGPU() == true)
return GetGPUValues() + row + GetLda()* col;
else
return nullptr;
}
//! Takes in a location and returns its CPU memory address
/*!
\param[in] row row index of the element
\param[in] col column index the element
\return pointer(CPU memory address) to the element; nullptr in case no memory is allocated on CPU
*/
DoubleComplex* GetSpecificLocationPtrCPU(const int row, const int col) const
{
assert(row < GetRows());
assert(col < GetCols());
if(ExistsCPU() == true)
return GetCPUValues() + row + GetLda()* col;
else
return nullptr;
}
//! Returns true if Dense matrix values are present on CPU memory
/*!
\return boolean value
*/
bool ExistsCPU() const
{
return cpu_exists == CPU_EXISTENCE::EXISTENT;
}
//! Returns true if Dense matrix values are present on GPU memory
/*!
\return boolean value
*/
bool ExistsGPU() const
{
return gpu_exists == GPU_EXISTENCE::EXISTENT;
}
void Allocate_Memory(const LOCATION loc);
Dense_Matrix(const int rows, const int cols, const int lda, const ORDER order, const CPU_EXISTENCE cpu_exists, const GPU_EXISTENCE gpu_exists);
~Dense_Matrix();
void CopyMatrix_cpu_to_gpu();
void CopyMatrix_gpu_to_cpu();
void Deallocate_Memory(const LOCATION loc);
Dense_Matrix(const Dense_Matrix& mat);
Dense_Matrix(Dense_Matrix&& mat);
Dense_Matrix& operator= (const Dense_Matrix& mat);
Dense_Matrix& operator= (Dense_Matrix&& mat);
void CopyMatrix_cpu_to_gpu(int col_start , int col_end , int row_start , int row_end);
void CopyMatrix_gpu_to_cpu(int col_start , int col_end, int row_start, int row_end);
};
//! Class for complex sparse CSR matrix
/*!
This class contains attributes and member functions for complex sparse CSR matrix class.
*/
class CSR_Matrix {
private:
const int rows; /*!< Number of rows in CSR matrix*/
const int cols; /*!< Number of columns in CSR matrix*/
const int nz; /*!< Number of nonzero elemnents in CSR matrix*/
CPU_EXISTENCE cpu_exists = CPU_EXISTENCE::NON_EXISTENT; /*!< presence/absence of CSR matrix internals in CPU memory*/
GPU_EXISTENCE gpu_exists = GPU_EXISTENCE::NON_EXISTENT; /*!< presence/absence of CSR matrix internals in GPU memory*/
DoubleComplex* cpu_values = nullptr; /*!< Pointer storing base address of the array allocated on CPU containing CSR matrix's values.
It is equal to nullptr in case no memory is allocated. Note:values on CPU and GPU do not match until they are copied.*/
DoubleComplex* gpu_values = nullptr; /*!< Pointer storing base address of the array allocated on GPU containing CSR matrix's values.
It is equal to nullptr in case no memory is allocated. Note:values on CPU and GPU do not match until they are copied.*/
int* cpu_row_ptr = nullptr; /*!< Pointer storing base address of the array allocated on CPU containing CSR matrix row pointers
It is equal to nullptr in case no memory is allocated.*/
int* gpu_row_ptr = nullptr;/*!< Pointer storing base address of the array allocated on GPU containing CSR matrix row pointers
It is equal to nullptr in case no memory is allocated.*/
int* cpu_col_ind = nullptr;/*!< Pointer storing base address of the array allocated on CPU containing CSR matrix column indices
It is equal to nullptr in case no memory is allocated.*/
int* gpu_col_ind = nullptr;/*!< Pointer storing base address of the array allocated on GPU containing CSR matrix column indices
It is equal to nullptr in case no memory is allocated.*/
public:
//! Returns number of rows in CSR matrix
/*!
\return number of rows in CSR matrix
*/
int GetRows() const
{
return rows;
}
//! Returns number of columns in CSR matrix
/*!
\return number of columns in CSR matrix
*/
int GetCols() const
{
return cols;
}
//! Returns number of non zero elements in CSR matrix
/*!
\return number of non zero elements in CSR matrix
*/
int Getnz() const
{
return nz;
}
//! Returns a pointer to the array allocated on CPU which stores the CSR matrix values
/*!
\return pointer to the array allocated on CPU which stores the CSR matrix values; nullptr in case no such array exists
*/
DoubleComplex* GetCPUValues() const
{
if(ExistsCPU() == true)
return cpu_values;
else
return nullptr;
}
//! Returns a pointer to the array allocated on CPU which stores the CSR matrix row pointers
/*!
\return pointer to the array allocated on CPU which stores the CSR matrix row pointers; nullptr in case no such array exists
*/
int* GetCPURowPtr() const
{
if(ExistsCPU() == true)
return cpu_row_ptr;
else
return nullptr;
}
//! Returns a pointer to the array allocated on CPU which stores the CSR matrix column indices
/*!
\return pointer to the array allocated on CPU which stores the CSR matrix column indices; nullptr in case no such array exists
*/
int* GetCPUColInd() const
{
if(ExistsCPU() == true)
return cpu_col_ind;
else
return nullptr;
}
//! Returns a pointer to the array allocated on GPU which stores the CSR matrix values
/*!
\return pointer to the array allocated on GPU which stores the CSR matrix values; nullptr in case no such array exists
*/
DoubleComplex* GetGPUValues() const
{
if(ExistsGPU() == true)
return gpu_values;
else
return nullptr;
}
//! Returns a pointer to the array allocated on GPU which stores the CSR matrix row pointers
/*!
\return pointer to the array allocated on GPU which stores the CSR matrix row pointers; nullptr in case no such array exists
*/
int* GetGPURowPtr() const
{
if(ExistsGPU() == true)
return gpu_row_ptr;
else
return nullptr;
}
//! Returns a pointer to the array allocated on GPU which stores the CSR matrix column indices
/*!
\return pointer to the array allocated on GPU which stores the CSR matrix column indices; nullptr in case no such array exists
*/
int* GetGPUColInd() const
{
return gpu_col_ind;
}
//! Returns true if CSR matrix internals(large arrays) are present on CPU memory
/*!
\return boolean value
*/
bool ExistsCPU() const
{
return cpu_exists == CPU_EXISTENCE::EXISTENT;
}
//! Returns true if CSR matrix internals(large arrays) are present on GPU memory
/*!
\return boolean value
*/
bool ExistsGPU() const
{
return gpu_exists == GPU_EXISTENCE::EXISTENT;
}
void Allocate_Memory(const LOCATION loc);
CSR_Matrix(const int rows, const int cols, const int nz, const CPU_EXISTENCE cpu_exists, const GPU_EXISTENCE gpu_exists);
~CSR_Matrix();
void CopyMatrix_cpu_to_gpu();
void CopyMatrix_gpu_to_cpu();
void Deallocate_Memory(const LOCATION loc);
//! Copy constructor for CSR Matrix class
/*!
A deleted constructor
*/
CSR_Matrix(const CSR_Matrix& mat) = delete;
//! Move constructor for CSR Matrix class
/*!
A deleted constructor
*/
CSR_Matrix(CSR_Matrix&& mat) = delete;
//! Copy assignment operator for CSR matrix class
/*!
A deleted operator.
*/
CSR_Matrix& operator= (const CSR_Matrix& mat) = delete;
//! Move assignment operator for CSR matrix class
/*!
A deleted operator.
*/
CSR_Matrix& operator= (CSR_Matrix&& mat) = delete;
};
//! Class for complex sparse COO matrix
/*!
This class contains attributes and member functions for complex COO matrix
*/
class COO_Matrix {
private:
const int rows;/*!< Number of rows in COO matrix*/
const int cols;/*!< Number of columns in COO matrix*/
int nz; /*!< Number of nonzero elemnents in COO matrix, this can also be changed by Set_nz(int) member function*/
CPU_EXISTENCE cpu_exists = CPU_EXISTENCE::NON_EXISTENT;/*!< presence/absence of COO matrix internals(matrix arrays) in CPU memory*/
GPU_EXISTENCE gpu_exists = GPU_EXISTENCE::NON_EXISTENT; /*!< presence/absence of COO matrix internals(matrix arrays) in GPU memory*/
DoubleComplex* cpu_values = nullptr;/*!< Pointer storing base address of the array allocated on CPU containing COO matrix's values.
It is equal to nullptr in case no memory is allocated. Note:values on CPU and GPU do not match until they are copied.*/
DoubleComplex* gpu_values = nullptr;/*!< Pointer storing base address of the array allocated on GPU containing COO matrix's values.
It is equal to nullptr in case no memory is allocated. Note:values on CPU and GPU do not match until thay are copied.*/
int* cpu_row_ind = nullptr;/*!< Pointer storing base address of the array allocated on CPU containing COO matrix row indices
It is equal to nullptr in case no memory is allocated.*/
int* gpu_row_ind = nullptr;/*!< Pointer storing base address of the array allocated on GPU containing COO matrix row indices
It is equal to nullptr in case no memory is allocated.*/
int* cpu_col_ind = nullptr;/*!< Pointer storing base address of the array allocated on CPU containing COO matrix column indices
It is equal to nullptr in case no memory is allocated.*/
int* gpu_col_ind = nullptr;/*!< Pointer storing base address of the array allocated on GPU containing COO matrix column indices
It is equal to nullptr in case no memory is allocated.*/
public:
//! Returns number of rows in COO matrix
/*!
\return number of rows in COO matrix
*/
int GetRows() const
{
return rows;
}
//! Returns number of columns in COO matrix
/*!
\return number of columns in COO matrix
*/
int GetCols() const
{
return cols;
}
//! Returns number of non zero elements in COO matrix
/*!
\return number of non zero elements in COO matrix
*/
int Getnz() const
{
return nz;
}
//! Sets the number of non zero elements in COO matrix
/*!
This is used to set the number of non zero elements in COO matrix object after it is formed.
Typical example of where it is useful is: If the number of non zero elemnets in COO matrix is unknown in the
beginning then an estimate of it is used while creating the object(estimate must be greater else the memory which is
allocated based on the estimate won't be enough to store matrix arrays) and later on, after writing the values
into memory and counting the elements along with that, the number of non zero elements can be set to the exact value using this function.
\param[in] mat_nz number of non zero elements to be set for the current matrix object
*/
void Set_nz(const int mat_nz)
{
nz = mat_nz;
}
//! Returns a pointer to the array allocated on CPU which stores the COO matrix values
/*!
\return pointer to the array allocated on CPU which stores the COO matrix values; nullptr in case no such array exists
*/
DoubleComplex* GetCPUValues() const
{
return cpu_values;
}
//! Returns a pointer to the array allocated on CPU which stores the COO matrix row indices
/*!
\return pointer to the array allocated on CPU which stores the COO matrix row indices; nullptr in case no such array exists
*/
int* GetCPURowInd() const
{
return cpu_row_ind;
}
//! Returns a pointer to the array allocated on CPU which stores the COO matrix column indices
/*!
\return pointer to the array allocated on CPU which stores the COO matrix column indices; nullptr in case no such array exists
*/
int* GetCPUColInd() const
{
return cpu_col_ind;
}
//! Returns a pointer to the array allocated on GPU which stores the COO matrix values
/*!
\return pointer to the array allocated on GPU which stores the COO matrix values; nullptr in case no such array exists
*/
DoubleComplex* GetGPUValues() const
{
return gpu_values;
}
//! Returns a pointer to the array allocated on GPU which stores the COO matrix row indices
/*!
\return pointer to the array allocated on GPU which stores the COO matrix row indices; nullptr in case no such array exists
*/
int* GetGPURowInd() const
{
return gpu_row_ind;
}
//! Returns a pointer to the array allocated on GPU which stores the COO matrix column indices
/*!
\return pointer to the array allocated on GPU which stores the COO matrix column indices; nullptr in case no such array exists
*/
int* GetGPUColInd() const
{
return gpu_col_ind;
}
//! Returns true if COO matrix internals(matrix arrays) are present on CPU memory
/*!
\return boolean value
*/
bool ExistsCPU() const
{
return cpu_exists == CPU_EXISTENCE::EXISTENT;
}
//! Returns true if COO matrix internals(matrix arrays) are present on GPU memory
/*!
\return boolean value
*/
bool ExistsGPU() const
{
return gpu_exists == GPU_EXISTENCE::EXISTENT;
}
void Allocate_Memory(const LOCATION loc);
COO_Matrix(const int rows, const int cols, const int nz, const CPU_EXISTENCE cpu_exists, const GPU_EXISTENCE gpu_exists);
~COO_Matrix();
void CopyMatrix_cpu_to_gpu();
void CopyMatrix_gpu_to_cpu();
void Deallocate_Memory(const LOCATION loc);
//! Copy constructor for COO Matrix class
/*!
A deleted constructor
*/
COO_Matrix(const COO_Matrix& mat) = delete;
//! Move constructor for COO Matrix class
/*!
A deleted constructor
*/
COO_Matrix(COO_Matrix&& mat) = delete;
//! Copy assignment operator for COO matrix class
/*!
A deleted operator.
*/
COO_Matrix& operator= (const COO_Matrix& mat) = delete;
//! Move assignment operator for COO matrix class
/*!
A deleted operator.
*/
COO_Matrix& operator= (COO_Matrix&& mat) = delete;
};
| [
"aggarwal2000chd@gmail.com"
] | aggarwal2000chd@gmail.com |
84d7b308256818236e1a5459e272be9b2b9c7b5c | 33f8a1164c44b4ade4a1ae9edca25a5d631b14dc | /MusicClip.cpp | 53dab6e1e0f72cc6018b8ff6f72dbdeaf06e5652 | [] | no_license | kuribohlv9/Skelly_Dungeon | fe2ef781c3e4169ef7300a3af1347ee7f18bf4a3 | 01d8d165a3d045b58b467a5e5c4594ba6c92a115 | refs/heads/master | 2020-04-30T09:03:41.956469 | 2015-02-07T15:29:12 | 2015-02-07T15:29:12 | 28,010,758 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | cpp | // MusicClip.cpp
#include "stdafx.h"
#include "MusicClip.h"
MusicClip::MusicClip()
{
m_xClip = nullptr;
m_iChannel = -1;
}
MusicClip::~MusicClip()
{
m_xClip = nullptr;
m_iChannel = -1;
}
MusicClip::MusicClip(Mix_Music* p_xClip)
{
m_xClip = p_xClip;
m_iChannel = -1;
}
void MusicClip::Play()
{
m_iChannel = Mix_PlayMusic(m_xClip, -1);
}
void MusicClip::Pause()
{
if (m_iChannel == -1)
return;
if ( Mix_PausedMusic() )
Mix_ResumeMusic();
else
Mix_Pause(m_iChannel);
}
void MusicClip::Volume(int p_iVolume)
{
Mix_VolumeMusic(p_iVolume);
}
void MusicClip::Stop()
{
if (m_iChannel == -1)
return;
Mix_HaltChannel(m_iChannel);
m_iChannel = -1;
} | [
"gamedesignwithdee@gmail.com"
] | gamedesignwithdee@gmail.com |
a969f570535f19af222f1023faa5f9039884f7ab | 44ab57520bb1a9b48045cb1ee9baee8816b44a5b | /Assist/Code/Toolset/CoreTools/ExportTest/CoreTools/Shared/MathematicsMacroShared.h | b2dc0d0e6549e0fd15b035850cd7f891099b35ec | [
"BSD-3-Clause"
] | permissive | WuyangPeng/Engine | d5d81fd4ec18795679ce99552ab9809f3b205409 | 738fde5660449e87ccd4f4878f7bf2a443ae9f1f | refs/heads/master | 2023-08-17T17:01:41.765963 | 2023-08-16T07:27:05 | 2023-08-16T07:27:05 | 246,266,843 | 10 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,025 | h | /// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// 作者:彭武阳,彭晔恩,彭晔泽
/// 联系作者:94458936@qq.com
///
/// 标准:std:c++20
/// 版本:0.9.1.2 (2023/07/28 15:00)
#ifndef EXPORT_TEST_MATHEMATICS_MACRO_SHARED_H
#define EXPORT_TEST_MATHEMATICS_MACRO_SHARED_H
#include "Mathematics/MathematicsDll.h"
#include "CoreTools/Contract/ContractFwd.h"
#include "CoreTools/Helper/Export/SharedExportMacro.h"
MATHEMATICS_SHARED_EXPORT_IMPL(MathematicsMacroSharedImpl);
namespace Mathematics
{
class MATHEMATICS_DEFAULT_DECLARE MathematicsMacroShared final
{
public:
SHARED_TYPE_DECLARE(MathematicsMacroShared);
public:
explicit MathematicsMacroShared(int count);
CLASS_INVARIANT_DECLARE;
NODISCARD int GetCount() const noexcept;
void SetCount(int count) noexcept;
NODISCARD const void* GetAddress() const noexcept;
private:
PackageType impl;
};
}
#endif // EXPORT_TEST_MATHEMATICS_MACRO_SHARED_H | [
"94458936@qq.com"
] | 94458936@qq.com |
522a169f3d7c26997b4279be7a9bbc3f50194c09 | 12f441018818dc2dcb1a8a89bccd946d87e0ac9e | /cppwinrt/winrt/impl/Windows.Graphics.Imaging.1.h | 12eca538456ba35555f8a70f04a136e509d26eff | [
"MIT"
] | permissive | dlech/bleak-winrt | cc7dd76fca9453b7415d65a428e22b2cbfe36209 | a6c1f3fd073a7b5678304ea6bc08b9b067544320 | refs/heads/main | 2022-09-12T00:15:01.497572 | 2022-09-09T22:57:53 | 2022-09-09T22:57:53 | 391,440,675 | 10 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,596 | h | // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.220608.4
#pragma once
#ifndef WINRT_Windows_Graphics_Imaging_1_H
#define WINRT_Windows_Graphics_Imaging_1_H
#include "winrt/impl/Windows.Foundation.0.h"
#include "winrt/impl/Windows.Graphics.Imaging.0.h"
WINRT_EXPORT namespace winrt::Windows::Graphics::Imaging
{
struct __declspec(empty_bases) IBitmapBuffer :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapBuffer>,
impl::require<winrt::Windows::Graphics::Imaging::IBitmapBuffer, winrt::Windows::Foundation::IClosable, winrt::Windows::Foundation::IMemoryBuffer>
{
IBitmapBuffer(std::nullptr_t = nullptr) noexcept {}
IBitmapBuffer(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapCodecInformation :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapCodecInformation>
{
IBitmapCodecInformation(std::nullptr_t = nullptr) noexcept {}
IBitmapCodecInformation(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapDecoder :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapDecoder>
{
IBitmapDecoder(std::nullptr_t = nullptr) noexcept {}
IBitmapDecoder(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapDecoderStatics :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapDecoderStatics>
{
IBitmapDecoderStatics(std::nullptr_t = nullptr) noexcept {}
IBitmapDecoderStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapDecoderStatics2 :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapDecoderStatics2>
{
IBitmapDecoderStatics2(std::nullptr_t = nullptr) noexcept {}
IBitmapDecoderStatics2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapEncoder :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapEncoder>
{
IBitmapEncoder(std::nullptr_t = nullptr) noexcept {}
IBitmapEncoder(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapEncoderStatics :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapEncoderStatics>
{
IBitmapEncoderStatics(std::nullptr_t = nullptr) noexcept {}
IBitmapEncoderStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapEncoderStatics2 :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapEncoderStatics2>
{
IBitmapEncoderStatics2(std::nullptr_t = nullptr) noexcept {}
IBitmapEncoderStatics2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapEncoderWithSoftwareBitmap :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapEncoderWithSoftwareBitmap>
{
IBitmapEncoderWithSoftwareBitmap(std::nullptr_t = nullptr) noexcept {}
IBitmapEncoderWithSoftwareBitmap(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapFrame :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapFrame>
{
IBitmapFrame(std::nullptr_t = nullptr) noexcept {}
IBitmapFrame(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapFrameWithSoftwareBitmap :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapFrameWithSoftwareBitmap>,
impl::require<winrt::Windows::Graphics::Imaging::IBitmapFrameWithSoftwareBitmap, winrt::Windows::Graphics::Imaging::IBitmapFrame>
{
IBitmapFrameWithSoftwareBitmap(std::nullptr_t = nullptr) noexcept {}
IBitmapFrameWithSoftwareBitmap(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapProperties :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapProperties>,
impl::require<winrt::Windows::Graphics::Imaging::IBitmapProperties, winrt::Windows::Graphics::Imaging::IBitmapPropertiesView>
{
IBitmapProperties(std::nullptr_t = nullptr) noexcept {}
IBitmapProperties(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapPropertiesView :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapPropertiesView>
{
IBitmapPropertiesView(std::nullptr_t = nullptr) noexcept {}
IBitmapPropertiesView(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapTransform :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapTransform>
{
IBitmapTransform(std::nullptr_t = nullptr) noexcept {}
IBitmapTransform(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapTypedValue :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapTypedValue>
{
IBitmapTypedValue(std::nullptr_t = nullptr) noexcept {}
IBitmapTypedValue(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IBitmapTypedValueFactory :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IBitmapTypedValueFactory>
{
IBitmapTypedValueFactory(std::nullptr_t = nullptr) noexcept {}
IBitmapTypedValueFactory(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IPixelDataProvider :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<IPixelDataProvider>
{
IPixelDataProvider(std::nullptr_t = nullptr) noexcept {}
IPixelDataProvider(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) ISoftwareBitmap :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<ISoftwareBitmap>,
impl::require<winrt::Windows::Graphics::Imaging::ISoftwareBitmap, winrt::Windows::Foundation::IClosable>
{
ISoftwareBitmap(std::nullptr_t = nullptr) noexcept {}
ISoftwareBitmap(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) ISoftwareBitmapFactory :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<ISoftwareBitmapFactory>
{
ISoftwareBitmapFactory(std::nullptr_t = nullptr) noexcept {}
ISoftwareBitmapFactory(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) ISoftwareBitmapStatics :
winrt::Windows::Foundation::IInspectable,
impl::consume_t<ISoftwareBitmapStatics>
{
ISoftwareBitmapStatics(std::nullptr_t = nullptr) noexcept {}
ISoftwareBitmapStatics(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
}
#endif
| [
"david@lechnology.com"
] | david@lechnology.com |
796027e8d72687c6dd5d3e7397f99064d8845caa | 96a59ce1d89472f3342de04123606816e4b88ca3 | /zswlib/mesh/mesh_op.h | eeb208cd55424034b20e4a55b4e3c26c4865fcd1 | [] | no_license | wegatron/geometry | f620796fbeffc25417090c580041cdacefe74a01 | 36aa73a04deb54c8c24c2919f723af89dbf91226 | refs/heads/master | 2020-04-06T07:04:48.212278 | 2016-03-31T07:11:50 | 2016-03-31T07:11:50 | 36,479,096 | 0 | 0 | null | 2016-03-31T07:11:51 | 2015-05-29T02:50:36 | C++ | UTF-8 | C++ | false | false | 329 | h | #ifndef MESH_OP_H
#define MESH_OP_H
#include <zswlib/config.h>
#include <zswlib/mesh/mesh_type.h>
#include <zswlib/data_type.h>
namespace zsw
{
namespace mesh {
void ZSW_API rRingVertex(const zsw::mesh::TriMesh &tm, const size_t r, std::vector<zsw::FakeSet<size_t>> &ring);
}
}
#endif /* MESH_OP_H */
| [
"wegatron@gmail.com"
] | wegatron@gmail.com |
2c27679e65e182cf55805ea8661aefacf8d08412 | ffdc77394c5b5532b243cf3c33bd584cbdc65cb7 | /mindspore/lite/tools/converter/micro/coder/opcoders/nnacl/fp32/shape_fp32_coder.cc | 2fae254c1c8c1a029780416350abca3ab653853c | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | permissive | mindspore-ai/mindspore | ca7d5bb51a3451c2705ff2e583a740589d80393b | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | refs/heads/master | 2023-07-29T09:17:11.051569 | 2023-07-17T13:14:15 | 2023-07-17T13:14:15 | 239,714,835 | 4,178 | 768 | Apache-2.0 | 2023-07-26T22:31:11 | 2020-02-11T08:43:48 | C++ | UTF-8 | C++ | false | false | 2,242 | cc | /**
* Copyright 2022 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "coder/opcoders/nnacl/fp32/shape_fp32_coder.h"
#include <string>
#include <vector>
#include "coder/opcoders/serializers/nnacl_serializer/nnacl_fp32_serializer.h"
#include "coder/opcoders/file_collector.h"
using mindspore::schema::PrimitiveType_Shape;
namespace mindspore::lite::micro::nnacl {
int ShapeFP32Coder::DoCode(CoderContext *const context) {
std::string output_str = allocator_->GetRuntimeAddr(output_tensor_);
NNaclFp32Serializer code;
MS_LOG(WARNING)
<< "The shape op can be fused and optimized by configuring the 'inputShape' parameter of the converter tool.";
code << " {\n";
int index = 0;
for (auto &shape : input_tensors_.at(0)->shape()) {
code << " " << output_str << "[" << index++ << "] = " << shape << ";\n";
}
code << " }\n";
context->AppendCode(code.str());
return RET_OK;
}
REG_OPERATOR_CODER(kAllTargets, kNumberTypeFloat32, PrimitiveType_Shape, CPUOpCoderCreator<ShapeFP32Coder>)
REG_OPERATOR_CODER(kAllTargets, kNumberTypeInt32, PrimitiveType_Shape, CPUOpCoderCreator<ShapeFP32Coder>)
REG_OPERATOR_CODER(kAllTargets, kNumberTypeBool, PrimitiveType_Shape, CPUOpCoderCreator<ShapeFP32Coder>)
REG_OPERATOR_CODER(kAllTargets, kNumberTypeInt8, PrimitiveType_Shape, CPUOpCoderCreator<ShapeFP32Coder>)
REG_OPERATOR_CODER(kAllTargets, kNumberTypeUInt8, PrimitiveType_Shape, CPUOpCoderCreator<ShapeFP32Coder>)
REG_OPERATOR_CODER(kAllTargets, kNumberTypeInt64, PrimitiveType_Shape, CPUOpCoderCreator<ShapeFP32Coder>)
REG_OPERATOR_CODER(kAllTargets, kNumberTypeFloat16, PrimitiveType_Shape, CPUOpCoderCreator<ShapeFP32Coder>)
} // namespace mindspore::lite::micro::nnacl
| [
"gongdaguo1@huawei.com"
] | gongdaguo1@huawei.com |
4d556bae0498eabf9dba7cfd2d964e91a34fd3ec | c9b02ab1612c8b436c1de94069b139137657899b | /sgonline_srv/app/logic/LogicUserInteract.h | cac0eef8294334147163d11e7d5dfddc6d7527bf | [] | no_license | colinblack/game_server | a7ee95ec4e1def0220ab71f5f4501c9a26ab61ab | a7724f93e0be5c43e323972da30e738e5fbef54f | refs/heads/master | 2020-03-21T19:25:02.879552 | 2020-03-01T08:57:07 | 2020-03-01T08:57:07 | 138,948,382 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,595 | h | #ifndef LOGICUSERINTERACT_H_
#define LOGICUSERINTERACT_H_
#include "LogicInc.h"
class CLogicUserInteract
{
public:
int AddHelp(unsigned uidFrom, unsigned uidTo);
int AddAttack(unsigned uidFrom, unsigned uidTo);
int GetInteract(unsigned uid, unsigned oppositeUid, DataUserInteract &interact);
int GetInteracts(unsigned uid, map<unsigned, DataUserInteract> &interacts);
int ProcessRequest(const DataMessage &request, unsigned from, unsigned to, const string &type, int action, const Json::Value &data);
int SendRequest(unsigned uid, const string &type, const string &data, const map<string, string> &userRequests);
int GetRequestFilter(unsigned uid, const string &requestType, Json::Value &users);
int FilterRequestUsers(const UidList &users, const Json::Value &filter, Json::Value &filterUsers);
int RequestItem(unsigned uid, const string &itemid, int requireCount, uint64_t &messageId, unsigned &waitTime);
int SendHelpReward(unsigned uid, const string &itemid, int count, uint64_t &messageId);
int GetFriendInteracts(unsigned uid, map<unsigned, int> &interacts);
int AddFriendInteract(unsigned uid, unsigned friendId, const string &type);
int ChangeInteractPoint(unsigned uid, int count);
int AddGiftReceiveCount(unsigned uid);
int AddInteract(const DataUserInteract &interact);
int SetInteract(const DataUserInteract &interact);
int GetInteractsAttackAfter(unsigned uid, unsigned last_attack_time, vector<DataUserInteract> &interacts);
int RemoveInteracts(unsigned uid);
int RemoveInteracts(unsigned uid, unsigned opposite_uid);
};
#endif /* LOGICUSERINTERACT_H_ */
| [
"178370407@qq.com"
] | 178370407@qq.com |
a951c3f84ba35b364b449b69270d70d57a44dbf4 | b58f14efef35c16681a41e1fa31166b26ebc251a | /informatics/apple2.cpp | 3a0eae34fdac8bb61114524e494e905410c5dc92 | [] | no_license | dari-kayoo/Cplusplus | 298a1d487f1484e2779f11ebbfca7d5315cf78e1 | df3d36f1cc533dc7a53bc93fbf282dfd2c4d41aa | refs/heads/main | 2023-09-02T19:45:06.592705 | 2021-10-25T14:54:45 | 2021-10-25T14:54:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 131 | cpp | #include <bits/stdc++.h>
using namespace std;
int main (){
int n, k;
cin >> n >> k;
cout << k%n;
return 0;
} | [
"noreply@github.com"
] | dari-kayoo.noreply@github.com |
501c1a1e373129a4267a207b570cecb4a1ec363f | fdaf20f014438477812de55aa21f0449293df0e9 | /dataserver/common/hash_combine.h | 179ee397e16b283ed4cb845b29ed8d6566e0196d | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Totopolis/dataserver | b9b3d4ddb93f63de804e92d9e878fe33fa04ddf7 | 4aabebf7920973c67fb4249a4aca735956d5209c | refs/heads/master | 2021-01-23T11:20:21.098020 | 2019-04-08T17:52:04 | 2019-04-08T17:52:04 | 46,785,828 | 6 | 4 | null | 2016-09-28T15:23:27 | 2015-11-24T10:56:16 | C++ | UTF-8 | C++ | false | false | 1,419 | h | // hash_combine.h
//
#pragma once
#ifndef __SDL_COMMON_HASH_COMBINE_H__
#define __SDL_COMMON_HASH_COMBINE_H__
#include "dataserver/common/common.h"
namespace sdl { namespace hash_detail {
/*#if defined(_MSC_VER)
# define SDL_FUNCTIONAL_HASH_ROTL32(x, r) _rotl(x,r)
#else
# define SDL_FUNCTIONAL_HASH_ROTL32(x, r) (x << r) | (x >> (32 - r))
#endif*/
template<uint32 r>
inline constexpr uint32 hash_rotl32(const uint32 x)
{
return (x << r) | (x >> (32 - r));
}
inline void hash_combine_impl(uint64 & h, uint64 k)
{
constexpr uint64_t m = UINT64_C(0xc6a4a7935bd1e995);
constexpr int r = 47;
k *= m;
k ^= k >> r;
k *= m;
h ^= k;
h *= m;
// Completely arbitrary number, to prevent 0's
// from hashing to 0.
h += 0xe6546b64;
}
template <typename SizeT>
inline void hash_combine_impl(SizeT & seed, SizeT value)
{
seed ^= value + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
inline void hash_combine_impl(uint32 & h1, uint32 k1)
{
constexpr uint32 c1 = 0xcc9e2d51;
constexpr uint32 c2 = 0x1b873593;
k1 *= c1;
k1 = hash_rotl32<15>(k1);
k1 *= c2;
h1 ^= k1;
h1 = hash_rotl32<13>(h1);
h1 = h1 * 5 + 0xe6546b64;
}
template <class T>
inline void hash_combine(std::size_t & seed, T const & v) // see boost::hash_combine
{
hash_combine_impl(seed, std::hash<T>{}(v));
}
} // hash_detail
} // sdl
#endif // __SDL_COMMON_HASH_COMBINE_H__
| [
"idalidchik@gmail.com"
] | idalidchik@gmail.com |
e13e9c5e81bb48ccad4f42a3e87f5618a60d9a3e | b52bb5ec68118ea7e1f1246c26d4c84c409ff6bf | /RTS_AE/Game/Presets.cpp | 56ff83247fa4c325c5767352ab4bb4cf1b92f8c9 | [] | no_license | varo5/RTS_2016B | 8c8c0bb62af9dd22e56e2cb270f8db5ae0b00705 | 3784cb6d6b9a16f3161281db25af69b5cca15bc5 | refs/heads/master | 2021-01-19T07:01:36.501508 | 2016-10-10T21:43:38 | 2016-10-10T21:43:38 | 65,869,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 160 | cpp | #include "stdafx.h"
#include "Presets.h"
aePresets::aePresets()
{
m_nClassID = ClassId::Preset;
}
aePresets::~aePresets()
{
}
void aePresets::Destroy()
{
}
| [
"monsal00@gmail.com"
] | monsal00@gmail.com |
e6d7f2ecb53458fd2ac5a688695c41d9311693e4 | f34f81ffa1edddcf935ffb752dc6d55d2d6bed0d | /memory.cpp | bf442bfa87245611ddee20583674e6d41bd6839d | [] | no_license | cesa1995/Enviromental3 | ad0ed3a85ccb58ec786061e8ff5f9215a61aec35 | cb075083c37a4aed2168783ab0e7330089932e12 | refs/heads/master | 2022-11-14T03:32:55.258251 | 2020-06-22T18:03:07 | 2020-06-22T18:03:07 | 274,207,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,169 | cpp | #include "memory.h"
memory::memory(){}
//iniciar la memoria del controlador
bool memory::begin(){
bool success=true;
if(!SPIFFS.begin(true)){
Serial.println("SPIFFS Mount Failed");
success=false;
}
return success;
}
void memory::getServerConfig(int type, String arg[], memory memory, timeClock timeClock, const char* conf){
switch(type){
//guardar apn
case 0:{
Serial.println("configurando APN");
memory.setApn(arg[0]);
memory.setApn_user(arg[1]);
memory.setApn_pass(arg[2]);
Serial.print(memory.getApn());
}break;
//guardar ap
case 1:{
Serial.println("configurando AP");
memory.setSsid_AP(arg[0]);
memory.setPasswd_AP(arg[1]);
// serverWifi.AP_connect(memory);
}break;
//guardar sta
case 2:{
Serial.println("configurando STA");
memory.setSsid_STA(arg[0]);
memory.setPasswd_STA(arg[1]);
//serverWifi.STA_connect(memory, timeClock);
}break;
//guardar la hora
case 3:{
Serial.println("configurando hora");
int yeard=arg[0].substring(0,4).toInt();
int mes=arg[0].substring(5,7).toInt()-1;
int dia=arg[0].substring(8,10).toInt();
int hora=arg[1].substring(0,2).toInt();
int minu=arg[1].substring(3,6).toInt();
timeClock.setTiempo(yeard, mes, dia, hora, minu);
}break;
//guardar el tiempo de espera
case 4:{
Serial.println("configurando time");
memory.setTime_to_sleep(arg[0].toInt());
}break;
}
memory.writeConfiguration(conf);
}
bool memory::existFile(const char * path){
bool success=true;
if(!SPIFFS.exists(path)){
success=false;
}
return success;
}
float memory::sizeFiles(){
float Size=0;
File root=SPIFFS.open("/");
File file = root.openNextFile();
while(file){
if(!file.isDirectory()){
Size+=file.size();
}
file = root.openNextFile();
}
Serial.print("Memoria usada:");
Serial.print(Size/1024);
Serial.println(" KB/4096 KB");
return Size;
}
void memory::deleteFile(const char * path){
Serial.printf("Deleting file: %s\n", path);
if(SPIFFS.remove(path)){
Serial.println("File deleted");
} else {
Serial.println("Delete failed");
}
}
// leer la configuacion si existe en la memoria del controlador
// en caso contrario colocar valores por defecto
bool memory::readConfiguration(const char * filename){
DynamicJsonDocument doc(1500);
bool success=true;
File file = SPIFFS.open(filename);
if(!file){
Serial.println("No existe el archivo. Configurando por defecto!");
success=false;
}
DeserializationError errorD = deserializeJson(doc, file);
if (errorD){
Serial.println("Error al deserializar el archivo.");
Serial.println(errorD.c_str());
success=false;
}
strlcpy(sim.apn, doc["sim"][0] | "", sizeof(sim.apn));
strlcpy(sim.user, doc["sim"][1] | "", sizeof(sim.user));
strlcpy(sim.pass, doc["sim"][2] | "", sizeof(sim.pass));
strlcpy(STA.ssid, doc["sta"][0] | "", sizeof(STA.ssid));
strlcpy(STA.pass, doc["sta"][1] | "", sizeof(STA.pass));
strlcpy(AP.ssid, doc["ap"][0] | "9-COCO2CH4", sizeof(AP.ssid));
strlcpy(AP.pass, doc["ap"][1] | "12345678", sizeof(AP.pass));
CO2.RO=doc["RoCO2"] | 18496.15;
CH4.RO=doc["RoCH4"] | 6765.0;
CO.RO=doc["RoCO"] | 320.0;
CO2.ATM=doc["atmCO2"] | 392.57;
CH4.ATM=doc["atmCH4"] | 1845.0;
CO.ATM=doc["atmCO"] | 1.0;
TIME_TO_SLEEP=doc["sleep"] | 1;
Mode=doc["mode"] | 3;
file.close();
delay(1000);
return success;
}
// Guardar los datos del programa en la memoria interna del controlador
bool memory::writeConfiguration(const char * filename){
DynamicJsonDocument doc(1500);
SPIFFS.remove(filename);
delay(100);
File file = SPIFFS.open(filename, FILE_WRITE);
if (!file) {
Serial.println("no se pudo abrir el archivo.");
return false;
}
JsonArray SIM=doc.createNestedArray("sim");
SIM.add(sim.apn);
SIM.add(sim.user);
SIM.add(sim.pass);
JsonArray sta=doc.createNestedArray("sta");
sta.add(STA.ssid);
sta.add(STA.pass);
JsonArray ap=doc.createNestedArray("ap");
ap.add(AP.ssid);
ap.add(AP.pass);
doc["RoCO2"]=(String)CO2.RO;
doc["RoCH4"]=(String)CH4.RO;
doc["RoCO"]=(String)CO.RO;
doc["atmCO2"]=(String)CO2.ATM;
doc["atmNH4"]=(String)CH4.ATM;
doc["atmCO"]=(String)CO.ATM;
doc["sleep"]=(String)TIME_TO_SLEEP;
doc["mode"]=(String)Mode;
if (serializeJson(doc, file) == 0) {
Serial.println("no se pudo guardar configuracion.");
return false;
}
file.close();
delay(1000);
return true;
}
char* memory::getSsid_AP(){
return AP.ssid;
}
void memory::setSsid_AP(String ssid){
ssid.toCharArray(AP.ssid,sizeof(AP.ssid));
}
char* memory::getPasswd_AP(){
return AP.pass;
}
void memory::setPasswd_AP(String passwd){
passwd.toCharArray(AP.pass,sizeof(AP.pass));
}
char* memory::getSsid_STA(){
return STA.ssid;
}
void memory::setSsid_STA(String ssid){
ssid.toCharArray(STA.ssid, sizeof(STA.ssid));
}
char* memory::getPasswd_STA(){
return STA.pass;
}
void memory::setPasswd_STA(String passwd){
passwd.toCharArray(STA.pass,sizeof(STA.pass));
}
char* memory::getApn(){
return sim.apn;
}
void memory::setApn(String Apn){
Apn.toCharArray(sim.apn, sizeof(sim.apn));
}
char* memory::getApn_user(){
return sim.user;
}
void memory::setApn_user(String user){
user.toCharArray(sim.user, sizeof(sim.user));
}
char* memory::getApn_pass(){
return sim.pass;
}
void memory::setApn_pass(String pass){
pass.toCharArray(sim.pass, sizeof(sim.pass));
}
int memory::getTime_to_sleep(){
return TIME_TO_SLEEP;
}
void memory::setTime_to_sleep(int time_to_sleep){
TIME_TO_SLEEP=time_to_sleep;
}
//getter a setter de sensores
//BME sensor
int memory::getHumidity(){
return BME.humidity;
}
void memory::setHumidity(int humidity){
BME.humidity=humidity;
}
int memory::getTemperature(){
return BME.temperature;
}
void memory::setTemperature(int temperature){
BME.temperature=temperature;
}
int memory::getHeight(){
return BME.height;
}
void memory::setHeight(int height){
BME.height=height;
}
int memory::getPressure(){
return BME.pressure;
}
void memory::setPressure(int pressure){
BME.pressure=pressure;
}
//co2 sensor
int memory::getCo2(){
return CO2.co2;
}
void memory::setCo2(int co2){
CO2.co2=co2;
}
int memory::getCo2_ro(){
return CO2.RO;
}
void memory::setCo2_ro(int ro){
CO2.RO=ro;
}
int memory::getCo2_Atm(){
return CO2.ATM;
}
void memory::setCo2_Atm(int Atm){
CO2.ATM=Atm;
}
//co sensor
int memory::getCo(){
return CO.co;
}
void memory::setCo(int co){
CO.co=co;
}
int memory::getCo_ro(){
return CO.RO;
}
void memory::setCo_ro(int ro){
CO.RO=ro;
}
int memory::getCo_Atm(){
return CO.ATM;
}
void memory::setCo_Atm(int Atm){
CO.ATM=Atm;
}
//ch4 sensor
int memory::getCh4(){
return CH4.ch4;
}
void memory::setCh4(int ch4){
CH4.ch4=ch4;
}
int memory::getCh4_ro(){
return CH4.RO;
}
void memory::setCh4_ro(int ro){
CH4.RO=ro;
}
int memory::getCh4_Atm(){
return CH4.ATM;
}
void memory::setCh4_Atm(int Atm){
CH4.ATM=Atm;
}
| [
"cesar.contreras24777@gmail.com"
] | cesar.contreras24777@gmail.com |
3d4803ce1a48c47b55dd694492e3fb3ec81c6526 | e1e43f3e90aa96d758be7b7a8356413a61a2716f | /datacommsserver/esockserver/test/te_mecunittest/src/mectestpanic6step.cpp | eadcc5863fbeee85c8a02eaad988c0e6c16c0456 | [] | no_license | SymbianSource/oss.FCL.sf.os.commsfw | 76b450b5f52119f6bf23ae8a5974c9a09018fdfa | bc8ac1a6d5273cbfa7852bbb8ce27d6ddc076984 | refs/heads/master | 2021-01-18T23:55:06.285537 | 2010-10-03T23:21:43 | 2010-10-03T23:21:43 | 72,773,202 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | cpp | // Copyright (c) 2009 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:
//
// mectestpanic6step.cpp
//
/**
@file
*/
#include "mectestpanic6step.h"
#include "testextensions.h"
#include <comms-infras/ss_rmetaextensioncontainer.h>
#include <comms-infras/ss_commsprov.h>
using namespace ESock;
CMecTestPanic6Step::~CMecTestPanic6Step()
{
}
/**
//! @SYMTestCaseID MEC_UNIT_TEST_106
//! @SYMTestCaseDesc Test Panic mecpanic:1 (ENoImplementation) for RMetaExtensionContainerC::FindExtensionL()
//! @SYMFssID COMMS-INFRAS/Esock/MetaExtensionContainer/UnitTest
//! @SYMTestActions 1) FindExtensionL T1 in constMec
//! @SYMTestExpectedResults Panic mecpanic:1
*/
TVerdict CMecTestPanic6Step::RunTestStepL()
{
RMetaExtensionContainerC mec;
const Meta::SMetaData& ext = mec.FindExtensionL(TTestExtension1::TypeId()); // PANIC
return EFail;
}
| [
"kirill.dremov@nokia.com"
] | kirill.dremov@nokia.com |
5c3737d68b6ebc0ac4d4ed621715a7092b1dfbcd | 3fee62a27cffa0853e019a3352ac4fc0e0496a3d | /zCleanupCamSpace/ZenGin/Gothic_I_Addon/API/oBarrier.h | 021dc7e4209330335b23e18e7a30b57d6d62c7d3 | [] | no_license | Gratt-5r2/zCleanupCamSpace | f4efcafe95e8a19744347ac40b5b721ddbd73227 | 77daffabac84c8e8bc45e0d7bcd7289520766068 | refs/heads/master | 2023-08-20T15:22:49.382145 | 2021-10-30T12:27:17 | 2021-10-30T12:27:17 | 422,874,598 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,661 | h | // Supported with union (c) 2018-2021 Union team
#ifndef __OBARRIER_H__VER1__
#define __OBARRIER_H__VER1__
namespace Gothic_I_Addon {
enum zTThunderSector {
zTThunderSector_None,
zTThunderSector_1,
zTThunderSector_2,
zTThunderSector_3,
zTThunderSector_4
};
// sizeof F8h
struct myVert {
public:
int vertIndex; // sizeof 04h offset 00h
int vertNeighbours[8]; // sizeof 20h offset 04h
int numNeighbours; // sizeof 04h offset 24h
int polyIndices[50]; // sizeof C8h offset 28h
int numPolyIndices; // sizeof 04h offset F0h
int active; // sizeof 04h offset F4h
myVert() {}
};
// sizeof 4Ch
struct myThunder {
public:
zVEC3 originVec; // sizeof 0Ch offset 00h
myThunder* childs; // sizeof 04h offset 0Ch
int numChilds; // sizeof 04h offset 10h
float startTime[5]; // sizeof 14h offset 14h
zCPolyStrip* polyStrip; // sizeof 04h offset 28h
int numSegs; // sizeof 04h offset 2Ch
int valid; // sizeof 04h offset 30h
float t0; // sizeof 04h offset 34h
float t1; // sizeof 04h offset 38h
int numSplits; // sizeof 04h offset 3Ch
int dead; // sizeof 04h offset 40h
int isChild; // sizeof 04h offset 44h
zTThunderSector sector; // sizeof 04h offset 48h
void myThunder_OnInit() zCall( 0x00655E80 );
~myThunder() zCall( 0x006550A0 );
myThunder() zInit( myThunder_OnInit() );
};
// sizeof 04h
struct myPoly {
public:
int Alpha; // sizeof 04h offset 00h
myPoly() {}
};
// sizeof 124h
class oCBarrier {
public:
zCMesh* skySphereMesh; // sizeof 04h offset 00h
myPoly* myPolyList; // sizeof 04h offset 04h
myVert* myVertList; // sizeof 04h offset 08h
int numMyVerts; // sizeof 04h offset 0Ch
int numMyPolys; // sizeof 04h offset 10h
myThunder* myThunderList; // sizeof 04h offset 14h
int numMaxThunders; // sizeof 04h offset 18h
int numMyThunders; // sizeof 04h offset 1Ch
int actualIndex; // sizeof 04h offset 20h
int rootBoltIndex; // sizeof 04h offset 24h
int startPointList1[10]; // sizeof 28h offset 28h
int numStartPoints1; // sizeof 04h offset 50h
int startPointList2[10]; // sizeof 28h offset 54h
int numStartPoints2; // sizeof 04h offset 7Ch
int startPointList3[10]; // sizeof 28h offset 80h
int numStartPoints3; // sizeof 04h offset A8h
int startPointList4[10]; // sizeof 28h offset ACh
int numStartPoints4; // sizeof 04h offset D4h
int topestPoint; // sizeof 04h offset D8h
int bFadeInOut; // sizeof 04h offset DCh
int fadeState; // sizeof 04h offset E0h
int fadeIn; // sizeof 04h offset E4h
int fadeOut; // sizeof 04h offset E8h
zCSoundFX* sfx1; // sizeof 04h offset ECh
int sfxHandle1; // sizeof 04h offset F0h
zCSoundFX* sfx2; // sizeof 04h offset F4h
int sfxHandle2; // sizeof 04h offset F8h
zCSoundFX* sfx3; // sizeof 04h offset FCh
int sfxHandle3; // sizeof 04h offset 100h
zCSoundFX* sfx4; // sizeof 04h offset 104h
int sfxHandle4; // sizeof 04h offset 108h
zCDecal* thunderStartDecal; // sizeof 04h offset 10Ch
int activeThunder_Sector1; // sizeof 04h offset 110h
int activeThunder_Sector2; // sizeof 04h offset 114h
int activeThunder_Sector3; // sizeof 04h offset 118h
int activeThunder_Sector4; // sizeof 04h offset 11Ch
zVEC2* originalTexUVList; // sizeof 04h offset 120h
void oCBarrier_OnInit() zCall( 0x006550D0 );
oCBarrier() zInit( oCBarrier_OnInit() );
~oCBarrier() zCall( 0x00655AB0 );
void Initialise( int ) zCall( 0x00655D90 );
void AddTremor( zTRenderContext& ) zCall( 0x00655E90 );
void RenderLayer( zTRenderContext&, int, int& ) zCall( 0x00655EA0 );
int Render( zTRenderContext&, int, int ) zCall( 0x006560E0 );
void InitThunder( myThunder* ) zCall( 0x00656B70 );
void RemoveThunder( myThunder* ) zCall( 0x00656BA0 );
int AddThunderSub( myThunder*, int, int, int, int ) zCall( 0x00656C50 );
int AddThunder( int, int, float, zTThunderSector ) zCall( 0x00656FE0 );
int RenderThunder( myThunder*, zTRenderContext& ) zCall( 0x00657820 );
void RenderThunderList( zTRenderContext& ) zCall( 0x00657AF0 );
// user API
#include "oCBarrier.inl"
};
// sizeof 688h
class oCSkyControler_Barrier : public zCSkyControler_Outdoor {
public:
oCBarrier* barrier; // sizeof 04h offset 680h
int bFadeInOut; // sizeof 04h offset 684h
void oCSkyControler_Barrier_OnInit() zCall( 0x00657B30 );
oCSkyControler_Barrier() zInit( oCSkyControler_Barrier_OnInit() );
virtual ~oCSkyControler_Barrier() zCall( 0x00657BF0 );
virtual void RenderSkyPre() zCall( 0x00657C60 );
// user API
#include "oCSkyControler_Barrier.inl"
};
} // namespace Gothic_I_Addon
#endif // __OBARRIER_H__VER1__ | [
"amax96@yandex.ru"
] | amax96@yandex.ru |
3de0a9fe34ad3392e07f869b899a97351ed66875 | 6762cae7e065d013247f6cce6404949d58cb7966 | /Software/SMT_Oven_stubs/Sources/fonts.h | 4dc7ac29a7e5590f4c2432ea45ef4e47499b6e87 | [] | no_license | podonoghue/T962a_Oven_Controller | c1569d474a134eea82a6b37e9a004df7bd27e699 | 816f82b0fba72aebe46eeb48660ff40b4e00e2d1 | refs/heads/master | 2021-01-17T18:23:13.665067 | 2019-06-12T11:25:57 | 2019-06-12T11:26:20 | 69,413,627 | 15 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,007 | h | /**
* @file fonts.h
* @brief Fonts for LCD
*/
#ifndef INCLUDE_USBDM_FONTS_H
#define INCLUDE_USBDM_FONTS_H
#include <stdint.h>
/*
* *****************************
* *** DO NOT EDIT THIS FILE ***
* *****************************
*
* This file is generated automatically.
* Any manual changes will be lost.
*/
namespace USBDM {
/**
* Represents a simple font
*/
class Font {
public:
static constexpr uint8_t BASE_CHAR = ' '; // First character in character set
const uint8_t width; // Width of the character in pixels
const uint8_t height; // Height of the character in pixels
const uint8_t bytesPerChar; // Bytes used for each character in data table
const uint8_t *const data; // Data describing the character pixels (index starts at BASE_CHAR)
};
/** Small 6x8 font */
extern Font smallFont;
/** Medium 8x8 font */
extern Font mediumFont;
/** Large 8x16 font */
extern Font largeFont;
}; // end namespace USBDM
#endif /* INCLUDE_USBDM_FONTS_H */
| [
"podonoghue@swin.edu.au"
] | podonoghue@swin.edu.au |
be19cdf6ae5a6d8518be5ccea1c5ae277b350541 | 33fa64e174fe0ba321b02f9c122d8eb97bb80cfa | /Source/Editor/Objects/SpriteEditor/spriteEditorTools.h | bd361cded7e95bded6b26b43539ad964341ff903 | [] | no_license | HumMan/BaluEngine | c59447d00e9b450a8a190ffc0f56821e423f057b | f62c2d6fbff0472389a6dd424e3cedbf72967979 | refs/heads/master | 2021-04-26T15:37:53.726774 | 2016-10-25T09:23:41 | 2016-10-25T09:23:41 | 43,567,178 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | h | #pragma once
#include <Editor/abstractEditor.h>
using namespace EngineInterface;
class TSpriteEditorScene;
class TSpriteEditorToolsRegistry
{
public:
std::vector<TToolWithDescription> tools;
TSpriteEditorScene* scene;
public:
TSpriteEditorToolsRegistry(TSpriteEditorScene* scene);
TSpriteEditorToolsRegistry(TSpriteEditorToolsRegistry&& o);
const std::vector<TToolWithDescription>& GetTools();
~TSpriteEditorToolsRegistry();
};
| [
"kop3nha@gmail.com"
] | kop3nha@gmail.com |
6c24425c29c07c480fbfa84260baa5dcf6c31729 | 36c31b485a5906ab514c964491b8f001a70a67f5 | /CSES/Problemset/Range Queries/subarraysumqueries.cpp | 9190157fae83d0ad24f7ab5a8ed53c63d34b6037 | [] | no_license | SMiles02/CompetitiveProgramming | 77926918d5512824900384639955b31b0d0a5841 | 035040538c7e2102a88a2e3587e1ca984a2d9568 | refs/heads/master | 2023-08-18T22:14:09.997704 | 2023-08-13T20:30:42 | 2023-08-13T20:30:42 | 277,504,801 | 25 | 5 | null | 2022-11-01T01:34:30 | 2020-07-06T09:54:44 | C++ | UTF-8 | C++ | false | false | 1,206 | cpp | #include <bits/stdc++.h>
#define ll long long
using namespace std;
const int mn = 2e5+1;
ll seg[mn<<2][4];
void recalc(int i)
{
int l=(i<<1)+1,r=(i<<1)+2;
seg[i][0]=seg[l][0]+seg[r][0];
seg[i][1]=max({seg[l][0],seg[l][0]+seg[r][0],seg[l][0]+seg[r][1],seg[l][1]});
seg[i][2]=max({seg[r][0],seg[r][0]+seg[l][0],seg[r][0]+seg[l][2],seg[r][2]});
seg[i][3]=max({seg[i][0],seg[i][1],seg[i][2],seg[l][3],seg[r][3],seg[l][2]+seg[r][1]});
}
void build(int i, int l, int r)
{
if (l==r)
{
cin>>seg[i][0];
seg[i][1]=seg[i][2]=seg[i][3]=seg[i][0];
return;
}
build((i<<1)+1,l,(l+r)>>1);
build((i<<1)+2,((l+r)>>1)+1,r);
recalc(i);
}
void update(int i, int l, int r, int j, int x)
{
if (r<j||j<l)
return;
if (l==r)
{
for (int k=0;k<4;++k)
seg[i][k]=x;
return;
}
update((i<<1)+1,l,(l+r)>>1,j,x);
update((i<<1)+2,((l+r)>>1)+1,r,j,x);
recalc(i);
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
int n,q,x,y;
cin>>n>>q;
build(0,1,n);
while (q--)
{
cin>>x>>y;
update(0,1,n,x,y);
cout<<max({seg[0][3],0LL})<<"\n";
}
return 0;
} | [
"mahajan.suneet2002@gmail.com"
] | mahajan.suneet2002@gmail.com |
dc4d99e897b94c1e245f92b0f5458954d46725c6 | d9650a91cde69003c0049779afd43e01646c56b7 | /Server/hdr/Logger.hpp | 65a6ffc6ca3e9c6caf64e90598a0c29a7a8be371 | [] | no_license | sdberardinelli/fault-detection | b080be8e1b3e45c5759b384933be803f08486e0b | f26bc9c6f92facb1a33ff4550aa9b48f833cc792 | refs/heads/master | 2020-12-24T17:08:33.775713 | 2014-04-23T02:29:19 | 2014-04-23T02:29:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,017 | hpp | /******************************************************************************
* Filename : Logger.hpp
* Source File(s): Logger.cpp
* Description :
* Authors(s) :
* Date Created :
* Date Modified :
* Modifier(s) :
*******************************************************************************/
#ifndef LOGGER_H
#define LOGGER_H
/*******************************************************************************
* INCLUDES
********************************************************************************/
#include <string>
/*******************************************************************************
* DEFINES
********************************************************************************/
/*******************************************************************************
* MACROS
********************************************************************************/
/*******************************************************************************
* DATA TYPES
********************************************************************************/
/*******************************************************************************
* EXTERNALS
********************************************************************************/
/*******************************************************************************
* CLASS DEFINITIONS
********************************************************************************/
class Logger
{
public:
/* constructors */
Logger ( bool, bool );
Logger ( void ); /* default */
Logger ( Logger& ); /* copy */
Logger& operator= ( const Logger& ); /* assign */
~Logger ( void );
/* functions */
void log (std::string,std::string,std::string);
void enable_logging ( void );
void disable_logging ( void );
void enable_timestamp ( void );
void disable_timestamp ( void );
private:
void _init (void);
bool logging;
bool timestamp;
};
#endif | [
"sethb@198.105.251.35"
] | sethb@198.105.251.35 |
338bffc422bb5e1e60a3f702a73e51831dc24e5c | 2139bff1c9096ea7d168d453470e2bc89848e72a | /all.h | 8975de1798b4d697b1135c995c0067ab15719a98 | [] | no_license | si0005hp/cpp-sandbox | 33814ceaa3f1131e22d781a0e1ae24f0b9f4963d | 68f946afd01c6abdab2595ad06dc5d6f8af74c95 | refs/heads/master | 2023-06-08T07:25:49.819312 | 2021-06-20T09:45:47 | 2021-06-20T09:45:47 | 338,561,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,267 | h | #include <cassert>
#include <cerrno>
#include <cfloat>
#include <climits>
#include <cstdalign>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <initializer_list>
#include <limits>
#include <new>
#include <stdexcept>
#include <string>
#include <system_error>
#include <typeinfo>
#if __has_include(<string_view>)
#include <string_view>
#endif
#include <unistd.h>
#include <algorithm>
#include <any>
#include <array>
#include <cfenv>
#include <cmath>
#include <deque>
#include <forward_list>
#include <fstream>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <optional>
#include <ostream>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <streambuf>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#if __has_include(<filesystem>)
#include <filesystem>
#endif
#include <atomic>
#include <cinttypes>
#include <condition_variable>
#include <cstdio>
#include <future>
#include <mutex>
#include <regex>
#include <shared_mutex>
#include <thread>
// Out of original list
#include <functional>
#include "util.h"
using namespace std::literals;
| [
"si0005hp@gmail.com"
] | si0005hp@gmail.com |
4d19449e6b45d8e9a07f94617db4140b66ac9e6e | 8e8b748965e211710f926deef69cab8077509fef | /Dusk/Graphics/RenderModules/FFTRenderPass.h | 65f6138dca070db1e537052a19fa1b8cb88d2d43 | [] | no_license | i0r/project_freeride | 09240c7725298b4946d911dfff9de22a17c9288b | 896e6c3f08b830f93083f719a0816678c9128efb | refs/heads/master | 2023-02-06T10:07:30.369487 | 2020-12-28T11:10:07 | 2020-12-28T11:10:07 | 263,069,858 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | h | /*
Dusk Source Code
Copyright (C) 2020 Prevost Baptiste
*/
#pragma once
class FrameGraph;
class RenderDevice;
class ShaderCache;
#include "Graphics/FrameGraph.h"
// Output of a FFT renderpass (inverse, convolution, etc.).
struct FFTPassOutput
{
FGHandle RealPart;
FGHandle ImaginaryPart;
FFTPassOutput()
: RealPart( FGHandle::Invalid )
, ImaginaryPart( FGHandle::Invalid )
{
}
};
FFTPassOutput AddFFTComputePass( FrameGraph& frameGraph, FGHandle input, f32 inputTargetWidth, f32 inputTargetHeight );
FGHandle AddInverseFFTComputePass( FrameGraph& frameGraph, FFTPassOutput& inputInFrequencyDomain, f32 outputTargetWidth, f32 outputTarget );
// Dimension (in pixels) for the FFT image.
constexpr i32 FFT_TEXTURE_DIMENSION = 512;
| [
"baptiste.prevost@protonmail.com"
] | baptiste.prevost@protonmail.com |
80af6eb91c0bd37f232f942052f404a7f8dbdf94 | 0149a18329517d09305285f16ab41a251835269f | /Problem Set Volumes/Volume 6 (600-699)/UVa_612_DNA_Sorting.cpp | 644ce8301b0bf740259c48ecaab9ab1c700ff47a | [] | no_license | keisuke-kanao/my-UVa-solutions | 138d4bf70323a50defb3a659f11992490f280887 | f5d31d4760406378fdd206dcafd0f984f4f80889 | refs/heads/master | 2021-05-14T13:35:56.317618 | 2019-04-16T10:13:45 | 2019-04-16T10:13:45 | 116,445,001 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 900 | cpp |
/*
UVa 612 - DNA Sorting
To build using Visual Studio 2008:
cl -EHsc -O2 UVa_612_DNA_Sorting.cpp
*/
#include <iostream>
#include <algorithm>
using namespace std;
const int n_max = 50, m_max = 100;
struct dna_string {
char s_[n_max + 1];
int sortedness_;
bool operator<(const dna_string& s) const {return sortedness_ < s.sortedness_;}
};
dna_string dna_strings[m_max];
int main()
{
int M;
cin >> M;
while (M--) {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
dna_string& ds = dna_strings[i];
cin >> ds.s_;
ds.sortedness_ = 0;
for (int j = 0; j < n - 1; j++)
for (int k = j + 1; k < n; k++)
if (ds.s_[j] > ds.s_[k])
ds.sortedness_++;
}
stable_sort(dna_strings, dna_strings + m);
for (int i = 0; i < m; i++)
cout << dna_strings[i].s_ << endl;
if (M)
cout << endl;
}
return 0;
}
| [
"keisuke.kanao.154@gmail.com"
] | keisuke.kanao.154@gmail.com |
6da2378488d0d6493ea99e8fc4ef0e3920a67ab5 | 67d18d4bb54f3e7da06674c2bb65e4658d4538ba | /frontend/include/g++_HEADERS/hdrs1/ext/pb_ds/detail/binomial_heap_base_/find_fn_imps.hpp | 5755938990137c056005a5d609421df794161499 | [
"MIT"
] | permissive | uwplse/stng | 8c1f483a96c8313b8ec36a15791db75d20cfcf33 | b077f4d469edf4971c356367f6019132047d6a3b | refs/heads/master | 2022-05-06T08:28:27.139569 | 2022-04-05T05:01:49 | 2022-04-05T05:01:49 | 63,819,139 | 15 | 7 | null | 2017-01-13T11:56:50 | 2016-07-20T22:32:32 | C++ | UTF-8 | C++ | false | false | 76 | hpp | /usr/include/c++/4.4/./ext/pb_ds/detail/binomial_heap_base_/find_fn_imps.hpp | [
"akcheung@cs.washington.edu"
] | akcheung@cs.washington.edu |
10920370e6fe997a6661ff2392c4a1a136719834 | ba9999ffb55fcd9491ddb796301f5c53975e275d | /include/sflight/mdls/modules/InverseDesign.hpp | e79e49b61a859a23260fe80131f96f177a0bad07 | [] | no_license | doughodson/sflight | 60c9d90d48e8a924652c38180c3031076e78e19e | 2200e5e8c9ececb3cde6e425ff95bea1ad336aca | refs/heads/master | 2022-02-28T21:34:35.854217 | 2019-09-06T18:11:29 | 2019-09-06T18:11:29 | 85,605,587 | 10 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,465 | hpp |
#ifndef __sflight_mdls_InverseDesign_HPP__
#define __sflight_mdls_InverseDesign_HPP__
#include "sflight/mdls/modules/Module.hpp"
#include "sflight/xml_bindings/init_InverseDesign.hpp"
namespace sflight {
namespace xml {
class Node;
}
namespace mdls {
class Player;
//------------------------------------------------------------------------------
// Class: InverseDesign
// Description: Sets up a simple aero lookup table system
//------------------------------------------------------------------------------
class InverseDesign : public Module
{
public:
InverseDesign(Player*, const double frameRate);
// module interface
virtual void update(const double timestep) override;
void getAeroCoefs(const double pitch, const double u, const double vz, const double rho,
const double weight, const double thrust, double& alpha, double& cl, double& cd);
double getThrust(double rho, double mach, double throttle);
double getFuelFlow(double rho, double mach, double thrust);
friend void xml_bindings::init_InverseDesign(xml::Node*, InverseDesign*);
private:
double designWeight{};
double designAlt{};
double wingSpan{};
double wingArea{};
double staticThrust{};
double staticTSFC{};
double thrustAngle{};
double dTdM{};
double dTdRho{};
double dTSFCdM{};
double qdes{};
double cdo{};
double clo{};
double a{};
double b{};
bool usingMachEffects{true};
};
}
}
#endif
| [
"doug@openeaagles.org"
] | doug@openeaagles.org |
8e3f4809ec4a5cf983c00aa6a27101dbbb0ab60e | da14530f0161ff1d0461e5eba14c996dc4d329de | /class_CommandLine.h | 69a828aebe74b626b99ca53797d8f2e68afba53e | [] | no_license | lancegatlin/sample-cpp | 2677fa2ff9ce7fc091489e195773593f47361da5 | ed754d5309ae965cd4875045c1293647461a958f | refs/heads/master | 2016-09-06T19:22:32.189562 | 2013-03-23T20:48:59 | 2013-03-23T20:48:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,005 | h | #ifndef __CLASS_COMMANDLINE_H
#define __CLASS_COMMANDLINE_H
#include <vector>
#include <string>
#include <iostream>
#include <string_algorithm.h>
class CommandLine {
public:
typedef std::vector<std::string> tokenList;
private:
std::ostream &_out;
std::istream &_in;
std::string _prompt;
std::string _unkcmd_err;
bool running;
int retcode;
public:
CommandLine(std::ostream &__out, std::istream &__in, const std::string &__prompt)
: _out(__out)
, _in(__in)
, running(true)
, retcode(0)
, _prompt(__prompt)
, _unkcmd_err("Unknown Command")
{ }
std::ostream &out() { return _out; };
std::istream &in() { return _in; };
const std::string &prompt() { return _prompt; };
void prompt(const std::string &s) { _prompt = s; };
const std::string &unkerr_cmd() { return _unkcmd_err; };
void unkcmd_err(const std::string &s) { _unkcmd_err = s; };
virtual void showPrompt() { _out << _prompt; }
virtual int onGo() { return 0; };
virtual int onExit() { return 0; };
virtual void onUnknownCommand(const std::string &input) { _out << _unkcmd_err << std::endl; };
virtual int onCommand(const std::string &input)
{
static tokenList tokens;
tokens.clear();
parse(input, tokens);
return onCommand(input, tokens);
}
virtual int onCommand(const std::string &input, const tokenList &tokens) { return -1; };
virtual int onException(std::exception &e, const std::string &input)
{
_out << "Exception: input=[" << input << "]" << std::endl;
_out << e.what() << std::endl;
}
void stop() { running = false; };
int go(int argc, char *argv[])
{
std::string startup;
if(argc >= 2)
{
startup = argv[1];
for(size_t i=2;i<argc;i++)
{
startup += ' ';
startup += argv[i];
}
}
go(startup);
}
int go(const std::string &startup = std::string())
{
int retcode = onGo();
if(retcode < -1)
return retcode;
std::string input;
input.reserve(1024);
if(startup.length())
input = startup;
else
{
showPrompt();
std::getline(_in, input);
}
tokenList tokens;
while(!_in.eof())
{
try {
if(onCommand(input) == -1)
onUnknownCommand(input);
} catch(std::exception &e)
{
onException(e, input);
}
if(!running)
break;
showPrompt();
std::getline(_in, input);
}
return onExit();
}
virtual void parse(const std::string &in, tokenList &tokens)
{
static const std::string &whitespace = std::string(" \t\n");
::parse(in, tokens, whitespace);
}
};
#endif
| [
"lance.gatlin@gtri.gatech.edu"
] | lance.gatlin@gtri.gatech.edu |
4fd155a1ce0d59004273936e6988965d92f86d59 | 5ec06dab1409d790496ce082dacb321392b32fe9 | /clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo.cpp | 98da913c3996a2fb976babfb5f264ff6b6bf6b6b | [
"Apache-2.0",
"MIT"
] | permissive | shinesolutions/swagger-aem-osgi | e9d2385f44bee70e5bbdc0d577e99a9f2525266f | c2f6e076971d2592c1cbd3f70695c679e807396b | refs/heads/master | 2022-10-29T13:07:40.422092 | 2021-04-09T07:46:03 | 2021-04-09T07:46:03 | 190,217,155 | 3 | 3 | Apache-2.0 | 2022-10-05T03:26:20 | 2019-06-04T14:23:28 | null | UTF-8 | C++ | false | false | 4,625 | cpp | /**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: opensource@shinesolutions.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo.h"
#include "OAIHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
namespace OpenAPI {
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo(QString json) {
this->fromJson(json);
}
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo() {
this->init();
}
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::~OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo() {
}
void
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::init() {
m_pid_isSet = false;
m_title_isSet = false;
m_description_isSet = false;
m_properties_isSet = false;
}
void
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::fromJson(QString jsonString) {
QByteArray array (jsonString.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
}
void
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::fromJsonObject(QJsonObject json) {
::OpenAPI::fromJsonValue(pid, json[QString("pid")]);
::OpenAPI::fromJsonValue(title, json[QString("title")]);
::OpenAPI::fromJsonValue(description, json[QString("description")]);
::OpenAPI::fromJsonValue(properties, json[QString("properties")]);
}
QString
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::asJson () const {
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::asJsonObject() const {
QJsonObject obj;
if(m_pid_isSet){
obj.insert(QString("pid"), ::OpenAPI::toJsonValue(pid));
}
if(m_title_isSet){
obj.insert(QString("title"), ::OpenAPI::toJsonValue(title));
}
if(m_description_isSet){
obj.insert(QString("description"), ::OpenAPI::toJsonValue(description));
}
if(properties.isSet()){
obj.insert(QString("properties"), ::OpenAPI::toJsonValue(properties));
}
return obj;
}
QString
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::getPid() const {
return pid;
}
void
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::setPid(const QString &pid) {
this->pid = pid;
this->m_pid_isSet = true;
}
QString
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::getTitle() const {
return title;
}
void
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::setTitle(const QString &title) {
this->title = title;
this->m_title_isSet = true;
}
QString
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::getDescription() const {
return description;
}
void
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::setDescription(const QString &description) {
this->description = description;
this->m_description_isSet = true;
}
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougProperties
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::getProperties() const {
return properties;
}
void
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::setProperties(const OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougProperties &properties) {
this->properties = properties;
this->m_properties_isSet = true;
}
bool
OAIComDayCqMcmLandingpageParserTaghandlersCtaGraphicalClickThrougInfo::isSet() const {
bool isObjectUpdated = false;
do{
if(m_pid_isSet){ isObjectUpdated = true; break;}
if(m_title_isSet){ isObjectUpdated = true; break;}
if(m_description_isSet){ isObjectUpdated = true; break;}
if(properties.isSet()){ isObjectUpdated = true; break;}
}while(false);
return isObjectUpdated;
}
}
| [
"cliffano@gmail.com"
] | cliffano@gmail.com |
411730936e9eb1ef35caddd0090aaa22eb0bdd64 | e6d888dedc7b5a98352a2cd0e78c90a5a2b40497 | /src/cpp/deus/unicode_view_impl/UTF8SymbolToByteIndex.inl | 82a818bba93fb299c3c9cf63cd0a3fa496bfd2b9 | [] | no_license | the-arcane-initiative/Deus | 91659f2ca229cea5af94935d78eb36e1b594c44b | b1780190c6dfb3f6257c3cb77c8d35115bb59ef8 | refs/heads/master | 2021-05-03T17:31:29.867167 | 2018-06-12T10:49:32 | 2018-06-12T10:49:32 | 120,448,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,879 | inl | /*!
* \file
* \author David Saxon
* \brief Inline definitions for UTF-8 implementations of the
* symbol_to_byte_index function.
*
* \copyright Copyright (c) 2018, The Arcane Initiative
* All rights reserved.
*
* \license BSD 3-Clause License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 THE COPYRIGHT HOLDER 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.
*/
#ifndef DEUS_UNICODEVIEWIMPL_UTF8SYMBOLTOBYTEINDEX_INL_
#define DEUS_UNICODEVIEWIMPL_UTF8SYMBOLTOBYTEINDEX_INL_
namespace deus
{
DEUS_VERSION_NS_BEGIN
namespace utf8_inl
{
DEUS_FORCE_INLINE std::size_t symbol_to_byte_index_naive(
const deus::UnicodeView& self,
std::size_t symbol_index)
{
// generic checks
// --
if(symbol_index >= self.length())
{
return self.c_str_length() + (symbol_index - self.length());
}
// --
const char* data = self.c_str();
std::size_t current_symbol = 0;
std::size_t byte_counter = 0;
while(current_symbol != symbol_index)
{
byte_counter += utf8_inl::bytes_in_symbol(data + byte_counter);
++current_symbol;
}
return byte_counter;
}
// TODO: can write a word batching version that checks whether we've reached the
// symbol index or not
// However for now this implementation seems suspiciously fast.
} // namespace utf8_inl
DEUS_VERSION_NS_END
} // namespace deus
#endif
| [
"davidesaxon@gmail.com"
] | davidesaxon@gmail.com |
967190f3ffe7c13adda19bff8c9b24375accb390 | 417e25aca1bbbaada5864d3b3b5814fa16ecbe11 | /supersonic/deke/table2data/table2data_q3_1.cc | 106d4caced4399b2a544bde6441aba66eefc6fd6 | [] | no_license | axyu/mixDB | 3f2da4935db870947156c139bd6a66be862778c1 | bf12a4d1d181c815d475eaef3920f4ad145d23f1 | refs/heads/master | 2021-01-17T13:25:59.423964 | 2016-07-14T05:44:32 | 2016-07-14T05:44:32 | 54,551,705 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,070 | cc | #include <iostream>
#include "supersonic/supersonic.h"
#include "supersonic/base/infrastructure/tuple_schema.h"
#include "supersonic/base/infrastructure/test_data_generater.h"
#include "supersonic/utils/file.h"
#include "supersonic/cursor/infrastructure/file_io.h"
#include <vector>
#include <sstream>
#include "deke/include/visit_times_to_locality.h"
#include "deke/include/ssb_q3_1.h"
using std::cout;
using std::endl;
using std::vector;
using std::stringstream;
using namespace supersonic;
int get_time(struct timespec& begin, struct timespec& end) {
return 1000 * (end.tv_sec - begin.tv_sec) + (end.tv_nsec - begin.tv_nsec) / 1000000;
}
int main(int argc, char* argv[]) {
Table2Data_Q3_1::Customer("/home/fish/data/ssb/customer.tbl", "../storage/customer_q3_1.tbl");
Table2Data_Q3_1::Supplier("/home/fish/data/ssb/supplier.tbl", "../storage/supplier_q3_1.tbl");
Table2Data_Q3_1::Date("/home/fish/data/ssb/date.tbl", "../storage/date_q3_1.tbl");
//Table2Data_Q3_1::Lineorder("/home/fish/data/ssb/lineorder.tbl", "../storage/lineorder_q3_1.tbl");
return 0;
}
| [
"lab.u@catfish.com"
] | lab.u@catfish.com |
e2df6ab700cfab5c6e24ed5ce19ef95bc6327c64 | d2d6aae454fd2042c39127e65fce4362aba67d97 | /build/iOS/Preview1/include/Fuse.Reactive.ThreadW-a73c34f4.h | 3d2c5851bcacc35bfeca53fa5b0fd1806a74ff3d | [] | no_license | Medbeji/Eventy | de88386ff9826b411b243d7719b22ff5493f18f5 | 521261bca5b00ba879e14a2992e6980b225c50d4 | refs/heads/master | 2021-01-23T00:34:16.273411 | 2017-09-24T21:16:34 | 2017-09-24T21:16:34 | 92,812,809 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,127 | h | // This file was generated based on '/Users/medbeji/Library/Application Support/Fusetools/Packages/Fuse.Reactive.JavaScript/1.0.2/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace Fuse{namespace Reactive{struct ThreadWorker;}}}
namespace g{namespace Fuse{namespace Reactive{struct ThreadWorker__MethodClosure;}}}
namespace g{namespace Fuse{namespace Scripting{struct Array;}}}
namespace g{namespace Fuse{namespace Scripting{struct Function;}}}
namespace g{namespace Fuse{namespace Scripting{struct ScriptMethod;}}}
namespace g{
namespace Fuse{
namespace Reactive{
// private sealed class ThreadWorker.MethodClosure :1598
// {
uType* ThreadWorker__MethodClosure_typeof();
void ThreadWorker__MethodClosure__ctor__fn(ThreadWorker__MethodClosure* __this, ::g::Fuse::Scripting::Function* cl, ::g::Fuse::Scripting::ScriptMethod* m, ::g::Fuse::Reactive::ThreadWorker* worker);
void ThreadWorker__MethodClosure__Callback_fn(ThreadWorker__MethodClosure* __this, uArray* args, uObject** __retval);
void ThreadWorker__MethodClosure__CopyArgs_fn(::g::Fuse::Scripting::Array* args, uArray** __retval);
void ThreadWorker__MethodClosure__New1_fn(::g::Fuse::Scripting::Function* cl, ::g::Fuse::Scripting::ScriptMethod* m, ::g::Fuse::Reactive::ThreadWorker* worker, ThreadWorker__MethodClosure** __retval);
struct ThreadWorker__MethodClosure : uObject
{
static uSStrong<uArray*> _emptyArgs_;
static uSStrong<uArray*>& _emptyArgs() { return ThreadWorker__MethodClosure_typeof()->Init(), _emptyArgs_; }
uStrong< ::g::Fuse::Scripting::ScriptMethod*> _m;
uStrong< ::g::Fuse::Reactive::ThreadWorker*> _worker;
void ctor_(::g::Fuse::Scripting::Function* cl, ::g::Fuse::Scripting::ScriptMethod* m, ::g::Fuse::Reactive::ThreadWorker* worker);
uObject* Callback(uArray* args);
static uArray* CopyArgs(::g::Fuse::Scripting::Array* args);
static ThreadWorker__MethodClosure* New1(::g::Fuse::Scripting::Function* cl, ::g::Fuse::Scripting::ScriptMethod* m, ::g::Fuse::Reactive::ThreadWorker* worker);
};
// }
}}} // ::g::Fuse::Reactive
| [
"medbeji@MacBook-Pro-de-MedBeji.local"
] | medbeji@MacBook-Pro-de-MedBeji.local |
c227489850397a1f1562772e73ff2198eb800d4e | 5d38d989e096bb2b2298d38c3c570e914e3a2c50 | /Source/OceanBoats/Private/UI/Menu/Widgets/SSoldierMenuItem.h | a807b2fe14990332211f83bd069e4c313cc9af26 | [] | no_license | magrlemon/OceanShips | 2b9b7419184aadea38f62acb123194c10a8dd42a | 7e4cb5a3aa6b6bd3c7c1027b3d9c1b9b270c6ebf | refs/heads/master | 2023-01-02T21:54:55.404769 | 2020-10-21T14:37:34 | 2020-10-21T14:37:34 | 285,441,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,578 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "SlateBasics.h"
#include "SlateExtras.h"
//class declare
class SSoldierMenuItem : public SCompoundWidget
{
public:
DECLARE_DELEGATE_OneParam( FOnArrowPressed, int );
SLATE_BEGIN_ARGS(SSoldierMenuItem)
{}
/** weak pointer to the parent PC */
SLATE_ARGUMENT(TWeakObjectPtr<ULocalPlayer>, PlayerOwner)
/** called when the button is clicked */
SLATE_EVENT(FOnClicked, OnClicked)
/** called when the left or right arrow is clicked */
SLATE_EVENT(FOnArrowPressed, OnArrowPressed)
/** menu item text attribute */
SLATE_ATTRIBUTE(FText, Text)
/** is it multi-choice item? */
SLATE_ARGUMENT(bool, bIsMultichoice)
/** menu item option text attribute */
SLATE_ATTRIBUTE(FText, OptionText)
/** menu item text transparency when item is not active, optional argument */
SLATE_ARGUMENT(TOptional<float>, InactiveTextAlpha)
/** end of slate attributes definition */
SLATE_END_ARGS()
/** needed for every widget */
void Construct(const FArguments& InArgs);
/** says that we can support keyboard focus */
virtual bool SupportsKeyboardFocus() const override { return true; }
/** mouse button down callback */
virtual FReply OnMouseButtonDown(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) override;
/** mouse button up callback */
virtual FReply OnMouseButtonUp(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) override;
/** sets this menu item as active (selected) */
void SetMenuItemActive(bool bIsMenuItemActive);
/** modify the displayed item text */
void UpdateItemText(const FText& UpdatedText);
/** set in option item to enable left arrow*/
EVisibility LeftArrowVisible;
/** set in option item to enable right arrow*/
EVisibility RightArrowVisible;
protected:
/** the delegate to execute when the button is clicked */
FOnClicked OnClicked;
/** the delegate to execute when one of arrows was pressed */
FOnArrowPressed OnArrowPressed;
private:
/** menu item text attribute */
TAttribute< FText > Text;
/** menu item option text attribute */
TAttribute< FText > OptionText;
/** menu item text widget */
TSharedPtr<STextBlock> TextWidget;
/** menu item text color */
FLinearColor TextColor;
/** item margin */
float ItemMargin;
/** getter for menu item background color */
FSlateColor GetButtonBgColor() const;
/** getter for menu item text color */
FSlateColor GetButtonTextColor() const;
/** getter for menu item text shadow color */
FLinearColor GetButtonTextShadowColor() const;
/** getter for left option arrow visibility */
EVisibility GetLeftArrowVisibility() const;
/** getter for right option arrow visibility */
EVisibility GetRightArrowVisibility() const;
/** getter option padding (depends on right arrow visibility) */
FMargin GetOptionPadding() const;
/** calls OnArrowPressed */
FReply OnRightArrowDown(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent);
/** calls OnArrowPressed */
FReply OnLeftArrowDown(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent);
/** inactive text alpha value*/
float InactiveTextAlpha;
/** active item flag */
bool bIsActiveMenuItem;
/** is this menu item represents multi-choice field */
bool bIsMultichoice;
/** pointer to our parent PC */
TWeakObjectPtr<class ULocalPlayer> PlayerOwner;
/** style for the menu item */
const struct FArmySimMenuItemStyle *ItemStyle;
};
| [
"magr_lemon@126.com"
] | magr_lemon@126.com |
367779c0fd92eb9ea361673e871055af8f66fb36 | 0dda8cef707f38f5058c3503666cbe3bf6ce8c57 | /CODEFORCES/373D_Counting_Rectangles_is_Fun.cpp | 36254a53fe909f3124831bf4460d2b6e004b84f8 | [] | no_license | Yuessiah/Destiny_Record | 4b1ea05be13fa8e78b55bc95f8ee9a1b682108f2 | 69beb5486d2048e43fb5943c96c093f77e7133af | refs/heads/master | 2022-10-09T07:05:04.820318 | 2022-10-07T01:50:58 | 2022-10-07T01:50:58 | 44,083,491 | 0 | 1 | null | 2017-05-04T12:50:35 | 2015-10-12T04:08:17 | C++ | UTF-8 | C++ | false | false | 998 | cpp | #include<bits/stdc++.h>
using namespace std;
int constexpr maxn = 50;
int n, m, q, a, b, c, d;
char grid[maxn][maxn];
int pre[maxn][maxn], dp[maxn][maxn][maxn][maxn];
int main()
{
cin >> n >> m >> q;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
cin >> grid[i][j];
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
pre[i][j] = pre[i][j-1]+pre[i-1][j]-pre[i-1][j-1]+(grid[i][j]=='1');
for(int a = n; a >= 1; a--)
for(int b = m; b >= 1; b--)
for(int c = a; c <= n; c++)
for(int d = b; d <= m; d++) {
dp[a][b][c][d] = pre[c][d]-pre[c][b-1]-pre[a-1][d]+pre[a-1][b-1] == 0; // good?
for(int k = 1; k < 1<<4; k++) {
int pie = (__builtin_popcount(k)&1)? 1 : -1; // principle of inclusion-exclusion
dp[a][b][c][d] += pie * dp[a+!!(k&1)][b+!!(k&2)][c-!!(k&4)][d-!!(k&8)];
}
}
while(q--) {
cin >> a >> b >> c >> d;
cout << dp[a][b][c][d] << endl;
}
return 0;
}
| [
"yuessiah@gmail.com"
] | yuessiah@gmail.com |
8a4effe750b80bbe7cb63866e75536880d844e47 | 3ded37602d6d303e61bff401b2682f5c2b52928c | /toy/0205/Classes/Model/CBAppManager.h | 64507d7d57847d9e00a7dc9f3d3a89187a617730 | [] | no_license | CristinaBaby/Demo_CC | 8ce532dcf016f21b442d8b05173a7d20c03d337e | 6f6a7ff132e93271b8952b8da6884c3634f5cb59 | refs/heads/master | 2021-05-02T14:58:52.900119 | 2018-02-09T11:48:02 | 2018-02-09T11:48:02 | 120,727,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 937 | h | //
// CBAppManager.h
// ColorBook
//
// Created by maxiang on 4/21/15.
//
//
#ifndef __ColorBook__CBAppManager__
#define __ColorBook__CBAppManager__
#include "cocos2d.h"
#include "CBAppGlobal.h"
#define xApp AppManager::getInstance()
class AppManager
{
public:
static AppManager* getInstance();
virtual ~AppManager();
AppManager();
//first launch app
bool isFirstLaunchApp(){return _isFirstLaunchApp;};
void setIsFirstLaunchApp(bool isFirstLaunch){_isFirstLaunchApp = isFirstLaunch;};
//ads
void requestCrossAd();
void requestCrossAd(cocos2d::Node* parent, int zorder = 0);
void requestFullScreenAd();
void requestFullScreenAd(cocos2d::Node* parent, int zorder);
/* Rate us logic, when user save picture 3 times, show rate us */
void rateUsLogic();
protected:
int _saveTimes;
bool _isFirstLaunchApp;
};
#endif /* defined(__ColorBook__CBAppManager__) */
| [
"wuguiling@smalltreemedia.com"
] | wuguiling@smalltreemedia.com |
7689076f1b0904bbd6d961ace044d0226e93eb50 | bf04643a3ef65d04eace73ea5757ea5f2a1841c4 | /LCOF/lcof51 数组中的逆序对(归并排序)/res.cpp | 200b974cde66e35554e8fa2f9aae8ab2361300a6 | [] | no_license | MiChuan/Leetcode | 4ec65ee65bc4769ba0f7dbdba2db38e50ec4b331 | 802386b9ad4dd89d085ea9a7c095d101eb3d5343 | refs/heads/master | 2022-12-23T07:58:02.425794 | 2020-10-04T08:18:49 | 2020-10-04T08:18:49 | 275,826,054 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 810 | cpp | class Solution {
public:
vector<int> tmp;
int merge(vector<int>& nums,int l,int r){
if(l>=r) return 0;
int mid = (l+r)>>1;
int res = merge(nums,l,mid)+merge(nums,mid+1,r);
for(int i = l;i<=r;i++) tmp[i]=nums[i];
for(int k = l,i =l,j=mid+1;k<=r;k++)
if( i > mid) nums[k]=tmp[j++];
else if( j > r) nums[k]=tmp[i++];
else if(tmp[i]>tmp[j]) {
//nums[i]>nums[j]时,res+=mid-i+1;
//其余与归并排序一样
nums[k]=tmp[j++];
res += mid-i+1;
}
else nums[k]=tmp[i++];
return res;
}
int reversePairs(vector<int>& nums) {
tmp = vector<int> (nums.begin(),nums.end());
return merge(nums,0,nums.size()-1);
}
}; | [
"1102066475@qq.com"
] | 1102066475@qq.com |
01ae59c3cb1726a7c7e12b64778e760b93a70608 | ecffba720cb0af51925868f17a4d558cbdcb546a | /Flight Software/PowerTest_V2/MPU6050.ino | c4e6462e4a0bb3e26980269cdbf7e4fa3fe4178d | [] | no_license | ndshetty/CanSatElectronics2017-18 | 7bda8d926ffce49b1935d6ca8b43c9ab0ec1be47 | 679087ba58f028c8622340cf8b87729e1ef66dd5 | refs/heads/master | 2020-09-15T12:16:24.813888 | 2018-05-29T22:15:37 | 2018-05-29T22:15:37 | 223,441,561 | 1 | 0 | null | 2019-11-22T16:19:31 | 2019-11-22T16:19:31 | null | UTF-8 | C++ | false | false | 573 | ino |
/*void mpuSetup()
{
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}
mpu.calibrateGyro();
mpu.setThreshold(3);
}
void mpuLoop()
{
mpuTime = millis();
Vector norm = mpu.readNormalizeGyro();
// Calculate Pitch, Roll and Yaw
pitch = pitch + norm.YAxis * mpuTimeStep;
roll = roll + norm.XAxis * mpuTimeStep;
yaw = yaw + norm.ZAxis * mpuTimeStep;
TeleArray[TeleTiltX] = roll;
TeleArray[TeleTiltY] = pitch;
TeleArray[TeleTiltZ] = yaw;
}
*/
| [
"ahsan.abrar16@hotmail.com"
] | ahsan.abrar16@hotmail.com |
1700581b3a83173edd4ab22d7ea6c3105fbbf97f | 2ce5246d19d55211172d79b4091aeafd73e77a27 | /Problems/boj1094.cpp | e53d7ddf0059f93f3919beff4f88475f2d0f1cdf | [] | no_license | MingNine9999/algorithm | 49e76a1fbcdbeea8388491c793f31ee6866054ae | 76be13e394e3e96cdcec0de9390f1fd573d442c5 | refs/heads/master | 2021-04-23T09:09:05.097401 | 2020-09-11T16:23:29 | 2020-09-11T16:23:29 | 249,915,663 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 367 | cpp | //Problem Number : 1094
//Problem Title : ¸·´ë±â
//Problem Link : https://www.acmicpc.net/problem/1094
#include <iostream>
#include <algorithm>
using namespace std;
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(0);
int n;
int ans = 0;
cin >> n;
for (int i = 1; i <= 64; i <<= 1) {
if (n & i) {
ans++;
}
}
cout << ans;
return 0;
} | [
"mingu.song@nhn.com"
] | mingu.song@nhn.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.