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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
95565e0f21684b1eb6e23e1df18c4a27373fa232 | 214838dc887c044c7b10f26a6fd85ee231ad8107 | /vendor/github.com/google/protobuf/src/google/protobuf/compiler/java/java_map_field_lite.h | df5fe64d5099c279bcf499b3b9c8ef633606f2c8 | [
"Apache-2.0",
"LicenseRef-scancode-protobuf"
] | permissive | coolbreeze000/ovs-gnxi | 5c486e192bad4880bff6ea38f6969417986fd262 | ad9c0bf3565a3cf8dfe5ca9929c2632a57fd279b | refs/heads/master | 2021-04-18T21:31:53.828567 | 2019-04-22T21:01:02 | 2019-04-22T21:01:02 | 126,850,919 | 2 | 1 | Apache-2.0 | 2019-04-22T21:01:03 | 2018-03-26T15:36:47 | Go | UTF-8 | C++ | false | false | 3,491 | h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. 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 GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_LITE_H__
#define GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_LITE_H__
#include <google/protobuf/compiler/java/java_field.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace java {
class ImmutableMapFieldLiteGenerator : public ImmutableFieldLiteGenerator {
public:
explicit ImmutableMapFieldLiteGenerator(const FieldDescriptor* descriptor,
int messageBitIndex,
Context* context);
~ImmutableMapFieldLiteGenerator();
// implements ImmutableFieldLiteGenerator ------------------------------------
int GetNumBitsForMessage() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
void GenerateMembers(io::Printer* printer) const;
void GenerateBuilderMembers(io::Printer* printer) const;
void GenerateInitializationCode(io::Printer* printer) const;
void GenerateVisitCode(io::Printer* printer) const;
void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const;
void GenerateParsingCode(io::Printer* printer) const;
void GenerateParsingDoneCode(io::Printer* printer) const;
void GenerateSerializationCode(io::Printer* printer) const;
void GenerateSerializedSizeCode(io::Printer* printer) const;
void GenerateFieldBuilderInitializationCode(io::Printer* printer) const;
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
std::string GetBoxedType() const;
private:
const FieldDescriptor* descriptor_;
std::map<std::string, std::string> variables_;
Context* context_;
ClassNameResolver* name_resolver_;
};
} // namespace java
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_LITE_H__
| [
"dherkel@google.com"
] | dherkel@google.com |
ea3d3212e74c75fdf86e2add037f1853f86f969a | 4646f97a4dee8f80b2da891d7d73f926d4e6e79d | /src/Graph.h | 43cca70048fa353d6a0be729111d587ddbf09e7d | [] | no_license | TobiasForner/DBGPThesis | d22db5c4037c6cfe41d126834cdf7a9a4b9cdd74 | 938ef33870f22935387a2abd708ee4975dff8839 | refs/heads/master | 2021-01-16T08:24:40.127259 | 2020-03-16T10:29:47 | 2020-03-16T10:29:47 | 243,041,019 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,982 | h | //
// Created by tobias on 24.10.19.
//
#ifndef DBGTTHESIS_GRAPH_H
#define DBGTTHESIS_GRAPH_H
#include "vector"
#include "Edge.h"
#include "DoublyLinkedList.h"
namespace decomposition_tree {
/**
* class representing an undirected graph
*/
class Graph {
private:
//number of nodes (dynamic), the graph always contains the nodes 0,...,n-1
unsigned int n;
//number of edges (dynamic)
unsigned int m;
//edges for each node, vector of adjacencies represented by edges
std::vector<std::vector<Edge *>> edges;
public:
/**
* constuctor
* @param n number of initial nodes
*/
Graph(const unsigned int n);
/**
* destructor
*/
~Graph();
/**
* adds nodes up until node (inclusive)
* @param node
*/
void addNode(const node_ node);
/**
* adds edge e to the graph or increases weight of the corresponding edge as well as the reverse edge, adds nodes if they are not yet in the graph
* @param e edge to be added
*/
void addEdge(const Edge &e);
/**
* returns the number of nodes
* @return number of nodes
*/
inline unsigned int getNodesNr() const {
return n;
}
/**
* retuns the number of edges
* @return number of edges
*/
inline unsigned int getEdgesNr() const {
return m;
}
/**
* retuns the edges adjacent to node i
* @param i node whose edges are to be returned
* @return edges of node i
*/
inline std::vector<Edge *> getEdges(node_ i) const {
if (i >= edges.size()) {
throw std::range_error("Node index " + std::to_string(i) + " out of range.");
}
return edges[i];
}
};
}
#endif //DBGTTHESIS_GRAPH_H
| [
"t.forner@tum.de"
] | t.forner@tum.de |
b91494ad370f4a32fdbe563e2b046b99670848db | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /Graphs/2662.cpp | 0471ece83b049a4f124b83180e5dbe805014eddb | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | #include <bits/stdc++.h>
using namespace std;
int n, m, k, nm, x, y;
vector<pair<int, int> > ans[100101];
void nxt() {
x = x + ((y & 1) ? -1 : 1);
if(x == n || x == -1) {
y++;
if(x == -1) x = 0;
else x = n-1;
}
nm--;
}
int main() {
scanf("%d %d %d", &n, &m, &k);
nm = n*m;
for(int i = 0; i + 1 < k; i++) {
ans[i].emplace_back(x, y);
nxt();
ans[i].emplace_back(x, y);
nxt();
}
while(nm) {
ans[k-1].emplace_back(x, y);
nxt();
}
for(int i = 0; i < k; i++) {
printf("%d", ans[i].size());
for(auto p : ans[i]) printf(" %d %d", p.first + 1, p.second + 1);
puts("");
}
return 0;
}
| [
"mukeshchugani10@gmail.com"
] | mukeshchugani10@gmail.com |
8568a2d8452a70bf96eddb3f6359600915f4ef53 | b5092515162282e7e2cf2d23a290244b1c599826 | /July'20/July_12_Reverse_Bits.cpp | c2f6875088cb2f41bfff37928bcbe2fd4de30da5 | [] | no_license | priyanshisharma/Leetcoding-Challenge | 6ccff0a601108c80df2155600cfd6470298eead2 | 58106095527366203b264710f08692115a04855e | refs/heads/master | 2023-08-24T18:11:50.644428 | 2021-10-31T08:09:42 | 2021-10-31T08:09:42 | 260,410,929 | 34 | 88 | null | 2021-10-31T16:30:12 | 2020-05-01T08:22:01 | C++ | UTF-8 | C++ | false | false | 566 | cpp | class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ret = 0, power = 31;
//power is 31, for num at location i new location is 31-i , index starts from 0 {2 to the power 0 is the first position}
while (n != 0)
{
ret += (n & 1) << power;
// n&1 works like n%2 <<power moves it to 31 spaces inititally
n = n >> 1;
// n>>1 works like n/2
power -= 1;
// power gets changed to 31-i for every i
}
return ret;
}
};
| [
"noreply@github.com"
] | priyanshisharma.noreply@github.com |
f26256e8c351a05733d6a8c62b1db920c5c55069 | 89baaf8c0c01a6b9c2a442ff57a0526dc1930c05 | /coding blocks lectures and programs/NAME_IN_SHORTHAND.cpp | 5cfb8b78a7bce26c439dfc2fa754dc489242787c | [] | no_license | prateekrawal/coding_blocks_launchpad | a9a8c1998ed162b45122a9ffc733049b8bb19bdc | 10ef1ba2280255154c7531fd28a8bd7efcaa2ba9 | refs/heads/master | 2020-03-21T22:08:52.664393 | 2017-12-21T09:24:55 | 2017-12-21T09:24:55 | 139,106,875 | 1 | 0 | null | 2018-06-29T05:54:24 | 2018-06-29T05:54:24 | null | UTF-8 | C++ | false | false | 1,334 | cpp | #include<bits/stdc++.h>
using namespace std;
int get_word_count(char *a)
{
int i=0;
char prev='\0';
int count=0;
while(a[i]!='\0')
{
if(a[i]==' ')
{
if(prev!='\0' && prev!=' ')
count++;
}
prev=a[i];
i++;
}
if(prev!=' ')
count++;
return count;
}
int main()
{
char a[100];
cout<<"enter the string :"<<endl;
cin.getline(a,100);
int word_count=get_word_count(a);
word_count--;
int count=word_count;
int i=0;
int flag=0;
int pos=0;
for(;a[i]!='\0';i++)
{
if(a[i]!=' ' && flag==0)
{
flag++;
a[pos]=a[i];
pos++;
word_count--;
}
if(a[i]==' ')
{
flag=0;
if(count!=word_count)
{
a[pos]='.';
pos++;
}
if(word_count==0)
{
i++;
while(a[i]!='\0')
{
a[pos]=a[i];
pos++;
i++;
}
a[pos]='\0';
break;
}
}
}
cout<<"NEW STRING IS:"<<endl<<a;
return 0;
}
| [
"harshitaggarwal283@yahoo.com"
] | harshitaggarwal283@yahoo.com |
6c84e5a28ae16e96cbe985be29e5f3c7d9330ee3 | f2931c3100f2608ba685de33fe9adacebf57c467 | /TGFlux.hh | dbd0d3ca736005c08fef7d0e7ae16746121f35c2 | [] | no_license | jlabsolid/evgen_BHphoton | bebe6a95271c074ae396c8d552794db6048fbffb | 557a69163c8b936af9e96695f070de845ee27b1e | refs/heads/master | 2021-04-15T04:18:56.639475 | 2018-03-21T21:39:46 | 2018-03-21T21:39:46 | 126,244,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 670 | hh | #ifndef TGFlux_HH
#define TGFlux_HH
#include <TF1.h>
class TGFlux
{
public:
TGFlux(double Mtarg = 0.9383, double Eb = 5.76);
double GetFlux(double W, double Q2) const;
double GetIntegrFlux(double W, double Q2_1, double Q2_2) const; // Flux Integrated over Q2 from Q2_1 to Q2_2
double GetIntegrFlux(double W, double Q2_2) const; // Flux Integrated over Q2 from Q2min to Q2_2
void SetEb(double a_Eb) { Eb = a_Eb; }
private:
double Eb;
double Mtarg;
static const double Alpha = 1./137.;
static const double PI = 3.14159265358979312;
static const double m_e = 0.00051;
TF1 *f_Gflux;
static double G_Flux(double *, double *);
};
#endif
| [
"zwzhao@jlab.org"
] | zwzhao@jlab.org |
6d79547cf3055d5ca1d8e6e06f44e9f3867a0554 | 1a5a3b9f8675000cf94b1a6797a909e1a0fcc40e | /src/client/src/Util/CDSound.h | 5fd10605847b01a138b64cb0d3f6433608e5a237 | [] | no_license | Davidixx/client | f57e0d82b4aeec75394b453aa4300e3dd022d5d7 | 4c0c1c0106c081ba9e0306c14607765372d6779c | refs/heads/main | 2023-07-29T19:10:20.011837 | 2021-08-11T20:40:39 | 2021-08-11T20:40:39 | 403,916,993 | 0 | 0 | null | 2021-09-07T09:21:40 | 2021-09-07T09:21:39 | null | UHC | C++ | false | false | 4,570 | h | #ifndef __DLL_DSOUND_H
#define __DLL_DSOUND_H
#include <mmsystem.h>
#include <dsound.h>
//-------------------------------------------------------------------------------------------------
typedef struct tagSOUNDDATA t_sounddata;
typedef struct tagWAVEDATA t_wavedata;
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
struct tagSOUNDDATA {
LPDIRECTSOUNDBUFFER m_pDSB;
t_sounddata* m_pNext;
short m_nMaxMixCnt;
LPDIRECTSOUND3DBUFFER m_pDS3DBuffer;
tagSOUNDDATA() {
m_pDSB = nullptr;
m_pNext = nullptr;
m_pDS3DBuffer = nullptr;
}
~tagSOUNDDATA() {
if ( m_pDSB ) {
m_pDSB->Stop();
}
SAFE_RELEASE( m_pDS3DBuffer );
SAFE_RELEASE( m_pDSB );
}
};
//-------------------------------------------------------------------------------------------------
class CWaveFile;
class CDSOUND {
protected :
virtual t_sounddata* CreateSoundData(CWaveFile* pCWave, DWORD dwCreationFlags, GUID guid3DAlgorithm);
virtual t_sounddata* CreateSoundData(t_wavedata* pWave, DWORD dwCreationFlags, GUID guid3DAlgorithm);
t_sounddata* DuplicateSoundData(LPDIRECTSOUNDBUFFER lpDSBSour);
bool SetPrimaryBufferFormat(DWORD dwPrimaryChannels, DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate);
public :
LPDIRECTSOUND8 m_pDS;
HRESULT m_hR;
CDSOUND();
virtual ~CDSOUND();
virtual bool _Init(HWND hWnd, DWORD dwCoopLevel, DWORD dwPrimaryChannels, DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate);
void _Free();
t_sounddata* LoadSoundData(LPSTR szFileName, short nMaxMixCnt, DWORD dwCreationFlags = DSBCAPS_STATIC | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPAN, GUID guid3DAlgorithm = DS3DALG_DEFAULT, long lFilePtr = -1);
void FreeSoundData(t_sounddata* pData);
//
// lVolume :: DSBVOLUME_MAX ( 0 ) to DSBVOLUME_MIN ( -10,000 - silence).
// lPan :: DSBPAN_LEFT( -10,000 ), DSBPAN_CENTER( 0 ), DSBPAN_RIGHT( 10,000 )
// dwFlags :: IDirectSoundBuffer8::Play 인자의 dwFlags에 전달된다.
//
void PlaySound(t_sounddata* pData, long lVolume, long lPan, DWORD dwFlags);
void StopSound(t_sounddata* pData);
DWORD GetStatus(t_sounddata* pData); // Return IDirectSoundBuffer8::GetStatus( &DWORD );
short GetMaxMixCount(t_sounddata* pData);
void SetMaxMixCount(t_sounddata* pData, short nMaxMinCnt);
};
//-------------------------------------------------------------------------------------------------
class CCamera;
class CD3DSOUND : public CDSOUND {
private :
t_sounddata* CreateSoundData(t_wavedata* pWave, DWORD dwCreationFlags, GUID guid3DAlgorithm) override;
HRESULT Get3DListenerInterface(LPDIRECTSOUND3DLISTENER* ppDSListener);
DS3DBUFFER m_dsBufferParams;
void Set3DBufferParam(t_sounddata* pSound, DS3DBUFFER& dsBufferParam);
void SetListenerParam(void );
static void ConvertToSoundSpace(D3DXVECTOR3& posSoundSpace, const D3DXVECTOR3& posWorldSpace);
public :
static LPDIRECTSOUND3DLISTENER m_pDSListener;
static DS3DLISTENER m_dsListenerParams;
GUID m_guid3DAlgorithm;
CD3DSOUND();
~CD3DSOUND();
bool _Init(HWND hWnd, DWORD dwCoopLevel, DWORD dwPrimaryChannels, DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate) override;
t_sounddata* LoadSoundData(LPSTR szFileName, short nMaxMixCnt, GUID guid3DAlgorithm = DS3DALG_NO_VIRTUALIZATION, long lFilePtr = -1);
// 리스너 관련
static bool SetListenerPosition(const D3DXVECTOR3& PosWorld);
static bool SetListenerOrientation(const D3DXVECTOR3& PosFront, const D3DXVECTOR3& PosTop);
static bool SetListenerRolloffFactor(float fMinRolloffFactor);
static bool UpdateListener(const CCamera* pCamera);
// 3D 사운드 속성 관련
bool Set3D(t_sounddata* pData, bool b3DMode); // 3D 모드인지 아닌지 여부 설정, 디폴트는 3D
bool SetPosition(t_sounddata* pData, const D3DXVECTOR3& posWorld);
bool SetVelocity(t_sounddata* pData, const D3DXVECTOR3& posVelocity);
bool SetMinDistance(t_sounddata* pData, float fMinDistance);
bool SetMaxDistance(t_sounddata* pData, float fMaxDistance);
};
//-------------------------------------------------------------------------------------------------
#endif
| [
"ralphminderhoud@gmail.com"
] | ralphminderhoud@gmail.com |
d2db586c7a8b9226028591c825df99a5d6bdf245 | 0390960b0a6de79ba39bee40e13a1cd639a04e5e | /滑雪(大数据)/源.cpp | 208445f52ab686b8995e95d6be532170451f5407 | [] | no_license | vivia1994/SummerTest5 | ee8db45ec0268b924b87f05027e6901584189bb8 | 11b15844529f43ac44124ba8e28da26e1623e804 | refs/heads/master | 2021-01-20T19:26:19.158057 | 2016-07-04T13:09:21 | 2016-07-04T13:09:21 | 61,603,211 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,084 | cpp | #include<iostream>
#include<string.h>
using namespace std;
int A[101][101],h[101][101];
int row, col;
int GetH(int r, int c)
{
if (h[r][c]!=-1)
return h[r][c];
int max = 1;
int tmp;
//上边界
if (r - 1 >= 1 && A[r - 1][c] < A[r][c])
{
tmp = GetH(r - 1, c)+1;
if (tmp > max)
max = tmp;
}
//左边界
if (c - 1 >= 1 && A[r ][c-1] < A[r][c])
{
tmp = GetH(r, c - 1) + 1;
if (tmp > max)
max = tmp;
}
//下边界
if (r + 1 <= row && A[r + 1][c] < A[r][c])
{
tmp = GetH(r + 1, c) + 1;
if (tmp > max)
max = tmp;
}
//右边界
if (c + 1 <= col && A[r][c + 1] < A[r][c])
{
tmp = GetH(r , c+1) + 1;
if (tmp > max)
max = tmp;
}
h[r][c] = max;
return max;
}
int MaxH()
{
int r=0;
memset(h, -1, sizeof(h));
for (int i = 1; i <= row; i++)
for (int j = 1; j <= col; j++)
{
int tmp = GetH(i, j);
if (tmp > r)
r = tmp;
}
return r;
}
int main()
{
int h;
cin >> row >> col;
memset(A, -1, sizeof(A));
for(int i=1;i<=row;i++)
for (int j = 1; j <= col; j++)
{
cin >> A[i][j];
}
cout << MaxH() << endl;
return 0;
} | [
"leiwei183@163.com"
] | leiwei183@163.com |
fa66691f2b1283b6121cb4b54db6023376633aad | 71678fe1cd31568a09935af4df4555de99bd5e27 | /13.CopyControl/48/String.cpp | 0b9b0a7bee581ca756e8f831fd22648a3cedb34b | [] | no_license | aFleetingTime/Cpp | 31e51a5fd3b84a8f79fa8c4b25326ea7ea20ab67 | 88c0f80c096cb4c24d611cbf89da25d8a63fe63f | refs/heads/master | 2021-01-25T13:19:23.474468 | 2018-08-08T14:32:50 | 2018-08-08T14:32:50 | 123,560,040 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,744 | cpp | #include "String.h"
std::allocator<char> String::alloc;
String::String() : String("") {}
String::String(const char *cstr)
{
setPoint(allocCopyMemory(cstr, getEndPoint(cstr)));
std::cout << "String(char*) " << first << std::endl;
}
String::String(const String &str)
{
setPoint(allocCopyMemory(str.begin(), str.end()));
std::cout << "String(String&) " << first << std::endl;
}
String::String(String &&str) noexcept : first(str.first), last(str.last)
{
str.first = str.last = nullptr;
std::cout << "String(String&&) " << first << std::endl;
}
String& String::operator=(String str)
{
swap(*this, str);
std::cout << "= operator(String) " << first << std::endl;
return *this;
}
String& String::operator=(const char *cstr)
{
auto flp = allocCopyMemory(cstr, getEndPoint(cstr));
freeMemory();
first = flp.first, last = flp.second;
std::cout << "= operator(char*) " << first << std::endl;
return *this;
}
String::~String()
{
freeMemory();
first = nullptr, last = nullptr;
}
std::size_t String::size() const
{
return last - first;
}
char* String::begin() const
{
return first;
}
char* String::end() const
{
return last;
}
const char* String::c_str() const
{
return begin();
}
std::pair<char*, char*> String::allocCopyMemory(const char *b, const char *e)
{
auto data = alloc.allocate(e - b);
return { data, std::uninitialized_copy(b, e, data) };
}
void String::freeMemory()
{
if(!first)
return;
std::for_each(first, last, [this](const char &c) { alloc.destroy(&c); });
alloc.deallocate(first, last - first);
}
void swap(String &s1, String &s2)
{
using std::swap;
swap(s1.first, s2.first);
swap(s1.last, s2.last);
}
void String::setPoint(std::pair<char*, char*> flp)
{
first = flp.first, last = flp.second;
}
| [
"liunian320@outlook.com"
] | liunian320@outlook.com |
abb6d08d61c4b5f618c9573b6222a268769ebbae | f65b125dd2e0abd1da989418736fbee883d57c6f | /src/vedittab.h | 2b7f59abb3e26876894aa7d8f2adffe2bea094d5 | [
"MIT",
"BSD-3-Clause",
"GPL-3.0-only",
"ISC",
"Apache-2.0"
] | permissive | maozhiyong/vnote | ddeef3299514cb2ec0382bb3042b9584b31e216c | c27e51bdee5fae2ec0a4e8fa6babeaa1f8aa2ffc | refs/heads/master | 2020-03-12T09:06:20.590690 | 2018-06-04T04:55:41 | 2018-06-04T04:55:41 | 130,544,854 | 1 | 0 | MIT | 2018-06-04T04:55:41 | 2018-04-22T07:24:11 | C++ | UTF-8 | C++ | false | false | 6,056 | h | #ifndef VEDITTAB_H
#define VEDITTAB_H
#include <QWidget>
#include <QString>
#include <QPointer>
#include "vtableofcontent.h"
#include "vfile.h"
#include "utils/vvim.h"
#include "vedittabinfo.h"
#include "vwordcountinfo.h"
class VEditArea;
class VSnippet;
// VEditTab is the base class of an edit tab inside VEditWindow.
class VEditTab : public QWidget
{
Q_OBJECT
public:
VEditTab(VFile *p_file, VEditArea *p_editArea, QWidget *p_parent = 0);
virtual ~VEditTab();
// Close current tab.
// @p_forced: if true, discard the changes.
virtual bool closeFile(bool p_forced) = 0;
// Enter read mode.
// @p_discard: whether set the discard action as the default one.
virtual void readFile(bool p_discard = false) = 0;
// Save file.
virtual bool saveFile() = 0;
bool isEditMode() const;
virtual bool isModified() const;
void focusTab();
// Whether this tab has focus.
bool tabHasFocus() const;
// Scroll to @p_header.
// Will emit currentHeaderChanged() if @p_header is valid.
virtual void scrollToHeader(const VHeaderPointer &p_header) { Q_UNUSED(p_header) }
VFile *getFile() const;
// User requests to insert image.
virtual void insertImage() = 0;
// User requests to insert link.
virtual void insertLink();
// Search @p_text in current note.
virtual void findText(const QString &p_text, uint p_options, bool p_peek,
bool p_forward = true) = 0;
// Replace @p_text with @p_replaceText in current note.
virtual void replaceText(const QString &p_text, uint p_options,
const QString &p_replaceText, bool p_findNext) = 0;
virtual void replaceTextAll(const QString &p_text, uint p_options,
const QString &p_replaceText) = 0;
// Return selected text.
virtual QString getSelectedText() const = 0;
virtual void clearSearchedWordHighlight() = 0;
// Request current tab to propogate its status about Vim.
virtual void requestUpdateVimStatus() = 0;
// Insert decoration markers or decorate selected text.
virtual void decorateText(TextDecoration p_decoration, int p_level = -1)
{
Q_UNUSED(p_decoration);
Q_UNUSED(p_level);
}
// Create a filled VEditTabInfo.
virtual VEditTabInfo fetchTabInfo(VEditTabInfo::InfoType p_type = VEditTabInfo::InfoType::All) const;
const VTableOfContent &getOutline() const;
const VHeaderPointer &getCurrentHeader() const;
// Restore status from @p_info.
// If this tab is not ready yet, it will restore once it is ready.
void tryRestoreFromTabInfo(const VEditTabInfo &p_info);
// Emit signal to update current status.
virtual void updateStatus();
// Called by evaluateMagicWordsByCaptain() to evaluate the magic words.
virtual void evaluateMagicWords();
// Insert snippet @p_snippet.
virtual void applySnippet(const VSnippet *p_snippet);
// Prompt for user to apply a snippet.
virtual void applySnippet();
// Check whether this file has been changed outside.
void checkFileChangeOutside();
// Reload the editor from file.
virtual void reload() = 0;
// Reload file from disk and reload the editor.
void reloadFromDisk();
// Handle the change of file or directory, such as the file has been moved.
virtual void handleFileOrDirectoryChange(bool p_isFile, UpdateAction p_act);
// Fetch tab stat info.
virtual VWordCountInfo fetchWordCountInfo(bool p_editMode) const;
virtual void toggleLivePreview()
{
}
public slots:
// Enter edit mode
virtual void editFile() = 0;
virtual void handleVimCmdCommandCancelled();
virtual void handleVimCmdCommandFinished(VVim::CommandLineType p_type, const QString &p_cmd);
virtual void handleVimCmdCommandChanged(VVim::CommandLineType p_type, const QString &p_cmd);
virtual QString handleVimCmdRequestNextCommand(VVim::CommandLineType p_type, const QString &p_cmd);
virtual QString handleVimCmdRequestPreviousCommand(VVim::CommandLineType p_type, const QString &p_cmd);
virtual QString handleVimCmdRequestRegister(int p_key, int p_modifiers);
protected:
void wheelEvent(QWheelEvent *p_event) Q_DECL_OVERRIDE;
// Called when VEditTab get focus. Should focus the proper child widget.
virtual void focusChild() = 0;
// Called to zoom in/out content.
virtual void zoom(bool p_zoomIn, qreal p_step = 0.25) = 0;
// Restore from @p_fino.
// Return true if succeed.
virtual bool restoreFromTabInfo(const VEditTabInfo &p_info) = 0;
// Write modified buffer content to backup file.
virtual void writeBackupFile();
// File related to this tab.
QPointer<VFile> m_file;
bool m_isEditMode;
// Table of content of this tab.
VTableOfContent m_outline;
// Current header in m_outline of this tab.
VHeaderPointer m_currentHeader;
VEditArea *m_editArea;
// Tab info to restore from once ready.
VEditTabInfo m_infoToRestore;
// Whether check the file change outside.
bool m_checkFileChange;
// File has diverged from disk.
bool m_fileDiverged;
// Tab has been ready or not.
int m_ready;
// Whether backup file is enabled.
bool m_enableBackupFile;
signals:
void getFocused();
void outlineChanged(const VTableOfContent &p_outline);
void currentHeaderChanged(const VHeaderPointer &p_header);
// The status of current tab has updates.
void statusUpdated(const VEditTabInfo &p_info);
// Emit when want to show message in status bar.
void statusMessage(const QString &p_msg);
void vimStatusUpdated(const VVim *p_vim);
// Request to close itself.
void closeRequested(VEditTab *p_tab);
// Request main window to show Vim cmd line.
void triggerVimCmd(VVim::CommandLineType p_type);
private slots:
// Called when app focus changed.
void handleFocusChanged(QWidget *p_old, QWidget *p_now);
};
#endif // VEDITTAB_H
| [
"tamlokveer@gmail.com"
] | tamlokveer@gmail.com |
7762d58eeb6d2e5dd749675b96ea610a69084f11 | d251464e8a3220ed4e98cee2f59727a070ede219 | /include/device/numeric.hpp | e43f5bb83f7cfa2e1f6d2572f0883de54f1df1fb | [] | no_license | samfairman/larbed_input_data_preparation | 802215786c8233e4da63f504808a2b10dbd00721 | cc5f25a36436fa02eec971ef3aed120da421392a | refs/heads/master | 2022-04-02T01:34:45.857203 | 2020-01-23T09:54:29 | 2020-01-23T09:54:29 | 235,591,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | hpp | #ifndef _NUMERIC_HPP_INCLUDED_DSIOUFALSKFDJN498HFDKSJHASFDKJB4EUHAFSKJHFDAKJFDFH
#define _NUMERIC_HPP_INCLUDED_DSIOUFALSKFDJN498HFDKSJHASFDKJB4EUHAFSKJHFDAKJFDFH
#include <device/numeric/accumulate.hpp>
#include <device/numeric/inner_product.hpp>
#include <device/numeric/static_inner_product.hpp>
#endif//_NUMERIC_HPP_INCLUDED_DSIOUFALSKFDJN498HFDKSJHASFDKJB4EUHAFSKJHFDAKJFDFH
| [
"sam.fairman2@gmail.com"
] | sam.fairman2@gmail.com |
bd92b1274e34e3195f6355fee3d00f4fda64c1a1 | 8aa7dec802fed3ee34f75b48b19e5dd26d477e46 | /813-largest-sum-of-averages/813-largest-sum-of-averages.cpp | 3d81519bc8c4523e853f768cd244fc9853277f2d | [] | no_license | niranjan35/coding-practise | 8508e6dddef068e2d08fdce8614929c2cf22fff2 | 1f1613e51c85caeec8f0d08acd2a8a5500c463cf | refs/heads/master | 2022-07-31T17:34:57.936989 | 2022-07-18T07:39:19 | 2022-07-18T07:39:19 | 134,059,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,050 | cpp | class Solution {
public:
double dp[110][110];
int sum[110];
double largestSumOfAverages(vector<int>& nums, int k) {
int n=nums.size();
for(int i=0;i<n;i++) {
for(int j=0;j<k;j++) {
dp[i][j]=0;
}
}
for(int i=0;i<n;i++) {
if(i==0) {
sum[i]=nums[i];
}
else {
sum[i]=sum[i-1]+nums[i];
}
}
for(int i=0;i<n;i++) {
dp[i][0]=sum[i];
dp[i][0]/=(i+1);
}
for(int x=1;x<k;x++) {
for(int i=0;i<n;i++) {
for(int j=0;j<i;j++) {
double tmp=sum[i]-sum[j];
tmp/=(i-j);
dp[i][x]=max(dp[i][x],dp[j][x-1]+tmp);
}
}
}
// for(int i=0;i<k;i++) {
// for(int j=0;j<n;j++) {
// cout<<dp[j][i]<<" ";
// }
// cout<<""<<endl;
// }
return dp[n-1][k-1];
}
}; | [
"niranjanbodiga3535@gmail.com"
] | niranjanbodiga3535@gmail.com |
09cb41185ab62282bcc222fea6c2b0113cc6dd41 | 3f38a2aaf0b768752e0eb28176f306bb34ad1033 | /solutions/CSES/Static Range Minimum Queries.cpp | 9b4ea8e17114b5b370a9c4eb920fc9cff28946e3 | [] | no_license | ahmadkkhaled/competitive-programming | 4c0adaa7051ce89377402751531d1a1c67867b5e | 890a5cee244342071c3a67f24f243e5f75d9825c | refs/heads/master | 2021-11-27T00:20:27.587179 | 2021-09-21T18:45:32 | 2021-09-21T18:45:32 | 151,935,856 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 869 | cpp | #include <bits/stdc++.h>
using namespace std;
#define nl '\n'
template<typename T>
ostream& operator<<(ostream& os, const vector<T> &v) {
for(const T &val: v)
os << val << ' ';
return os;
}
const int N = 2e5 + 7;
const int LOG = 18;
int a[N];
int mn[N][LOG];
int msb(int x){
return 31 - __builtin_clz(x);
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
int n,q;
cin >> n >> q;
for(int i = 0; i < n; i++){
cin >> a[i];
mn[i][0] = a[i];
}
for(int j = 1; j < LOG; j++)
for(int i = 0; i + (1 << j) - 1 < n; i++)
mn[i][j] = min(mn[i][j-1], mn[i + (1 << (j - 1))][j-1]);
while(q--) {
int l, r;
cin >> l >> r;
l--, r--;
int k = msb(r - l + 1);
cout << min(mn[l][k], mn[r - (1 << k) + 1][k]) << nl;
}
} | [
"36166958+ahmadkkhaled@users.noreply.github.com"
] | 36166958+ahmadkkhaled@users.noreply.github.com |
83a49e81d503a4706b963472121922ab390fb30e | 773357b475f59bbdde3a2de632638fef976e330a | /src/RenderDefs.h | b6593d98e2aced3201c4c84c30fb28ff4d12f9d1 | [
"MIT"
] | permissive | q4a/GLKeeper | 568544cc86a88536f104f7f38d6e018a62e47510 | a2207e2a459a254cbc703306ef92a09ecf714090 | refs/heads/master | 2022-11-25T08:32:44.100454 | 2020-06-26T11:36:25 | 2020-06-26T11:36:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | h | #pragma once
// forwards
class DebugRenderer;
class RenderManager;
class RenderProgram;
class MeshMaterial;
enum eRenderPass
{
eRenderPass_Opaque,
eRenderPass_Translucent,
eRenderPass_Count,
};
decl_enum_strings(eRenderPass);
// render context
class SceneRenderContext
{
public:
SceneRenderContext() = default;
public:
eRenderPass mCurrentPass;
};
// anim model cached render data, it is managed by AnimModelsRenderer
class ModelAssetRenderdata
{
public:
ModelAssetRenderdata() = default;
// reset renderdata to initial state
inline void Clear()
{
mVertexBuffer = nullptr;
mIndexBuffer = nullptr;
mSubsets.clear();
mSubsetMaterials.clear();
}
public:
struct SubsetLOD
{
public:
int mIndexDataOffset = 0;
};
struct Subset
{
public:
std::vector<SubsetLOD> mSubsetLODs;
int mVertexDataOffset = 0;
int mIndexDataOffset = 0;
};
public:
std::vector<Subset> mSubsets;
std::vector<MeshMaterial> mSubsetMaterials;
GpuBuffer* mVertexBuffer = nullptr;
GpuBuffer* mIndexBuffer = nullptr;
};
| [
"codename.cpp@gmail.com"
] | codename.cpp@gmail.com |
6cab8bf7e6611fcd1d38c896b29355f9d29c4783 | 72414e441408d6d63d24e2154a3694e243a4f2a9 | /Multi-JSON-Interface/include/mjsoni/generic_json_config_reader.hpp | 0df3276345768bd2864c7b2ee4ca5c86dbfdfb8b | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | IAmTrial/Multi-JSON-Interface | 75f11174ae17b83e90a59ff6d33675af8f3f02c7 | 95f9e6c2d953af9e104a9f43532ef17daaf2f1bb | refs/heads/master | 2021-06-16T16:15:49.814767 | 2021-04-07T03:29:16 | 2021-04-07T03:29:16 | 192,013,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,840 | hpp | /**
* Multi JSON Interface
* Copyright (C) 2019 Mir Drualga
*
* This file is part of Multi JSON Interface.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MJSONI_GENERIC_JSON_CONFIG_READER_HPP_
#define MJSONI_GENERIC_JSON_CONFIG_READER_HPP_
#include <cstdint>
#include <deque>
#include <filesystem>
#include <initializer_list>
#include <map>
#include <set>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace mjsoni {
template<typename DOC, typename OBJ, typename VAL>
class GenericConfigReader {
using JsonDocument = DOC;
using JsonObject = OBJ;
using JsonValue = VAL;
public:
GenericConfigReader() = delete;
explicit GenericConfigReader(
std::filesystem::path config_file_path
);
/* Read and Write */
bool Read();
bool Write(int indent_width);
/* Functions for Generic Types */
template <typename ...Args>
bool ContainsKey(
const Args&... keys
) const;
template <typename ...Args>
const JsonValue& GetValueRef(
const Args&... keys
) const;
template <typename Container, typename ...Args>
Container GetArrayCopy(
const Args&... keys
) const;
template <typename Iter, typename ...Args>
void SetArray(
Iter first,
Iter last,
const Args&... keys
);
template <typename Iter, typename ...Args>
void SetDeepArray(
Iter first,
Iter last,
const Args&... keys
);
template <typename ...Args>
void SetValue(
JsonValue value,
const Args&... keys
);
template <typename ...Args>
void SetDeepValue(
JsonValue value,
const Args&... keys
);
/* Functions for bool */
template <typename ...Args>
bool GetBool(
const Args&... keys
) const;
template <typename ...Args>
bool GetBoolOrDefault(
bool default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasBool(
const Args&... keys
) const;
template <typename ...Args>
void SetBool(
bool value,
const Args&... keys
);
template <typename ...Args>
void SetDeepBool(
bool value,
const Args&... keys
);
/* Functions for std::deque */
template <typename T, typename ...Args>
std::deque<T> GetDeque(
const Args&... keys
) const;
template <typename T, typename ...Args>
std::deque<T> GetDequeOrDefault(
const std::deque<T>& default_value,
const Args&... keys
) const;
template <typename T, typename ...Args>
std::deque<T> GetDequeOrDefault(
std::deque<T>&& default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasDeque(
const Args&... keys
) const;
template <typename T, typename ...Args>
void SetDeque(
const std::deque<T>& value,
const Args&... keys
);
template <typename ...Args>
void SetDeque(
const std::deque<std::string_view>& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetDeque(
std::deque<T>&& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetDeepDeque(
const std::deque<T>& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetDeepDeque(
std::deque<T>&& value,
const Args&... keys
);
/* Functions for int */
template <typename ...Args>
int GetInt(
const Args&... keys
) const;
template <typename ...Args>
int GetIntOrDefault(
int default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasInt(
const Args&... keys
) const;
template <typename ...Args>
void SetInt(
int value,
const Args&... keys
);
template <typename ...Args>
void SetDeepInt(
int value,
const Args&... keys
);
/* Functions for std::int32_t */
template <typename ...Args>
std::int32_t GetInt32(
const Args&... keys
) const;
template <typename ...Args>
std::int32_t GetInt32OrDefault(
std::int32_t default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasInt32(
const Args&... keys
) const;
template <typename ...Args>
void SetInt32(
std::int32_t value,
const Args&... keys
);
template <typename ...Args>
void SetDeepInt32(
std::int32_t value,
const Args&... keys
);
/* Functions for std::int64_t */
template <typename ...Args>
std::int64_t GetInt64(
const Args&... keys
) const;
template <typename ...Args>
std::int64_t GetInt64OrDefault(
std::int64_t default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasInt64(
const Args&... keys
) const;
template <typename ...Args>
void SetInt64(
std::int64_t value,
const Args&... keys
);
template <typename ...Args>
void SetDeepInt64(
std::int64_t value,
const Args&... keys
);
/* Functions for long */
template <typename ...Args>
long GetLong(
const Args&... keys
) const;
template <typename ...Args>
long GetLongOrDefault(
long default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasLong(
const Args&... keys
) const;
template <typename ...Args>
void SetLong(
long value,
const Args&... keys
);
template <typename ...Args>
void SetDeepLong(
long value,
const Args&... keys
);
/* Functions for long long */
template <typename ...Args>
long long GetLongLong(
const Args&... keys
) const;
template <typename ...Args>
long long GetLongLongOrDefault(
long long default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasLongLong(
const Args&... keys
) const;
template <typename ...Args>
void SetLongLong(
long long value,
const Args&... keys
);
template <typename ...Args>
void SetDeepLongLong(
long long value,
const Args&... keys
);
/* Functions for std::filesystem::path */
template <typename ...Args>
std::filesystem::path GetPath(
const Args&... keys
) const;
template <typename ...Args>
std::filesystem::path GetPathOrDefault(
const std::filesystem::path& default_value,
const Args&... keys
) const;
template <typename ...Args>
std::filesystem::path GetPathOrDefault(
std::filesystem::path&& default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasPath(
const Args&... keys
) const;
template <typename ...Args>
void SetPath(
const std::filesystem::path& value,
const Args&... keys
);
template <typename ...Args>
void SetDeepPath(
const std::filesystem::path& value,
const Args&... keys
);
/* Functions for std::set */
template <typename T, typename ...Args>
std::set<T> GetSet(
const Args&... keys
) const;
template <typename T, typename ...Args>
std::set<T> GetSetOrDefault(
const std::set<T>& default_value,
const Args&... keys
) const;
template <typename T, typename ...Args>
std::set<T> GetSetOrDefault(
std::set<T>&& default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasSet(
const Args&... keys
) const;
template <typename T, typename ...Args>
void SetSet(
const std::set<T>& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetSet(
std::set<T>&& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetDeepSet(
const std::set<T>& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetDeepSet(
std::set<T>&& value,
const Args&... keys
);
/* Functions for std::string */
template <typename ...Args>
std::string GetString(
const Args&... keys
) const;
template <typename ...Args>
std::string GetStringOrDefault(
const std::string& default_value,
const Args&... keys
) const;
template <typename ...Args>
std::string GetStringOrDefault(
std::string&& default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasString(
const Args&... keys
) const;
template <typename ...Args>
void SetString(
const std::string& value,
const Args&... keys
);
template <typename ...Args>
void SetString(
std::string&& value,
const Args&... keys
);
template <typename ...Args>
void SetDeepString(
const std::string& value,
const Args&... keys
);
template <typename ...Args>
void SetDeepString(
std::string&& value,
const Args&... keys
);
/* Functions for unsigned int */
template <typename ...Args>
unsigned int GetUnsignedInt(
const Args&... keys
) const;
template <typename ...Args>
unsigned int GetUnsignedIntOrDefault(
unsigned int default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasUnsignedInt(
const Args&... keys
) const;
template <typename ...Args>
void SetUnsignedInt(
unsigned int value,
const Args&... keys
);
template <typename ...Args>
void SetDeepUnsignedInt(
unsigned int value,
const Args&... keys
);
/* Functions for std::uint32_t */
template <typename ...Args>
std::uint32_t GetUnsignedInt32(
const Args&... keys
) const;
template <typename ...Args>
std::uint32_t GetUnsignedInt32OrDefault(
std::uint32_t default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasUnsignedInt32(
const Args&... keys
) const;
template <typename ...Args>
void SetUnsignedInt32(
std::uint32_t value,
const Args&... keys
);
template <typename ...Args>
void SetDeepUnsignedInt32(
std::uint32_t value,
const Args&... keys
);
/* Functions for std::uint64_t */
template <typename ...Args>
std::uint64_t GetUnsignedInt64(
const Args&... keys
) const;
template <typename ...Args>
std::uint64_t GetUnsignedInt64OrDefault(
std::uint64_t default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasUnsignedInt64(
const Args&... keys
) const;
template <typename ...Args>
void SetUnsignedInt64(
std::uint64_t value,
const Args&... keys
);
template <typename ...Args>
void SetDeepUnsignedInt64(
std::uint64_t value,
const Args&... keys
);
/* Functions for unsigned long */
template <typename ...Args>
unsigned long GetUnsignedLong(
const Args&... keys
) const;
template <typename ...Args>
unsigned long GetUnsignedLongOrDefault(
unsigned long default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasUnsignedLong(
const Args&... keys
) const;
template <typename ...Args>
void SetUnsignedLong(
unsigned long value,
const Args&... keys
);
template <typename ...Args>
void SetDeepUnsignedLong(
unsigned long value,
const Args&... keys
);
/* Functions for unsigned long long */
template <typename ...Args>
unsigned long long GetUnsignedLongLong(
const Args&... keys
) const;
template <typename ...Args>
unsigned long long GetUnsignedLongLongOrDefault(
unsigned long long default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasUnsignedLongLong(
const Args&... keys
) const;
template <typename ...Args>
void SetUnsignedLongLong(
unsigned long long value,
const Args&... keys
);
template <typename ...Args>
void SetDeepUnsignedLongLong(
unsigned long long value,
const Args&... keys
);
/* Functions for std::unordered_set */
template <typename T, typename ...Args>
std::unordered_set<T> GetUnorderedSet(
const Args&... keys
) const;
template <typename T, typename ...Args>
std::unordered_set<T> GetUnorderedSetOrDefault(
const std::unordered_set<T>& default_value,
const Args&... keys
) const;
template <typename T, typename ...Args>
std::unordered_set<T> GetUnorderedSetOrDefault(
std::unordered_set<T>&& default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasUnorderedSet(
const Args&... keys
) const;
template <typename T, typename ...Args>
void SetUnorderedSet(
const std::unordered_set<T>& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetUnorderedSet(
std::unordered_set<T>&& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetDeepUnorderedSet(
const std::unordered_set<T>& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetDeepUnorderedSet(
std::unordered_set<T>&& value,
const Args&... keys
);
/* Functions for std::vector */
template <typename T, typename ...Args>
std::vector<T> GetVector(
const Args&... keys
) const;
template <typename T, typename ...Args>
std::vector<T> GetVectorOrDefault(
const std::vector<T>& default_value,
const Args&... keys
) const;
template <typename T, typename ...Args>
std::vector<T> GetVectorOrDefault(
std::vector<T>&& default_value,
const Args&... keys
) const;
template <typename ...Args>
bool HasVector(
const Args&... keys
) const;
template <typename T, typename ...Args>
void SetVector(
const std::vector<T>& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetVector(
std::vector<T>&& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetDeepVector(
const std::vector<T>& value,
const Args&... keys
);
template <typename T, typename ...Args>
void SetDeepVector(
std::vector<T>&& value,
const Args&... keys
);
/* Getter and Setters */
constexpr const std::filesystem::path& config_file_path() const noexcept {
return this->config_file_path_;
}
constexpr const JsonDocument& json_document() const noexcept {
return this->json_document_;
}
private:
std::filesystem::path config_file_path_;
JsonDocument json_document_;
template <typename ...Args>
bool ContainsKeyRecursive(
const JsonObject& object,
std::string_view current_key,
const Args&... keys
) const;
template <typename ...Args>
JsonValue& GetValueRefRecursive(
JsonObject& object,
std::string_view current_key,
const Args&... keys
);
template <typename ...Args>
const JsonValue& GetValueRefRecursive(
const JsonObject& object,
std::string_view current_key,
const Args&... keys
) const;
template <typename ...Args>
void SetValueRecursive(
JsonValue value,
JsonObject& object,
std::string_view current_key,
const Args&... keys
);
template <typename ...Args>
void SetDeepValueRecursive(
JsonValue value,
JsonObject& object,
std::string_view current_key,
const Args&... keys
);
};
} // namespace mjsoni
#endif // MJSONI_GENERIC_JSON_CONFIG_READER_HPP_
| [
"IAmRealTrial@gmail.com"
] | IAmRealTrial@gmail.com |
215cb264a60394fa7049e7865c3d569eb93a4465 | c1466e0815558818829d51326d445df6ffad9c17 | /structure/massive17.cpp | 8d2d183f0d84aa7242c52e117e1e9c159e4572bf | [] | no_license | ojaster/first_project | 2177bc78d6a6000862a306ebce71d2cdeee8d475 | 0a09308acd6270085959251ca8892dc22d272cfb | refs/heads/master | 2021-07-07T13:04:51.200496 | 2020-06-25T10:52:08 | 2020-06-25T10:52:08 | 129,524,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | cpp | #include <iostream>
using namespace std;
int main(){
int k[6];
for(int i = 0; i<6; i++){
cin>>k[i];
}
int last = k[5];
cout<<"----"<<endl;
for( int i = 0; i<6; i++ ) {
k[i]= k[i] * (int) last;
cout<<k[i]<<endl;
}
} | [
"daniil.gusev@icloud.com"
] | daniil.gusev@icloud.com |
61d75f47bbfabda68cb3277de17270ae9d61ecfa | 46f53e9a564192eed2f40dc927af6448f8608d13 | /media/cast/sender/h264_vt_encoder_unittest.cc | 04f3d629da95b23a9d9f8786347b5eb691ddacfd | [
"BSD-3-Clause"
] | permissive | sgraham/nope | deb2d106a090d71ae882ac1e32e7c371f42eaca9 | f974e0c234388a330aab71a3e5bbf33c4dcfc33c | refs/heads/master | 2022-12-21T01:44:15.776329 | 2015-03-23T17:25:47 | 2015-03-23T17:25:47 | 32,344,868 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 11,179 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <queue>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/test/test_suite.h"
#include "media/base/decoder_buffer.h"
#include "media/base/media.h"
#include "media/base/media_switches.h"
#include "media/cast/sender/h264_vt_encoder.h"
#include "media/cast/sender/video_frame_factory.h"
#include "media/cast/test/utility/default_config.h"
#include "media/cast/test/utility/video_utility.h"
#include "media/ffmpeg/ffmpeg_common.h"
#include "media/filters/ffmpeg_glue.h"
#include "media/filters/ffmpeg_video_decoder.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const int kVideoWidth = 1280;
const int kVideoHeight = 720;
class MediaTestSuite : public base::TestSuite {
public:
MediaTestSuite(int argc, char** argv) : TestSuite(argc, argv) {}
~MediaTestSuite() override {}
protected:
void Initialize() override;
};
void MediaTestSuite::Initialize() {
base::TestSuite::Initialize();
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kEnableInbandTextTracks);
media::InitializeMediaLibraryForTesting();
}
} // namespace
int main(int argc, char** argv) {
{
base::AtExitManager at_exit_manager;
CHECK(VideoToolboxGlue::Get())
<< "VideoToolbox is not available. Requires OS X 10.8 or iOS 8.0.";
}
MediaTestSuite test_suite(argc, argv);
return base::LaunchUnitTests(
argc, argv,
base::Bind(&MediaTestSuite::Run, base::Unretained(&test_suite)));
}
namespace media {
namespace cast {
// See comment in end2end_unittest.cc for details on this value.
const double kVideoAcceptedPSNR = 38.0;
void SavePipelineStatus(PipelineStatus* out_status, PipelineStatus in_status) {
*out_status = in_status;
}
void SaveOperationalStatus(OperationalStatus* out_status,
OperationalStatus in_status) {
*out_status = in_status;
}
class MetadataRecorder : public base::RefCountedThreadSafe<MetadataRecorder> {
public:
MetadataRecorder() : count_frames_delivered_(0) {}
int count_frames_delivered() const { return count_frames_delivered_; }
void PushExpectation(uint32 expected_frame_id,
uint32 expected_last_referenced_frame_id,
uint32 expected_rtp_timestamp,
const base::TimeTicks& expected_reference_time) {
expectations_.push(Expectation{expected_frame_id,
expected_last_referenced_frame_id,
expected_rtp_timestamp,
expected_reference_time});
}
void CompareFrameWithExpected(scoped_ptr<EncodedFrame> encoded_frame) {
ASSERT_LT(0u, expectations_.size());
auto e = expectations_.front();
expectations_.pop();
if (e.expected_frame_id != e.expected_last_referenced_frame_id) {
EXPECT_EQ(EncodedFrame::DEPENDENT, encoded_frame->dependency);
} else {
EXPECT_EQ(EncodedFrame::KEY, encoded_frame->dependency);
}
EXPECT_EQ(e.expected_frame_id, encoded_frame->frame_id);
EXPECT_EQ(e.expected_last_referenced_frame_id,
encoded_frame->referenced_frame_id)
<< "frame id: " << e.expected_frame_id;
EXPECT_EQ(e.expected_rtp_timestamp, encoded_frame->rtp_timestamp);
EXPECT_EQ(e.expected_reference_time, encoded_frame->reference_time);
EXPECT_FALSE(encoded_frame->data.empty());
++count_frames_delivered_;
}
private:
friend class base::RefCountedThreadSafe<MetadataRecorder>;
virtual ~MetadataRecorder() {}
int count_frames_delivered_;
struct Expectation {
uint32 expected_frame_id;
uint32 expected_last_referenced_frame_id;
uint32 expected_rtp_timestamp;
base::TimeTicks expected_reference_time;
};
std::queue<Expectation> expectations_;
DISALLOW_COPY_AND_ASSIGN(MetadataRecorder);
};
class EndToEndFrameChecker
: public base::RefCountedThreadSafe<EndToEndFrameChecker> {
public:
explicit EndToEndFrameChecker(const VideoDecoderConfig& config)
: decoder_(base::MessageLoop::current()->task_runner()),
count_frames_checked_(0) {
PipelineStatus pipeline_status;
decoder_.Initialize(
config, false, base::Bind(&SavePipelineStatus, &pipeline_status),
base::Bind(&EndToEndFrameChecker::CompareFrameWithExpected,
base::Unretained(this)));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_EQ(PIPELINE_OK, pipeline_status);
}
void PushExpectation(const scoped_refptr<VideoFrame>& frame) {
expectations_.push(frame);
}
void EncodeDone(scoped_ptr<EncodedFrame> encoded_frame) {
auto buffer = DecoderBuffer::CopyFrom(encoded_frame->bytes(),
encoded_frame->data.size());
decoder_.Decode(buffer, base::Bind(&EndToEndFrameChecker::DecodeDone,
base::Unretained(this)));
}
void CompareFrameWithExpected(const scoped_refptr<VideoFrame>& frame) {
ASSERT_LT(0u, expectations_.size());
auto& e = expectations_.front();
expectations_.pop();
EXPECT_LE(kVideoAcceptedPSNR, I420PSNR(e, frame));
++count_frames_checked_;
}
void DecodeDone(VideoDecoder::Status status) {
EXPECT_EQ(VideoDecoder::kOk, status);
}
int count_frames_checked() const { return count_frames_checked_; }
private:
friend class base::RefCountedThreadSafe<EndToEndFrameChecker>;
virtual ~EndToEndFrameChecker() {}
FFmpegVideoDecoder decoder_;
std::queue<scoped_refptr<VideoFrame>> expectations_;
int count_frames_checked_;
DISALLOW_COPY_AND_ASSIGN(EndToEndFrameChecker);
};
void CreateFrameAndMemsetPlane(VideoFrameFactory* const video_frame_factory) {
const scoped_refptr<media::VideoFrame> video_frame =
video_frame_factory->MaybeCreateFrame(
gfx::Size(kVideoWidth, kVideoHeight), base::TimeDelta());
ASSERT_TRUE(video_frame.get());
auto cv_pixel_buffer = video_frame->cv_pixel_buffer();
ASSERT_TRUE(cv_pixel_buffer);
CVPixelBufferLockBaseAddress(cv_pixel_buffer, 0);
auto ptr = CVPixelBufferGetBaseAddressOfPlane(cv_pixel_buffer, 0);
ASSERT_TRUE(ptr);
memset(ptr, 0xfe, CVPixelBufferGetBytesPerRowOfPlane(cv_pixel_buffer, 0) *
CVPixelBufferGetHeightOfPlane(cv_pixel_buffer, 0));
CVPixelBufferUnlockBaseAddress(cv_pixel_buffer, 0);
}
class H264VideoToolboxEncoderTest : public ::testing::Test {
protected:
H264VideoToolboxEncoderTest()
: operational_status_(STATUS_UNINITIALIZED) {
frame_->set_timestamp(base::TimeDelta());
}
void SetUp() override {
clock_ = new base::SimpleTestTickClock();
clock_->Advance(base::TimeTicks::Now() - base::TimeTicks());
cast_environment_ = new CastEnvironment(
scoped_ptr<base::TickClock>(clock_).Pass(),
message_loop_.message_loop_proxy(), message_loop_.message_loop_proxy(),
message_loop_.message_loop_proxy());
encoder_.reset(new H264VideoToolboxEncoder(
cast_environment_,
video_sender_config_,
gfx::Size(kVideoWidth, kVideoHeight),
0u,
base::Bind(&SaveOperationalStatus, &operational_status_)));
message_loop_.RunUntilIdle();
EXPECT_EQ(STATUS_INITIALIZED, operational_status_);
}
void TearDown() override {
encoder_.reset();
message_loop_.RunUntilIdle();
}
void AdvanceClockAndVideoFrameTimestamp() {
clock_->Advance(base::TimeDelta::FromMilliseconds(33));
frame_->set_timestamp(frame_->timestamp() +
base::TimeDelta::FromMilliseconds(33));
}
static void SetUpTestCase() {
// Reusable test data.
video_sender_config_ = GetDefaultVideoSenderConfig();
video_sender_config_.codec = CODEC_VIDEO_H264;
const gfx::Size size(kVideoWidth, kVideoHeight);
frame_ = media::VideoFrame::CreateFrame(
VideoFrame::I420, size, gfx::Rect(size), size, base::TimeDelta());
PopulateVideoFrame(frame_.get(), 123);
}
static void TearDownTestCase() { frame_ = nullptr; }
static scoped_refptr<media::VideoFrame> frame_;
static VideoSenderConfig video_sender_config_;
base::SimpleTestTickClock* clock_; // Owned by CastEnvironment.
base::MessageLoop message_loop_;
scoped_refptr<CastEnvironment> cast_environment_;
scoped_ptr<VideoEncoder> encoder_;
OperationalStatus operational_status_;
private:
DISALLOW_COPY_AND_ASSIGN(H264VideoToolboxEncoderTest);
};
// static
scoped_refptr<media::VideoFrame> H264VideoToolboxEncoderTest::frame_;
VideoSenderConfig H264VideoToolboxEncoderTest::video_sender_config_;
TEST_F(H264VideoToolboxEncoderTest, CheckFrameMetadataSequence) {
scoped_refptr<MetadataRecorder> metadata_recorder(new MetadataRecorder());
VideoEncoder::FrameEncodedCallback cb = base::Bind(
&MetadataRecorder::CompareFrameWithExpected, metadata_recorder.get());
metadata_recorder->PushExpectation(
0, 0, TimeDeltaToRtpDelta(frame_->timestamp(), kVideoFrequency),
clock_->NowTicks());
EXPECT_TRUE(encoder_->EncodeVideoFrame(frame_, clock_->NowTicks(), cb));
message_loop_.RunUntilIdle();
for (uint32 frame_id = 1; frame_id < 10; ++frame_id) {
AdvanceClockAndVideoFrameTimestamp();
metadata_recorder->PushExpectation(
frame_id, frame_id - 1,
TimeDeltaToRtpDelta(frame_->timestamp(), kVideoFrequency),
clock_->NowTicks());
EXPECT_TRUE(encoder_->EncodeVideoFrame(frame_, clock_->NowTicks(), cb));
}
encoder_.reset();
message_loop_.RunUntilIdle();
EXPECT_EQ(10, metadata_recorder->count_frames_delivered());
}
#if defined(USE_PROPRIETARY_CODECS)
TEST_F(H264VideoToolboxEncoderTest, CheckFramesAreDecodable) {
VideoDecoderConfig config(kCodecH264, H264PROFILE_MAIN, frame_->format(),
frame_->coded_size(), frame_->visible_rect(),
frame_->natural_size(), nullptr, 0, false);
scoped_refptr<EndToEndFrameChecker> checker(new EndToEndFrameChecker(config));
VideoEncoder::FrameEncodedCallback cb =
base::Bind(&EndToEndFrameChecker::EncodeDone, checker.get());
for (uint32 frame_id = 0; frame_id < 6; ++frame_id) {
checker->PushExpectation(frame_);
EXPECT_TRUE(encoder_->EncodeVideoFrame(frame_, clock_->NowTicks(), cb));
AdvanceClockAndVideoFrameTimestamp();
}
encoder_.reset();
message_loop_.RunUntilIdle();
EXPECT_EQ(5, checker->count_frames_checked());
}
#endif
TEST_F(H264VideoToolboxEncoderTest, CheckVideoFrameFactory) {
auto video_frame_factory = encoder_->CreateVideoFrameFactory();
ASSERT_TRUE(video_frame_factory.get());
CreateFrameAndMemsetPlane(video_frame_factory.get());
// TODO(jfroy): Need to test that the encoder can encode VideoFrames provided
// by the VideoFrameFactory.
encoder_.reset();
message_loop_.RunUntilIdle();
CreateFrameAndMemsetPlane(video_frame_factory.get());
}
} // namespace cast
} // namespace media
| [
"scottmg@chromium.org"
] | scottmg@chromium.org |
3804f7d0537814ee3ced368895cd3fab83a707a6 | 6c9281f226df8a9c743dd0a2e0c185ba01de2060 | /Game/Main.cpp | 0c81538d0ed5150dd0895726513de59c3a4f398e | [] | no_license | KonstantinTomashevich/GamedevResourcePackerTestProject | a84f082bea42c65a781ad1d0ecaa0a70d0be6cd5 | 05aa60229c63c6aebda9fe0c50282cc88b392306 | refs/heads/master | 2020-07-26T01:52:08.764623 | 2020-02-07T10:41:46 | 2020-02-07T10:41:46 | 208,493,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,522 | cpp | #include <ResourceSubsystem/Core.hpp>
#include <ResourceSubsystem/Defines.hpp>
#include <ResourceSubsystem/Ids.hpp>
#include <ResourceSubsystem/DataObjects/TileMap.hpp>
#include <ResourceSubsystem/DataObjects/TileSet.hpp>
#include <ResourceSubsystem/DataObjects/MapObjectSet.hpp>
#include <exception>
#include <boost/log/trivial.hpp>
#include <boost/exception/all.hpp>
int main (int argc, char **argv)
{
try
{
ResourceSubsystem::Init ("Assets");
}
catch (boost::exception &exception)
{
BOOST_LOG_TRIVIAL (error) << "Unable to init resource subsystem!\n" <<
boost::diagnostic_information (exception) << "\n"
<< ((std::exception *) &exception)->what () << "\n";
return 2;
}
ResourceSubsystem::DataObjects::TileMap *tileMap;
{
using namespace ResourceSubsystem;
tileMap = (DataObjects::TileMap *) GetResource (
object_class_loader_TileMap, Ids::TileMapGroupId, Ids::TileMap::Level1);
}
printf ("Tiles:\n");
for (auto &tile : tileMap->GetTiles ())
{
printf (" Tile: %d.\n", tile.GetType ());
}
printf ("Objects:\n");
for (auto &object : tileMap->GetObjects ())
{
printf (" Object: %d (%d, %d).\n", object.GetType (), object.GetX (), object.GetY ());
}
printf ("TileSet id: %d.\n", tileMap->GetTileSet ()->GetId ());
printf ("ObjectSet id: %d.\n", tileMap->GetObjectSet ()->GetId ());
return 0;
}
| [
"ekit.mail@gmail.com"
] | ekit.mail@gmail.com |
02374a357553bf2e929ee08e868a1046d58bc2e4 | c2d0dd60ef40d3514aed93026c37b5f18804c525 | /src/physicscore/collisionshapes/collisionshape.h | 22d53d7de970de05a03850f33b31e6d9d4ed6eff | [] | no_license | mansisaksson/yet_another_game_engine | ffeedf384961df4b07d52871691748c3a058fc6a | d92baa5b9cb52d125824c5ec83715415b6525d9a | refs/heads/master | 2021-07-05T23:25:41.458975 | 2020-12-06T09:19:27 | 2020-12-06T09:19:27 | 212,355,836 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | h | #pragma once
enum class shape_type
{
invalid,
box,
sphere,
capsule
};
class collision_shape
{
private:
shape_type m_shape_type;
public:
collision_shape()
: m_shape_type(shape_type::invalid)
{
}
collision_shape(shape_type shape_type)
: m_shape_type(shape_type)
{
}
inline shape_type get_shape_type() const
{
return m_shape_type;
}
inline bool is_box() const
{
return m_shape_type == shape_type::box;
}
inline bool is_sphere() const
{
return m_shape_type == shape_type::sphere;
}
inline bool is_capsule() const
{
return m_shape_type == shape_type::capsule;
}
}; | [
"mans.95.isaksson@gmail.com"
] | mans.95.isaksson@gmail.com |
142e7648587b7142b56bccc9747617ba1adc9217 | 057e1322219d15eea892f9b8f80e83a3513ed27d | /the hunter/Client/Dx11Engine/Include/Core/Dx11TimerManager.cpp | 59048647bb67b99616cfc3e7530d5d6c04d0ca1e | [] | no_license | KPUTeam/The-Hunter | 06b3fa23f8a63f5d681ca2c70bbe5484b4740bd0 | 5702438b10c3df7f0d92db14348a6c9fef41ed27 | refs/heads/master | 2021-01-12T03:57:54.466231 | 2017-08-21T00:44:29 | 2017-08-21T00:44:29 | 81,659,237 | 0 | 1 | null | 2017-04-10T14:53:47 | 2017-02-11T14:47:09 | C++ | UTF-8 | C++ | false | false | 950 | cpp | #include "Dx11TimerManager.h"
#include "Dx11Timer.h"
DX11_USING
DX11_SINGLE_DEFINITION(CDx11TimerManager)
CDx11TimerManager::CDx11TimerManager()
{
SetTypeName<CDx11TimerManager>();
}
CDx11TimerManager::~CDx11TimerManager()
{
Safe_Release_Map(m_mapTimer);
}
bool CDx11TimerManager::Init()
{
CDx11Timer* pTimer = CreateTimer("MainTimer");
SAFE_RELEASE(pTimer);
return true;
}
CDx11Timer* CDx11TimerManager::CreateTimer(const string& strKey)
{
CDx11Timer* pTimer = FindTimer(strKey);
if (pTimer)
return pTimer;
pTimer = new CDx11Timer;
if (!pTimer->Init())
{
SAFE_RELEASE(pTimer);
return NULL;
}
pTimer->AddRef();
m_mapTimer.insert(make_pair(strKey, pTimer));
return pTimer;
}
CDx11Timer* CDx11TimerManager::FindTimer(const string& strKey)
{
unordered_map<string, CDx11Timer*>::iterator iter = m_mapTimer.find(strKey);
if (iter == m_mapTimer.end())
return NULL;
iter->second->AddRef();
return iter->second;
}
| [
"aiuv0324@gmail.com"
] | aiuv0324@gmail.com |
b67799fd4e126398d933f93e2828e97166bd10df | a563e5fc2acf7103453ac23e85130b5571f78df1 | /RGAME1/core/GDevices.h | b1a1aabcbdfdf4322d1828c68c4794cfc10e0814 | [] | no_license | baifan233/RGame | fdc7f5534b38388acfa43951328a75df542e4be2 | f43194e620aa7235d75529a0a783002fa3f4d208 | refs/heads/master | 2022-11-27T23:47:41.489539 | 2020-08-10T14:50:47 | 2020-08-10T14:50:47 | 284,248,885 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,271 | h | #pragma once
#include"framework.h"
#include"Resource.h"
#include"GameLogRecorder.h"
struct RMouseptPointer { int* x; int* y; };
class GDevices
{
//Input System
private:
LPDIRECTINPUT8 inp_dinputDeivce = NULL; //dinput8设备
LPDIRECTINPUTDEVICE8 inp_KeyBoard = NULL; //键盘设备
LPDIRECTINPUTDEVICE8 inp_Mouse = NULL; //鼠标设备
LPDIRECTINPUTDEVICE8 inp_Joy = NULL; //手柄设备
DIJOYSTATE2 inp_JoyState = { 0 }; //手柄输入状态
DIDEVICEOBJECTDATA inp_keyBoardDidod[8] = { 0 }; //键盘输入状态数据
DIMOUSESTATE inp_mouseState = { 0 }; //鼠标输入状态
DIMOUSESTATE inp_mouseStateAfter = { 0 };////鼠标输入状态(经处置) 调用请调用这个
RSKEYSTATE KeyState[256] = { 0 }; //键盘输入状态
bool inp_bMouseReady = false; //如果鼠标设备启用 则为true
bool inp_bJoyReady = false; //如果手柄设备启用 则为true
bool inp_bKeyBoardReady = false; //如果键盘设备启用 则为true
int MouseY = 0; //鼠标在窗口内X坐标
int MouseX = 0; //鼠标在窗口内Y坐标
vector<WPARAM>* charwParam; //指向窗口过程中输入字符储存的vetor
//窗口内XY指针结构体
RMouseptPointer mpt = { &MouseX,&MouseY };
public:
vector<WPARAM>* GetCharParam() { return charwParam; }
void SetCharParam(vector<WPARAM>* wparam) { charwParam = wparam; };
void ClearInputData() //清除所有输入设备的输入状态
{
memset(&inp_mouseState, 0, sizeof(DIMOUSESTATE));
memset(&inp_mouseStateAfter, 0, sizeof(DIMOUSESTATE));
for (size_t i = 0; i < 8; i++)
{
memset(&inp_keyBoardDidod[i], 0, sizeof(DIDEVICEOBJECTDATA));
}
memset(&KeyState, 0, sizeof(RSKEYSTATE));
}
//检查输入设备 如果设备还没初始化 就初始化
void CheckInputDevice(DeviceType deviceType);
//获取键盘输入状态
RSKEYSTATE* GetKeyState() { return KeyState; };
//获取手柄输入状态
DIJOYSTATE2 GetJoyState() { return inp_JoyState; }
//初始化输入设备
int inp_InitinputDevice(HINSTANCE hInstance, DeviceType deviceType);
//获取设备的运行状态(是否工作)
bool inp_IsDeviceReady(DeviceType deviceType);
void inp_DealInput(DeviceType deviceType);
//获取设备数据(设备是否有信息)
bool UpdateDeviceData(DeviceType deviceType);
void inp_ShutDown(DeviceType deviceType);
DIMOUSESTATE GetMouseState() { return inp_mouseStateAfter; };
RMouseptPointer* GetMousePoint()
{
return &mpt;
}
void UpdateMousePoint(int x, int y) { MouseX = x; MouseY = y; }
//Window
private:
HWND mainWindow = 0; //主窗口句柄
wchar_t* ClassName = 0; //窗口类名
int width = 0, height = 0; //宽度 高度
HINSTANCE hIns = 0; //实例句柄
public:
RECT GetWindowRect() { RECT rect = { 0 }; rect.right = width; rect.bottom = height; return rect; };
bool InitMainWindow(HINSTANCE hInstance, WNDPROC WndProc, const wchar_t* szWindowClass, int width, int height,bool border)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_RGAME1));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_RGAME1);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
if (!RegisterClassExW(&wcex))
return false;
this->width = width;
this->height = height;
DWORD ws = WS_OVERLAPPEDWINDOW;
if (border == true)ws = WS_POPUP;
mainWindow = CreateWindowW(szWindowClass, 0, ws,
CW_USEDEFAULT, 0, width, height, nullptr, nullptr, hInstance, nullptr);
if (!mainWindow)
{
return FALSE;
}
return TRUE;
}
bool window_Show(bool show);
HWND GetMainWindow() { return mainWindow; };
~GDevices();
GDevices() {};
//Graphic
protected:
//D2D
IDWriteFactory* g_dWriteFactory = NULL; //dwrite工厂
ID2D1Factory4* g_d2dFactory = NULL; //d2d工厂
IWICImagingFactory2* g_image_factory = NULL;
ID2D1Device3* g_d2dDevice = 0; //d2d设备
ID2D1DeviceContext3* g_d2dContext = 0; //d2d设备上下文
IDXGISwapChain1* g_SwapChain = 0; //交换链
ID2D1Bitmap1* g_d2dTargetBitmap = 0;
D3D_FEATURE_LEVEL g_featurelevel; //特征级
DXGI_PRESENT_PARAMETERS g_m_parameters; //手动交换链
ID3D11Device* g_d3dDevice = 0; //d3d设备
ID3D11DeviceContext* g_d3dDeviceContext = 0; //d3d设备上下文
//OpenGL
HGLRC g_glrc=0;
HDC g_hdc = 0;
sp::Scene* scene=nullptr;
sp::Renderer r=sp::Renderer();
D2D1_RECT_F cameraRect = { 0.0f,0.0f,1024.0f,768.0f };
public:
//获取交换链
IDXGISwapChain1* g_GetSwapChain() { return g_SwapChain; }
IDWriteFactory* g_GetDwriteFactory() { return g_dWriteFactory; }
ID2D1Factory4* g_GetFactory() { return g_d2dFactory; }
ID2D1DeviceContext3* g_GetD2DRen()
{
return g_d2dContext;
};
IWICImagingFactory* g_GetimageFacotry() { return g_image_factory; };
void g_D2DPresent()
{
if (g_d2dContext)g_d2dContext->EndDraw();
};
bool g_InitGraphic(HWND hWnd);
void g_CreateWindowSizeResources();
void SetCamera(float x, float y)
{
/*x = x/scaleSize;
y = y/scaleSize;*/
cameraRect.left = x;
cameraRect.top = y;
cameraRect.right = cameraRect.left + width;
cameraRect.bottom = cameraRect.top + height;
}
void MoveCamera(float x, float y)
{
/*if (cameraRect.left + x >= 0)
{
cameraRect.left += x;
}
else
{
cameraRect.left = 0.0f;
}
if (cameraRect.top + y >= 0)
{
cameraRect.top += y;
}
else
{
cameraRect.top = 0.0f;
}*/
cameraRect.left += x;
cameraRect.top += y;
cameraRect.right = cameraRect.left + width;
cameraRect.bottom = cameraRect.top + height;
}
float GetCameraX() { return cameraRect.left; };
float GetCameraY() { return cameraRect.top; };
D2D1_RECT_F GetCameraRect() { return cameraRect; };
sp::Scene* g_GetScene() { return scene; }
sp::Renderer* g_GetRenderer() { return &r; }
void g_OpenGLPresent() { SwapBuffers(g_hdc); }
HDC g_GetHDC() { return g_hdc; }
//Recorder
protected:
GameLogRecorder Recorder = GameLogRecorder();
public:
GameLogRecorder* GetRecorder() { return &Recorder; }
};
| [
"ab2942704765@163.com"
] | ab2942704765@163.com |
514f4f3332d840590abc2d9cc10889b75ebf415f | f05c77c783902a3fff2ae1be09f7ccc629cc4c46 | /forPracticeC++/compareString.cpp | ff0a5e23c03b005e8321cbf979083e322e0f5438 | [] | no_license | piyushac123/PracticeProblems | c3eba2f405b5683629ff69883eaee2b0364193cf | 819ce8b8254dff2c139e6b82c420f93c693bc8f7 | refs/heads/master | 2020-04-09T04:54:06.708739 | 2018-12-02T12:02:13 | 2018-12-02T12:02:13 | 160,042,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,740 | cpp | #include<iostream>
#include<string.h>
using namespace std;
class use{
public:
int checkRange(int val){
if((val>=65&&val<=90)||(val>=97&&val<=122)){
return 1;
}
return 0;
}
int compare(char val1,char val2){
int a=val1,b=val2;
if(a>b){
return 1;
}
else if(a<b){
return -1;
}
return 0;
}
};
int main(){
/*char c1,c2;
cin>>c1>>c2;
int result=strcmp((const char*)&c1,(const char*)&c2);
cout<<result;*/
use u;
string str1,str3;
getline(cin,str1);
getline(cin,str3);
char str2[str1.length()];
char str4[str3.length()];
strcpy(str2,str1.c_str());
strcpy(str4,str3.c_str());
int val1=0;
int actlen1=0,actlen2=0;
for(int i=0;i<str1.length();i++){
val1=str2[i];
if(u.checkRange(val1)){
cout<<str2[i];
actlen1++;
}
}
cout<<"\n";
val1=0;
for(int i=0;i<str3.length();i++){
val1=str4[i];
if(u.checkRange(val1)){
cout<<str4[i];
actlen2++;
}
}
cout<<"\n";
char string1[actlen1];
char string2[actlen2];
val1=0;
int cnt1=0,cnt2=0;
for(int i=0;i<str1.length();i++){
val1=str2[i];
if(u.checkRange(val1)){
string1[cnt1++]=str2[i];
}
}
val1=0;
for(int i=0;i<str3.length();i++){
val1=str4[i];
if(u.checkRange(val1)){
string2[cnt2++]=str4[i];
}
}
cout<<"\n";
for(int i=0;i<actlen1;i++){
cout<<string1[i];
}
cout<<"\n";
for(int i=0;i<actlen2;i++){
cout<<string2[i];
}
cout<<"\n";
int i=0,j=0;
char a,b;
int value1=0,value2=0,result=0;
while(str2[i]!='\0'&&str4[j]!='\0'){
cout<<string1[i]<<" "<<string2[i]<<"\n";
result=u.compare(string1[i],string2[j]);
cout<<result<<"\n";
if(result!=0){
break;
}
j++;
i++;
}
if(result>0){
cout<<"\n"<<str3<<" "<<str1;
}
else if(result<=0){
cout<<"\n"<<str1<<" "<<str3;
}
return 0;
} | [
"piyush.chincholikar@gmail.com"
] | piyush.chincholikar@gmail.com |
f7b6715382ed9e9f7fde4f07fa7bf5ff06431223 | ffa83215d4a44581f44173100331bda1900b24fe | /build/iOS/Preview/include/Uno.UX.UXValueBindingArgumentAttribute.h | a1c71110895ddf2fa33d9c095512aab721fd908f | [] | no_license | imkimbosung/ARkit_fuse | 167d1c77ee497d5b626e69af16e0e84b13c54457 | 3b378d6408551d6867f2e5b3d7d8b6f5114e7f69 | refs/heads/master | 2020-04-19T02:34:33.970273 | 2019-02-04T08:26:54 | 2019-02-04T08:26:54 | 167,907,696 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 837 | h | // This file was generated based on /usr/local/share/uno/Packages/UnoCore/1.10.0-rc1/Source/Uno/UX/Attributes/UXValueBindingArgumentAttribute.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Attribute.h>
namespace g{namespace Uno{namespace UX{struct UXValueBindingArgumentAttribute;}}}
namespace g{
namespace Uno{
namespace UX{
// public sealed class UXValueBindingArgumentAttribute :5
// {
uType* UXValueBindingArgumentAttribute_typeof();
void UXValueBindingArgumentAttribute__ctor_1_fn(UXValueBindingArgumentAttribute* __this);
void UXValueBindingArgumentAttribute__New1_fn(UXValueBindingArgumentAttribute** __retval);
struct UXValueBindingArgumentAttribute : ::g::Uno::Attribute
{
void ctor_1();
static UXValueBindingArgumentAttribute* New1();
};
// }
}}} // ::g::Uno::UX
| [
"ghalsru@naver.com"
] | ghalsru@naver.com |
70cb0218d303eb7494869e3fb8573d9e47e8d69e | c0c44b30d6a9fd5896fd3dce703c98764c0c447f | /cpp/include/symbian-r6/Nav2ErrorSymbian.h | 256f7fc96b8d478006cba05c3e5d8c3b03e3af94 | [
"BSD-3-Clause"
] | permissive | wayfinder/Wayfinder-CppCore-v2 | 59d703b3a9fdf4a67f9b75fbbf4474933aeda7bf | f1d41905bf7523351bc0a1a6b08d04b06c533bd4 | refs/heads/master | 2020-05-19T15:54:41.035880 | 2010-06-29T11:56:03 | 2010-06-29T11:56:03 | 744,294 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,148 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
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 the Vodafone Group Services Ltd 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 Nav2ErrorSymbian_H
#define Nav2ErrorSymbian_H
#include "Nav2Error.h"
namespace isab {
namespace Nav2Error {
class Nav2ErrorTableSymbian : public Nav2ErrorTable {
void ConstructFromResourceL(TInt aResourceId);
Nav2ErrorTableSymbian();
public:
Nav2ErrorTableSymbian(TInt aResourceId);
static class Nav2ErrorTableSymbian* NewLC(TInt aResourceId);
static class Nav2ErrorTableSymbian* NewL(TInt aResourceId);
virtual ~Nav2ErrorTableSymbian();
};
} /* namespace Nav2Error */
} /* namespace isab */
#endif /* Nav2ErrorSymbian_H */
| [
"hlars@sema-ovpn-morpheus.itinerary.com"
] | hlars@sema-ovpn-morpheus.itinerary.com |
07be78b1f422404f3849e65fea60f44691a6b7f2 | c78c926155760aa63d24ad26b3356f6d19398f69 | /HDOJ/基础题/AC代码/1_20/1003_Max Sum(区间最大和)(DP).cpp | b04396d5808f59140447a283fb0e73d2cf7dc716 | [] | no_license | fhyPayaso/ACM | 34c26aff0697ef0e7956cd03e30f13739a286466 | 0c7f4bf298e9a164f8a5ae140f30f441ccc226dc | refs/heads/master | 2021-08-30T05:04:53.518780 | 2017-12-16T03:39:10 | 2017-12-16T03:39:10 | 114,429,801 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 833 | cpp | #include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int maxn=100000+10;
struct no
{
int val;
int l,r;
}sum[100010];
int main()
{
int t,ok=0;
cin>>t;
for(int ti=1;ti<=t;ti++)
{
int n,m=-2000,left,right;
cin>>n;
for(int i=1;i<=n;i++)
{
int temp;
cin>>temp;
if(i==1)
{
sum[i].val=temp;
sum[i].l=i;
sum[i].r=i;
}
else
{
if(sum[i-1].val+temp>=temp)
{
sum[i].val=sum[i-1].val+temp;
sum[i].l=sum[i-1].l;
sum[i].r=i;
}
else
{
sum[i].val=temp;
sum[i].l=i;
sum[i].r=i;
}
}
if(sum[i].val>m)
{
m=sum[i].val;
right=sum[i].r;
left=sum[i].l;
}
}
if(!ok) ok=1;
else cout<<endl;
cout<<"Case "<<ti<<":"<<endl;
cout<<m<<" "<<left<<" "<<right<<endl;
}
return 0;
}
| [
"410619823@qq.com"
] | 410619823@qq.com |
babb4dfa4f8da882b755118edb4c20e610d46c1e | 307cdf04a3ab90a2d91ad9210daf4357a1c205bd | /Sistema_experto/lista.h | 7a335558a7159ee36ee3e94f755e66903e9c59b4 | [] | no_license | luisthmn/ED_Parcial3 | 43f6ddab45766c05e067a3df6abd4c88ca5e9cb0 | e9088e5afe5f0b8cf5ec6c390999f10cccaf7a02 | refs/heads/master | 2020-05-23T19:46:53.669067 | 2019-05-17T07:39:38 | 2019-05-17T07:39:38 | 186,917,809 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,093 | h | #ifndef LISTA_H_INCLUDED
#define LISTA_H_INCLUDED
#include "lista_arcos.h"
#include "lista_nodos.h"
using namespace std;
//En este archivo se encuentra la clase de la lista auxiliar junto con la estructura de nodos auxiliares
struct caja2;
//------------------------------------------------------------------------
struct caja3{ //Estructura para los nodos auxiliares
caja2 *direccion_nodo;
caja3 *siguiente, *anterior;
};
//--------------------------------------------------------------------------
class lista{ //Clase de la lista auxiliar
caja3 *principio, *anterior, *Final, *lugaragregado;
enum _encontrado{SI, NO};
enum _encontrado encontrado;
enum _donde{VACIO, PRINCIPIO, ENMEDIO, FINAL};
enum _donde donde;
int cuantos;
public:
lista();
~lista();
void Iniciar();
void buscar(int a);
int agregar( caja2 *p);
caja2* sacar();
caja3 *lugar_agregado();
caja3* Principio();
};
//-------------------------------------------------------------------------
#endif // LISTA_H_INCLUDED
| [
"33427296+luisthmn@users.noreply.github.com"
] | 33427296+luisthmn@users.noreply.github.com |
d8ace6812e0141780867886c2f0ec792692387d7 | 40150c4e4199bca594fb21bded192bbc05f8c835 | /build/iOS/Preview/include/Fuse.Entities.Light.h | 6f0b2a1adea8140ec9848ffa463fd527c9927282 | [] | no_license | thegreatyuke42/fuse-test | af0a863ab8cdc19919da11de5f3416cc81fc975f | b7e12f21d12a35d21a394703ff2040a4f3a35e00 | refs/heads/master | 2016-09-12T10:39:37.656900 | 2016-05-20T20:13:31 | 2016-05-20T20:13:31 | 58,671,009 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,910 | h | // This file was generated based on '/usr/local/share/uno/Packages/Fuse.Entities/0.27.14/$.uno#5'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Entities.Component.h>
#include <Uno.Float3.h>
namespace g{namespace Fuse{namespace Entities{struct Entity;}}}
namespace g{namespace Fuse{namespace Entities{struct Light;}}}
namespace g{
namespace Fuse{
namespace Entities{
// public abstract class Light :821
// {
struct Light_type : ::g::Fuse::Entities::Component_type
{
void(*fp_Accept)(::g::Fuse::Entities::Light*, uObject*);
};
Light_type* Light_typeof();
void Light__ctor_1_fn(Light* __this);
void Light__Accept_fn(Light* __this, uObject* visitor);
void Light__get_CastShadow_fn(Light* __this, bool* __retval);
void Light__set_CastShadow_fn(Light* __this, bool* value);
void Light__get_Color_fn(Light* __this, ::g::Uno::Float3* __retval);
void Light__set_Color_fn(Light* __this, ::g::Uno::Float3* value);
void Light__get_Multiplier_fn(Light* __this, float* __retval);
void Light__set_Multiplier_fn(Light* __this, float* value);
void Light__OnAdded_fn(Light* __this, ::g::Fuse::Entities::Entity* e);
void Light__OnRemoved_fn(Light* __this, ::g::Fuse::Entities::Entity* e);
void Light__get_Range_fn(Light* __this, float* __retval);
void Light__set_Range_fn(Light* __this, float* value);
void Light__get_ShadowMapDepthBias_fn(Light* __this, float* __retval);
void Light__set_ShadowMapDepthBias_fn(Light* __this, float* value);
void Light__get_ShadowMapNearPlane_fn(Light* __this, float* __retval);
void Light__set_ShadowMapNearPlane_fn(Light* __this, float* value);
void Light__get_ShadowMapResolution_fn(Light* __this, int* __retval);
void Light__set_ShadowMapResolution_fn(Light* __this, int* value);
void Light__get_ShowDesignerSprite_fn(Light* __this, bool* __retval);
void Light__set_ShowDesignerSprite_fn(Light* __this, bool* value);
struct Light : ::g::Fuse::Entities::Component
{
bool showSprite;
bool _CastShadow;
::g::Uno::Float3 _Color;
float _Multiplier;
float _Range;
float _ShadowMapDepthBias;
float _ShadowMapNearPlane;
int _ShadowMapResolution;
void ctor_1();
void Accept(uObject* visitor) { (((Light_type*)__type)->fp_Accept)(this, visitor); }
bool CastShadow();
void CastShadow(bool value);
::g::Uno::Float3 Color();
void Color(::g::Uno::Float3 value);
float Multiplier();
void Multiplier(float value);
float Range();
void Range(float value);
float ShadowMapDepthBias();
void ShadowMapDepthBias(float value);
float ShadowMapNearPlane();
void ShadowMapNearPlane(float value);
int ShadowMapResolution();
void ShadowMapResolution(int value);
bool ShowDesignerSprite();
void ShowDesignerSprite(bool value);
static void Accept(Light* __this, uObject* visitor) { Light__Accept_fn(__this, visitor); }
};
// }
}}} // ::g::Fuse::Entities
| [
"johnrbennett3@gmail.com"
] | johnrbennett3@gmail.com |
c1854d2d6da0b2352d8fcbab3c92ca494c900e89 | 26d3688d1839717de6edec3aa6fa60fb1fe3483d | /src/math/primitives.cpp | 012ec156a1e8e678b8a82b9edc6e99a969cab824 | [
"MIT"
] | permissive | wouterboomsma/quickstep | 7d91c8070dca9f0d1d5ac30a38a9e159224a5e13 | a33447562eca1350c626883f21c68125bd9f776c | refs/heads/master | 2021-01-22T19:25:45.689105 | 2017-04-19T09:25:23 | 2017-04-19T09:25:23 | 88,726,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,979 | cpp | /*
LoopTK: Protein Loop Kinematic Toolkit
Copyright (C) 2007 Stanford University
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "quickstep/math/primitives.h"
namespace Math3D {
Vector2::Vector2()
{}
Vector2::Vector2(const Vector2& v)
:x(v.x), y(v.y)
{}
Vector2::Vector2(Real _x)
:x(_x), y(_x)
{}
Vector2::Vector2(Real _x, Real _y)
:x(_x), y(_y)
{}
Vector2::Vector2(const Real data[2])
:x(data[0]), y(data[1])
{}
Vector3::Vector3(): x(0.0), y(0.0), z(0.0)
{}
Vector3::Vector3(const Vector3& v)
:x(v.x), y(v.y), z(v.z)
{}
Vector3::Vector3(Real _x)
:x(_x), y(_x), z(_x)
{}
Vector3::Vector3(Real _x, Real _y, Real _z)
:x(_x), y(_y), z(_z)
{}
Vector3::Vector3(const Real data[3])
:x(data[0]), y(data[1]), z(data[2])
{}
Vector4::Vector4()
{}
Vector4::Vector4(const Vector4& v)
:x(v.x), y(v.y), z(v.z), w(v.w)
{}
Vector4::Vector4(Real _x)
:x(_x), y(_x), z(_x), w(_x)
{}
Vector4::Vector4(Real _x, Real _y, Real _z, Real _w)
:x(_x), y(_y), z(_z), w(_w)
{}
Vector4::Vector4(const Real data[4])
:x(data[0]), y(data[1]), z(data[2]), w(data[3])
{}
Vector4::Vector4(const Vector3& v)
:x(v.x), y(v.y), z(v.z), w(One)
{}
Matrix2::Matrix2()
{}
Matrix2::Matrix2(const Matrix2& m)
{
set(m);
}
Matrix2::Matrix2(Real x)
{
set(x);
}
Matrix2::Matrix2(const Real m[2][2])
{
set(m);
}
Matrix2::Matrix2(const Real m[4])
{
set(m);
}
Matrix2::Matrix2(const Vector2& xb, const Vector2& yb)
{
set(xb,yb);
}
bool Matrix2::operator == (const Matrix2& a) const
{
for(int i=0; i<2; i++)
{
for(int j=0; j<2; j++)
if(data[i][j] != a.data[i][j])
return false;
}
return true;
}
bool Matrix2::operator != (const Matrix2& a) const
{
for(int i=0; i<2; i++)
{
for(int j=0; j<2; j++)
if(data[i][j] == a.data[i][j])
return false;
}
return true;
}
Matrix3::Matrix3()
{}
Matrix3::Matrix3(const Matrix3& m)
{
set(m);
}
Matrix3::Matrix3(Real x)
{
set(x);
}
Matrix3::Matrix3(const Real m[3][3])
{
set(m);
}
Matrix3::Matrix3(const Real m[9])
{
set(m);
}
Matrix3::Matrix3(const Vector3& xb, const Vector3& yb, const Vector3& zb)
{
set(xb,yb,zb);
}
bool Matrix3::operator == (const Matrix3& a) const
{
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
if(data[i][j] != a.data[i][j])
return false;
}
return true;
}
bool Matrix3::operator != (const Matrix3& a) const
{
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
if(data[i][j] == a.data[i][j])
return false;
}
return true;
}
void Matrix3::mul(const Matrix3& a, const Matrix3& b)
{
int i,j,k;
Real sum;
Real dat[3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
sum = Zero;
for(k=0; k<3; k++)
sum += b.data[i][k]*a.data[k][j]; //column major
dat[i][j] = sum;
}
}
set(dat);
}
void Matrix3::mulTransposeA(const Matrix3& a, const Matrix3& b)
{
int i,j,k;
Real sum;
Real dat[3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
sum = Zero;
for(k=0; k<3; k++)
sum += b.data[i][k]*a.data[j][k]; //column major
dat[i][j] = sum;
}
}
set(dat);
}
void Matrix3::mulTransposeB(const Matrix3& a, const Matrix3& b)
{
int i,j,k;
Real sum;
Real dat[3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
sum = Zero;
for(k=0; k<3; k++)
sum += b.data[k][i]*a.data[k][j]; //column major
dat[i][j] = sum;
}
}
set(dat);
}
#define SWAP(a,b) { tmp = (a) ; (a) = (b) ; (b) = tmp; }
static void rowswap(Matrix3 &m, int i, int j) {
Real tmp;
SWAP(m(i,0),m(j,0));
SWAP(m(i,1),m(j,1));
SWAP(m(i,2),m(j,2));
}
bool Matrix3::setInverse(const Matrix3& a)
{
Matrix3 _a(a);
Matrix3& _b = *this;
_b.setIdentity();
int i,j,i1;
for(j=0;j<3;j++) {
i1 = j;
for(i=j+1;i<3;i++)
if (Abs(_a(i,j)) > Abs(_a(i1,j)))
i1 = i;
rowswap(_a,i1,j);
rowswap(_b,i1,j);
if (FuzzyZero(_a(j,j))){
fprintf(stderr, "Inverse of singular matrix\n");
abort();
}
Real div = Inv(_a(j,j));
_b(j,0) *= div;
_b(j,1) *= div;
_b(j,2) *= div;
_a(j,0) *= div;
_a(j,1) *= div;
_a(j,2) *= div;
for(i=0;i<3;i++) {
if (i != j) {
Real tmp = _a(i,j);
_b(i,0) -= tmp*_b(j,0);
_b(i,1) -= tmp*_b(j,1);
_b(i,2) -= tmp*_b(j,2);
_a(i,0) -= tmp*_a(j,0);
_a(i,1) -= tmp*_a(j,1);
_a(i,2) -= tmp*_a(j,2);
}
}
}
return true;
}
Real Matrix3::determinant() const
{
Real a = data[0][0] * (data[1][1] * data[2][2] - data[1][2] * data[2][1]);
Real b = data[0][1] * (data[1][2] * data[2][0] - data[1][0] * data[2][2]);
Real c = data[0][2] * (data[1][0] * data[2][1] - data[1][1] * data[2][0]);
return a + b + c;
}
Real Matrix3::cofactor(int i, int j) const
{
const static int rotation [] = { 0, 1, 2, 0, 1, 2};
int i1,i2,j1,j2;
i1 = rotation[(i+1)];
i2 = rotation[(i+2)];
j1 = rotation[(j+1)];
j2 = rotation[(j+2)];
return data[i1][j1]*data[i2][j2] - data[i1][j2]*data[i2][j1];
}
Matrix4::Matrix4()
{}
Matrix4::Matrix4(const Matrix4& m)
{
set(m);
}
Matrix4::Matrix4(Real x)
{
set(x);
}
Matrix4::Matrix4(const Real m[4][4])
{
set(m);
}
Matrix4::Matrix4(const Real m[16])
{
set(m);
}
Matrix4::Matrix4(const Vector3& xb, const Vector3& yb, const Vector3& zb, const Vector3& trans)
{
set(xb,yb,zb,trans);
}
Matrix4::Matrix4(const Vector4& x, const Vector4& y, const Vector4& z, const Vector4& w)
{
set(x,y,z,w);
}
Matrix4::Matrix4(const Matrix3& m)
{
set(m);
}
Matrix4::Matrix4(const Matrix3& m, const Vector3& trans)
{
set(m,trans);
}
Matrix4::Matrix4(const Vector3& trans)
{
setTranslate(trans);
}
Matrix4::operator Matrix3() const
{
Matrix3 tmp;
get(tmp);
return tmp;
}
bool Matrix4::operator == (const Matrix4& a) const
{
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
if(data[i][j] != a.data[i][j])
return false;
}
return true;
}
bool Matrix4::operator != (const Matrix4& a) const
{
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
if(data[i][j] == a.data[i][j])
return false;
}
return true;
}
void Matrix4::mul(const Matrix4& a, const Matrix4& b)
{
int i,j,k;
Real sum;
Real dat[4][4];
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
{
sum = Zero;
for(k=0; k<4; k++)
sum += b.data[i][k]*a.data[k][j]; //column major
dat[i][j] = sum;
}
}
set(dat);
}
void Matrix4::mulTransposeA(const Matrix4& a, const Matrix4& b)
{
int i,j,k;
Real sum;
Real dat[4][4];
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
{
sum = Zero;
for(k=0; k<4; k++)
sum += b.data[i][k]*a.data[j][k]; //column major
dat[i][j] = sum;
}
}
set(dat);
}
void Matrix4::mulTransposeB(const Matrix4& a, const Matrix4& b)
{
int i,j,k;
Real sum;
Real dat[4][4];
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
{
sum = Zero;
for(k=0; k<4; k++)
sum += b.data[k][i]*a.data[k][j]; //column major
dat[i][j] = sum;
}
}
set(dat);
}
#define MATSWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
bool Matrix4::setInverse(const Matrix4& a)
{
Real tmp[12]; /* temp array for pairs */
Real src[16]; /* array of transpose source matrix */
Real dst[16]; /* array of destination matrix */
Real det; /* determinant */
int i;
/* transpose matrix */
for (i = 0; i < 4; i++) {
src[i] = a.data[i][0];
src[i + 4] = a.data[i][1];
src[i + 8] = a.data[i][2];
src[i + 12] = a.data[i][3];
}
/* calculate pairs for first 8 elements (cofactors) */
tmp[0] = src[10] * src[15];
tmp[1] = src[11] * src[14];
tmp[2] = src[9] * src[15];
tmp[3] = src[11] * src[13];
tmp[4] = src[9] * src[14];
tmp[5] = src[10] * src[13];
tmp[6] = src[8] * src[15];
tmp[7] = src[11] * src[12];
tmp[8] = src[8] * src[14];
tmp[9] = src[10] * src[12];
tmp[10] = src[8] * src[13];
tmp[11] = src[9] * src[12];
/* calculate first 8 elements (cofactors) */
dst[0] = tmp[0]*src[5] + tmp[3]*src[6] + tmp[4]*src[7];
dst[0] -= tmp[1]*src[5] + tmp[2]*src[6] + tmp[5]*src[7];
dst[1] = tmp[1]*src[4] + tmp[6]*src[6] + tmp[9]*src[7];
dst[1] -= tmp[0]*src[4] + tmp[7]*src[6] + tmp[8]*src[7];
dst[2] = tmp[2]*src[4] + tmp[7]*src[5] + tmp[10]*src[7];
dst[2] -= tmp[3]*src[4] + tmp[6]*src[5] + tmp[11]*src[7];
dst[3] = tmp[5]*src[4] + tmp[8]*src[5] + tmp[11]*src[6];
dst[3] -= tmp[4]*src[4] + tmp[9]*src[5] + tmp[10]*src[6];
dst[4] = tmp[1]*src[1] + tmp[2]*src[2] + tmp[5]*src[3];
dst[4] -= tmp[0]*src[1] + tmp[3]*src[2] + tmp[4]*src[3];
dst[5] = tmp[0]*src[0] + tmp[7]*src[2] + tmp[8]*src[3];
dst[5] -= tmp[1]*src[0] + tmp[6]*src[2] + tmp[9]*src[3];
dst[6] = tmp[3]*src[0] + tmp[6]*src[1] + tmp[11]*src[3];
dst[6] -= tmp[2]*src[0] + tmp[7]*src[1] + tmp[10]*src[3];
dst[7] = tmp[4]*src[0] + tmp[9]*src[1] + tmp[10]*src[2];
dst[7] -= tmp[5]*src[0] + tmp[8]*src[1] + tmp[11]*src[2];
/* calculate pairs for second 8 elements (cofactors) */
tmp[0] = src[2]*src[7];
tmp[1] = src[3]*src[6];
tmp[2] = src[1]*src[7];
tmp[3] = src[3]*src[5];
tmp[4] = src[1]*src[6];
tmp[5] = src[2]*src[5];
tmp[6] = src[0]*src[7];
tmp[7] = src[3]*src[4];
tmp[8] = src[0]*src[6];
tmp[9] = src[2]*src[4];
tmp[10] = src[0]*src[5];
tmp[11] = src[1]*src[4];
/* calculate second 8 elements (cofactors) */
dst[8] = tmp[0]*src[13] + tmp[3]*src[14] + tmp[4]*src[15];
dst[8] -= tmp[1]*src[13] + tmp[2]*src[14] + tmp[5]*src[15];
dst[9] = tmp[1]*src[12] + tmp[6]*src[14] + tmp[9]*src[15];
dst[9] -= tmp[0]*src[12] + tmp[7]*src[14] + tmp[8]*src[15];
dst[10] = tmp[2]*src[12] + tmp[7]*src[13] + tmp[10]*src[15];
dst[10]-= tmp[3]*src[12] + tmp[6]*src[13] + tmp[11]*src[15];
dst[11] = tmp[5]*src[12] + tmp[8]*src[13] + tmp[11]*src[14];
dst[11]-= tmp[4]*src[12] + tmp[9]*src[13] + tmp[10]*src[14];
dst[12] = tmp[2]*src[10] + tmp[5]*src[11] + tmp[1]*src[9];
dst[12]-= tmp[4]*src[11] + tmp[0]*src[9] + tmp[3]*src[10];
dst[13] = tmp[8]*src[11] + tmp[0]*src[8] + tmp[7]*src[10];
dst[13]-= tmp[6]*src[10] + tmp[9]*src[11] + tmp[1]*src[8];
dst[14] = tmp[6]*src[9] + tmp[11]*src[11] + tmp[3]*src[8];
dst[14]-= tmp[10]*src[11] + tmp[2]*src[8] + tmp[7]*src[9];
dst[15] = tmp[10]*src[10] + tmp[4]*src[8] + tmp[9]*src[9];
dst[15]-= tmp[8]*src[9] + tmp[11]*src[10] + tmp[5]*src[8];
/* calculate determinant */
det=src[0]*dst[0]+src[1]*dst[1]+src[2]*dst[2]+src[3]*dst[3];
/* calculate matrix inverse */
if(det == Zero) return false;
det = Inv(det);
for (i = 0; i < 16; i++)
dst[i] *= det;
for (i = 0; i < 4; i++) {
data[i][0] = dst[i*4];
data[i][1] = dst[i*4+1];
data[i][2] = dst[i*4+2];
data[i][3] = dst[i*4+3];
}
return true;
/*
int i, j, k, l, ll;
int icol=0, irow=0;
int indxc[4], indxr[4], ipiv[4];
Real big, dum, pivinv;
set(a);
// Gauss-jordan elimination with full pivoting. Yes, folks, a
// GL Matrix4 is inverted like any other, since the identity is
// still the identity.
// from numerical recipies in C second edition, pg 39
for(j=0;j<=3;j++) ipiv[j] = 0;
for(i=0;i<=3;i++) {
big=0.0;
for (j=0;j<=3;j++) {
if(ipiv[j] != 1) {
for (k=0;k<=3;k++) {
if(ipiv[k] == 0) {
if(fabs(data[j][k]) >= big) {
big = (Real) fabs(data[j][k]);
irow=j;
icol=k;
}
} else if (ipiv[k] > 1) {
printf("Error in gauss-jordan inversion\n");
return false;
}
}
}
}
++(ipiv[icol]);
if (irow != icol) {
for (l=0;l<=3;l++) swap(data[irow][l],data[icol][l]);
}
indxr[i]=irow;
indxc[i]=icol;
if(data[icol][icol] == Zero) {
printf("Error in gauss-jordan inversion\n");
return false;
}
pivinv = One / data[icol][icol];
data[icol][icol]=One;
for (l=0;l<=3;l++) data[icol][l] *= pivinv;
for (ll=0;ll<=3;ll++) {
if (ll != icol) {
dum=data[ll][icol];
data[ll][icol]=Zero;
for (l=0;l<=3;l++) data[ll][l] -= data[icol][l]*dum;
}
}
}
for (l=3;l>=0;l--) {
if (indxr[l] != indxc[l]) {
for (k=0;k<=3;k++) {
swap(data[k][indxr[l]],data[k][indxc[l]]);
}
}
}
return true;
*/
/*
Real det = m.determinant();
if(det == Zero)
return false;
Real detinv = One/det;
int i,j;
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
{
data[i][j] = m.cofactor(j,i) * detinv;
}
}
return true;*/
}
Real Matrix4::determinant() const
{
Real a = data[0][0] * cofactor(0,0);
Real b = data[0][1] * cofactor(0,1);
Real c = data[0][2] * cofactor(0,2);
Real d = data[0][3] * cofactor(0,3);
return a - b + c - d;
}
Real Matrix4::cofactor(int i, int j) const
{
static int rotation [] = { 0, 1, 2, 3, 0, 1, 2};
int i1,i2,i3,j1,j2,j3;
i1 = rotation[(i+1)];
i2 = rotation[(i+2)];
i3 = rotation[(i+3)];
j1 = rotation[(j+1)];
j2 = rotation[(j+2)];
j3 = rotation[(j+3)];
Real a = data[i1][j1] * (data[i2][j2] * data[i3][j3] - data[i2][j3] * data[i3][j2]);
Real b = data[i1][j2] * (data[i2][j3] * data[i3][j1] - data[i2][j1] * data[i3][j3]);
Real c = data[i1][j3] * (data[i2][j1] * data[i3][j2] - data[i2][j2] * data[i3][j1]);
return a - b + c;
}
RigidTransform::RigidTransform()
{
setIdentity();
}
RigidTransform::RigidTransform(const RigidTransform& x)
:R(x.R), t(x.t)
{}
RigidTransform::RigidTransform(const Matrix3& _R, const Vector3& _t)
:R(_R), t(_t)
{}
RigidTransform::RigidTransform(const Vector3& x, const Vector3& y, const Vector3& z, const Vector3& _t)
:R(x,y,z), t(_t)
{}
RigidTransform::RigidTransform(const Matrix4& m)
{
m.get(R,t);
}
bool RigidTransform::isValid(Real eps) const
{
return FuzzyEquals(R.determinant(),One,eps);
}
// Row major, post multiplication
void RigidTransform::get(Real m[16]) const
{
m[0] = R.data[0][0]; m[1] = R.data[1][0]; m[2] = R.data[2][0]; m[3] = t.x;
m[4] = R.data[0][1]; m[5] = R.data[1][1]; m[6] = R.data[2][1]; m[7] = t.y;
m[8] = R.data[0][2]; m[9] = R.data[1][2]; m[10] = R.data[2][2]; m[11]= t.z;
m[12] = 0; m[13] = 0; m[14] = 0; m[15]= 1;
}
// Matrix3 is columan-major matrix. m is used for post multiplication
// So it can be used directly for OpenGL which also uses column major and post multiplication (V' = M *V)
void RigidTransform::getGL(Real m[16]) const
{
m[0] = R.data[0][0]; m[4] = R.data[1][0]; m[8] = R.data[2][0]; m[12] = t.x;
m[1] = R.data[0][1]; m[5] = R.data[1][1]; m[9] = R.data[2][1]; m[13] = t.y;
m[2] = R.data[0][2]; m[6] = R.data[1][2]; m[10] = R.data[2][2]; m[14] = t.z;
m[3] = 0; m[7] = 0; m[11] = 0; m[15] = 1;
}
RigidTransform2D::RigidTransform2D()
{
}
RigidTransform2D::RigidTransform2D(const RigidTransform2D& rhs)
:R(rhs.R),t(rhs.t)
{
}
RigidTransform2D::RigidTransform2D(const Matrix3& m)
{
set(m);
}
RigidTransform2D::RigidTransform2D(const Matrix2& _R,const Vector2& _t)
:R(_R),t(_t)
{
}
RigidTransform2D::RigidTransform2D(Real theta,const Vector2& t)
{
set(theta,t);
}
bool RigidTransform2D::isValid(Real eps) const
{
return FuzzyEquals(R.determinant(),One,eps);
}
double Random01()
{
return (1.0 * rand()) / RAND_MAX;
}
///Generate a random number between -1 and 1
double RandomN1P1()
{
return (2.0 * rand()) / RAND_MAX - 1;
}
///Generate a random angle between -Pi and Pi according to the normal distribution with mean and sdv2
double RandomNormalNPiPPi (double mean, double sdv2) {
double random, p_random, p_control;
while (true) {
random = RandomN1P1()*dPi;
p_random = exp(-0.5*pow((random-mean),2)/sdv2)/(sqrt(2*dPi*sdv2));
p_control = Random01();
if (p_random>=p_control) {
break;
}
}
return random;
}
///Generate a random number between -1 and 1 according to Normal distribution with mean and sdv2
double RandomNormalN1P1 (double mean, double sdv2) {
double random, p_random, p_control;
while (true) {
random = RandomN1P1();
p_random = exp(-0.5*pow((random-mean),2)/sdv2)/(sqrt(2*dPi*sdv2));
p_control = Random01();
if (p_random>=p_control) {
break;
}
}
return random;
}
///Generate a random angle between -A and A according to uniform distribution
double RandomAngleUniform (double A) {
return RandomN1P1()*A;
}
///Compute the torsional angle p1-p2-p3-p4 in radians
double TorsionalAngle (Vector3 &p1, Vector3 &p2, Vector3 &p3, Vector3 &p4) {
Vector3 p21 = p1-p2;
Vector3 p23 = p3-p2;
Vector3 p43 = p3-p4;
Vector3 normal_213 = cross(p21,p23);
Vector3 normal_432 = cross(p23,p43);
normalize(normal_213);
normalize(normal_432);
normalize(p23);
double angle = VectorRotationAngle(normal_213,normal_432,p23);
return angle;
}
// The function computes the angle to rotate p1 to p2 around axis clockwisely.
// p1 and p2 are perpendicular to the axis.
// All 3 input vectors are unit vectors
double VectorRotationAngle (Vector3 p1, Vector3 p2, Vector3 axis) {
double cos = dot(p1,p2);
if (cos<-1.0) {
cos = -1.0;
}
else if (cos>1.0) {
cos = 1.0;
}
double angle = acos(cos);
double s = axis.x*(p1.z*p2.y-p1.y*p2.z)+axis.y*(p1.x*p2.z-p1.z*p2.x)+axis.z*(p1.y*p2.x-p1.x*p2.y);
if (s>0.0) {
angle *= -1;
}
return angle;
}
std::ostream& operator << (std::ostream& out, const Vector2& v)
{
out << v.x << " " << v.y;
return out;
}
std::istream& operator >> (std::istream& in, Vector2& v)
{
in >> v.x >> v.y;
return in;
}
std::ostream& operator << (std::ostream& out, const Vector3& v)
{
out << v.x << " " << v.y << " " << v.z;
return out;
}
std::istream& operator >> (std::istream& in, Vector3& v)
{
in >> v.x >> v.y >> v.z;
return in;
}
std::ostream& operator << (std::ostream& out, const Vector4& v)
{
out << v.x << " " << v.y << " " << v.z << " " << v.w;
return out;
}
std::istream& operator >> (std::istream& in, Vector4& v)
{
in >> v.x >> v.y >> v.z >> v.w;
return in;
}
std::ostream& operator << (std::ostream& out, const Matrix2& m)
{
out << m(0,0) << " " << m(0,1) << std::endl;
out << m(1,0) << " " << m(1,1);
return out;
}
std::istream& operator >> (std::istream& in, Matrix2& m)
{
in >> m(0,0) >> m(0,1);
in >> m(1,0) >> m(1,1);
return in;
}
std::ostream& operator << (std::ostream& out, const Matrix3& m)
{
out << m(0,0) << " " << m(0,1) << " " << m(0,2) << std::endl;
out << m(1,0) << " " << m(1,1) << " " << m(1,2) << std::endl;
out << m(2,0) << " " << m(2,1) << " " << m(2,2);
return out;
}
std::istream& operator >> (std::istream& in, Matrix3& m)
{
in >> m(0,0) >> m(0,1) >> m(0,2);
in >> m(1,0) >> m(1,1) >> m(1,2);
in >> m(2,0) >> m(2,1) >> m(2,2);
return in;
}
std::ostream& operator << (std::ostream& out, const Matrix4& m)
{
out << m(0,0) << " " << m(0,1) << " " << m(0,2) << " " << m(0,3) << std::endl;
out << m(1,0) << " " << m(1,1) << " " << m(1,2) << " " << m(1,3) << std::endl;
out << m(2,0) << " " << m(2,1) << " " << m(2,2) << " " << m(2,3) << std::endl;
out << m(3,0) << " " << m(3,1) << " " << m(3,2) << " " << m(3,3);
return out;
}
std::istream& operator >> (std::istream& in, Matrix4& m)
{
in >> m(0,0) >> m(0,1) >> m(0,2) >> m(0,3);
in >> m(1,0) >> m(1,1) >> m(1,2) >> m(1,3);
in >> m(2,0) >> m(2,1) >> m(2,2) >> m(2,3);
in >> m(3,0) >> m(3,1) >> m(3,2) >> m(3,3);
return in;
}
std::ostream& operator << (std::ostream& out, const RigidTransform& x)
{
out << x.R << std::endl;
out << x.t;
return out;
}
std::istream& operator >> (std::istream& in, RigidTransform& x)
{
in >> x.R;
in >> x.t;
return in;
}
std::ostream& operator << (std::ostream& out, const RigidTransform2D& x)
{
out << x.R << std::endl;
out << x.t;
return out;
}
std::istream& operator >> (std::istream& in, RigidTransform2D& x)
{
in >> x.R;
in >> x.t;
return in;
}
} //namespace Math3D
| [
"fonseca.rasmus@gmail.com"
] | fonseca.rasmus@gmail.com |
8bd31d0be2430cecf878b20a8cc7820b355dbc48 | 1660665a327c1ae59d4ee58a75f35ffbb4da8601 | /code for data structure/qune/queue base array/queue_baseArray/QueType.cpp | bfc726e2486f407abfcae2334145ead6cbc8650f | [] | no_license | Abdo-Gamal/DataStructur | aed474f6655cf6fcf9ff9d4fa35c1a0d319dd781 | 236f2d0e2600e74e0b78f0d421ddc593da3f8952 | refs/heads/main | 2023-04-15T12:46:21.077046 | 2021-04-30T15:26:40 | 2021-04-30T15:26:40 | 363,175,499 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,798 | cpp | #include "QueType.h"
QueType::QueType(int max)
// Parameterized class constructor
// Post: maxQue, front, and rear have been initialized.
// The array to hold the queue elements has been dynamically
// allocated.
{
maxQue = max + 1; //as there are one place will be empty
front = maxQue - 1;
rear = maxQue - 1;
items = new ItemType[maxQue];
}
QueType::QueType() // Default class constructor
// Post: maxQue, front, and rear have been initialized.
// The array to hold the queue elements has been dynamically
// allocated.
{
maxQue = 501;
front = maxQue - 1;
rear = maxQue - 1;
items = new ItemType[maxQue];
}
QueType::~QueType() // Class destructor
{
delete [] items;
}
void QueType::MakeEmpty()
// Post: front and rear have been reset to the empty state.
{
front = maxQue - 1;
rear = maxQue - 1;
}
bool QueType::IsEmpty() const
// Returns true if the queue is empty; false otherwise.
{
return (rear == front);
}
bool QueType::IsFull() const
// Returns true if the queue is full; false otherwise.
{
return ((rear + 1) % maxQue == front);
}
void QueType::Enqueue(ItemType newItem)
// Post: If (queue is not full) newItem is at the rear of the queue;
// otherwise a FullQueue exception is thrown.
{
if (IsFull())
throw FullQueue();
else
{
rear = (rear + 1) % maxQue;
items[rear] = newItem;
}
}
void QueType::Dequeue(ItemType& item)
// Post: If (queue is not empty) the front of the queue has been
// removed and a copy returned in item;
// othersiwe a EmptyQueue exception has been thrown.
{
if (IsEmpty())
throw EmptyQueue();
else
{
front = (front + 1) % maxQue;
item = items[front];
}
}
| [
"abdulrahmangamalahmedgaber@gmail.com"
] | abdulrahmangamalahmedgaber@gmail.com |
11cf59d34e437c3fcf6a7c3823b9c83d1b013ef9 | b4881b5b71c66b5210bf05cf10bfd1cc1bf2822d | /modulo_gps/src/GPS_Management.cpp | 31c2be5c09171110f8a43634a739b2870291f80e | [] | no_license | grvcPerception/gps_measurements | 679798f0ef804453061a462dd0542f74235c5dc9 | 2a0ac64e7d11b5109fd8967a6b4f5d83c9607f1a | refs/heads/master | 2021-04-15T18:05:27.122187 | 2018-07-19T09:27:48 | 2018-07-19T09:27:48 | 126,209,958 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,096 | cpp | /**
@file GPS_Management.cpp
@brief Implementación de la clase GPS_Management
@author Carlos Amores
@date 2013,2014,2015
*/
#include <string.h>
#include "modulo_gps/GPS_Management.h"
using namespace std;
/**
* Constructor de la clase
*/
GPS_Management::GPS_Management(const char *pDev){
port_opened=false;
if(port.openSerial((char *)pDev)){
port.configura(B115200);
port_opened=true;
}else{
cerr << "No se ha podido abrir el puerto serie" << endl;
}
}
/**
* Método consultor del atributo bestgpsvel
* @return Atributo bestgpsvel de la clase
*/
Bestgpsvel GPS_Management::getGPSVel(){return this->bestgpsvel;}
/**
* Método consultor del atributo bestgpspos
* @return Atributo bestgpspos de la clase
*/
Bestgpspos GPS_Management::getGPSPos(){return this->bestgpspos;}
/**
* Método consultor del atributo inspvas
* @return Atributo inspvas de la clase
*/
Inspvas GPS_Management::getInspVas(){return this->inspvas;}
/**
* Método consultor del atributo inspva
* @return Atributo inspva de la clase
*/
Inspva GPS_Management::getInspVa(){return this->inspva;}
/**
* Método consultor del atributo bestleverarm
* @return Atributo bestleverarm de la clase
*/
Bestleverarm GPS_Management::getLeverarm(){return this->bestleverarm;}
/**
* Método consultor del atributo corrimudata
* @return Atributo corrimudata de la clase
*/
Corrimudata GPS_Management::getCorrIMUData(){return this->corrimudata;}
/**
* Método consultor del atributo inspos
* @return Atributo inspos de la clase
*/
Inspos GPS_Management::getInsPos(){return this->inspos;}
/**
* Método consultor del atributo heading
* @return Atributo heading de la clase
*/
Heading GPS_Management::getHeading(){return this->heading;}
/**
* Método consultor del atributo clockmodel
* @return Atributo clockmodel de la clase
*/
Clockmodel GPS_Management::getClockModel(){return this->clockmodel;}
/**
* Método público que configura la forma de alinearse de la IMU
* @param[in] mode Tipo de alineamiento
* @return Booleano indicando si la petición se realizo correctamente
*/
bool GPS_Management::gps_conf_alignmentmode(string mode){
// Formacion del mensaje
string options[1];
options[0]=mode;
string msg = create_message("ALIGNMENTMODE",1,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que activa o desactiva la rotación del gps respecto al vehículo
* @param[in] mode Indica si se habilita o no la rotación
* @return Booleano que indica si la petición se realizo correctamente
*/
bool GPS_Management::gps_conf_applyvehiclebodyrotation(string mode){
// Formacion del mensaje
string options[1];
options[0]=mode;
string msg = create_message("APPLYVEHICLEBODYROTATION",1,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Méotodo público para configuración del puerto CAN
* @param[in] port Puerto a gestionar
* @param[in] mode Activa/desactiva la configuración
* @param[in] bitrate Velocidad de comunicación por el puerto
* @param[in] base Dirección base
* @param[in] tx_max Máscara de los datos transmitidos
* @param[in] source De donde vienen los daros
* @return Booleano que indica si la petición se realizó correctamente
*/
bool GPS_Management::gps_conf_canconfig(string port, string mode, string bitrate, int base, int tx_max, string source){
string options[6];
options[0]=port;
options[1]=mode;
options[2]=bitrate;
options[3]=toString(base);
options[4]=toString(tx_max);
options[5]=source;
string msg = create_message("CANCONFIG",6,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que configura el offset angular de la antena de GPS
* @param[in] heading Offset angular en azimuth
* @param[in] headingSTD Desviación del heading
* @param[in] pitch Offset angular en pitch
* @param[in] pitchSTD Desviación del pitch
* @return Booleano que indica si la petición se realizó correctamente
*/
bool GPS_Management::gps_conf_exthdgoffset(double heading,double headingSTD, double pitch, double pitchSTD){
// Formacion del mensaje
string options[4];
options[0]=toString(heading);
options[1]=toString(headingSTD);
options[2]=toString(pitch);
options[3]=toString(pitchSTD);
string msg = create_message("EXTHDGOFFSET",4,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que resetea la configuración del GPS
* @param[in] target Módulo a resetear
* @return Booleano que indica si la petición se realizó con éxito
*/
bool GPS_Management::gps_conf_freset(string target){
// Formacion del mensaje
string options[1];
options[0]=target;
string msg = create_message("FRESET",1,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que activa/desactiva el posicionamiento de la IMU
* @param[in] stateIndica si se habilita o no el posicionamiento de la IMU
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_inscommand(string state){
// Formacion del mensaje
string options[1];
options[0]=state;
string msg = create_message("INSCOMMAND",1,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que configura el periodo de operación del dispositivo
* @param[in] mode Activa/Desactiva el control de fase
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_insphaseupdate(string mode){
// Formacion del mensaje
string options[1];
options[0]=mode;
string msg = create_message("INSPHASEUPDATE",1,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que actializa la velocidad a '
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_inszupt(){
// Formacion del mensaje
string msg = create_message("INZUPT",0,NULL);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que activa/desactiva la posibilidad de actualizar la velocidad a 0
* @param[in] state Indica si se habilita o no esta posibilidad
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_inszuptcontrol(string state){
// Formacion del mensaje
string options[1];
options[0]=state;
string msg = create_message("INSZUPTCONTROL",1,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que cambia el comportamiento del emisor NMEA
* @param[in] id Tipo de comportamiento
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_nmeatalker(string id){
// Formacion del mensaje
string options[1];
options[0]=id;
string msg = create_message("NMEATALKER",1,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que activa o desactiva la posibilidad de configurar el oofset
* angular de la antena
* @param[in] state Indica si se habilita o no esta posibilidad
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_rvbcalibrate(string state){
// Formacion del mensaje
string options[1];
options[0]=state;
string msg = create_message("RVBCALIBRATE",1,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que configura la orientacion del SPAN-CPT
* @param[in] orientation Orientacion de los ejes del SPAN-CPT (que eje esta alineado
* con la gravedad)
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_setimuorientation(string orientation){
// Formacion del mensaje
string options[1];
options[0]=orientation;
string msg = create_message("SETIMUORIENTATION",1,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que configura el offset lineal de la antena
* @param[in] x Offset en eje X
* @param[in] y Offset en eje Y
* @param[in] z Offset en eje Z
* @param[in] a Incertidumbre en X
* @param[in] b Incertidumbre en Y
* @param[in] c Incertidumbre en Z
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_setimutoantoffset(double x,double y, double z, double a,double b, double c){
// Formacion del mensaje
string options[6];
options[0]=toString(x);
options[1]=toString(y);
options[2]=toString(z);
options[3]=toString(a);
options[4]=toString(b);
options[5]=toString(c);
string msg = create_message("SETIMUTOANTOFFSET",6,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que configura el offset lineal de una segunda antena
* @param[in] x Offset en eje X
* @param[in] y Offset en eje Y
* @param[in] z Offset en eje Z
* @param[in] a Incertidumbre en X
* @param[in] b Incertidumbre en Y
* @param[in] c Incertidumbre en Z
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_setimutoantoffset2(double x,double y, double z, double a,double b, double c){
// Formacion del mensaje
string options[6];
options[0]=toString(x);
options[1]=toString(y);
options[2]=toString(z);
options[3]=toString(a);
options[4]=toString(b);
options[5]=toString(c);
string msg = create_message("SETIMUTOANTOFFSET2",6,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que inicializa la orientación del SPAN-CPT
* @param[in] pitch Valor de pitch inicial
* @param[in] roll Valor de roll inicial
* @param[in] azimuth Valor de azimuth inicial
* @param[in] pitchSTD Desviación de pitch inicial
* @param[in] rollSTD Desviación de roll inicial
* @param[in] azSTD Desviación de azimuth inicial
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_setinitattitude(double pitch,double roll, double azimuth, double pitchSTD,double rollSTD, double azSTD){
// Formacion del mensaje
string options[6];
options[0]=toString(roll);
options[1]=toString(pitch);
options[2]=toString(azimuth);
options[3]=toString(rollSTD);
options[4]=toString(pitchSTD);
options[5]=toString(azSTD);
string msg = create_message("SETINITATTITUDE",6,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que inicializa solo el azimuth del SPAN-CPT
* @param[in] azimuth Valor del azimuth inicial
* @param[in] azSTD Desviación del azimuth inicial
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_setinitazimuth(double azimuth,double azSTD){
// Formacion del mensaje
string options[2];
options[0]=toString(azimuth);
options[1]=toString(azSTD);
string msg = create_message("SETINITAZIMUTH",2,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que especifica el offset de la posición del SPAN-CPT
* @param[in] x Valor inicial en X
* @param[in] y Valor inicial en Y
* @param[in] z Valor inicial en Z
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_setinsoffset(double x,double y,double z){
// Formacion del mensaje
string options[3];
options[0]=toString(x);
options[1]=toString(y);
options[2]=toString(z);
string msg = create_message("SETINSOFFSET",3,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que especifica el offset al Mark1 del evento
* @param[in] x Offset en el eje X
* @param[in] y Offset en el eje Y
* @param[in] z Offset en el eje Z
* @param[in] alphaOffset Offset en roll
* @param[in] betaOffset Offset en pitch
* @param[in] gammaOffset Offset en azimuth
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_setmark1offset(double x,double y,double z, double alphaOffset, double betaOffset, double gammaOffset){
// Formacion del mensaje
string options[6];
options[0]=toString(x);
options[1]=toString(y);
options[2]=toString(z);
options[3]=toString(alphaOffset);
options[4]=toString(betaOffset);
options[5]=toString(gammaOffset);
string msg = create_message("SETMARK1OFFSET",6,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que configura los parámetros de la rueda en caso de disponer
* de un sensor para esta
* @param[in] ticks Número de ticks por revolución
* @param[in] circ Circunferencia de la rueda
* @param[in] spacing Espacio entre ticks o resolución del sensor (en metros)
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_setwheelparameters(unsigned short ticks,double circ,double spacing){
// Formacion del mensaje
string options[3];
options[0]=toString(ticks);
options[1]=toString(circ);
options[2]=toString(spacing);
string msg = create_message("SETWHEELPARAMETERS",3,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que configura el offset angular entre el vehículo y el SPAN-CPT
* @param[in] xAngle Ángulo en eje X
* @param[in] yAngle Ángulo en eje Y
* @param[in] zAngle Ángulo en eje Z
* @param[in] a Incertidumbre del valor de xAngle
* @param[in] b Incertidumbre del valor de yAngle
* @param[in] c Incertidumbre del valor de zAngle
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_conf_vehiclebodyrotation(double xAngle,double yAngle, double zAngle, double a,double b, double c){
// Formacion del mensaje
string options[6];
options[0]=toString(xAngle);
options[1]=toString(yAngle);
options[2]=toString(zAngle);
options[3]=toString(a);
options[4]=toString(b);
options[5]=toString(c);
string msg = create_message("VEHICLEBODYROTATION",6,options);
// Envio del mensaje
this->port.send((char *)msg.c_str(),msg.length());
// Recepcion de la respuesta
Response r = reception_management(true,false);
return r.ok;
}
/**
* Método público que genera y envia un comando de tipo log
* @param[in] command Comando
* @param[in] type Tipo de respuesta deseada (onchange, onnew, etc.)
* @return Booleano que indica si la petición se ha realizado con éxito
*/
bool GPS_Management::gps_log_general(string command, string type){
string options[2];
options[0] = command;
options[1] = type;
string msg = create_message("log", 2, options);
// Envio del mensaje
this->port.send((char *) msg.c_str(), msg.length());
// Recepcion de la respuesta
Response r = reception_management(true, false);
return r.ok;
}
/**
* Método público para adquisición de datos de tipo BESTGPSVEL
* @param[in] res Respuesta a descomponer
* @return Booleano que indica si la operación se ha realizado con éxito
*/
bool GPS_Management::gps_adq_bestgpsvel(Response res){
// Rellenar atributo bestgpsvel con los datos obtenidos de Response
string *datos = getData(8,res.data);
this->bestgpsvel.sol_status=datos[0];
this->bestgpsvel.vel_type=datos[1];
this->bestgpsvel.latency=stringToFloat(datos[2]);
this->bestgpsvel.age=stringToFloat(datos[3]);
this->bestgpsvel.hor_spd=stringToDouble(datos[4]);
this->bestgpsvel.trk_gnd=stringToDouble(datos[5]);
this->bestgpsvel.ver_spd=stringToDouble(datos[6]);
this->bestgpsvel.reserved=stringToFloat(datos[7]);
return true;
}
/**
* Método público para adquisición de datos de tipo BESTGPSPOS
* @param[in] res Respuesta a descomponer
* @return Booleano que indica si la operación se ha realizado con éxito
*/
bool GPS_Management::gps_adq_bestgpspos(Response res){
// Rellenar atributo bestgpspos con los datos obtenidos de Response
string *datos = getData(21,res.data);
this->bestgpspos.sol_status=datos[0];
this->bestgpspos.state=getStateOfGPS(datos[0]);
this->bestgpspos.pos_type=datos[1];
this->bestgpspos.lat=stringToDouble(datos[2]);
this->bestgpspos.lon=stringToDouble(datos[3]);
this->bestgpspos.hgt=stringToDouble(datos[4]);
this->bestgpspos.undulation=stringToFloat(datos[5]);
this->bestgpspos.datum_id=datos[6];
this->bestgpspos.lat_dev=stringToFloat(datos[7]);
this->bestgpspos.lon_dev=stringToFloat(datos[8]);
this->bestgpspos.hgt_dev=stringToFloat(datos[9]);
this->bestgpspos.stn_id=datos[10];
this->bestgpspos.diff_age=stringToFloat(datos[11]);
this->bestgpspos.sol_age=stringToFloat(datos[12]);
this->bestgpspos.obs=datos[13][0];
this->bestgpspos.gpsL1=datos[14][0];
this->bestgpspos.l1=datos[15][0];
this->bestgpspos.l2=datos[16][0];
this->bestgpspos.res1=datos[17][0];
this->bestgpspos.res2=datos[18][0];
this->bestgpspos.res3=datos[19][0];
this->bestgpspos.res4=datos[20][0];
return true;
}
/**
* Método público para adquisición de datos de tipo INSPVAS
* @param[in] res Respuesta a descomponer
* @return Booleano que indica si la operación se ha realizado con éxito
*/
bool GPS_Management::gps_adq_inspvas(Response res){
// Rellenar atributo bestgpspos con los datos obtenidos de Response
string *datos = getData(12,res.data);
this->inspvas.week=stringToLong(datos[0]);
this->inspvas.seconds=stringToDouble(datos[1]);
this->inspvas.lat=stringToDouble(datos[2]);
this->inspvas.lon=stringToDouble(datos[3]);
this->inspvas.hgt=stringToDouble(datos[4]);
this->inspvas.north_velocity=stringToDouble(datos[5]);
this->inspvas.east_velocity=stringToDouble(datos[6]);
this->inspvas.up_velocity=stringToDouble(datos[7]);
this->inspvas.roll=stringToDouble(datos[8]);
this->inspvas.pitch=stringToDouble(datos[9]);
this->inspvas.azimuth=stringToDouble(datos[10]);
this->inspvas.status=datos[11];
return true;
}
/**
* Método público para adquisición de datos de tipo INSPVA
* @param[in] res Respuesta a descomponer
* @return Booleano que indica si la operación se ha realizado con éxito
*/
bool GPS_Management::gps_adq_inspva(Response res){
// Rellenar atributo bestgpspos con los datos obtenidos de Response
string *datos = getData(12,res.data);
this->inspva.state=getStateOfIMU(datos[11]);
this->inspva.week=stringToLong(datos[0]);
this->inspva.seconds=stringToDouble(datos[1]);
this->inspva.lat=stringToDouble(datos[2]);
this->inspva.lon=stringToDouble(datos[3]);
this->inspva.hgt=stringToDouble(datos[4]);
this->inspva.north_velocity=stringToDouble(datos[5]);
this->inspva.east_velocity=stringToDouble(datos[6]);
this->inspva.up_velocity=stringToDouble(datos[7]);
this->inspva.roll=stringToDouble(datos[8]);
this->inspva.pitch=stringToDouble(datos[9]);
this->inspva.azimuth=stringToDouble(datos[10]);
this->inspva.status=datos[11];
return true;
}
/**
* Método público para adquisición de datos de tipo BESTLEVERARM
* @param[in] res Respuesta a descomponer
* @return Booleano que indica si la operación se ha realizado con éxito
*/
bool GPS_Management::gps_adq_bestleverarm(Response res){
string *datos = getData(7,res.data);
this->bestleverarm.x_offset=stringToDouble(datos[0]);
this->bestleverarm.y_offset=stringToDouble(datos[1]);
this->bestleverarm.z_offset=stringToDouble(datos[2]);
this->bestleverarm.x_uncertainty=stringToDouble(datos[3]);
this->bestleverarm.y_uncertainty=stringToDouble(datos[4]);
this->bestleverarm.z_uncertainty=stringToDouble(datos[5]);
this->bestleverarm.imapping=stringToInt(datos[6]);
return true;
}
/**
* Método público para adquisición de datos de tipo CORRIMUDATA
* @param[in] res Respuesta a descomponer
* @return Booleano que indica si la operación se ha realizado con éxito
*/
bool GPS_Management::gps_adq_corrimudata(Response res){
string *datos = getData(8,res.data);
this->corrimudata.week=stringToLong(datos[0]);
this->corrimudata.seconds=stringToDouble(datos[1]);
this->corrimudata.roll_rate=stringToDouble(datos[2]);
this->corrimudata.pitch_rate=stringToDouble(datos[3]);
this->corrimudata.yaw_rate=stringToDouble(datos[4]);
this->corrimudata.lateral_acc=stringToDouble(datos[5]);
this->corrimudata.longitudinal_acc=stringToDouble(datos[6]);
this->corrimudata.vertical_acc=stringToDouble(datos[7]);
return true;
}
/**
* Método público para adquisición de datos de tipo INSPOS
* @param[in] res Respuesta a descomponer
* @return Booleano que indica si la operación se ha realizado con éxito
*/
bool GPS_Management::gps_adq_inspos(Response res){
string *datos = getData(6,res.data);
this->inspos.week=stringToLong(datos[0]);
this->inspos.seconds=stringToDouble(datos[1]);
this->inspos.lat=stringToDouble(datos[2]);
this->inspos.lon=stringToDouble(datos[3]);
this->inspos.hgt=stringToDouble(datos[4]);
this->inspos.status=datos[5];
return true;
}
/**
* Método público para adquisición de datos de tipo HEADING
* @param[in] res Respuesta a descomponer
* @return Booleano que indica si la operación se ha realizado con éxito
*/
bool GPS_Management::gps_adq_heading(Response res) {
string *datos = getData(17, res.data);
this->heading.sol_stat=datos[0];
this->heading.pos_type=datos[1];
this->heading.length=stringToFloat(datos[2]);
this->heading.heading=stringToFloat(datos[3]);
this->heading.pitch=stringToFloat(datos[4]);
this->heading.res=stringToFloat(datos[5]);
this->heading.hdg_std_dev=stringToFloat(datos[6]);
this->heading.ptch_std_dev=stringToFloat(datos[7]);
this->heading.stn_id=datos[8];
this->heading.observations=datos[9][0];
this->heading.num_satellites=datos[10][0];
this->heading.obs=datos[11][0];
this->heading.multi=datos[12][0];
this->heading.res2=datos[13][0];
this->heading.ext_sol_stat=datos[14][0];
this->heading.res3=datos[15][0];
this->heading.sig_mask=datos[16][0];
return true;
}
/**
* Método público para adquisición de datos de tipo CLOCKMODEL
* @param[in] res Respuesta a descomponer
* @return Booleano que indica si la operación se ha realizado con éxito
*/
bool GPS_Management::gps_adq_clockmodel(Response res) {
string *datos = getData(19, res.data);
this->clockmodel.status=datos[0];
this->clockmodel.reject=stringToFloat(datos[1]);
this->clockmodel.noise_time=stringToDouble(datos[2]);
this->clockmodel.update_time=stringToDouble(datos[3]);
for(int i=0; i < 3; i++)
this->clockmodel.parameters[i]=stringToDouble(datos[4+i]);
for(int i=0; i < 9; i++)
this->clockmodel.cov_data[i]=stringToDouble(datos[7+i]);
this->clockmodel.range_bias=stringToDouble(datos[16]);
this->clockmodel.range_bias_rate=stringToDouble(datos[17]);
this->clockmodel.change=datos[18];
return true;
}
/**
* Método público para generación de mensajes
* @param[in] command Cabecera del mensaje
* @param[in] num_param Número de parámetros del mensaje
* @param[in] options Parámetros para generar el mensaje tras la cabecera
* @return Mensaje generado en formato String
*/
string GPS_Management::create_message(string command, int num_param, string options[]){
string message=command;
for(int i=0;i<num_param;i++){
message+= " ";
message+=options[i];
}
message+="\r";
return message;
}
/**
* Método público para la obtención de una estructura de tipo Response en base
* a los datos en crudo obtenidos del GPS
* @param[in] confirmation Indica si la recepción es de un mensaje de confirmación
* @param[in] data Indica si la receipción es un de un mensaje de datos
* @return Estructura de la respuesta recibida ya escapsulada en datos
*/
Response GPS_Management::reception_management(bool confirmation, bool data){
Response resp;
bool startConfirmation = false, endConfirmation = false;
bool startData = false, endData =false;
if (confirmation)
{
// Se lee OK o Error
char c;
string conf = "";
// Se busca el comienzo de confirmacion
while (!startConfirmation)
{
if (this->port.recv(&c, 1, 1) == SERIAL_OK){
if (c == '<')
startConfirmation = true;
}else{
resp.error = SERIAL_ERROR;
resp.ok = false;
return resp;
}
}
// Se busca la confirmacion
while (!endConfirmation){
if (this->port.recv(&c, 1, 1) == SERIAL_OK)
{
conf += c;
if (c == '\r')
endConfirmation = true;
}else{
resp.error = FRAME_ERROR;
resp.ok = false;
return resp;
}
}
// Se busca si es OK o ERROR dentro del mensaje de confirmacion
if (conf.find("OK") != string::npos)
resp.ok = true;
else
resp.ok = false;
// No se esperan datos
resp.data = "";
}
if(data){
// Se lee los datos
char c;
string dataFrame = "";
// Se busca el comienzo de los datos
while (!startData){
if (this->port.recv(&c, 1, 10) == SERIAL_OK){
if (c == '$' || c=='#' || c=='%')
startData = true;
}else{
resp.error = SERIAL_ERROR;
resp.ok = false;
return resp;
}
}
// Se busca el final de los datos
while (!endData){
if (this->port.recv(&c, 1, 1) == SERIAL_OK){
dataFrame += c;
if (c == '\r')
endData = true;
}else{
resp.error = FRAME_ERROR;
resp.ok = false;
return resp;
}
}
analizeFrame(dataFrame, &resp);
// Comprobacion de checksum
string buf = resp.header + resp.headerdata + resp.data;
unsigned long crcCalculated = CalculateBlockCRC32(buf.length(), (unsigned char*) buf.c_str());
unsigned long checksumFrame;
stringstream ss;
ss << std::hex << resp.checksum;
ss >> checksumFrame;
if(crcCalculated==checksumFrame){
resp.ok = true;
}else{
cerr << "Checksum ERROR" << endl;
}
}
return resp;
}
/**
* Método público para descomposición del mensaje en partes
* @param[in] numData Número de partes que componen el mensaje
* @param[in] frameData Mensaje en sí
* @return Partes del mensaje descompuesto
*/
string* GPS_Management::getData(int numData, string frameData){
int pos=0;
string* data=new string[numData];
char *s;
s=strtok((char*)frameData.c_str(),",;");
while(s!=NULL)
{
data[pos++]=s;
s=strtok(NULL,",");
}
return data;
}
/**
* Método consultor del atriburo port_opened
* @return Atributo port_opened
*/
bool GPS_Management::isPortOpened(){
return port_opened;
}
/**
* Método público que analiza una trama de datos
* @param[in] frame Trama de datos
* @param[io] resp Mensaje a transformar mediante análisis
*/
void GPS_Management::analizeFrame(string frame,Response* resp){
unsigned int pos=0;
while(frame[pos]!=',')
{
resp->header+=frame[pos++];
}
while(frame[pos]!=';')
{
resp->headerdata+=frame[pos++];
}
while(frame[pos]!='*')
{
resp->data+=frame[pos++];
}
pos++;
while(frame[pos]!='\r'){
resp->checksum+=frame[pos++];
}
}
/**
* Método público que lee y clasifica un mensaje del dispositivo por puerto serie
* @return Tipo de trama obtenida
*/
int GPS_Management::rcvData(){
int tt=TT_ERROR;
Response res = reception_management(false,true);
if(res.ok){
if(res.header=="BESTGPSVELA"){
gps_adq_bestgpsvel(res);
tt=TT_GPSVELA;
}else if(res.header=="BESTGPSPOSA"){
gps_adq_bestgpspos(res);
tt=TT_BESTGPSPOSA;
}else if(res.header=="INSPVASA"){
gps_adq_inspvas(res);
tt=TT_INSPVASA;
}else if(res.header=="BESTLEVERARMA"){
gps_adq_bestleverarm(res);
tt=TT_BESTLEVERARMA;
}else if(res.header=="CORRIMUDATASA"){
gps_adq_corrimudata(res);
tt=TT_CORRIMUDATASA;
}else if(res.header=="INSPOSA"){
gps_adq_inspos(res);
tt=TT_INSPOSA;
}else if(res.header=="HEADINGA"){
gps_adq_heading(res);
tt=TT_HEADINGA;
}else if(res.header=="INSPVAA"){
gps_adq_inspva(res);
tt=TT_INSPVAA;
}
else if(res.header=="CLOCKMODEL"){
gps_adq_clockmodel(res);
tt=TT_CLOCKMODEL;
}
}else{
tt=TT_ERROR;
}
return tt;
}
/**
* Método público que obtiene el estado del GPS mediante la consulta en el campo
* correspondiente de un mensaje
* @param[in] s Campo del mensaje
* @return Valor entero que indica el estado mediante el uso de constantes
*/
short GPS_Management::getStateOfGPS(string s){
if(strcmp(s.c_str(),"INSUFFICIENT_OBS")==0)
return INSUFFICIENT_OBS;
else if(strcmp(s.c_str(),"NO_CONVERGENCE")==0)
return NO_CONVERGENCE;
else if(strcmp(s.c_str(),"SINGULARITY")==0)
return SINGULARITY;
else if(strcmp(s.c_str(),"COV_TRACE")==0)
return COV_TRACE;
else if(strcmp(s.c_str(),"TEST_DIST")==0)
return TEST_DIST;
else if(strcmp(s.c_str(),"COLD_START")==0)
return COLD_START;
else if(strcmp(s.c_str(),"V_H_LIMIT")==0)
return V_H_LIMIT;
else if(strcmp(s.c_str(),"VARIANCE")==0)
return VARIANCE;
else if(strcmp(s.c_str(),"RESIDUALS")==0)
return RESIDUALS;
else if(strcmp(s.c_str(),"DELTA_POS")==0)
return DELTA_POS;
else if(strcmp(s.c_str(),"NEGATIVE_VAR")==0)
return NEGATIVE_VAR;
else if(strcmp(s.c_str(),"INTEGRITY_WARNING")==0)
return INTEGRITY_WARNING;
else if(strcmp(s.c_str(),"IMU_UNPLUGGED")==0)
return IMU_UNPLUGGED;
else if(strcmp(s.c_str(),"PENDING")==0)
return PENDING;
else if(strcmp(s.c_str(),"INVALID_FIX")==0)
return INVALID_FIX;
else if(strcmp(s.c_str(),"UNAUTHORIZED_STATE")==0)
return UNAUTHORIZED_STATE;
else
return GPS_GLOBAL_ERROR;
}
/**
* Método público que obtiene el estado de la IMU mediante la consulta en el campo
* correspondiente de un mensaje
* @param[in] s Campo del mensaje
* @return Valor entero que indica el estado mediante el uso de constantes
*/
short GPS_Management::getStateOfIMU(string s){
if(strcmp(s.c_str(),"NS_INACTIVE")==0)
return INS_INACTIVE;
else if(strcmp(s.c_str(),"INS_ALIGNING")==0)
return INS_ALIGNING;
else if(strcmp(s.c_str(),"INS_SOLUTION_NOT_GOOD")==0)
return INS_SOLUTION_NOT_GOOD;
else if(strcmp(s.c_str(),"INS_BAD_GPS_AGREEMENT")==0)
return INS_BAD_GPS_AGREEMENT;
else if(strcmp(s.c_str(),"INSUFFICIENT_OBS")==0)
return INSUFFICIENT_OBS;
else if(strcmp(s.c_str(),"INS_ALIGNMENT_COMPLETE")==0)
return GPS_GLOBAL_ERROR;
else
return GPS_GLOBAL_ERROR;
}
/**
* Método público que envía las tramas correspondientes para la configuración
* del puerto serie COM2 para la recepción de correcciones GPS (RTK)
*/
void GPS_Management::setCom2ToRcvCorrections() {
cout << "Configurando COM2 para obtencion de correcciones..." << endl;
cout << "Enviando INTERFACE MODE...";
string options[4];
options[0] = "COM2";
options[1] = "RTCMV3";
options[2] = "NONE";
options[3] = "OFF";
string msg = create_message("INTERFACEMODE", 4, options);
this->port.send((char *) msg.c_str(), msg.length());
// Recepcion de la respuesta
Response r = reception_management(true, false);
if (r.ok) cout << "OK" << endl;
else {
cout << "ERROR" << endl;
cout << "Fallo la configuracion RTK" << endl;
return;
}
cout << "Enviando configuracion COM...";
string optionsCom[7];
optionsCom[0] = "COM2";
optionsCom[1] = "57600";
optionsCom[2] = "N";
optionsCom[3] = "8";
optionsCom[4] = "1";
optionsCom[5] = "N";
optionsCom[6] = "OFF";
msg = create_message("COM", 7, optionsCom);
this->port.send((char *) msg.c_str(), msg.length());
// Recepcion de la respuesta
r = reception_management(true, false);
if (r.ok) cout << "OK" << endl;
else {
cout << "ERROR" << endl;
cout << "Fallo la configuracion RTK" << endl;
return;
}
}
| [
"JLPaneque94@gmail.com"
] | JLPaneque94@gmail.com |
923cec86eae5210fa7b005d2022697ceabe42798 | d597d667bade224bc70b739205b454e3ec6e04ab | /effects/008_res.cpp | c172be9db84ae7fb92e0f05a3bc85557e6c02cb8 | [] | no_license | templeblock/lovefx | 09b1919b5e60c0f30a92cf0efb07ea407ebb46d0 | fb6a6b3c9c07119dd824c300b414d7fd3fd09d8b | refs/heads/master | 2021-04-29T08:10:59.302327 | 2016-03-07T17:59:55 | 2016-03-07T17:59:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,280 | cpp | #include "../startupfx.h"
#if (STARTUPFX_ID==8)
#include "../lovefx.hpp"
#include "../thirdparty/glm/glm.hpp"
#include "../thirdparty/glm/gtc/matrix_transform.hpp"
#include "../thirdparty/glm/gtc/type_ptr.hpp"
// ----------------------------------------------------------------------------- VARIABLES
GLuint fsquad;
LFXrendertarget defRT, smallRT;
int width, height;
GLuint displayProgram;
GLint inTex_uloc;
// resize_mipmap
void resize_mipmap();
// resize_shader
struct
{
GLuint program;
GLint inTex_uloc, resolution_uloc;
} resshdr;
void resize_shader();
// resize_compute
void resize_compute();
// resize
uint8_t resizeMode = 1;
void resize();
// ----------------------------------------------------------------------------- EVENT HANDLERS
void h_keyUp(unsigned int k)
{
switch (k)
{
case INPUT_KEY_ESC:
PostQuitMessage(0);
break;
case INPUT_KEY_1:
resizeMode = 1;
break;
case INPUT_KEY_2:
resizeMode = 2;
break;
case INPUT_KEY_3:
resizeMode = 3;
break;
case INPUT_KEY_4:
resizeMode = 4;
break;
}
}
// ----------------------------------------------------------------------------- VARIOUS FUNCTIONS
void resize_mipmap()
{
PerfMarker("mipmap", 0xFFFFC90E);
}
void resize_shader()
{
PerfMarker("shader", 0xFF880015);
glDisable(GL_DEPTH_TEST);
lovefx::fbo::use(smallRT.fbo);
lovefx::program::use(resshdr.program);
glBindTexture(GL_TEXTURE_2D, defRT.col0);
glUniform1i(resshdr.inTex_uloc, 0);
lovefx::utils::drawFSQuad(fsquad);
glEnable(GL_DEPTH_TEST);
}
void resize_compute()
{
PerfMarker("compute", 0xFF3F48CC);
}
void resize()
{
if (1 == resizeMode)
{
resize_mipmap();
}
else if (2 == resizeMode)
{
resize_shader();
}
else //if (3 == resizeMode)
{
resize_compute();
}
}
// ----------------------------------------------------------------------------- MAIN APP
void InitApp()
{
PerfMarker("INIT", 0xFF0000FF);
// globals
{
PerfMarker("g_init", 0xFF8888FF);
lovefx::utils::getResolution(width, height);
// setup handlers
INPUT_f_keyUp(h_keyUp);
// full screen quad
lovefx::utils::initFSQuad(fsquad);
// default render target
lovefx::rt::create(defRT, width, height);
// small RT
lovefx::rt::create(smallRT, width/2, height/2);
// init shaders
const char* vs = LFX_GLSL(330,
layout(location = 0) in vec2 aPosition;
out vec2 uv;
void main()
{
gl_Position = vec4(aPosition, 0.5, 1.0);
uv = (aPosition + vec2(1.0)) * 0.5;
}
);
const char* fs = LFX_GLSL(330,
uniform sampler2D inTex;
in vec2 uv;
out vec4 fragColor;
void main()
{
vec4 col = texture(inTex, uv);
fragColor = col;
}
);
lovefx::program::createFromSource(displayProgram, vs, 0, 0, 0, fs, 0);
lovefx::program::log(displayProgram);
lovefx::program::location(displayProgram, "inTex", inTex_uloc);
// set texture active
glActiveTexture(GL_TEXTURE0);
}
// shader version init
{
PerfMarker("vS_init", 0xFFFF8888);
// init shaders
const char* vs = LFX_GLSL(330,
layout(location = 0) in vec2 aPosition;
out vec2 uv;
void main()
{
gl_Position = vec4(aPosition, 0.5, 1.0);
uv = (aPosition + vec2(1.0)) * 0.5;
}
);
const char* fs = LFX_GLSL(330,
uniform sampler2D inTex;
uniform vec2 resolution;
in vec2 uv;
out vec4 fragColor;
void main()
{
vec4 col = texture(inTex, uv);
for (int i = 0; i < 20; i++)
{
col = texture(inTex, uv);
}
fragColor = col;
}
);
lovefx::program::createFromSource(resshdr.program, vs, 0, 0, 0, fs, 0);
lovefx::program::log(resshdr.program);
lovefx::program::location(resshdr.program, "inTex", resshdr.inTex_uloc);
lovefx::program::location(resshdr.program, "resolution", resshdr.resolution_uloc);
}
}
void RenderApp()
{
PerfMarker("frame", 0xFFFF6666);
// 1. render a scene
{
PerfMarker("scene", 0xFF494949);
lovefx::fbo::use(defRT.fbo);
glClearColor(1, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// TODO: render scene
}
// 2. do a resize
resize();
// 3. display
{
PerfMarker("display", 0xFF888888);
lovefx::fbo::use(GL_NONE);
glClearColor(0, 0, 1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
lovefx::program::use(displayProgram);
glBindTexture(GL_TEXTURE_2D, smallRT.col0);
glUniform1i(inTex_uloc, 0);
lovefx::utils::drawFSQuad(fsquad);
}
LFX_ERRCHK();
}
void CleanupApp()
{
lovefx::utils::destroyFSQuad(fsquad); // delete fullscreen quad
}
#endif | [
"largo.etf@gmail.com"
] | largo.etf@gmail.com |
091c5074c0c65595b953704519fe117492ecd28c | cfa94c2db14fbbe2558be933d00c26bec11c7b4b | /platform/win32/win32cpuid.cpp | 7c107212ca4a72b7b84b7f90a6c4ffe188f4595f | [] | no_license | bsdf/trx | 5c74ec9b03dff287b8d89e00cac37e78f13cd54f | 4de6530036d05021a95e19c99cefc94a0c80c303 | refs/heads/master | 2021-01-10T18:50:25.815304 | 2011-10-04T01:39:30 | 2011-10-04T01:39:30 | 2,496,549 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,972 | cpp | /* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 1993-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <windows.h>
#include <winbase.h>
// disable warnings about "Inline asm assigning to FS:0 handler not registered as safe handler"
#pragma warning(disable:4733)
// Code from Intel that crashes a Cyrix CPU
#define CPUID _asm _emit 0x0F _asm _emit 0xA2
#define CPUID_SSE2_FLAG 0x04000000 //; Is IA SSE2 bit (Bit 26 of EDX) in feature flags set
static BOOL gP4OsSupport = FALSE;
#ifndef _WIN64
EXCEPTION_DISPOSITION __cdecl MyExceptionHandlerSSE2(struct _EXCEPTION_RECORD * /*ExceptionRecord*/,
void * /*EstablisherFrame*/,
struct _CONTEXT *ContextRecord,
void * /*DispatcherContext*/)
{
// Turn off the P4 OS support flag.
gP4OsSupport = FALSE;
// The offending P4 instruction is 3 bytes long. Skip it and continue.
ContextRecord->Eip += 3;
return ExceptionContinueExecution;
}
#endif
bool P4Available()
{
#ifdef _M_AMD64
// we support all this stuff
return true;
#else
long featureFlags = 0;
//arun
BOOL procType = 0;
// disable warnings about unreferenced _asm labels.
#pragma warning(disable:4102)
_asm {
push ecx
push ebx
; i386 CPU check
; The AC bit, bit #18, is a new bit introduced in the EFLAGS
; register on the i486 DX CPU to generate alignment faults.
; This bit can not be set on the i386 CPU.
;
check_Intel386:
pushfd
pop eax ; get original EFLAGS
mov ecx,eax ; save original EFLAGS
xor eax,40000h ; flip AC bit in EFLAGS
push eax ; save for EFLAGS
popfd ; copy to EFLAGS
pushfd ; push EFLAGS
pop eax ; get new EFLAGS value
xor eax,ecx ; can't toggle AC bit, CPU=Intel386
je end_get_cpuid ; CPU is i386,
; i486 DX CPU / i487 SX MCP and i486 SX CPU checking
;
; Checking for ability to set/clear ID flag (Bit 21) in EFLAGS
; which indicates the presence of a processor
; with the ability to use the CPUID instruction.
;
check_Intel486:
pushfd ; push original EFLAGS
pop eax ; get original EFLAGS in eax
mov ecx,eax ; save original EFLAGS in ecx
xor eax,200000h ; flip ID bit in EFLAGS
push eax ; save for EFLAGS
popfd ; copy to EFLAGS
pushfd ; push EFLAGS
pop eax ; get new EFLAGS value
xor eax, ecx
je end_get_cpuid ; CPU=486 without CPUID instruction functionality
; Execute CPUID instruction to determine vendor, family,
; model and stepping. The use of the CPUID instruction used
; in this program can be used for B0 and later steppings
; of the P5 processor.
cpuid_data:
// At this point we know we can do our CPUID instruction
// We need some special code here to handle Cyrix buggy processors
// Get our Vendors name out first
mov eax, 0
CPUID
//arun
cmp ebx, 0x47656e75
jz cyrix_version
cmp edx, 0x696e6549
jz cyrix_version
cmp ecx, 0x6e74656c
jz cyrix_version
mov procType, 1
jmp non_cyrix_version
cyrix_version:
// EAX returns the highest value we can use as input into the
// CPUID instruction. If for some reason it returns 0, assume
// no MMX support. (Since we need to input 1 to query MMX)
cmp eax, 0
jz end_get_cpuid
cmp ebx, 0x69727943 // This is "iryC", "Cyri" in memory
jne non_cyrix_version
// EAX now contains the stepping, model and family information
and eax, 0x0FF0 // isolate model and family info
cmp eax, 0x0520 // We're a 6x86, so there's no MMX
je end_get_cpuid
non_cyrix_version:
// Non Cyrix version
mov eax, 1 // Our input flag for our CPUID instruction
CPUID
mov featureFlags, edx ; save feature flags
end_get_cpuid:
pop ecx
pop ebx
}
BOOL bOsSupport = FALSE;
BOOL bHwSupport = (featureFlags & CPUID_SSE2_FLAG);
if(bHwSupport) {
// Execute a KNI instruction and use Structured Exception Handling
// to catch the exception if the OS does not support KNI.
DWORD handler = (DWORD)MyExceptionHandlerSSE2;
gP4OsSupport = TRUE;
__asm { // Build EXCEPTION_REGISTRATION record:
push handler // Address of handler function
push FS:[0] // Address of previous handler
mov FS:[0],ESP // Install new EXECEPTION_REGISTRATION
}
// If so, test a KNI instruction and make sure you don't get
// an exception (this tests OS support)
__asm{
pushad;
//orpd xmm1,xmm1; //Below are the op codes for this instruction
//emits will compile w/ MSVC 5.0 compiler
//You can comment these out and uncomment the
//orpd when using the Intel Compiler
__emit 0x66
__emit 0x0f
__emit 0x56
__emit 0xc9
popad;
}
__asm { // Remove our EXECEPTION_REGISTRATION record
mov eax,[ESP] // Get pointer to previous record
mov FS:[0], EAX // Install previous record
add esp, 8 // Clean our EXECEPTION_REGISTRATION off stack
}
bOsSupport = gP4OsSupport;
}
return bHwSupport && bOsSupport && procType;
#endif
}
| [
"EMAILBEN145@gmail.com"
] | EMAILBEN145@gmail.com |
96d5bf1f9af47ef52adc095fbc5ab40573811991 | 49a8e5ed3d46724984391d7c3c110553c5f4a4d9 | /Heap_Priority_Queues/ArrayMaxHeap.h | 24cc5d75af7e38a7a3679811bf3bec0522804560 | [] | no_license | EasonJia9598/Heap_Priority_Queues | 976a0d37a500ab0569724a159f6da1096cd4b19e | 34973441203d463c6f1bd1a05685bf89fa7bf062 | refs/heads/master | 2020-03-12T13:03:08.420591 | 2018-04-23T02:59:34 | 2018-04-23T02:59:34 | 130,632,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,229 | h | //
// ArrayMaxHeap.hpp
// HeapSort
//
// Created by WillJia on 08/04/2018.
// Copyright © 2018 Zesheng Jia A00416452. All rights reserved.
//
#ifndef ArrayMaxHeap_hpp
#define ArrayMaxHeap_hpp
#include <stdio.h>
#include "HeapInterface.h"
#include "PrecondViolatedExcep.h"
#include <math.h>
template <class ItemType>
class ArrayMaxHeap : public HeapInterface<ItemType> {
private:
static const int ROOT_INDEX = 0;
static const int DEFAULT_CAPACITY = 21;
ItemType* items;
int itemCount;
int maxItems;
int getLeftChildIndex(const int nodeIndex) const;
int getRightChildIndex(int nodeIndex) const;
int getParentIndex(int nodeIndex) const;
bool isLeaf(int nodeIndex) const;
void heapRebuild(int subTreeRootIndex);
void heapCreate();
public:
ArrayMaxHeap();
ArrayMaxHeap(const ItemType someArray[] , const int arraySize);
virtual ~ArrayMaxHeap();
bool isEmpty() const;
int getNumberOfNodes() const;
int getHeight() const;
ItemType peekTop() const throw (PrecondViolatedExcep);
bool add(const ItemType& newData);
bool remove();
bool clear();
}; // end ArrayMaxHeap
#include "ArrayMaxHeap.cpp"
#endif /* ArrayMaxHeap_hpp */
| [
"will.jia.sheng@gmail.com"
] | will.jia.sheng@gmail.com |
d583e1808c8c86bb88991ff804bde1dc886e4f35 | 1d8cff4ae94d2312c5386b6c64db795f18e7168e | /topics/openacc/solutions/diffusion/diffusion2d_openacc_mpi.cpp | fa76a4111e34b7ee3e37206b9e7cea1fa91dac73 | [] | no_license | pkestene/SummerSchool2017 | 3655257b338c5a85cba764ad39171e965a490901 | 5ff663029f896cc157e535dc09bf273262104052 | refs/heads/master | 2020-11-23T20:58:59.122116 | 2019-12-25T16:17:39 | 2019-12-25T16:17:39 | 227,818,602 | 1 | 0 | null | 2019-12-13T10:51:38 | 2019-12-13T10:51:37 | null | UTF-8 | C++ | false | false | 4,753 | cpp | #include <iostream>
#include <mpi.h>
#include "diffusion2d.hpp"
#include "util.h"
// 2D diffusion example
// the grid has a fixed width of nx=128
// the use specifies the height, ny, as a power of two
// note that nx and ny have 2 added to them to account for halos
int main(int argc, char** argv) {
// set up parameters
// first argument is the y dimension = 2^arg
size_t pow = read_arg(argc, argv, 1, 8);
// second argument is the number of time steps
size_t nsteps = read_arg(argc, argv, 2, 100);
// third argument is nonzero if shared memory version is to be used
bool use_shared = read_arg(argc, argv, 3, 0);
// set domain size
size_t nx = 128;
size_t ny = 1 << pow;
double dt = 0.1;
// initialize MPI
int mpi_rank, mpi_size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
if (ny % mpi_size) {
std::cout << "error : global domain dimension " << ny
<< "must be divisible by number of MPI ranks "
<< mpi_size << "\n";
exit(1);
} else if (mpi_rank == 0) {
std::cout << "\n## " << mpi_size << " MPI ranks" << std::endl;
std::cout << "## " << nx << "x" << ny
<< " : " << nx << "x" << ny/mpi_size << " per rank"
<< " for " << nsteps << " time steps"
<< " (" << nx*ny << " grid points)\n";
}
ny /= mpi_size;
// adjust dimensions for halo
nx += 2;
ny += 2;
// allocate memory on device and host
// note : allocate enough memory for the halo around the boundary
auto buffer_size = nx*ny;
#ifdef OPENACC_DATA
double *x0 = malloc_host_pinned<double>(buffer_size);
double *x1 = malloc_host_pinned<double>(buffer_size);
#else
double *x_host = malloc_host_pinned<double>(buffer_size);
double *x0 = malloc_device<double>(buffer_size);
double *x1 = malloc_device<double>(buffer_size);
#endif
double start_diffusion, time_diffusion;
#ifdef OPENACC_DATA
#pragma acc data create(x0[0:buffer_size]) copyout(x1[0:buffer_size])
#endif
{
// set initial conditions of 0 everywhere
fill_gpu(x0, 0., buffer_size);
fill_gpu(x1, 0., buffer_size);
// set boundary conditions of 1 on south border
if (mpi_rank == 0) {
fill_gpu(x0, 1., nx);
fill_gpu(x1, 1., nx);
}
if (mpi_rank == mpi_size-1) {
fill_gpu(x0+nx*(ny-1), 1., nx);
fill_gpu(x1+nx*(ny-1), 1., nx);
}
auto south = mpi_rank - 1;
auto north = mpi_rank + 1;
// time stepping loop
#pragma acc wait
start_diffusion = get_time();
for(auto step=0; step<nsteps; ++step) {
MPI_Request requests[4];
MPI_Status statuses[4];
auto num_requests = 0;
#ifdef OPENACC_DATA
#pragma acc host_data use_device(x0, x1)
#endif
{
if (south >= 0) {
// x0(:, 0) <- south
MPI_Irecv(x0, nx, MPI_DOUBLE, south, 0, MPI_COMM_WORLD,
&requests[0]);
// x0(:, 1) -> south
MPI_Isend(x0+nx, nx, MPI_DOUBLE, south, 0, MPI_COMM_WORLD,
&requests[1]);
num_requests += 2;
}
// exchange with north
if(north < mpi_size) {
// x0(:, ny-1) <- north
MPI_Irecv(x0+(ny-1)*nx, nx, MPI_DOUBLE, north, 0,
MPI_COMM_WORLD, &requests[num_requests]);
// x0(:, ny-2) -> north
MPI_Isend(x0+(ny-2)*nx, nx, MPI_DOUBLE, north, 0,
MPI_COMM_WORLD, &requests[num_requests+1]);
num_requests += 2;
}
}
MPI_Waitall(num_requests, requests, statuses);
diffusion_gpu(x0, x1, nx-2, ny-2, dt);
#ifdef OPENACC_DATA
copy_gpu(x0, x1, buffer_size);
#else
std::swap(x0, x1);
#endif
}
#pragma acc wait
time_diffusion = get_time() - start_diffusion;
} // end of acc data
#ifdef OPENACC_DATA
auto x_res = x1;
#else
copy_to_host<double>(x0, x_host, buffer_size);
auto x_res = x_host;
#endif
if (mpi_rank == 0) {
std::cout << "## " << time_diffusion << "s, "
<< nsteps*(nx-2)*(ny-2)*mpi_size / time_diffusion
<< " points/second\n\n";
std::cout << "writing to output.bin/bov\n";
write_to_file(nx, ny, x_res);
}
MPI_Finalize();
return 0;
}
| [
"karakasis@cscs.ch"
] | karakasis@cscs.ch |
5a4918f7fbc5ac70c6ecf1a5170b0402dbd7961b | 4e8fb3672f0c561bf85bd8230c5492e4457f33d1 | /dev/src/GameEditor/InspectorProperty.cpp | ece4a78e7bcf9aeaea81b7884d69d79f20e215e9 | [] | no_license | lythm/ld3d | 877abefefcea9b39734857714fe1974a8320fe6c | 91de1cca7cca77c1f8eae8e8a9423abc34f9b38f | refs/heads/master | 2020-12-24T15:23:29.766231 | 2014-07-11T04:42:49 | 2014-07-11T04:42:49 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,089 | cpp | // InpsectorProperty.cpp : 实现文件
//
#include "stdafx.h"
#include "GameEditor.h"
#include "InspectorProperty.h"
#include "afxdialogex.h"
#include "InspectorPanel.h"
// CInpsectorProperty 对话框
IMPLEMENT_DYNAMIC(CInspectorProperty, CDialogEx)
CInspectorProperty::CInspectorProperty(CString name, ld3d::Property* pProp, void* pUserData, UINT nIDD)
: CDialogEx(nIDD, nullptr)
{
m_pProp = pProp;
m_nIDD = nIDD;
m_pPanel = nullptr;
m_name = name;
m_pUserData = pUserData;
m_bReadOnly = false;
m_bVisible = true;
}
CInspectorProperty::~CInspectorProperty()
{
m_bkBrush.DeleteObject();
}
void CInspectorProperty::SetReadOnly(bool bReadOnly)
{
m_bReadOnly = bReadOnly;
}
bool CInspectorProperty::GetReadOnly()
{
return m_bReadOnly;
}
const CString& CInspectorProperty::GetName() const
{
return m_name;
}
void CInspectorProperty::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CInspectorProperty, CDialogEx)
ON_WM_CREATE()
ON_WM_PAINT()
ON_WM_SIZE()
ON_WM_CTLCOLOR()
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
// CInpsectorProperty 消息处理程序
bool CInspectorProperty::Create(CWnd* pParent)
{
m_pPanel = (CInspectorPanel*)pParent;
m_bkBrush.CreateSolidBrush(RGB(70, 70, 70));
return CDialogEx::Create(m_nIDD, pParent);
}
int CInspectorProperty::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialogEx::OnCreate(lpCreateStruct) == -1)
return -1;
return 0;
}
void CInspectorProperty::OnPaint()
{
CPaintDC dc(this); // device context for painting
CRect rc;
GetClientRect(rc);
dc.FillRect(rc, &m_bkBrush);
CDialogEx::OnPaint();
}
void CInspectorProperty::OnSize(UINT nType, int cx, int cy)
{
CDialogEx::OnSize(nType, cx, cy);
//Invalidate();
}
HBRUSH CInspectorProperty::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
if(nCtlColor==CTLCOLOR_STATIC)
{
pDC->SetTextColor(RGB(200,200,200));
pDC->SetBkColor(RGB(70, 70, 70));
}
if(nCtlColor == CTLCOLOR_EDIT)
{
return hbr;
}
return m_bkBrush;
}
void CInspectorProperty::OnOK()
{
// TODO: 在此添加专用代码和/或调用基类
m_pPanel->SetFocus();
//CDialogEx::OnOK();
}
void CInspectorProperty::OnCancel()
{
// TODO: 在此添加专用代码和/或调用基类
m_pPanel->SetFocus();
//CDialogEx::OnCancel();
}
void CInspectorProperty::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
SetFocus();
CDialogEx::OnLButtonDown(nFlags, point);
}
void CInspectorProperty::SetUserData(void* pUserData)
{
m_pUserData = pUserData;
}
void* CInspectorProperty::GetUserData()
{
return m_pUserData;
}
void CInspectorProperty::OnValueChanged()
{
m_pPanel->OnPropertyChanged(this);
}
ld3d::Property* CInspectorProperty::GetProperty()
{
return m_pProp;
}
void CInspectorProperty::Hide()
{
m_bVisible = false;
}
void CInspectorProperty::Show()
{
m_bVisible = true;
}
bool CInspectorProperty::IsVisible()
{
return m_bVisible;
}
CInspectorPanel* CInspectorProperty::GetPanel()
{
return m_pPanel;
} | [
"lythm780522@gmail.com"
] | lythm780522@gmail.com |
75a7d82a876f53a39dd91756ff2c66c4873420e6 | e1a09dc27075171d218ccc6f0021d655e62eb30d | /src/tssl/fileObject.h | 52bc66ab2c6563acf2c2961e762c2400ac612d8f | [] | no_license | bansheerubber/torquescript-interpreter | edae71fcd9fe5a4d4dc2d3e6cbd1ac2c20fac402 | 01779d678703a9b6ab70a225fd53b2c9a8a4b381 | refs/heads/master | 2023-08-21T18:03:57.582151 | 2021-10-02T23:58:17 | 2021-10-02T23:58:17 | 366,219,031 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,415 | h | #pragma once
#include <fstream>
#include <string>
#include "../interpreter/entry.h"
#include "../interpreter/object.h"
using namespace std;
namespace ts {
class Engine;
namespace sl {
enum FileObjectMode {
NOT_OPEN,
READ,
WRITE,
APPEND,
};
class FileObject {
public:
void open(const char* fileName, FileObjectMode mode);
void close();
char* readLine();
void writeLine(const char* string);
bool isEOF();
private:
fstream file;
FileObjectMode mode = NOT_OPEN;
};
void FileObject__constructor(ObjectWrapper* wrapper);
Entry* FileObject__openForRead(Engine* engine, unsigned int argc, Entry* args);
Entry* FileObject__openForWrite(Engine* engine, unsigned int argc, Entry* args);
Entry* FileObject__openForAppend(Engine* engine, unsigned int argc, Entry* args);
Entry* FileObject__close(Engine* engine, unsigned int argc, Entry* args);
Entry* FileObject__readLine(Engine* engine, unsigned int argc, Entry* args);
Entry* FileObject__writeLine(Engine* engine, unsigned int argc, Entry* args);
Entry* FileObject__isEOF(Engine* engine, unsigned int argc, Entry* args);
Entry* fileBase(Engine* engine, unsigned int argc, Entry* args);
Entry* fileExt(Engine* engine, unsigned int argc, Entry* args);
Entry* fileName(Engine* engine, unsigned int argc, Entry* args);
Entry* filePath(Engine* engine, unsigned int argc, Entry* args);
}
} | [
"gary.cactus.email@gmail.com"
] | gary.cactus.email@gmail.com |
929ad0669a5e208d7336b0efbbba37a7c8b54bba | 7d07a4453b6faad6cbc24d44caaa3ad1ab6ebe7f | /src/common/dircmn.cpp | b449b0c1d87b39fe7d65637bbe6242cece5103d6 | [] | no_license | rickyzhang82/wxpython-src-2.9.4.0 | 5a7fff6156fbf9ec1f372a3c6afa860c59bf8ea8 | c9269e81638ccb74ae5086557567592aaa2aa695 | refs/heads/master | 2020-05-24T12:12:13.805532 | 2019-05-17T17:34:34 | 2019-05-17T17:34:34 | 187,259,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,831 | cpp | ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/dircmn.cpp
// Purpose: wxDir methods common to all implementations
// Author: Vadim Zeitlin
// Modified by:
// Created: 19.05.01
// RCS-ID: $Id: dircmn.cpp 71355 2012-05-04 20:35:31Z VZ $
// Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/string.h"
#include "wx/log.h"
#include "wx/intl.h"
#include "wx/filefn.h"
#include "wx/arrstr.h"
#endif //WX_PRECOMP
#include "wx/dir.h"
#include "wx/filename.h"
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// wxDirTraverser
// ----------------------------------------------------------------------------
wxDirTraverseResult
wxDirTraverser::OnOpenError(const wxString& WXUNUSED(dirname))
{
return wxDIR_IGNORE;
}
// ----------------------------------------------------------------------------
// wxDir::HasFiles() and HasSubDirs()
// ----------------------------------------------------------------------------
// dumb generic implementation
bool wxDir::HasFiles(const wxString& spec) const
{
wxString s;
return GetFirst(&s, spec, wxDIR_FILES | wxDIR_HIDDEN);
}
// we have a (much) faster version for Unix
#if (defined(__CYGWIN__) && defined(__WINDOWS__)) || !defined(__UNIX_LIKE__) || defined(__EMX__) || defined(__WINE__)
bool wxDir::HasSubDirs(const wxString& spec) const
{
wxString s;
return GetFirst(&s, spec, wxDIR_DIRS | wxDIR_HIDDEN);
}
#endif // !Unix
// ----------------------------------------------------------------------------
// wxDir::GetNameWithSep()
// ----------------------------------------------------------------------------
wxString wxDir::GetNameWithSep() const
{
// Note that for historical reasons (i.e. because GetName() was there
// first) we implement this one in terms of GetName() even though it might
// actually make more sense to reverse this logic.
wxString name = GetName();
if ( !name.empty() )
{
// Notice that even though GetName() isn't supposed to return the
// separator, it can still be present for the root directory name.
if ( name.Last() != wxFILE_SEP_PATH )
name += wxFILE_SEP_PATH;
}
return name;
}
// ----------------------------------------------------------------------------
// wxDir::Traverse()
// ----------------------------------------------------------------------------
size_t wxDir::Traverse(wxDirTraverser& sink,
const wxString& filespec,
int flags) const
{
wxCHECK_MSG( IsOpened(), (size_t)-1,
wxT("dir must be opened before traversing it") );
// the total number of files found
size_t nFiles = 0;
// the name of this dir with path delimiter at the end
const wxString prefix = GetNameWithSep();
// first, recurse into subdirs
if ( flags & wxDIR_DIRS )
{
wxString dirname;
for ( bool cont = GetFirst(&dirname, wxEmptyString, wxDIR_DIRS | (flags & wxDIR_HIDDEN) );
cont;
cont = cont && GetNext(&dirname) )
{
const wxString fulldirname = prefix + dirname;
switch ( sink.OnDir(fulldirname) )
{
default:
wxFAIL_MSG(wxT("unexpected OnDir() return value") );
// fall through
case wxDIR_STOP:
cont = false;
break;
case wxDIR_CONTINUE:
{
wxDir subdir;
// don't give the error messages for the directories
// which we can't open: there can be all sorts of good
// reason for this (e.g. insufficient privileges) and
// this shouldn't be treated as an error -- instead
// let the user code decide what to do
bool ok;
do
{
wxLogNull noLog;
ok = subdir.Open(fulldirname);
if ( !ok )
{
// ask the user code what to do
bool tryagain;
switch ( sink.OnOpenError(fulldirname) )
{
default:
wxFAIL_MSG(wxT("unexpected OnOpenError() return value") );
// fall through
case wxDIR_STOP:
cont = false;
// fall through
case wxDIR_IGNORE:
tryagain = false;
break;
case wxDIR_CONTINUE:
tryagain = true;
}
if ( !tryagain )
break;
}
}
while ( !ok );
if ( ok )
{
nFiles += subdir.Traverse(sink, filespec, flags);
}
}
break;
case wxDIR_IGNORE:
// nothing to do
;
}
}
}
// now enum our own files
if ( flags & wxDIR_FILES )
{
flags &= ~wxDIR_DIRS;
wxString filename;
bool cont = GetFirst(&filename, filespec, flags);
while ( cont )
{
wxDirTraverseResult res = sink.OnFile(prefix + filename);
if ( res == wxDIR_STOP )
break;
wxASSERT_MSG( res == wxDIR_CONTINUE,
wxT("unexpected OnFile() return value") );
nFiles++;
cont = GetNext(&filename);
}
}
return nFiles;
}
// ----------------------------------------------------------------------------
// wxDir::GetAllFiles()
// ----------------------------------------------------------------------------
class wxDirTraverserSimple : public wxDirTraverser
{
public:
wxDirTraverserSimple(wxArrayString& files) : m_files(files) { }
virtual wxDirTraverseResult OnFile(const wxString& filename)
{
m_files.push_back(filename);
return wxDIR_CONTINUE;
}
virtual wxDirTraverseResult OnDir(const wxString& WXUNUSED(dirname))
{
return wxDIR_CONTINUE;
}
private:
wxArrayString& m_files;
wxDECLARE_NO_COPY_CLASS(wxDirTraverserSimple);
};
/* static */
size_t wxDir::GetAllFiles(const wxString& dirname,
wxArrayString *files,
const wxString& filespec,
int flags)
{
wxCHECK_MSG( files, (size_t)-1, wxT("NULL pointer in wxDir::GetAllFiles") );
size_t nFiles = 0;
wxDir dir(dirname);
if ( dir.IsOpened() )
{
wxDirTraverserSimple traverser(*files);
nFiles += dir.Traverse(traverser, filespec, flags);
}
return nFiles;
}
// ----------------------------------------------------------------------------
// wxDir::FindFirst()
// ----------------------------------------------------------------------------
class wxDirTraverserFindFirst : public wxDirTraverser
{
public:
wxDirTraverserFindFirst() { }
virtual wxDirTraverseResult OnFile(const wxString& filename)
{
m_file = filename;
return wxDIR_STOP;
}
virtual wxDirTraverseResult OnDir(const wxString& WXUNUSED(dirname))
{
return wxDIR_CONTINUE;
}
const wxString& GetFile() const
{
return m_file;
}
private:
wxString m_file;
wxDECLARE_NO_COPY_CLASS(wxDirTraverserFindFirst);
};
/* static */
wxString wxDir::FindFirst(const wxString& dirname,
const wxString& filespec,
int flags)
{
wxDir dir(dirname);
if ( dir.IsOpened() )
{
wxDirTraverserFindFirst traverser;
dir.Traverse(traverser, filespec, flags | wxDIR_FILES);
return traverser.GetFile();
}
return wxEmptyString;
}
// ----------------------------------------------------------------------------
// wxDir::GetTotalSize()
// ----------------------------------------------------------------------------
#if wxUSE_LONGLONG
class wxDirTraverserSumSize : public wxDirTraverser
{
public:
wxDirTraverserSumSize() { }
virtual wxDirTraverseResult OnFile(const wxString& filename)
{
// wxFileName::GetSize won't use this class again as
// we're passing it a file and not a directory;
// thus we are sure to avoid an endless loop
wxULongLong sz = wxFileName::GetSize(filename);
if (sz == wxInvalidSize)
{
// if the GetSize() failed (this can happen because e.g. a
// file is locked by another process), we can proceed but
// we need to at least warn the user that the resulting
// final size could be not reliable (if e.g. the locked
// file is very big).
m_skippedFiles.Add(filename);
return wxDIR_CONTINUE;
}
m_sz += sz;
return wxDIR_CONTINUE;
}
virtual wxDirTraverseResult OnDir(const wxString& WXUNUSED(dirname))
{
return wxDIR_CONTINUE;
}
wxULongLong GetTotalSize() const
{ return m_sz; }
const wxArrayString& GetSkippedFiles() const
{ return m_skippedFiles; }
protected:
wxULongLong m_sz;
wxArrayString m_skippedFiles;
};
wxULongLong wxDir::GetTotalSize(const wxString &dirname, wxArrayString *filesSkipped)
{
if (!wxDirExists(dirname))
return wxInvalidSize;
// to get the size of this directory and its contents we need
// to recursively walk it...
wxDir dir(dirname);
if ( !dir.IsOpened() )
return wxInvalidSize;
wxDirTraverserSumSize traverser;
if (dir.Traverse(traverser) == (size_t)-1 )
return wxInvalidSize;
if (filesSkipped)
*filesSkipped = traverser.GetSkippedFiles();
return traverser.GetTotalSize();
}
#endif // wxUSE_LONGLONG
// ----------------------------------------------------------------------------
// wxDir helpers
// ----------------------------------------------------------------------------
/* static */
bool wxDir::Exists(const wxString& dir)
{
return wxFileName::DirExists(dir);
}
/* static */
bool wxDir::Make(const wxString &dir, int perm, int flags)
{
return wxFileName::Mkdir(dir, perm, flags);
}
/* static */
bool wxDir::Remove(const wxString &dir, int flags)
{
return wxFileName::Rmdir(dir, flags);
}
| [
"rickyzhang@gmail.com"
] | rickyzhang@gmail.com |
2e89ae4b9c904864b1afd73213dcb92176b23125 | 96eb30bbf3237b9419c254008ff5bac5c3ebc3ab | /multicord_v1/FC_01_ButtonAddition/FC_01_ButtonAddition.ino | 1519c268ea4a7ad0d2cb4faf9588773c87d0f993 | [] | no_license | dovydasgulbinas/arduino-projects | 238178e7d3302afef300a884b644759c1fbe9c6b | 5d4162d034eb090bb4db0b8fea8747a7fefbea6f | refs/heads/master | 2021-06-06T20:49:42.661729 | 2016-12-03T22:16:58 | 2016-12-03T22:16:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,179 | ino |
#include <Wire.h>
#include <TimerOne.h>
#define interruptPin_1 (2)// pin 0 hardware interrupt used for dimmer circuit
#define socketPin_B0 (3) // Socket pin BASIC0
#define socketPin_B1 (4) // Socket pin BASIC1
#define socketPin_D0 (5) //Socket pin w/ DIMMER
#define dimmerPin (6) //nuspresti veliau
#define buttonPin_0 (7)//
#define buttonPin_1 (8)
#define buttonPin_2 (9)
#define buttonLine (10)
///NON pin constants
#define OFF (0)
#define ON (1)
#define DIM (2)
#define I2C_ID (4)
////
///DIMMER VARIABLES
volatile byte increment = 0; // Variable to use as a counter
volatile boolean zero_cross = 0; // Stores state of zero cross true means zero cross was present
volatile boolean powerDimmer = false;
byte brightness = 64; // Dimming level (0-128) 0 = on;128 = off
byte freqStep = 75; // frequency step in uS that defines how often we make interrupt
////
///Communication VARIABLES
const byte dimmerisON = 2;
const byte dimmerisOFF = 3;
const byte rozeteON = 4;
const byte rozeteOFF = 5;
const byte readPower_MSB = 6;
const byte readPower_LSB = 7;
const byte getStates = 8;
////
////misc VARIABLES
uint16_t power = 1234;
uint16_t powerArr[3] ={0,222,333};
byte MSB_POWER[3]= {0} ;
byte LSB_POWER[3] ={0};
byte lastCMD = 0;
byte lastByte2;
byte stateByte = 0;
///
struct buttonStruct{
uint8_t cState : 1;
uint8_t pState : 1;
uint8_t buttPin : 4;
} button[3];
void ctrlSockets(byte socketID, byte socketState) { //Assuming sockets are counted from 0; socketID is the id of a specific socket; socketState is on or off or dim ; statesByte is the refere
//Assuming that socketState is either HIGH or LOW; HIGH means socket is ON; LOW means socket is OFF! //Function must be modified for button inverting states
byte bitVal = 0;
switch (socketID) {
case 0:
if(socketState == ON)
bitVal = HIGH;
else
bitVal =LOW;
digitalWrite(socketPin_B0, bitVal);
if(socketState == ON)
bitVal = 1;
else
bitVal =0;
bitWrite(stateByte, socketID, bitVal); // if socketState is ON the n-th bit will be turned to 1 else 0
Serial.print("StateByte: = B");
Serial.println(stateByte, BIN);
break;
//////////////////
case 1:
digitalWrite(socketPin_B1, (socketState == ON) ? HIGH : LOW);
if(socketState == ON)
bitVal = 1;
else
bitVal =0;
bitWrite(stateByte, socketID, bitVal); // if socketState is ON the n-th bit will be turned to 1 else 0
Serial.print("StateByte: = B");
Serial.println(stateByte, BIN);
break;
/////////////////
case 2: //Dimmed socket everything is different!!!
if (socketState == ON) { // DIMMER.PIN = LOW; socketPin_D0 = HIGH; //Relay as been switched!
powerDimmer = false; // was an error no false mechanism
digitalWrite(dimmerPin, LOW);
digitalWrite(socketPin_D0, HIGH);
bitWrite(stateByte, socketID, 1);
break;
}//if1
else if (socketState == DIM) { //Investigation is needed
//digitalWrite(socketPin_D0,LOW); // I made an erros previuosly because going from on to dim i did not set dimmer pin to low
//delay(600);
powerDimmer = true;
bitWrite(stateByte, socketID, 1);
//Value is set by global variable brightness
break;
}//else if1
else {//socketState == OFF
powerDimmer = false; // is needed so that dimmerPin state is not overridden by dim_check
digitalWrite(dimmerPin, LOW);
digitalWrite(socketPin_D0, LOW);
bitWrite(stateByte, socketID, 0);
}//else1
} //Switch
}// ctrlSockets
///Interupt based functions
void zero_cross_detect() {
zero_cross = true; // set the boolean to true to tell our dimming function that a zero cross has occured
increment = 0;
digitalWrite(dimmerPin, LOW); // turn off TRIAC (and AC)
}
void dim_check() {
if (powerDimmer == true) { // if dimmer power is requested then open!
if (zero_cross == true ) { //Cross turns of the the TRIAC if cross is present then dim_check turns
if (increment >= brightness) {
digitalWrite(dimmerPin, HIGH); // turn on light
increment = 0; // reset time step counter
zero_cross = false; //reset zero cross detection
}
else {
increment++; // we will incremement until we have reached needed number of steps i*75uS/step
}
}//if2
}//if1
}
void setup()
{
pinMode(dimmerPin, OUTPUT); // Set the Triac pin as output
pinMode(socketPin_B0, OUTPUT);
pinMode(socketPin_B1, OUTPUT);
pinMode(socketPin_D0, OUTPUT);
pinMode(buttonPin_0, OUTPUT);
pinMode(buttonPin_1, OUTPUT);
pinMode(buttonPin_2, OUTPUT);
pinMode(buttonLine, INPUT);
for(byte i = socketPin_B0; i<=dimmerPin;i++){
digitalWrite(i,LOW); // pulls all outputs low!
}//for1
for(byte b = buttonPin_0; b <=buttonPin_2;b++){
digitalWrite(b,HIGH);
}//for2
///Initializing structure
button[0]= {0,0,buttonPin_0};
button[1]={0,0,buttonPin_1};
button[2]={0,0,buttonPin_2};
////
attachInterrupt(0, zero_cross_detect, RISING); // Attach an Interupt to Pin 2 (interupt 0) for Zero Cross Detection
Timer1.initialize(freqStep); // Initialize TimerOne library for the freq we need
Timer1.attachInterrupt(dim_check, freqStep);
Wire.begin(I2C_ID); // // join i2c bus with address #4
Wire.onReceive(receiveEvent); // register event
Wire.onRequest(requestEvent);
Serial.begin(9600); // start serial for output
delay(100);
//DEFINE ALL FUCKING PINS AND SET THEM TO LOW!!!!
}
void loop()
{
if(millis()%500 == 0){
powerArr[0] = random(15,2000) ;
}
if((millis()%100)==0){// Scanns button state every 0.1 sec // register changes
for(int i = 0; i<4; i++){
digitalWrite(button[i].buttPin,HIGH);
button[i].cState = digitalRead(buttonLine); // Reads the current state of buttonLine
if(button[i].cState != button[i].pState){ //Button was either pressed or released
if(button[i].cState == 1){//Button has been pressed!
Serial.print ("Pressed: ");
Serial.println(i);
if(bitRead(stateByte,i)==1){ //socket was ON and will be turned OFF!
ctrlSockets(i,OFF);
}//if4
else{ //socket was OFF and will be turned ON!
ctrlSockets(i,ON);
}//else1.if4
}//if3
}//if2
button[i].pState = button[i].cState; // Saves the last state for the next loop
digitalWrite(button[i].buttPin,LOW); // Writes button pin low
}//for1
}//if1
}//loop
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
byte byte1 = Wire.read();
lastCMD = byte1;
lastByte2 = Wire.read();
switch (byte1) {
case dimmerisON:
Serial.print("DimmerON! = ");
Serial.println(lastByte2);
Serial.println("");
break;
case dimmerisOFF:
Serial.print("DimmerOFF! = ");
Serial.println(lastByte2);
Serial.println("");
break;
case rozeteON:
ctrlSockets(lastByte2, ON);
Serial.print("rozeteON! = ");
Serial.println(lastByte2);
Serial.println("");
break;
case rozeteOFF:
ctrlSockets(lastByte2, OFF);
Serial.print("rozeteOFF! = ");
Serial.println(lastByte2);
Serial.println("");
break;
case readPower_MSB :
Serial.print("POWER_MSB = ");
Serial.println(lastByte2);
/// convert to byte array;
//MSB_POWER[] = byte(powerArr[0] >> 8);
Serial.println("");
break;
case readPower_LSB:
Serial.print("POWER_LSB = ");
Serial.println(lastByte2);
//LSB_POWER= (byte)(powerArr[lastByte2]); //Should be handeled by iternal power measuring function
Serial.println("");
break;
case getStates:
Serial.print("socket States = ");
Serial.println(stateByte, BIN);
Serial.println("");
break;
default:
Serial.print("No Such command! = ");
Serial.println(lastByte2);
Serial.println("");
// if nothing else matches, do the default
// default is optional
} //Switch
} //Event
void requestEvent( ) { //After receive event has been triggered MCU stores lastCMD which is used in I2C request so that data could be sent
switch (lastCMD) {
case readPower_MSB :
Serial.print("READPOWER = ");
//Wire.write(MSB_POWER[lastByte2]);
Wire.write((int)random(10,2000));
Serial.println("");
break;
case readPower_LSB:
Serial.print("READPOWER = ");
Wire.write(LSB_POWER[lastByte2]);
Serial.println("");
break;
case getStates:
Serial.print("statesPushed!");
Wire.write(stateByte);
Serial.println("");
break;
default :
Serial.println("NO CASE!");
}//switch
}//requestEvent
void serialEvent() {
int socket = 0;
switch (Serial.read()) {
case 'b': // Used for setting the brightness
brightness = Serial.parseInt();
Serial.print("brightnes = ");
Serial.println(brightness);
break;
case 'd':
ctrlSockets(2, DIM);
Serial.println("Dimming!");
break;
case 'o':
ctrlSockets(2, OFF);
Serial.println("dim OFF!");
break;
case 'q': // turns on any socket
socket = Serial.parseInt();
//digitalWrite(socketPin_B0,HIGH);
ctrlSockets(socket, ON);
Serial.print("socket on = ");
Serial.println(socket);
break;
case 'w': // turns off any socket
socket = Serial.parseInt();
//digitalWrite(socketPin_B0,LOW);
ctrlSockets(socket, OFF);
Serial.print("socket off = ");
Serial.println(socket);
break;
default :
Serial.println("NO SUCH COMMAND!");
}//switch
}
| [
"dovydasgulbinas@gmail.com"
] | dovydasgulbinas@gmail.com |
3e50a4f98b39c9fa10b7dfca4424aae6eba85db2 | fb825df2e5ac8de24e7a2495f212c45c06389c05 | /Drawing App/matrix.h | 63bb20eec3696e4ebe46904e8c1006db1152c6bf | [] | no_license | boesigerg/MSOE_Projects | 2b73d1086a9e1ae3e2a1227830a0d6c9a41a09ba | 43fe4c30b7e911c956a727510c82339a2777a140 | refs/heads/master | 2021-08-28T00:39:23.318223 | 2017-12-10T22:23:56 | 2017-12-10T22:23:56 | 113,696,824 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,466 | h | /**
* matrix.h - declaration of matrix class. This class will be
* capable of represting a Matrix as a first-class type.
*
* Do not change any public methods in this file unless otherwise instructed.
*
* For CS321. (c) 2014 Dr. Darrin Rothe
*/
// compile guard
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream> // for std::ostream
#include <stdexcept> // for std::runtime_error
#include <string> // used in exception
// a helper class to bundle a message with any thrown exceptions. To use,
// simply 'throw matrixException("A descriptive message about the problem")'
// This will throw the exception object by value. Recommendation is to
// catch by reference (to prevent slicing).
class matrixException:public std::runtime_error
{
public:
matrixException(std::string message):
std::runtime_error((std::string("Matrix Exception: ") +
message).c_str()) {}
};
class matrix
{
public:
// No-Arg Constructor - create Matrix and clear cells
// Make a 1x1 "default" Matrix
matrix();
// Constructor - create Matrix and clear cells. If rows or cols
// is < 1, throw a matrixException. Note, we will not use
// "exception specifications" as multiple sources report that the
// mechanism is not properly supported by most compilers.
//
// throw (matrixException)
//
matrix(unsigned int rows, unsigned int cols);
// Copy constructor - make a new Matrix just like rhs
matrix(const matrix& from);
// Destructor. Free allocated memory
~matrix();
// Assignment operator - make this just like rhs. Must function
// correctly even if rhs is a different size than this.
matrix& operator=(const matrix& rhs);
// Matrix addition - lhs and rhs must be same size otherwise
// an exception shall be thrown
//
// throw (matrixException)
//
matrix operator+(const matrix& rhs) const;
// Matrix multiplication - lhs and rhs must be compatible otherwise
// an exception shall be thrown
//
// throw (matrixException)
//
matrix operator*(const matrix& rhs) const;
// Scalar multiplication. Note, this function will support
// someMatrixObject * 5.0, but not 5.0 * someMatrixObject.
matrix operator*(const double scale) const;
// Inverse of a square Matrix - must be invertible, otherwise an
// exception shall be thrown. An invertible matrix is square and
// has a non-zero determinate.
//
// Implementing Gauss-Jordan elimination is recommended as detailed
// here: http://en.wikipedia.org/wiki/Gaussian_elimination
// #Finding_the_inverse_of_a_matrix
//
// You may wish to build "helper" methods for creating the augmented
// matrix, operating on the rows, etc, but they are not explicitly
// required. The implementation should work for any size square
// matrix.
//
// As at least a 3rd-year CE student, you are expected to be able to
// perform independent research and implement various algorithms
// as needed.
//
// throw (matrixException)
//
matrix operator!() const;
// Clear Matrix to all members 0.0
void clear();
// Access Operators - throw an exception if index out of range
//
// Note how these operators are to work. Consider a Matrix object
// being addressed with two sets of brackets - m1[1][2], for example.
// The compiler will execute this: (m1[1])[2]. The first set of
// brackets will call this function, and this function should return a
// pointer to the first element of the requested row. The second set
// of brackets is applied to the double*, which results in it being
// treated as an array, thus the requested column is indexed. The
// const version is necessary if you would like to use the operator
// within other const methods. Both of these operators are extremely
// dangerous as prototyped. The nature of the danger and a fix are
// left up to you to discover and fix. A proper fix will
// require a change to these function signatures and the use of an
// internal "helper class."
//
// throw (matrixException)
//
double* operator[](unsigned int row);
// const version of above - throws an exception if indices are out of
// range
//
// throw (matrixException)
//
double* operator[](unsigned int row) const;
// I/O - for convenience - this is intended to be called by the global
// << operator declared below.
std::ostream& out(std::ostream& os) const;
private:
// The data - note, per discussion on arrays, you can store these data
// as a 1-D dynamic array, thus the double* below. Alternatively, and
// perhaps preferred, you could store the data as an array of arrays
// which would require the_Matrix to be changed to a double**.
double** the_matrix;
unsigned int rows;
unsigned int cols;
/** routines **/
//Finds the transpose of the matrix
matrix transpose(const matrix rhs) const;
//Finds the Matrix of Minors for the matrix
//Each element in the Matrix of Minors is the determinant of the
//remaining elements if you were to take out the row and column
//of the element in question
matrix createMoM(const matrix rhs) const;
//Finds the determinant of a given matrix
//Finds the sum of the product of each downward diagonal, then subtracts
//the sum of the product of each upward diagonal
//
//For use in matrix inversion
double getDeterminant(const matrix rhs) const;
};
/** Some Related Global Functions **/
// Overloaded global << with std::ostream as lhs, Matrix as rhs. This method
// should generate output compatible with an ostream which is commonly used
// with console (cout) and files. Something like:
// [[ r0c0, r0c1, r0c2 ]
// [ r1c0, r1c1, r1c2 ]
// [ r0c0, r0c1, r0c2 ]]
// would be appropriate.
//
// Since this is a global function, it does not have access to the private
// data of a Matrix object. So, it will need to use the public interface of
// Matrix to do its job. The method Matrix::out was added to Matrix
// specifically for this purpose. The other option would have been to make
// it a "friend"
std::ostream& operator<<(std::ostream& os, const matrix& rhs);
// We would normally have a corresponding >> operator, but
// will defer that exercise until a later assignment.
// Scalar multiplication with a global function. Note, this function will
// support 5.0 * someMatrixObject, but not someMatrixObject * 5.0
matrix operator*(const double scale, const matrix& rhs);
#endif
| [
"noreply@github.com"
] | boesigerg.noreply@github.com |
9a08fcee80c1b26d28c713da839f2ace03656df7 | 0fe66feeb075fe5bf88b3b7da5c13c0d0da09dc1 | /SmartHouse/SmartHouseMain/Commands.h | de50d04223e462905a7b8cfc13427bfbf78c8436 | [] | no_license | loshadka1980/SmartHouse | 7f7e45afb4125585c7f835aa0c1fcdf45cf58242 | e007a26cd67bd74397f70bf8f4530519ff6790ff | refs/heads/master | 2021-01-10T07:35:05.919752 | 2016-04-09T21:58:28 | 2016-04-09T21:58:28 | 36,606,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | h | #pragma once
#include <vector>
using SingleCommandDesc = std::pair<int, bool>;
struct CommandDesc
{
CommandDesc(){};
CommandDesc(const SingleCommandDesc& singleCommand){ listOfCommands.push_back(singleCommand); }
void addSingleCommand(int id, bool status)
{
listOfCommands.push_back(std::pair<int, bool>(id, status));
}
void addSingleCommand(const SingleCommandDesc& scmd)
{
listOfCommands.push_back(scmd);
}
bool isEmpty(void)
{
return listOfCommands.empty();
}
std::vector<SingleCommandDesc> listOfCommands;
}; | [
"roschin001@ramble.ru"
] | roschin001@ramble.ru |
82e076cdf0ed017ee98e6c79a1f8334cdd161ac8 | 00e2c6ef96decc736ffce22e59dcdfffda478a5c | /1_sem_ZS_2019-20/ZPRPR1/programy/programy k prednaskam/02_prednaska/02p02.cpp | d5fcadc72ab97757b0b527b7f20953db1d6a56ad | [] | no_license | nfssfn/FIIT | cd69a9ca780a6275111d79963a2b7b38800db241 | 18e20826c5da0dc1f30c5af7771db48368e4e6ad | refs/heads/master | 2023-08-11T10:57:13.547550 | 2021-09-22T19:04:59 | 2021-09-22T19:04:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 279 | cpp | // realne konstanty: prevod cm na inch
#include <stdio.h>
int main()
{
int vyska_cm = 0xAA;
double vyska_inch;
vyska_inch = vyska_cm * .393701;
printf("vyska: %d cm = %f inch\n", vyska_cm, vyska_inch);
printf("vyska: %f mikrometrov\n\n", vyska_cm * 1e4);
return 0;
}
| [
"emmachac@gmail.com"
] | emmachac@gmail.com |
c0aa9cd8f6309fe7603006684692eb74af180e29 | 36fe018f06ce51d576eeb50b8601d0d386b19880 | /Lab/lab5test/Cat.cpp | f55a0bf5629d5df5f12fb2d190d5a53195749698 | [] | no_license | ParanoidMarvin0/CS115 | 50e18635aa72a383198454e45f9139d260ede5cf | 4a81a458d2736548dbe2771d7a22b87484772aeb | refs/heads/master | 2020-04-01T19:18:24.378470 | 2018-12-06T00:54:13 | 2018-12-06T00:54:13 | 153,547,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,991 | cpp | #include "Cat.h"
#include <iostream>
using namespace std;
void initCat (Cat& cat, double l, double h, double tL, string eC, string fCl, const string furCol[])
{
int i = 0;
cat.length = l;
cat.height = h;
cat.tailLength = tL;
cat.eyeColour = eC;
cat.furClassification = fCl; //long, medium, short, none
while (furCol[i] != "")
{
cat.furColours[i] = furCol[i];
i++;
}
cat.furColours[i] = "";
}
void readCat (Cat& cat)
{
int i = 0;
cout << "Please decribe the cat" << endl;
cout << "Please enter a length: ";
cin >> cat.length;
cout << "Please enter a height: ";
cin >> cat.height;
cout << "Please enter a tail length: ";
cin >> cat.tailLength;
cout << "Please enter an eye colour: ";
cin >> cat.eyeColour;
cout << "Please enter a description of the fur (long, medium, short, none): ";
cin >> cat.furClassification;
cout << "Please enter the colours of the fur (separated by a space or a newline character). ";
cout << "Add \"done\" at the end: ";
cin >> cat.furColours[i];
while (cat.furColours[i] != "done")
{
i++;
cin >> cat.furColours[i];
}
cat.furColours[i] = "";
}
void printCat (const Cat& cat)
{
int i = 0;
cout << "Length: "<< cat.length << " Height: "<< cat.height
<< " Tail Length: " << cat.tailLength << endl;
cout << "Eye Colour: " << cat.eyeColour
<< " Fur Classification: " << cat.furClassification << endl;
cout << "Cat Colours: ";
while (cat.furColours[i] != "")
{
cout << cat.furColours[i++] << " ";
}
cout << endl;
}
bool isCalico (const Cat& cat)
{
if (cat.furColours[3] != "")
return false;
for (int i=0; i< 3; i++)
{
if (cat.furColours[i] != "black" &&
cat.furColours[i] != "orange" &&
cat.furColours[i] != "white")
return false;
}
return true;
}
bool isTaller (const Cat& cat1, const Cat& cat2)
{
return (cat1.height > cat2.height);
}
| [
"paranoidmarvin0@gmail.com"
] | paranoidmarvin0@gmail.com |
29b2e095777c9214cc1f91bc83d472fdfcf0f9e5 | 188fb8ded33ad7a2f52f69975006bb38917437ef | /Fluid/processor0/0.42/meshPhi | 4faca5d955e98e13d48a9b8bf039f5f9550ecd65 | [] | no_license | abarcaortega/Tuto_2 | 34a4721f14725c20471ff2dc8d22b52638b8a2b3 | 4a84c22efbb9cd2eaeda92883343b6910e0941e2 | refs/heads/master | 2020-08-05T16:11:57.674940 | 2019-10-04T09:56:09 | 2019-10-04T09:56:09 | 212,573,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,021 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: dev |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "0.42";
object meshPhi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 3 -1 0 0 0 0];
internalField nonuniform List<scalar>
879
(
4.74334e-06
1.80672e-05
5.11953e-05
4.98858e-06
1.9113e-05
9.01738e-06
5.41954e-05
8.36473e-05
5.22197e-06
2.01374e-05
9.47201e-06
5.70991e-05
1.22823e-05
8.81883e-05
0.000113474
5.47564e-06
2.11284e-05
9.93935e-06
5.99152e-05
1.29432e-05
9.25567e-05
1.43405e-05
0.000119204
0.000140539
5.7522e-06
2.20776e-05
1.04591e-05
6.26137e-05
1.36518e-05
9.67562e-05
1.52261e-05
0.000124671
1.51734e-05
0.000147151
0.00016485
6.0589e-06
2.29759e-05
1.10395e-05
6.51691e-05
1.44607e-05
0.000100738
1.62085e-05
0.000129873
1.63186e-05
0.000153391
1.48787e-05
0.000172049
0.000186411
6.40331e-06
2.38136e-05
1.16955e-05
6.75535e-05
1.53835e-05
0.000104458
1.73523e-05
0.000134744
1.76254e-05
0.00015926
1.63312e-05
0.000178763
1.36089e-05
0.000193915
9.59925e-06
0.000205218
0.00021304
6.79318e-06
2.45802e-05
1.24419e-05
6.97374e-05
1.64423e-05
0.000107872
1.86781e-05
0.000139225
1.91711e-05
0.000164675
1.8036e-05
0.000185003
1.54559e-05
0.000200878
1.16147e-05
0.00021284
6.79853e-06
0.000221405
0.0002269
7.23634e-06
2.52645e-05
1.32942e-05
7.16895e-05
1.76591e-05
0.000110931
2.02156e-05
0.000143253
2.09842e-05
0.000169562
2.00785e-05
0.000190659
1.76764e-05
0.000207227
1.39884e-05
0.000219836
9.29686e-06
0.000228965
3.84747e-06
0.000235031
-2.19346e-06
0.000238271
0.000238718
7.74052e-06
2.58552e-05
1.42671e-05
7.33773e-05
1.90562e-05
0.000113586
2.19937e-05
0.000146765
2.31005e-05
0.000173844
2.24895e-05
0.000195642
2.0338e-05
0.000212857
1.68648e-05
0.000226073
1.23248e-05
0.000235776
6.97642e-06
0.000242355
1.02732e-06
0.000246073
-5.27897e-06
0.000247189
-1.17242e-05
0.000245934
0.000242315
8.31309e-06
2.63401e-05
1.53753e-05
7.47671e-05
2.06544e-05
0.000115783
2.40399e-05
0.000149691
2.55539e-05
0.000177439
2.53092e-05
0.000199859
2.34824e-05
0.00021766
2.02924e-05
0.000231437
1.59843e-05
0.00024168
1.0806e-05
0.000248784
4.98741e-06
0.000253052
-1.23281e-06
0.00025474
-7.64611e-06
0.000254066
-1.40536e-05
0.000251321
0.000246568
8.96084e-06
2.67073e-05
1.66317e-05
7.58244e-05
2.24732e-05
0.000117469
2.63796e-05
0.000151962
2.83755e-05
0.000180264
2.85742e-05
0.000203214
2.71511e-05
0.000221529
2.43229e-05
0.000235812
2.03288e-05
0.00024656
1.5413e-05
0.000254176
9.8117e-06
0.000258983
3.75512e-06
0.000261248
-2.54675e-06
0.000261203
-8.9061e-06
0.00025906
-1.51524e-05
0.000255073
-2.11631e-05
0.000249405
0.000242035
9.6897e-06
2.69443e-05
1.8048e-05
7.65141e-05
2.45293e-05
0.000118591
2.90348e-05
0.000153508
3.15926e-05
0.000182232
3.23168e-05
0.000205608
3.13819e-05
0.000224356
2.90017e-05
0.000239081
2.54117e-05
0.000250288
2.08532e-05
0.000258387
1.55625e-05
0.000263715
9.7661e-06
0.00026655
3.67227e-06
0.000267133
-2.53275e-06
0.000265683
-8.69129e-06
0.000262409
-1.46716e-05
0.000257484
-2.03394e-05
0.000251173
-2.55999e-05
0.00024377
0.000235283
1.05044e-05
2.70388e-05
1.96334e-05
7.6801e-05
2.68364e-05
0.000119092
3.20232e-05
0.000154255
3.52271e-05
0.000183258
3.65633e-05
0.000206942
3.62057e-05
0.000226028
3.43659e-05
0.000241123
3.12758e-05
0.000252732
2.71741e-05
0.000261275
2.22954e-05
0.000267096
1.68635e-05
0.000270482
1.10847e-05
0.000271683
5.14388e-06
0.000270922
-7.98374e-07
0.00026841
-6.60406e-06
0.000264351
-1.21639e-05
0.000258973
-1.73823e-05
0.000252494
-2.21594e-05
0.00024517
-2.64328e-05
0.000237158
0.000227619
1.14082e-05
2.69784e-05
2.13941e-05
7.66498e-05
2.94037e-05
0.000118918
3.53573e-05
0.000154132
3.92942e-05
0.000183252
4.13321e-05
0.000207113
4.16446e-05
0.000226432
4.04412e-05
0.000241811
3.79512e-05
0.000253758
3.44103e-05
0.000262693
3.00508e-05
0.000268967
2.5094e-05
0.000272875
1.97446e-05
0.000274673
1.41869e-05
0.00027459
8.5825e-06
0.000272842
3.07034e-06
0.000269644
-2.23406e-06
0.000265223
-7.23377e-06
0.000259822
-1.18624e-05
0.000253723
-1.60754e-05
0.000246837
1.24024e-05
2.67509e-05
2.3333e-05
7.60253e-05
3.22355e-05
0.000118012
3.90426e-05
0.000153064
4.3801e-05
0.000182125
4.66319e-05
0.000206019
4.7709e-05
0.000225451
4.72404e-05
0.000241019
4.54528e-05
0.000253225
4.25793e-05
0.00026249
3.88495e-05
0.000269167
3.44824e-05
0.000273557
2.9681e-05
0.000275917
2.46291e-05
0.000276481
1.94886e-05
0.000275469
1.43997e-05
0.000273096
9.47994e-06
0.000269587
4.82532e-06
0.000265181
5.10006e-07
0.000260156
0.000254134
1.34863e-05
2.63441e-05
2.54486e-05
7.48928e-05
3.53297e-05
0.00011632
4.30765e-05
0.000150977
4.87446e-05
0.000179787
5.24593e-05
0.000203554
5.43953e-05
0.000222968
5.47597e-05
0.000238615
5.3777e-05
0.00025099
5.16777e-05
0.000260512
4.86886e-05
0.00026753
4.50266e-05
0.000272346
4.08929e-05
0.00027522
3.64703e-05
0.000276384
3.19211e-05
0.000276057
2.73859e-05
0.000274449
2.29839e-05
0.000271767
1.88131e-05
0.000268221
1.49529e-05
0.000264016
0.000258742
1.46564e-05
2.57463e-05
2.77345e-05
7.32178e-05
3.86772e-05
0.000113786
4.74474e-05
0.000147798
5.41105e-05
0.000176147
5.87971e-05
0.000199611
6.16837e-05
0.00021886
6.29767e-05
0.000234464
6.28987e-05
0.000246907
6.16776e-05
0.000256598
5.95378e-05
0.000263884
5.66937e-05
0.00026906
5.33447e-05
0.000272385
4.96725e-05
0.000274089
4.58388e-05
0.000274382
4.19847e-05
0.000273465
3.82305e-05
0.000271528
3.46763e-05
0.000268757
3.14047e-05
0.000265323
0.000260842
1.59068e-05
2.49458e-05
3.01788e-05
7.09665e-05
4.22608e-05
0.000110357
5.21326e-05
0.000143453
5.9871e-05
0.000171112
6.56124e-05
0.000194082
6.95357e-05
0.000213004
7.18471e-05
0.000228429
7.27678e-05
0.000240824
7.25233e-05
0.000250585
7.13353e-05
0.000258051
6.94158e-05
0.000263509
6.6962e-05
0.000267212
6.41543e-05
0.000269382
6.11534e-05
0.000270222
5.81003e-05
0.00026992
5.51157e-05
0.000268651
5.2301e-05
0.00026658
4.974e-05
0.000263864
0.000260145
1.72281e-05
2.39312e-05
3.27636e-05
6.81056e-05
4.60542e-05
0.000105976
5.7098e-05
0.000137868
6.59838e-05
0.000164592
7.28545e-05
0.000186857
7.7892e-05
0.000205275
8.13029e-05
0.000220369
8.33071e-05
0.000232585
8.41279e-05
0.000242304
8.39843e-05
0.000249849
8.30858e-05
0.000255499
8.16273e-05
0.000259494
7.97872e-05
0.00026205
7.7725e-05
0.000263356
7.55808e-05
0.000263588
7.34754e-05
0.000262908
7.15101e-05
0.000261465
6.97693e-05
0.000259399
0.000256384
1.86076e-05
2.26915e-05
3.54642e-05
6.46028e-05
5.00217e-05
0.000100593
6.22967e-05
0.00013097
7.23905e-05
0.000156493
8.04534e-05
0.000177827
8.66706e-05
0.000195546
9.12496e-05
0.000210141
9.44092e-05
0.000222033
9.63705e-05
0.000231582
9.73501e-05
0.000239093
9.75546e-05
0.000244831
9.71765e-05
0.000249025
9.63918e-05
0.000251874
9.53583e-05
0.000253559
9.42147e-05
0.000254241
9.30808e-05
0.000254067
9.20575e-05
0.000253174
9.12288e-05
0.000251686
0.000249304
2.00292e-05
2.12162e-05
3.82494e-05
6.04268e-05
5.41172e-05
9.41546e-05
6.76679e-05
0.000122688
7.90158e-05
0.000146726
8.83186e-05
0.000166883
9.57654e-05
0.00018369
0.000101565
0.000197602
0.000105934
0.000209008
0.000109094
0.000218245
0.000111257
0.000225595
0.000112628
0.000231307
0.000113396
0.000235592
0.000113735
0.000238636
0.0001138
0.000240604
0.000113727
0.000241644
0.000113636
0.000241891
0.000113626
0.000241464
0.000113779
0.000240477
0.000238653
2.14731e-05
1.94952e-05
4.10806e-05
5.55477e-05
5.82841e-05
8.66118e-05
7.31371e-05
0.000112952
8.57666e-05
0.000135202
9.63382e-05
0.000153918
0.000105045
0.000169583
0.000112096
0.000182609
0.00011771
0.000193353
0.000122103
0.00020212
0.000125488
0.000209169
0.000128065
0.000214726
0.000130022
0.000218984
0.000131527
0.000222113
0.000132735
0.000224262
0.000133779
0.000225564
0.000134776
0.000226139
0.000135823
0.000226093
0.000137001
0.000225525
0.000224184
2.29162e-05
1.75193e-05
4.39125e-05
4.99379e-05
6.24553e-05
7.79183e-05
7.86155e-05
0.000101698
9.25321e-05
0.000121837
0.000104378
0.000138831
0.000114351
0.000153105
0.000122662
0.000165028
0.000129527
0.000174915
0.000135164
0.000183039
0.000139782
0.000189632
0.000143577
0.000194893
0.000146735
0.000198996
0.000149422
0.000202091
0.000151788
0.00020431
0.000153965
0.00020577
0.000156066
0.000206575
0.000158186
0.00020682
0.000160403
0.000206587
0.000205654
2.43321e-05
1.528e-05
4.66931e-05
4.35723e-05
6.6554e-05
6.80318e-05
8.40008e-05
8.88655e-05
9.91838e-05
0.000106555
0.000112283
0.000121526
0.0001235
0.000134145
0.000133048
0.00014473
0.000141144
0.000153552
0.000148003
0.000160846
0.000153831
0.000166814
0.000158824
0.000171627
0.000163164
0.000175434
0.000167014
0.000178366
0.00017052
0.000180536
0.000173812
0.000182043
0.000177
0.000182978
0.000180175
0.000183418
0.000183413
0.000183435
0.000182834
2.56918e-05
1.27702e-05
4.93654e-05
3.64292e-05
7.04946e-05
5.69159e-05
8.91783e-05
7.44034e-05
0.000105577
8.92886e-05
0.000119877
0.000101922
0.000132284
0.000112606
0.000143014
0.000121602
0.000152283
0.000129136
0.000160305
0.0001354
0.000167287
0.000140561
0.00017342
0.000144761
0.000178884
0.000148123
0.00018384
0.000150755
0.000188431
0.00015275
0.000192784
0.00015419
0.000197004
0.000155147
0.000201182
0.000155686
0.000205388
0.000155865
0.00015552
2.6965e-05
9.98408e-06
5.18687e-05
2.84916e-05
7.41853e-05
4.45415e-05
9.40236e-05
5.82696e-05
0.000111552
6.99825e-05
0.000126965
7.995e-05
0.000140471
8.84057e-05
0.000152287
9.55513e-05
0.000162632
0.00010156
0.00017172
0.000106582
0.000179755
0.000110745
0.000186928
0.000114159
0.000193417
0.000116919
0.000199379
0.000119107
0.000204958
0.000120796
0.000210274
0.000122049
0.000215433
0.000122921
0.000220522
0.00012346
0.000225607
0.000123712
0.00012355
2.81222e-05
6.91784e-06
5.41425e-05
1.97475e-05
7.75318e-05
3.08883e-05
9.84061e-05
4.04353e-05
0.000116942
4.85985e-05
0.000133338
5.55625e-05
0.000147808
6.14871e-05
0.000160573
6.65099e-05
0.000171852
7.07498e-05
0.00018186
7.43087e-05
0.000190801
7.72741e-05
0.000198866
7.97215e-05
0.000206231
8.17156e-05
0.000213054
8.3313e-05
0.000219474
8.45626e-05
0.000225612
8.55074e-05
0.000231572
8.61851e-05
0.000237438
8.66288e-05
0.000243274
8.68685e-05
8.68185e-05
2.91388e-05
3.56913e-06
5.61322e-05
1.01903e-05
8.04437e-05
1.59453e-05
0.000102196
2.08842e-05
0.000121572
2.51145e-05
0.000138777
2.87306e-05
0.000154031
3.18138e-05
0.000167556
3.44344e-05
0.000179575
3.66529e-05
0.000190306
3.85212e-05
0.000199953
4.00841e-05
0.000208708
4.13798e-05
0.000216747
4.24415e-05
0.000224228
4.3298e-05
0.000231291
4.39741e-05
0.000238058
4.44916e-05
0.00024463
4.48697e-05
0.000251092
4.51249e-05
0.00025751
4.52716e-05
4.52691e-05
3.00014e-05
5.78158e-05
8.28876e-05
0.000105345
0.000125381
0.000143204
0.000159039
0.000173114
0.000185657
0.000196885
0.00020701
0.000216224
0.000224705
0.000232615
0.000240093
0.000247263
0.00025423
0.000261079
0.000267881
)
;
boundaryField
{
inlet
{
type calculated;
value uniform 0;
}
outlet
{
type calculated;
value nonuniform 0();
}
flap
{
type calculated;
value nonuniform 0();
}
upperWall
{
type calculated;
value nonuniform List<scalar>
20
(
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
-8.52589e-15
0
0
0
-7.71978e-15
)
;
}
lowerWall
{
type calculated;
value nonuniform 0();
}
frontAndBack
{
type empty;
value nonuniform 0();
}
procBoundary0to1
{
type processor;
value nonuniform List<scalar>
18
(
-2.99954e-05
-1.97396e-05
0.000238215
-3.48729e-06
1.12858e-05
2.81915e-05
4.70982e-05
6.78065e-05
9.00363e-05
0.000113426
0.000137535
0.000161841
0.000185745
0.000208569
0.000229559
0.000247885
0.000262637
0.000273354
)
;
}
procBoundary0to3
{
type processor;
value nonuniform List<scalar>
34
(
-1.69824e-05
-4.80307e-05
8.46537e-06
-7.88259e-05
1.15194e-05
-0.000107345
1.33697e-05
-0.00013339
1.39826e-05
-0.000156945
1.34459e-05
-0.000178064
1.19127e-05
-0.000196792
-0.00020337
4.5933e-06
-0.000217414
1.2216e-06
-0.000229285
-0.000228403
-8.54624e-06
-0.000236354
-0.000230975
-1.8081e-05
-0.000235889
-2.02532e-05
-0.000239513
-0.000230082
-2.67627e-05
-0.000233018
-0.00022249
-3.03257e-05
-0.000225644
-0.000214467
)
;
}
}
// ************************************************************************* //
| [
"aldo.abarca.ortega@gmail.com"
] | aldo.abarca.ortega@gmail.com | |
2ba92ed8fe68e0509dd5b08ea4dbbc9b88e41833 | 2536dc36d24a6c4783597f00e57fdd899189c4cb | /Multiples.cpp | 03b0df24399395e060617c8f1de5bc15a8f32ef1 | [
"MIT"
] | permissive | aaryan0348/E-Lab-Object-Oriented-Programming | 363a2375cba9e89c5d50a0d84a3cc7cb644a9f6c | 29f3ca80dbf2268441b5b9e426415650a607195a | refs/heads/master | 2020-07-11T23:34:14.945864 | 2019-09-04T09:17:20 | 2019-09-04T09:17:20 | 204,666,504 | 0 | 0 | MIT | 2019-08-27T14:50:35 | 2019-08-27T09:20:35 | null | UTF-8 | C++ | false | false | 327 | cpp | #include <iostream>
using namespace std;
class base
{
public:
virtual void mTable()=0;
};
class derived:public base
{
public:int a;
void mTable(){for(int i=0;i<5;i++)cout << a*(i+1)<<" ";};
void input(){cin >> a;}
};
int main()
{
base *b;
derived d;
b=&d;
d.input();
b->mTable();
return 0;
} | [
"noreply@github.com"
] | aaryan0348.noreply@github.com |
c08bd1a2e30058134c1339d14f6b7246069f3a57 | 4ad26968ff4256966992edb434570332b8cb5853 | /HairChange/HairChange/boost/compute/random/bernoulli_distribution.hpp | 8a88236f7bdc1f2e97dbbc1ac03c945fdd8c5660 | [
"MIT"
] | permissive | daliborristic883/HairColorChange | 582bcbe5dfd9f670438e1d770b8221c756929640 | 286ef0a8c89c4f63072ee8c8404178aac897cad5 | refs/heads/master | 2022-08-02T04:25:35.032365 | 2020-05-29T19:48:25 | 2020-05-29T19:48:25 | 267,933,189 | 19 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,852 | hpp | //---------------------------------------------------------------------------//
// Copyright (c) 2014 Roshan <thisisroshansmail@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//
#ifndef BOOST_COMPUTE_RANDOM_BERNOULLI_DISTRIBUTION_HPP
#define BOOST_COMPUTE_RANDOM_BERNOULLI_DISTRIBUTION_HPP
#include <boost/compute/command_queue.hpp>
#include <boost/compute/function.hpp>
#include <boost/compute/types/fundamental.hpp>
#include <boost/compute/detail/iterator_range_size.hpp>
#include <boost/compute/detail/literal.hpp>
namespace boost {
namespace compute {
///
/// \class bernoulli_distribution
/// \brief Produces random boolean values according to the following
/// discrete probability function with parameter p :
/// P(true/p) = p and P(false/p) = (1 - p)
///
/// The following example shows how to setup a bernoulli distribution to
/// produce random boolean values with parameter p = 0.25
///
/// \snippet test/test_bernoulli_distribution.cpp generate
///
template<class RealType = float>
class bernoulli_distribution
{
public:
/// Creates a new bernoulli distribution
bernoulli_distribution(RealType p = 0.5f)
: m_p(p)
{
}
/// Destroys the bernoulli_distribution object
~bernoulli_distribution()
{
}
/// Returns the value of the parameter p
RealType p() const
{
return m_p;
}
/// Generates bernoulli distributed booleans and stores
/// them in the range [\p first, \p last).
template<class OutputIterator, class Generator>
void generate(OutputIterator first,
OutputIterator last,
Generator &generator,
command_queue &queue)
{
size_t count = detail::iterator_range_size(first, last);
vector<uint_> tmp(count, queue.get_context());
generator.generate(tmp.begin(), tmp.end(), queue);
BOOST_COMPUTE_FUNCTION(bool, scale_random, (const uint_ x),
{
return (convert_RealType(x) / MAX_RANDOM) < PARAM;
});
scale_random.define("PARAM", detail::make_literal(m_p));
scale_random.define("MAX_RANDOM", "UINT_MAX");
scale_random.define(
"convert_RealType", std::string("convert_") + type_name<RealType>()
);
transform(
tmp.begin(), tmp.end(), first, scale_random, queue
);
}
private:
RealType m_p;
};
} // end compute namespace
} // end boost namespace
#endif // BOOST_COMPUTE_RANDOM_BERNOULLI_DISTRIBUTION_HPP
| [
"daliborristic883@gmail.com"
] | daliborristic883@gmail.com |
e97c8a56a3856893a599cbf85e633ff1f58a5c22 | ee0b1e7bcb3f6feb57ef7475ec0e8369f41f0bb3 | /Array/CombinationSum.cpp | efb2f5977044cc78cf13432131ceb4a951ab2a09 | [] | no_license | AlexLai1990/LintCode_OJ_-_- | c9d3cfa7f83a61ba98c36c59950ae28cdeb905f0 | 9125c384e6f75b1039546727f1d41a165645d645 | refs/heads/master | 2020-12-24T08:18:09.293613 | 2015-03-16T07:11:57 | 2015-03-16T07:11:57 | 27,499,993 | 2 | 1 | null | 2016-08-09T00:24:48 | 2014-12-03T17:56:49 | C++ | UTF-8 | C++ | false | false | 1,204 | cpp | class Solution {
public:
/**
* @param candidates: A list of integers
* @param target:An integer
* @return: A list of lists of integers
*/
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
// write your code here
vector<vector<int> > m_ret;
if (candidates.size() == 0)
return m_ret;
sort(candidates.begin(), candidates.end());
vector<int> curr;
combinationSumHelper(candidates, curr, 0, target, 0, m_ret);
return m_ret;
}
void combinationSumHelper(vector<int> &candidates, vector<int> curr, int start_index,
int target, int curr_sum, vector<vector<int> >&m_ret) {
if (curr_sum > target)
return ;
if (curr_sum == target) {
m_ret.push_back(curr);
return;
}
for (int i = start_index; i < candidates.size(); i++) {
int temp_curr_sum = curr_sum + candidates[i];
curr.push_back(candidates[i]);
combinationSumHelper(candidates, curr, i, target, temp_curr_sum, m_ret);
curr.pop_back();
}
return;
}
};
| [
"xincheng.lai@gmail.com"
] | xincheng.lai@gmail.com |
4cc33c5b2b8f8ff36cf15ad1b421e4fbdb444692 | b7cb693df78d0b79ef52ee9ed5e31abe9cfafbac | /C++Tut/PrintingMDArrays_35.cpp | 973a41854dc83062198012d6d90e9719b93609af | [
"MIT"
] | permissive | dedhun/Ded_CP | 43dbda6a5448772be2ef002bb51577306be284ac | 593abfbf703199f748633600041c251c39d76cfe | refs/heads/master | 2022-11-07T04:41:23.275173 | 2020-06-25T00:33:32 | 2020-06-25T00:33:32 | 274,648,638 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 340 | cpp | //
// Created by Jihun on 6/24/2020.
//
#include <iostream>
using namespace std;
int main() {
int bertha[2][3] = {{1, 2, 3}, {7, 8 , 9}};
for (int row=0; row < 2; row++) {
for (int column = 0; column < 3; column++) {
cout << bertha[row][column] << " ";
}
cout << endl;
}
}
| [
"noreply@github.com"
] | dedhun.noreply@github.com |
a968bcd8bb087fd57c43dc7446b224f664436f54 | d31c4ca988650b26a2998d3d62d659c878325402 | /Table.cpp | 6a256b435e00333a5609cf81a6bd9aba15e7844b | [] | no_license | msalguero/ProyectoOrganizacion | e911598c19df93c5927d06f2db36de4d91e758a2 | 5a7d0785b1fb94275b645980ccdaec2713b76125 | refs/heads/master | 2020-05-19T15:47:39.191822 | 2014-12-16T02:28:07 | 2014-12-16T02:28:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,040 | cpp | #include "Table.h"
#include <QDebug>
Table::Table(char* nombre="")
{
//ctor
metaData = new MetaDataReg(nombre);
// metaData->setName(nombre);
registros = new Lista<Register*>();
}
Table::~Table()
{
//dtor
}
void Table::agregarRegistro(char* data)
{
Register* registro = new Register(metaData);
registro->fromBytes(data);
registros->Agregar(registro);
metaData->cantRegistros++;
}
void Table::agregarRegistro(Register* registro)
{
qDebug()<<"Se agrego un registro";
registros->Agregar(registro);
metaData->cantRegistros++;
}
void Table::agregarCampo(int tipoDato, char* nombreCampo, int tamanio)
{
metaData->newField(tipoDato, nombreCampo, tamanio);
}
void Table::recibirBloqueRegistros(char* bloque)
{
int cantRegistros = metaData->cantRegistros;
qDebug()<<cantRegistros;
int tamRegistro = metaData->getSizeRegistro();
char* bytesRegistro = (char*) malloc(tamRegistro);
int pos = 0;
for(int i = 0; i<cantRegistros; i++)
{
Register* reg = new Register(metaData);
memcpy(bytesRegistro, &(bloque[pos]), tamRegistro);
pos+=tamRegistro;
reg->fromBytes(bytesRegistro);
registros->Agregar(reg);
}
}
void Table::recibirMetaDataTabla(char* data)
{
metaData->fromBytes(data);
}
void Table::recibirMetaDataCampos(char* data)
{
metaData->setMetaDataBytes(data);
}
char* Table::mandarRegistros()
{
int tamRegistro = metaData->getSizeRegistro();
char* data = (char*)malloc(metaData->cantRegistros*tamRegistro);
int pos = 0;
for(int i = 0; i<metaData->cantRegistros; i++)
{
Register* registro = registros->Recupera(i);
char* bytesRegistro = (char*)malloc(tamRegistro);
registro->toBytes(bytesRegistro);
memcpy(&(data[pos]), bytesRegistro, tamRegistro);
pos+=tamRegistro;
}
return data;
}
char* Table::mandarMetaDataTabla()
{
return metaData->toBytes();
}
char* Table::mandarMetaDataCampos()
{
return metaData->getMetaDataBytes();
}
| [
"msalguero@unitec.edu"
] | msalguero@unitec.edu |
0902ba34f4568bb664714965894a661628738fa6 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/067/946/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memcpy_73b.cpp | ff24a997d22a6094f41bd683100073d696a046a1 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,900 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memcpy_73b.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193.label.xml
Template File: sources-sink-73b.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate memory for a string, but do not allocate space for NULL terminator
* GoodSource: Allocate enough memory for a string and the NULL terminator
* Sinks: memcpy
* BadSink : Copy string to data using memcpy()
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
#ifndef _WIN32
#include <wchar.h>
#endif
/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING "AAAAAAAAAA"
using namespace std;
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memcpy_73
{
#ifndef OMITBAD
void badSink(list<char *> dataList)
{
/* copy data out of dataList */
char * data = dataList.back();
{
char source[10+1] = SRC_STRING;
/* Copy length + 1 to include NUL terminator from source */
/* POTENTIAL FLAW: data may not have enough space to hold source */
memcpy(data, source, (strlen(source) + 1) * sizeof(char));
printLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<char *> dataList)
{
char * data = dataList.back();
{
char source[10+1] = SRC_STRING;
/* Copy length + 1 to include NUL terminator from source */
/* POTENTIAL FLAW: data may not have enough space to hold source */
memcpy(data, source, (strlen(source) + 1) * sizeof(char));
printLine(data);
delete [] data;
}
}
#endif /* OMITGOOD */
} /* close namespace */
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
3d512a3db41778cbb1175a3b03aa01c867f7fda8 | 40f25cc8b7f86bb04afbdba88aea16243a3143c1 | /NUMB3RS/numb3rs.cpp | 44494e3b5ccc7203a84d76a321361b1f663369bb | [] | no_license | rlaskarb09/AlgorithmProblemSolvingStrategies | 5b342f30fc6c44b29da5e4e9770de7975439af74 | 30aef078a23e2c9ff90a9048c8b01321d8405398 | refs/heads/main | 2023-01-13T22:41:58.026992 | 2020-11-04T06:23:16 | 2020-11-04T06:23:16 | 304,533,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,879 | cpp | #include <bits/stdc++.h>
using namespace std;
const int MAX_TEST_CASES = 50;
const int MAX_CITIES = 50;
const int MAX_DAYS = 100;
double transfer[MAX_CITIES][MAX_CITIES];
double locateProb[MAX_DAYS + 1][MAX_CITIES];
void calcLocateProb(int numOfCities, int days) {
for (int i = 1; i <= days; ++i) {
for (int j = 0; j < numOfCities; ++j) {
for (int k = 0; k < numOfCities; ++k) {
locateProb[i][j] += locateProb[i-1][k] * transfer[k][j];
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int numOfTestCases;
cin >> numOfTestCases;
int numOfCities, days, start;
for (int caseIdx = 0; caseIdx < numOfTestCases; ++caseIdx) {
cin >> numOfCities >> days >> start;
for (int i = 0; i < numOfCities; ++i) {
int count = 0;
for (int j = 0; j < numOfCities; ++j) {
int inputNum;
cin >> inputNum;
transfer[i][j] = inputNum;
if (inputNum == 1) count++;
}
if (count > 0)
for (int j = 0; j < numOfCities; ++j) {
transfer[i][j] /= count;
}
}
// init locate probability
for (int i = 0; i <= days; ++i) {
for (int j = 0; j < numOfCities; ++j) {
locateProb[i][j] = 0;
}
}
locateProb[0][start] = 1.0;
// calculate probabilities
calcLocateProb(numOfCities, days);
// print probabilities of each cities
int numOfPrints;
cin >> numOfPrints;
for (int i = 0; i < numOfPrints; ++i) {
int cityIdx;
cin >> cityIdx;
cout << setprecision(8) << locateProb[days][cityIdx] << ' ';
}
cout << '\n';
}
return 0;
} | [
"rlaskarb09@naver.com"
] | rlaskarb09@naver.com |
0bc536af5c46d15aa2d7ae5e726ba313235e1094 | 6c6ac89ff6f86ad25396e5a90944e94efefbad38 | /source/RSErasureEncoder.cpp | 00c963a748b895104d09b1b8400ed6278088b377 | [] | no_license | mattlentz/ebn-sddr | dbc1614111eb73ef36770e519e1ed63290f34174 | 0573df54fe672321f4c30e009e0309b890d9f6d1 | refs/heads/master | 2021-04-09T16:46:46.889716 | 2015-05-28T18:57:30 | 2015-05-28T18:57:30 | 21,573,151 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,591 | cpp | #include "RSErasureEncoder.h"
extern "C"
{
#include "jerasure/jerasure.h"
#include "jerasure/reed_sol.h"
}
using namespace std;
RSErasureEncoder::RSErasureEncoder(const RSMatrix &matrix)
: matrix_(matrix),
partSymbols_(matrix.getNumParts()),
partSymbolPtrs_(matrix.getNumParts()),
symbols_((matrix.K() + matrix.M()) * matrix.W(), 0)
{
size_t KM = matrix.K() + matrix.M();
for(size_t p = 0; p < matrix.getNumParts(); p++)
{
partSymbols_[p].resize(KM * sizeof(long));
partSymbolPtrs_[p].resize(KM);
for(size_t s = 0; s < KM; s++)
{
partSymbolPtrs_[p][s] = &partSymbols_[p][s * sizeof(long)];
}
}
}
RSErasureEncoder::RSErasureEncoder(const RSErasureEncoder &other)
: matrix_(other.matrix_),
partSymbols_(other.partSymbols_),
partSymbolPtrs_(matrix_.getNumParts()),
symbols_(other.symbols_)
{
size_t KM = matrix_.K() + matrix_.M();
for(size_t p = 0; p < matrix_.getNumParts(); p++)
{
partSymbolPtrs_[p].resize(KM);
for(size_t s = 0; s < KM; s++)
{
partSymbolPtrs_[p][s] = &partSymbols_[p][s * sizeof(long)];
}
}
}
RSErasureEncoder& RSErasureEncoder::operator = (const RSErasureEncoder &other)
{
matrix_ = other.matrix_;
partSymbols_ = other.partSymbols_;
partSymbolPtrs_ = vector<vector<char*> >(matrix_.getNumParts());
symbols_ = other.symbols_;
size_t KM = matrix_.K() + matrix_.M();
for(size_t p = 0; p < matrix_.getNumParts(); p++)
{
partSymbolPtrs_[p].resize(KM);
for(size_t s = 0; s < KM; s++)
{
partSymbolPtrs_[p][s] = &partSymbols_[p][s * sizeof(long)];
}
}
return *this;
}
void RSErasureEncoder::encode(const uint8_t *data)
{
for(size_t k = 0; k < matrix_.K(); k++)
{
for(size_t p = 0; p < matrix_.getNumParts(); p++)
{
long symbol = 0;
for(size_t b = 0; b < matrix_.getPartW(p); b++)
{
symbol |= *(data++) << (8 * b);
}
*((long *)&partSymbols_[p][k * sizeof(long)]) = symbol;
}
}
for(size_t p = 0; p < matrix_.getNumParts(); p++)
{
jerasure_matrix_encode(matrix_.K(), matrix_.M(), 8 * matrix_.getPartW(p), matrix_.getMatrix(p), partSymbolPtrs_[p].data(), &partSymbolPtrs_[p][matrix_.K()], sizeof(long));
}
uint8_t *pSymbols = symbols_.data();
for(size_t s = 0; s < (matrix_.K() + matrix_.M()); s++)
{
for(size_t p = 0; p < matrix_.getNumParts(); p++)
{
long symbol = *((long *)&partSymbols_[p][s * sizeof(long)]);
for(size_t b = 0; b < matrix_.getPartW(p); b++)
{
*(pSymbols++) = (symbol >> (8 * b)) & 0xFF;
}
}
}
}
| [
"mlentz@cs.umd.edu"
] | mlentz@cs.umd.edu |
27f3063403114099561a9d151fc46c79c1fb05ec | 9fbb56ec06ecbb1c8b864164def247ad8d6aa64e | /Lecturer.cpp | 4f481083641102357bdfe388d1929c3e97680f01 | [] | no_license | hadeson/USTHStudentManagement_NEW | fd8209c2613d38bd9d1e31262b26ebeb5c599e86 | 6ab9ed48193217c2bcd51c65803c6e4939bbe3a6 | refs/heads/master | 2016-09-06T08:38:01.110178 | 2014-03-21T06:30:05 | 2014-03-21T06:30:05 | 17,580,902 | 0 | 2 | null | 2014-03-10T04:00:56 | 2014-03-10T03:38:14 | C++ | UTF-8 | C++ | false | false | 815 | cpp | #include "Lecturer.h"
Lecturer::Lecturer():Person() {
}
Lecturer::~Lecturer() {
field = "";
title = "";
years = 0;
}
Lecturer::Lecturer (int id, string name, string dOB, string address,
string field, string title, int years)
:Person (id, name, dOB, address) {
this->field = field;
this->title = title;
this->years = years;
}
//Person (Person);
void Lecturer::Print() {
Person::Print();
cout << ":"<< field << ":";
cout << title << ":";
cout << years;
}
void Lecturer::Set_years(int years) {
this->years = years;
}
void Lecturer::Set_field(string field) {
this->field = field;
}
void Lecturer::Set_title(string title) {
this->title = title;
}
int Lecturer::Get_years() {
return years;
}
string Lecturer::Get_field() {
return field;
}
string Lecturer::Get_title() {
return title;
}
| [
"caothanhson94@gmail.com"
] | caothanhson94@gmail.com |
6deae650fc3f54b9ff351af99a5664f10489bd6a | 69957429158cc2baff2b718b8d0e54c4dd4661b8 | /chap07/list0709.cpp | 4064ded6a6de91b3d817b3e3f5674e5087968546 | [] | no_license | chc1129/MeikaiCpp | d7bbbab37a7f7ab7de5d467d097ef2dd8b5ad5f4 | 4140133fbb87f9644ce62aa1b2ef470b16afca72 | refs/heads/main | 2023-04-12T13:39:55.451715 | 2021-05-02T02:12:13 | 2021-05-02T02:12:13 | 357,937,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 723 | cpp | // 配列の要素の並びを反転する(関数版)
#include <iostream>
using namespace std;
//--- 要素数nの配列aの並びを反転する ---//
void reverse(int a[], int n)
{
for (int i = 0; i < n / 2; i++) {
int t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
int main()
{
const int n = 5; // 配列cの要素数
int c[n];
for (int i = 0; i < n; i++) { // 各要素に値を読み込む
cout << "c[" << i << "] : ";
cin >> c[i];
}
reverse(c, n); // 配列cの要素の並びを反転する
cout << "要素の並びを反転しました。\n";
for (int i = 0; i < n; i++) // 配列cを表示
cout << "c[" << i << "] = " << c[i] << '\n';
}
| [
"chc1129@gmail.com"
] | chc1129@gmail.com |
c4fb5092dec43e6ea5f4920081cd909a5094c59d | 3901c417970b095021a284dac0ce6eabc9e1db1e | /include/terrainclass.h | cfffa3238aaddda3f343d9d5b365073b8d6555d8 | [] | no_license | manituan/DirectX-10-Engine | 518e85f2e29b03b22b729dcf8ef98a4409d2e373 | a922cf299c18aeb45db4af0545faa280c823eb29 | refs/heads/master | 2021-01-19T08:15:51.227389 | 2012-05-12T13:32:59 | 2012-05-12T13:32:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,788 | h | ////////////////////////////////////////////////////////////////////////////////
// Filename: terrainclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _TERRAINCLASS_H_
#define _TERRAINCLASS_H_
/////////////
// GLOBALS //
/////////////
const int TEXTURE_REPEAT = 8;
//////////////
// INCLUDES //
//////////////
#include <fstream>
using namespace std;
///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "textureclass.h"
////////////////////////////////////////////////////////////////////////////////
// Class name: TerrainClass
////////////////////////////////////////////////////////////////////////////////
class TerrainClass
{
private:
struct VertexType
{
D3DXVECTOR3 position;
D3DXVECTOR2 texture;
D3DXVECTOR3 normal;
D3DXVECTOR4 color;
};
struct HeightMapType
{
float x, y, z;
float tu, tv;
float nx, ny, nz;
float r, g, b;
};
struct VectorType
{
float x, y, z;
};
public:
TerrainClass();
TerrainClass(const TerrainClass&);
~TerrainClass();
bool Initialize(ID3D10Device*, char*, WCHAR*, char*);
void Shutdown();
int GetVertexCount();
ID3D10ShaderResourceView* GetTexture();
void CopyVertexArray(void*);
private:
bool LoadHeightMap(char*);
void NormalizeHeightMap();
bool CalculateNormals();
void ShutdownHeightMap();
void CalculateTextureCoordinates();
bool LoadTexture(ID3D10Device*, WCHAR*);
void ReleaseTexture();
bool LoadColorMap(char*);
bool InitializeBuffers();
void ShutdownBuffers();
private:
VertexType* m_vertices;
int m_vertexCount;
int m_terrainWidth, m_terrainHeight;
HeightMapType* m_heightMap;
TextureClass* m_Texture;
};
#endif | [
"manituan@gmail.com"
] | manituan@gmail.com |
1636bb65dec99f9e3ed8e56294e8d6746539004a | 542c81463a14d3918b986a1f997e1dde4bad6ca1 | /lamp_basic.ino | 94bf1efdc0067ce516632f5c627917092699d420 | [
"MIT"
] | permissive | westberliner/lamp_basic | 0d5d368164c2015208ce4422572457382d8f12cf | 6e900e8d013c68075f49150da11830d1ce7ac113 | refs/heads/master | 2021-01-21T17:24:09.760821 | 2017-05-21T11:05:43 | 2017-05-21T11:05:43 | 91,951,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,314 | ino | /**
* lamp basic
* sleep time - https://github.com/esp8266/Arduino/issues/1381
* connects to wifi
* connects to mqtt
* just waits and toggle lamp
*
*/
/**
* GPIO Mapping
* static const uint8_t D0 = 16; // Reset - Deep Sleep
* static const uint8_t D1 = 5;
* static const uint8_t D2 = 4;
* static const uint8_t D3 = 0;
* static const uint8_t D4 = 2; // Status LED
* static const uint8_t D5 = 14;
* static const uint8_t D6 = 12;
* static const uint8_t D7 = 13;
* static const uint8_t D8 = 15;
* static const uint8_t D9 = 3;
* static const uint8_t D10 = 1;
*/
/**
* Additional Libraries
*/
#include <ESP8266WiFi.h> // wifi library
#include <PubSubClient.h> // mqtt client library
#include <Bounce2.h> // buttonswitch handling library
#include <EEPROM.h> // write/read eeprom library
#include <everytime.h> // timer library to set timeouts
#include <TaskScheduler.h> // addtional timing
#include <stdlib.h> // string conversion
extern "C" {
#include "user_interface.h" // additional types library
}
/**
* wlan settings
*/
const char* ssid = "";
const char* wlanPasrword = "";
IPAddress router(192, 168, 178, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress fixedIP(192, 168, 178, 152);
/**
* mqtt settings
*/
const char mqttClientServer[] = "192.168.178.33";
const char mqttClientId[] = "home/bedroom/lamp/0"; // location/room/type/id
const char mqttSubscribeCommand[] = "home/bedroom/lamp/0/toggle"; // location/room/type/id/command
const char mqttSubscribeGetStatus[] = "home/bedroom/lamp/0/get/status"; // location/room/type/id/overwrite/status
const char mqttPublishStatus[] = "home/bedroom/lamp/0/status"; // location/room/type/id/status
/**
* system settings
*/
const byte statusGPIO = B10; // 2
const bool debugMode = true;
/**
* shutter status
*/
bool currentStatus = false;
/**
* instantiate objects
*/
WiFiClient espClient;
PubSubClient client(espClient);
/**
* Main Loop
*/
void loop() {
// loop for mqtt
client.loop();
}
/**
* mqtt
*/
void mqttEventHandler(char* topic, byte* payload, unsigned int length) {
char msg[length];
for (int i = 0; i < length; i++) {
msg[i] = (char)payload[i];
}
if(debugMode) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
Serial.print(msg);
Serial.println();
}
if(!strcmp(mqttSubscribeCommand ,topic)) {
if(debugMode) {
Serial.println("command");
}
toggleCommand();
}
if(!strcmp(mqttSubscribeGetStatus ,topic)) {
sendCurrentStatus();
if(debugMode) {
Serial.println("overwrite status");
}
}
}
void mqttConnect() {
// Loop until we're reconnected
while (!client.connected()) {
if(debugMode) {
Serial.print("Attempting MQTT connection...");
}
// Attempt to connect
if (client.connect(mqttClientId)) {
if(debugMode) {
Serial.println("connected");
}
// subscribe
client.subscribe(mqttSubscribeCommand);
client.subscribe(mqttSubscribeGetStatus);
sendCurrentStatus();
} else {
if(debugMode) {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
}
// Wait 5 seconds before retrying
delay(5000);
}
}
}
/**
* commandHandler
*/
void toggleCommand() {
if(debugMode) {
Serial.print("toggle Command\n");
}
if(currentStatus) {
currentStatus = false;
digitalWrite(statusGPIO, HIGH);
} else {
currentStatus = true;
digitalWrite(statusGPIO, LOW);
}
sendCurrentStatus();
}
/**
* getCurrentStatus
*/
char sendCurrentStatus() {
if(currentStatus) {
client.publish(mqttPublishStatus, "on");
} else {
client.publish(mqttPublishStatus, "off");
}
}
/**
* Setup
*/
void setup() {
// start debug mode
if(debugMode) {
Serial.begin(115200);
Serial.print("\n");
Serial.print("Start Debugmode\n");
rst_info *resetInfo;
resetInfo = ESP.getResetInfoPtr();
Serial.println(resetInfo->reason);
if( resetInfo->reason == REASON_DEEP_SLEEP_AWAKE ) {
Serial.println("Deep Sleep Reset");
} else {
Serial.println("Other Reset Reason");
}
}
// setup button
setupGpio();
// setup wifi
setupWifi();
// setup mqtt
setupMQTT();
}
void setupGpio() {
if(debugMode) {
Serial.print("Setup GPIOs\n");
}
pinMode(statusGPIO, OUTPUT);
if(currentStatus) {
digitalWrite(statusGPIO, LOW);
} else {
digitalWrite(statusGPIO, HIGH);
}
}
void setupWifi() {
// We start by connecting to a WiFi network
if(debugMode) {
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
}
// we use a fixed ip for quick access
WiFi.begin(ssid, wlanPassword);
WiFi.config(fixedIP, router, subnet, router, router);
while (WiFi.status() != WL_CONNECTED) {
for(int i = 0; i<500; i++){
delay(1);
}
if(debugMode) {
Serial.print(".");
}
}
if(debugMode) {
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
}
void setupMQTT() {
client.setServer(mqttClientServer, 1883);
client.setCallback(mqttEventHandler);
mqttConnect();
}
| [
"patrick@westberliner.net"
] | patrick@westberliner.net |
8a343254c721ffa95425e7e13b649ebbb3c6a054 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/squid/old_hunk_5060.cpp | fb233487d06c6ad1ec3b935579c4fdf41a3e6e60 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 340 | cpp | req->action = xstrdup(q);
}
make_pub_auth(req);
debug(1) fprintf(stderr, "cmgr: got req: host: '%s' port: %d uname: '%s' passwd: '%s' auth: '%s' oper: '%s'\n",
safe_str(req->hostname), req->port, safe_str(req->user_name), safe_str(req->passwd), safe_str(req->pub_auth), safe_str(req->action));
| [
"993273596@qq.com"
] | 993273596@qq.com |
8e8ac9244adddbedb4b47877a067918f1f9dbd8b | a7e734a32c5684c229da502ef57edb3c69a65885 | /add_edit_forms/addoredit_gak_bally.cpp | 2b6a000cbfd0edb0c612e71d7b9593ca85feb5c9 | [] | no_license | lingnanxiaocai666/kafpocs | 8eb57f3105006fde424284f7cc334de8161cc767 | f3302e875232cc1eb3e07c4555e97dd78f2ab7db | refs/heads/master | 2021-05-17T06:55:54.337849 | 2014-05-14T09:08:13 | 2014-05-14T09:08:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,737 | cpp | #include "addoredit_gak_bally.h"
#include "ui_addoredit_gak_bally.h"
#include "delegates/readonlydelegate.h"
#include "delegates/checkboxdelegate.h"
#include "delegates/spinboxdelegate.h"
addoredit_gak_bally::addoredit_gak_bally(QWidget *parent, int id_gak) :
QDialog(parent),
id_gak(id_gak),
ui(new Ui::addoredit_gak_bally)
{
ui->setupUi(this);
if (! dal_main->checkConnection())
{
QMessageBox::warning(this, tr("Ошибка подключения"), tr("Соединение не установлено"));
throw std::exception();
}
dal_studentscontrol = new Dal_studentsControl(this);
ui->comboBox_spec->setModel(dal_studentscontrol->getSpec());
ui->comboBox_spec->setModelColumn(1);
ui->comboBox_spec->setCurrentIndex(-1);
QSqlQuery *querySrez = new QSqlQuery();
querySrez->prepare("SELECT discp1, discp2, discp3, discp4 FROM GAKView WHERE gak_id = " + QString::number(id_gak));
querySrez->exec();
querySrez->first();
ui->tableWidget->horizontalHeaderItem(1)->setText(querySrez->value(0).toString());
ui->tableWidget->horizontalHeaderItem(2)->setText(querySrez->value(1).toString());
ui->tableWidget->horizontalHeaderItem(3)->setText(querySrez->value(2).toString());
ui->tableWidget->horizontalHeaderItem(4)->setText(querySrez->value(3).toString());
ui->tableWidget->setItemDelegateForColumn(0, new readOnlyDelegate(ui->tableWidget));
ui->tableWidget->setItemDelegateForColumn(1, new SpinBoxDelegate(ui->tableWidget));
ui->tableWidget->setItemDelegateForColumn(2, new SpinBoxDelegate(ui->tableWidget));
ui->tableWidget->setItemDelegateForColumn(3, new SpinBoxDelegate(ui->tableWidget));
ui->tableWidget->setItemDelegateForColumn(4, new SpinBoxDelegate(ui->tableWidget));
ui->tableWidget->setItemDelegateForColumn(5, new checkboxdelegate(ui->tableWidget));
ui->tableWidget->setColumnHidden(6, true);
ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
ui->tableWidget->verticalHeader()->hide();
ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
ui->comboBox_group->setEnabled(false);
}
addoredit_gak_bally::~addoredit_gak_bally()
{
delete ui;
}
void addoredit_gak_bally::on_pushButton_cancel_clicked()
{
this->close();
}
void addoredit_gak_bally::on_pushButton_save_clicked()
{
if (ui->comboBox_group->currentIndex() == -1)
{
ui->label_error->setVisible(true);
return;
}
if (! dal_main->checkConnection())
{
QMessageBox::warning(this, tr("Ошибка соединения"), tr("Соединение не установлено"));
return;
}
QSqlQuery* deleteQuery = new QSqlQuery;
deleteQuery->prepare("DELETE FROM is_gak_bally WHERE gak_id = " + QString::number(id_gak) + " AND group_id = " + ui->comboBox_group->model()->index(ui->comboBox_group->currentIndex(),0).data().toString());
deleteQuery->exec();
qDebug()<<deleteQuery->lastError();
for (int i = 0; i < ui->tableWidget->rowCount(); ++i)
{
bool r = dal_studentscontrol->addGakBally(ui->tableWidget->item(i, 6)->text().toInt(),
ui->tableWidget->item(i, 1)->text().toInt(),
ui->tableWidget->item(i, 2)->text().toInt(),
ui->tableWidget->item(i, 3)->text().toInt(),
ui->tableWidget->item(i, 4)->text().toInt(),
ui->tableWidget->item(i, 5)->text().toInt(),
this->id_gak,
ui->comboBox_group->model()->index(ui->comboBox_group->currentIndex(),0).data().toInt());
qDebug()<<r, i;
}
QMessageBox::information(this, tr("Информация"), tr("Записи успешно добавлены"));
this->close();
}
void addoredit_gak_bally::on_comboBox_group_activated(int index)
{
if (ui->comboBox_group->currentIndex() == -1 )
return;
while (ui->tableWidget->rowCount() > 0)
ui->tableWidget->removeRow(0);
QSqlQueryModel *queryBally = new QSqlQueryModel();
queryBally = dal_studentscontrol->getGakBally(0, ui->comboBox_group->model()->index(ui->comboBox_group->currentIndex(),0).data().toInt(), this->id_gak);
if(queryBally->rowCount()>0)
{
for (int i = 0; i < queryBally->rowCount(); ++i)
{
ui->tableWidget->insertRow(i);
ui->tableWidget->setItem(i, 0, new QTableWidgetItem(queryBally->record(i).value(6).toString()));
ui->tableWidget->setItem(i, 1, new QTableWidgetItem(queryBally->record(i).value(7).toString()));
ui->tableWidget->setItem(i, 2, new QTableWidgetItem(queryBally->record(i).value(8).toString()));
ui->tableWidget->setItem(i, 3, new QTableWidgetItem(queryBally->record(i).value(9).toString()));
ui->tableWidget->setItem(i, 4, new QTableWidgetItem(queryBally->record(i).value(10).toString()));
ui->tableWidget->setItem(i, 5, new QTableWidgetItem(queryBally->record(i).value(11).toString()));
ui->tableWidget->setItem(i, 6, new QTableWidgetItem(queryBally->record(i).value(3).toString()));
}
}
else
{
QSqlQueryModel *queryStud = new QSqlQueryModel();
queryStud = dal_studentscontrol->getStudentGroup(ui->comboBox_group->model()->index(ui->comboBox_group->currentIndex(),0).data().toInt());
for (int i = 0; i < queryStud->rowCount(); ++i)
{
ui->tableWidget->insertRow(i);
ui->tableWidget->setItem(i, 0, new QTableWidgetItem(queryStud->record(i).value(1).toString()));
ui->tableWidget->setItem(i, 1, new QTableWidgetItem());
ui->tableWidget->setItem(i, 2, new QTableWidgetItem());
ui->tableWidget->setItem(i, 3, new QTableWidgetItem());
ui->tableWidget->setItem(i, 4, new QTableWidgetItem());
ui->tableWidget->setItem(i, 5, new QTableWidgetItem());
ui->tableWidget->setItem(i, 6, new QTableWidgetItem(queryStud->record(i).value(0).toString()));
}
}
}
void addoredit_gak_bally::on_comboBox_spec_activated(int index)
{
ui->comboBox_group->setEnabled(true);
ui->comboBox_group->setModel(dal_studentscontrol->getComboGroup(ui->comboBox_spec->model()->index(ui->comboBox_spec->currentIndex(),0).data().toInt()));
ui->comboBox_group->setModelColumn(1);
ui->comboBox_group->setCurrentIndex(-1);
}
| [
"kanbodows@mail.ru"
] | kanbodows@mail.ru |
396207f18cac34261e5eebee5a4e14c73f3f4fc6 | 3e4fd5153015d03f147e0f105db08e4cf6589d36 | /Cpp/SDK/GenericResourceWidget_functions.cpp | 3c618dc8d43247ac0f7706a689dbefcd5abc99df | [] | no_license | zH4x-SDK/zTorchlight3-SDK | a96f50b84e6b59ccc351634c5cea48caa0d74075 | 24135ee60874de5fd3f412e60ddc9018de32a95c | refs/heads/main | 2023-07-20T12:17:14.732705 | 2021-08-27T13:59:21 | 2021-08-27T13:59:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,631 | cpp | // Name: Torchlight3, Version: 4.26.1
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function GenericResourceWidget.GenericResourceWidget_C.GetItemSpawnWidget
// (Event, Protected, HasOutParms, BlueprintCallable, BlueprintEvent, Const)
// Parameters:
// class UItemSpawnWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UItemSpawnWidget* UGenericResourceWidget_C::GetItemSpawnWidget()
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.GetItemSpawnWidget");
UGenericResourceWidget_C_GetItemSpawnWidget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function GenericResourceWidget.GenericResourceWidget_C.GetMinionWidget
// (Event, Protected, HasOutParms, BlueprintCallable, BlueprintEvent, Const)
// Parameters:
// class UPetIconWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UPetIconWidget* UGenericResourceWidget_C::GetMinionWidget()
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.GetMinionWidget");
UGenericResourceWidget_C_GetMinionWidget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function GenericResourceWidget.GenericResourceWidget_C.GetFortPropWidget
// (Event, Protected, HasOutParms, BlueprintCallable, BlueprintEvent, Const)
// Parameters:
// class UFortPropIconWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UFortPropIconWidget* UGenericResourceWidget_C::GetFortPropWidget()
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.GetFortPropWidget");
UGenericResourceWidget_C_GetFortPropWidget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function GenericResourceWidget.GenericResourceWidget_C.RefreshName
// (Public, BlueprintCallable, BlueprintEvent)
void UGenericResourceWidget_C::RefreshName()
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.RefreshName");
UGenericResourceWidget_C_RefreshName_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GenericResourceWidget.GenericResourceWidget_C.GetItemCostWidget
// (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, Const)
// Parameters:
// class UInventoryItemCostWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UInventoryItemCostWidget* UGenericResourceWidget_C::GetItemCostWidget()
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.GetItemCostWidget");
UGenericResourceWidget_C_GetItemCostWidget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function GenericResourceWidget.GenericResourceWidget_C.GetCurrencyCostWidget
// (Event, Protected, HasOutParms, BlueprintCallable, BlueprintEvent, Const)
// Parameters:
// class UCurrencyCostWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UCurrencyCostWidget* UGenericResourceWidget_C::GetCurrencyCostWidget()
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.GetCurrencyCostWidget");
UGenericResourceWidget_C_GetCurrencyCostWidget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function GenericResourceWidget.GenericResourceWidget_C.GetCurrencyWidget
// (Event, Protected, HasOutParms, BlueprintCallable, BlueprintEvent, Const)
// Parameters:
// class UCurrencyWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UCurrencyWidget* UGenericResourceWidget_C::GetCurrencyWidget()
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.GetCurrencyWidget");
UGenericResourceWidget_C_GetCurrencyWidget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function GenericResourceWidget.GenericResourceWidget_C.GetItemWidget
// (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, Const)
// Parameters:
// class UInventoryItemBaseWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UInventoryItemBaseWidget* UGenericResourceWidget_C::GetItemWidget()
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.GetItemWidget");
UGenericResourceWidget_C_GetItemWidget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function GenericResourceWidget.GenericResourceWidget_C.GetSwitcher
// (Event, Protected, HasOutParms, BlueprintCallable, BlueprintEvent, Const)
// Parameters:
// class UWidgetSwitcher* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UWidgetSwitcher* UGenericResourceWidget_C::GetSwitcher()
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.GetSwitcher");
UGenericResourceWidget_C_GetSwitcher_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function GenericResourceWidget.GenericResourceWidget_C.PreConstruct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// bool IsDesignTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void UGenericResourceWidget_C::PreConstruct(bool IsDesignTime)
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.PreConstruct");
UGenericResourceWidget_C_PreConstruct_Params params;
params.IsDesignTime = IsDesignTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GenericResourceWidget.GenericResourceWidget_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UGenericResourceWidget_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.Construct");
UGenericResourceWidget_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function GenericResourceWidget.GenericResourceWidget_C.ExecuteUbergraph_GenericResourceWidget
// (Final)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UGenericResourceWidget_C::ExecuteUbergraph_GenericResourceWidget(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function GenericResourceWidget.GenericResourceWidget_C.ExecuteUbergraph_GenericResourceWidget");
UGenericResourceWidget_C_ExecuteUbergraph_GenericResourceWidget_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
9b04a8404a9944b729fb791c40bf78e2930f9943 | a5ab2164769f7ddfdb5c8406f5c145821562442d | /Charts/vtkPlotLine.cxx | 28ae83a0f3299781b7337b49327cc9d3becd1fb1 | [
"BSD-3-Clause"
] | permissive | huayang/VTK | 68c7e59a54503dc5c368f5ee2de455d59a2a9e79 | 98226aade65cd9ecf3f7bcfbe26967a8f6687ce1 | refs/heads/master | 2021-01-17T16:25:42.602388 | 2010-05-16T19:09:49 | 2010-05-16T19:09:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,859 | cxx | /*=========================================================================
Program: Visualization Toolkit
Module: vtkPlotLine.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.
=========================================================================*/
#include "vtkPlotLine.h"
#include "vtkContext2D.h"
#include "vtkAxis.h"
#include "vtkPen.h"
#include "vtkFloatArray.h"
#include "vtkVector.h"
#include "vtkTransform2D.h"
#include "vtkContextDevice2D.h"
#include "vtkContextMapper2D.h"
#include "vtkPoints2D.h"
#include "vtkTable.h"
#include "vtkDataArray.h"
#include "vtkIdTypeArray.h"
#include "vtkImageData.h"
#include "vtkExecutive.h"
#include "vtkTimeStamp.h"
#include "vtkInformation.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkstd/vector"
#include "vtkstd/algorithm"
//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkPlotLine);
//-----------------------------------------------------------------------------
vtkPlotLine::vtkPlotLine()
{
this->Points = NULL;
this->Sorted = NULL;
this->BadPoints = NULL;
this->MarkerStyle = vtkPlotLine::NONE;
this->LogX = false;
this->LogY = false;
this->Marker = NULL;
this->HighlightMarker = NULL;
}
//-----------------------------------------------------------------------------
vtkPlotLine::~vtkPlotLine()
{
if (this->Points)
{
this->Points->Delete();
this->Points = NULL;
}
if (this->Sorted)
{
this->Sorted->Delete();
this->Sorted = NULL;
}
if (this->BadPoints)
{
this->BadPoints->Delete();
this->BadPoints = NULL;
}
if (this->Marker)
{
this->Marker->Delete();
}
if (this->HighlightMarker)
{
this->HighlightMarker->Delete();
}
if (this->Selection)
{
this->Selection->Delete();
}
}
//-----------------------------------------------------------------------------
void vtkPlotLine::Update()
{
if (!this->Visible)
{
return;
}
// Check if we have an input
vtkTable *table = this->Data->GetInput();
if (!table)
{
vtkDebugMacro(<< "Update event called with no input table set.");
return;
}
else if(this->Data->GetMTime() > this->BuildTime ||
table->GetMTime() > this->BuildTime ||
this->MTime > this->BuildTime)
{
vtkDebugMacro(<< "Updating cached values.");
this->UpdateTableCache(table);
}
else if ((this->XAxis && this->XAxis->GetMTime() > this->BuildTime) ||
(this->YAxis && this->YAxis->GetMaximum() > this->BuildTime))
{
if (this->LogX != this->XAxis->GetLogScale() ||
this->LogY != this->YAxis->GetLogScale())
{
this->UpdateTableCache(table);
}
}
}
//-----------------------------------------------------------------------------
bool vtkPlotLine::Paint(vtkContext2D *painter)
{
// This is where everything should be drawn, or dispatched to other methods.
vtkDebugMacro(<< "Paint event called in vtkPlotLine.");
if (!this->Visible)
{
return false;
}
float width = this->Pen->GetWidth() * 2.3;
if (width < 8.0)
{
width = 8.0;
}
// Now add some decorations for our selected points...
if (this->Selection)
{
vtkDebugMacro(<<"Selection set " << this->Selection->GetNumberOfTuples());
for (int i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
{
this->GeneraterMarker(static_cast<int>(width+2.7), true);
painter->GetPen()->SetColor(255, 50, 0, 255);
painter->GetPen()->SetWidth(width+2.7);
vtkIdType id = 0;
this->Selection->GetTupleValue(i, &id);
if (id < this->Points->GetNumberOfPoints())
{
double *point = this->Points->GetPoint(id);
float p[] = { point[0], point[1] };
painter->DrawPointSprites(this->HighlightMarker, p, 1);
}
}
}
else
{
vtkDebugMacro("No selection set.");
}
// Now to plot the points
if (this->Points)
{
painter->ApplyPen(this->Pen);
painter->DrawPoly(this->Points);
painter->GetPen()->SetLineType(vtkPen::SOLID_LINE);
}
// If there is a marker style, then draw the marker for each point too
if (this->MarkerStyle)
{
this->GeneraterMarker(static_cast<int>(width));
painter->ApplyBrush(this->Brush);
painter->GetPen()->SetWidth(width);
painter->DrawPointSprites(this->Marker, this->Points);
}
return true;
}
void vtkPlotLine::GeneraterMarker(int width, bool highlight)
{
// Set up the image data, if highlight then the mark shape is different
vtkImageData *data = 0;
if (!highlight)
{
if (!this->Marker)
{
this->Marker = vtkImageData::New();
this->Marker->SetScalarTypeToUnsignedChar();
this->Marker->SetNumberOfScalarComponents(4);
}
else
{
if (this->Marker->GetMTime() >= this->GetMTime() &&
this->Marker->GetMTime() >= this->Pen->GetMTime())
{
// Marker already generated, no need to do this again.
return;
}
}
data = this->Marker;
}
else
{
if (!this->HighlightMarker)
{
this->HighlightMarker = vtkImageData::New();
this->HighlightMarker->SetScalarTypeToUnsignedChar();
this->HighlightMarker->SetNumberOfScalarComponents(4);
data = this->HighlightMarker;
}
else
{
if (this->HighlightMarker->GetMTime() >= this->GetMTime() &&
this->HighlightMarker->GetMTime() >= this->Pen->GetMTime())
{
// Marker already generated, no need to do this again.
return;
}
}
data = this->HighlightMarker;
}
data->SetExtent(0, width-1, 0, width-1, 0, 0);
data->AllocateScalars();
unsigned char* image =
static_cast<unsigned char*>(data->GetScalarPointer());
// Generate the marker image at the required size
switch (this->MarkerStyle)
{
case vtkPlotLine::CROSS:
{
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < width; ++j)
{
unsigned char color = 0;
if (highlight)
{
if ((i >= j-1 && i <= j+1) || (i >= width-j-1 && i <= width-j+1))
{
color = 255;
}
}
else
{
if (i == j || i == width-j)
{
color = 255;
}
}
image[4*width*i + 4*j] = image[4*width*i + 4*j + 1] =
image[4*width*i + 4*j + 2] = color;
image[4*width*i + 4*j + 3] = color;
}
}
break;
}
case vtkPlotLine::PLUS:
{
int x = width / 2;
int y = width / 2;
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < width; ++j)
{
unsigned char color = 0;
if (i == x || j == y)
{
color = 255;
}
if (highlight)
{
if (i == x-1 || i == x+1 || j == y-1 || j == y+1)
{
color = 255;
}
}
image[4*width*i + 4*j] = image[4*width*i + 4*j + 1] =
image[4*width*i + 4*j + 2] = color;
image[4*width*i + 4*j + 3] = color;
}
}
break;
}
case vtkPlotLine::SQUARE:
{
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < width; ++j)
{
unsigned char color = 255;
image[4*width*i + 4*j] = image[4*width*i + 4*j + 1] =
image[4*width*i + 4*j + 2] = color;
image[4*width*i + 4*j + 3] = color;
}
}
break;
}
case vtkPlotLine::CIRCLE:
{
double c = width/2.0;
for (int i = 0; i < width; ++i)
{
double dx2 = (i - c)*(i-c);
for (int j = 0; j < width; ++j)
{
double dy2 = (j - c)*(j - c);
unsigned char color = 0;
if (sqrt(dx2 + dy2) < c)
{
color = 255;
}
image[4*width*i + 4*j] = image[4*width*i + 4*j + 1] =
image[4*width*i + 4*j + 2] = color;
image[4*width*i + 4*j + 3] = color;
}
}
break;
}
case vtkPlotLine::DIAMOND:
{
int c = width/2;
for (int i = 0; i < width; ++i)
{
int dx = i-c > 0 ? i-c : c-i;
for (int j = 0; j < width; ++j)
{
int dy = j-c > 0 ? j-c : c-j;
unsigned char color = 0;
if (c-dx >= dy)
{
color = 255;
}
image[4*width*i + 4*j] = image[4*width*i + 4*j + 1] =
image[4*width*i + 4*j + 2] = color;
image[4*width*i + 4*j + 3] = color;
}
}
break;
}
default:
{
int x = width / 2;
int y = width / 2;
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < width; ++j)
{
unsigned char color = 0;
if (i == x || j == y)
{
color = 255;
}
image[4*width*i + 4*j] = image[4*width*i + 4*j + 1] =
image[4*width*i + 4*j + 2] = color;
image[4*width*i + 4*j + 3] = color;
}
}
}
}
}
//-----------------------------------------------------------------------------
bool vtkPlotLine::PaintLegend(vtkContext2D *painter, float rect[4])
{
painter->ApplyPen(this->Pen);
painter->DrawLine(rect[0], rect[1]+0.5*rect[3],
rect[0]+rect[2], rect[1]+0.5*rect[3]);
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotLine::GetBounds(double bounds[4])
{
if (this->Points)
{
if (!this->BadPoints)
{
this->Points->GetBounds(bounds);
}
else
{
// There are bad points in the series - need to do this ourselves.
this->CalculateBounds(bounds);
}
}
vtkDebugMacro(<< "Bounds: " << bounds[0] << "\t" << bounds[1] << "\t"
<< bounds[2] << "\t" << bounds[3]);
}
namespace
{
// Compare the two vectors, in X component only
bool compVector2fX(const vtkVector2f& v1, const vtkVector2f& v2)
{
if (v1.X() < v2.X())
{
return true;
}
else
{
return false;
}
}
// See if the point is within tolerance.
bool inRange(const vtkVector2f& point, const vtkVector2f& tol,
const vtkVector2f& current)
{
if (current.X() > point.X() - tol.X() && current.X() < point.X() + tol.X() &&
current.Y() > point.Y() - tol.Y() && current.Y() < point.Y() + tol.Y())
{
return true;
}
else
{
return false;
}
}
}
//-----------------------------------------------------------------------------
bool vtkPlotLine::GetNearestPoint(const vtkVector2f& point,
const vtkVector2f& tol,
vtkVector2f* location)
{
// Right now doing a simple bisector search of the array. This should be
// revisited. Assumes the x axis is sorted, which should always be true for
// line plots.
if (!this->Points)
{
return false;
}
vtkIdType n = this->Points->GetNumberOfPoints();
if (n < 2)
{
return false;
}
if (!this->Sorted)
{
this->Sorted = vtkPoints2D::New();
}
// Sort the data if necessary
if (this->Sorted->GetNumberOfPoints() == 0)
{
this->Sorted->DeepCopy(this->Points);
vtkVector2f* data =
static_cast<vtkVector2f*>(this->Sorted->GetVoidPointer(0));
vtkstd::vector<vtkVector2f> v(data, data+n);
vtkstd::sort(v.begin(), v.end(), compVector2fX);
}
// Set up our search array, use the STL lower_bound algorithm
vtkVector2f* data =
static_cast<vtkVector2f*>(this->Sorted->GetVoidPointer(0));
vtkstd::vector<vtkVector2f> v(data, data+n);
vtkstd::vector<vtkVector2f>::iterator low;
// Get the lowest point we might hit within the supplied tolerance
vtkVector2f lowPoint(point.X()-tol.X(), 0.0f);
low = vtkstd::lower_bound(v.begin(), v.end(), lowPoint, compVector2fX);
// Now consider the y axis
float highX = point.X() + tol.X();
while (low != v.end())
{
if (inRange(point, tol, *low))
{
*location = *low;
return true;
}
else if (low->X() > highX)
{
break;
}
++low;
}
return false;
}
//-----------------------------------------------------------------------------
bool vtkPlotLine::SelectPoints(const vtkVector2f& min, const vtkVector2f& max)
{
if (!this->Points)
{
return false;
}
if (!this->Selection)
{
this->Selection = vtkIdTypeArray::New();
}
this->Selection->SetNumberOfTuples(0);
// Iterate through all points and check whether any are in range
vtkVector2f* data = static_cast<vtkVector2f*>(this->Points->GetVoidPointer(0));
vtkIdType n = this->Points->GetNumberOfPoints();
for (vtkIdType i = 0; i < n; ++i)
{
if (data[i].X() >= min.X() && data[i].X() <= max.X() &&
data[i].Y() >= min.Y() && data[i].Y() <= max.Y())
{
this->Selection->InsertNextValue(i);
}
}
return this->Selection->GetNumberOfTuples() > 0;
}
//-----------------------------------------------------------------------------
namespace {
// Copy the two arrays into the points array
template<class A>
void CopyToPointsSwitch(vtkPoints2D *points, A *a, vtkDataArray *b, int n)
{
switch(b->GetDataType())
{
vtkTemplateMacro(
CopyToPoints(points, a, static_cast<VTK_TT*>(b->GetVoidPointer(0)), n));
}
}
// Copy the two arrays into the points array
template<class A, class B>
void CopyToPoints(vtkPoints2D *points, A *a, B *b, int n)
{
points->SetNumberOfPoints(n);
float* data = static_cast<float*>(points->GetVoidPointer(0));
for (int i = 0; i < n; ++i)
{
data[2*i] = a[i];
data[2*i+1] = b[i];
}
}
// Copy one array into the points array, use the index of that array as x
template<class A>
void CopyToPoints(vtkPoints2D *points, A *a, int n)
{
points->SetNumberOfPoints(n);
float* data = static_cast<float*>(points->GetVoidPointer(0));
for (int i = 0; i < n; ++i)
{
data[2*i] = static_cast<float>(i);
data[2*i+1] = a[i];
}
}
}
//-----------------------------------------------------------------------------
bool vtkPlotLine::UpdateTableCache(vtkTable *table)
{
// Get the x and y arrays (index 0 and 1 respectively)
vtkDataArray* x = this->UseIndexForXSeries ?
0 : this->Data->GetInputArrayToProcess(0, table);
vtkDataArray* y = this->Data->GetInputArrayToProcess(1, table);
if (!x && !this->UseIndexForXSeries)
{
vtkErrorMacro(<< "No X column is set (index 0).");
return false;
}
else if (!y)
{
vtkErrorMacro(<< "No Y column is set (index 1).");
return false;
}
else if (!this->UseIndexForXSeries &&
x->GetNumberOfTuples() != y->GetNumberOfTuples())
{
vtkErrorMacro("The x and y columns must have the same number of elements. "
<< x->GetNumberOfTuples() << ", " << y->GetNumberOfTuples());
return false;
}
if (!this->Points)
{
this->Points = vtkPoints2D::New();
}
// Now copy the components into their new columns
if (this->UseIndexForXSeries)
{
switch(y->GetDataType())
{
vtkTemplateMacro(
CopyToPoints(this->Points,
static_cast<VTK_TT*>(y->GetVoidPointer(0)),
y->GetNumberOfTuples()));
}
}
else
{
switch(x->GetDataType())
{
vtkTemplateMacro(
CopyToPointsSwitch(this->Points,
static_cast<VTK_TT*>(x->GetVoidPointer(0)),
y, x->GetNumberOfTuples()));
}
}
this->CalculateLogSeries();
this->FindBadPoints();
this->Points->Modified();
if (this->Sorted)
{
this->Sorted->SetNumberOfPoints(0);
}
this->BuildTime.Modified();
return true;
}
//-----------------------------------------------------------------------------
inline void vtkPlotLine::CalculateLogSeries()
{
if (!this->XAxis || !this->YAxis)
{
return;
}
this->LogX = this->XAxis->GetLogScale();
this->LogY = this->YAxis->GetLogScale();
float* data = static_cast<float*>(this->Points->GetVoidPointer(0));
vtkIdType n = this->Points->GetNumberOfPoints();
if (this->LogX)
{
for (vtkIdType i = 0; i < n; ++i)
{
data[2*i] = log10(data[2*i]);
}
}
if (this->LogY)
{
for (vtkIdType i = 0; i < n; ++i)
{
data[2*i+1] = log10(data[2*i+1]);
}
}
}
//-----------------------------------------------------------------------------
inline void vtkPlotLine::FindBadPoints()
{
// This should be run after CalculateLogSeries as a final step.
float* data = static_cast<float*>(this->Points->GetVoidPointer(0));
vtkIdType n = this->Points->GetNumberOfPoints();
if (!this->BadPoints)
{
this->BadPoints = vtkIdTypeArray::New();
}
else
{
this->BadPoints->SetNumberOfTuples(0);
}
// Scan through and find any bad points.
for (vtkIdType i = 0; i < n; ++i)
{
vtkIdType p = 2*i;
if (vtkMath::IsInf(data[p]) || vtkMath::IsInf(data[p+1]) ||
vtkMath::IsNan(data[p]) || vtkMath::IsNan(data[p+1]))
{
this->BadPoints->InsertNextValue(i);
}
}
if (this->BadPoints->GetNumberOfTuples() == 0)
{
this->BadPoints->Delete();
this->BadPoints = NULL;
}
}
//-----------------------------------------------------------------------------
inline void vtkPlotLine::CalculateBounds(double bounds[4])
{
// We can use the BadPoints array to skip the bad points
if (!this->Points || !this->BadPoints)
{
return;
}
vtkIdType start = 0;
vtkIdType end = 0;
vtkIdType i = 0;
vtkIdType nBad = this->BadPoints->GetNumberOfTuples();
vtkIdType nPoints = this->Points->GetNumberOfPoints();
if (this->BadPoints->GetValue(i) == 0)
{
while (i < nBad && i == this->BadPoints->GetValue(i))
{
start = this->BadPoints->GetValue(i++) + 1;
}
if (start < nPoints)
{
end = nPoints;
}
else
{
// They are all bad points
return;
}
}
if (i < nBad)
{
end = this->BadPoints->GetValue(i++);
}
else
{
end = nPoints;
}
vtkVector2f* pts = static_cast<vtkVector2f*>(this->Points->GetVoidPointer(0));
// Initialize our min/max
bounds[0] = bounds[1] = pts[start].X();
bounds[2] = bounds[3] = pts[start++].Y();
while (start < nPoints)
{
// Calculate the min/max in this range
while (start < end)
{
float x = pts[start].X();
float y = pts[start++].Y();
if (x < bounds[0])
{
bounds[0] = x;
}
else if (x > bounds[1])
{
bounds[1] = x;
}
if (y < bounds[2])
{
bounds[2] = y;
}
else if (y > bounds[3])
{
bounds[3] = y;
}
}
// Now figure out the next range
start = end + 1;
if (++i < nBad)
{
end = this->BadPoints->GetValue(i);
}
else
{
end = nPoints;
}
}
}
//-----------------------------------------------------------------------------
void vtkPlotLine::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
| [
"marcus.hanwell@kitware.com"
] | marcus.hanwell@kitware.com |
ed0e51fe555ad399efdff01564e932f8bdcce4b1 | dfc94e9e7dfc9adaf3c6730ae874acd59a1a3232 | /Source/Engine/World/Entities/E_SoundEmitter.h | 9cc3c9e56c7c701ada94daa30836b0c12a47a6fa | [] | no_license | joeriedel/Radiance | c0685d924e3d9414ee2f40047dd9c07f78317261 | 557ba94e7a55635561ab8776682b6aac1454ccea | refs/heads/master | 2021-01-09T20:05:23.177522 | 2014-10-27T02:00:10 | 2014-10-27T02:00:10 | 60,389,459 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 672 | h | // E_SoundEmitter.h
// Copyright (c) 2010 Sunside Inc., All Rights Reserved
// Author: Joe Riedel
// See Radiance/LICENSE for licensing terms.
#pragma once
#include "../Entity.h"
#include <Runtime/PushPack.h>
namespace world {
class RADENG_CLASS E_SoundEmitter : public Entity
{
E_DECL_BASE(Entity);
public:
E_SoundEmitter();
protected:
virtual void Tick(
int frame,
float dt,
const xtime::TimeSlice &time
);
virtual int Spawn(
const Keys &keys,
const xtime::TimeSlice &time,
int flags
);
private:
bool m_on;
float m_maxDistance;
bool m_positional;
};
} // world
E_DECL_SPAWN(RADENG_API, info_sound_emitter)
#include <Runtime/PopPack.h>
| [
"joe@sunsidegames.com"
] | joe@sunsidegames.com |
4494a9b88539b3d09c9fb07f8db2bc8b240c5365 | 818919bf2b335ee5faf8a282dc1eecf034a656e2 | /sources/src/streamitemwidget.cpp | 0f0834115f41289367f8ce7ec623a25b2fa06a84 | [] | no_license | Oyuret/liveGUIMobile | a373d051a7664b41fe381ce5f36252a1b363187c | e764c16d808bc246c18d8b176b09cc1b0d1abac0 | refs/heads/master | 2021-01-23T13:28:48.197539 | 2014-09-09T14:40:13 | 2014-09-09T14:40:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 777 | cpp | #include "../include/streamitemwidget.h"
#include "ui_streamitemwidget.h"
StreamItemWidget::StreamItemWidget(const Stream &stream) :
QWidget(),
ui(new Ui::StreamItemWidget),
stream(stream)
{
ui->setupUi(this);
ui->streamerName->setText(stream.getDisplayName());
ui->gameText->setText(stream.getGame());
QPixmap icon(stream.getServiceLogoResource());
ui->serviceIcon->setPixmap(icon);
}
StreamItemWidget::~StreamItemWidget()
{
delete ui;
}
void StreamItemWidget::on_playStreamButton_clicked()
{
emit play(stream.getUrl());
}
void StreamItemWidget::on_previewStreamButton_clicked()
{
emit goToPreview();
emit fetchStreamPreview(stream);
}
void StreamItemWidget::on_favoriteButton_clicked()
{
emit addFavorite(stream);
}
| [
"yuris@kth.se"
] | yuris@kth.se |
31339713c8864fcad45b9a70ffd62abe39703e00 | 05e1f94ae1a5513a222d38dfe4c3c6737cb84251 | /Mulberry/branches/users/kenneth_porter/FromTrunk/Sources_Common/HTTP/HTTPClient/CHTTPRequestResponse.h | 1bb8cdad27a1abd30d84cd932d66472cc1234cb8 | [
"Apache-2.0"
] | permissive | eskilblomfeldt/mulberry-svn | 16ca9d4d6ec05cbbbd18045c7b59943b0aca9335 | 7ed26b61244e47d4d4d50a1c7cc2d31efa548ad7 | refs/heads/master | 2020-05-20T12:35:42.340160 | 2014-12-24T18:03:50 | 2014-12-24T18:03:50 | 29,127,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,764 | h | /*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
CHTTPRequestResponse.h
Author:
Description: <describe the CHTTPRequestResponse class here>
*/
#ifndef CHTTPRequestResponse_H
#define CHTTPRequestResponse_H
#include <stdint.h>
#include <exception>
#include <istream>
#include <map>
#include <ostream>
#include "cdstring.h"
#include "CHTTPData.h"
#include "CHTTPDefinitions.h"
using namespace std;
namespace http {
class CHTTPSession;
class CHTTPRequestResponse
{
public:
enum ERequestMethod
{
// HTTP Requests
eRequest_OPTIONS,
eRequest_GET,
eRequest_HEAD,
eRequest_POST,
eRequest_PUT,
eRequest_DELETE,
eRequest_TRACE,
eRequest_CONNECT,
// WebDAV requests
eRequest_MKCOL,
eRequest_MOVE,
eRequest_COPY,
eRequest_PROPFIND,
eRequest_PROPPATCH,
eRequest_LOCK,
eRequest_UNLOCK,
// WebDAV Version extension
eRequest_REPORT,
// WebDAV ACL extension
eRequest_ACL,
// CalDAV requests
eRequest_MKCALENDAR
};
class CHTTPResponseException : public exception
{
public:
CHTTPResponseException(const char* error)
{
mError = error;
}
~CHTTPResponseException() throw() {}
virtual const char* what () const throw()
{
return mError.c_str();
}
private:
cdstring mError;
};
CHTTPRequestResponse(const CHTTPSession* session, ERequestMethod method, const cdstring& ruri);
CHTTPRequestResponse(const CHTTPSession* session, ERequestMethod method, const cdstring& ruri, const cdstring& etag, bool etag_match);
virtual ~CHTTPRequestResponse();
void SetSession(const CHTTPSession* session)
{
mSession = session;
}
const CHTTPSession* GetSession() const
{
return mSession;
}
const char* GetMethod() const;
void SetRURI(const cdstring& ruri)
{
mURI = ruri;
}
const cdstring& GetRURI() const
{
return mURI;
}
void SetETag(const cdstring& etag, bool etag_match)
{
mETag = etag;
mETagMatch = etag_match;
}
void QueuedForSending(const CHTTPSession* session)
{
mSession = session;
}
void SetData(CHTTPInputData* request_data, CHTTPOutputData* response_data)
{
mRequestData = request_data;
mResponseData = response_data;
}
virtual bool HasRequestData() const;
virtual istream* GetRequestDataStream();
virtual ostream* GetResponseDataStream();
void StartRequestData()
{
if (mRequestData != NULL)
mRequestData->Start();
}
void StopRequestData()
{
if (mRequestData != NULL)
mRequestData->Stop();
}
void StartResponseData()
{
if (mResponseData != NULL)
mResponseData->Start();
}
void StopResponseData()
{
if (mResponseData != NULL)
mResponseData->Stop();
}
cdstring GetRequestHeader();
void GenerateRequestHeader(ostream& os);
void ParseResponseHeader(istream& is, ostream* log);
void ClearResponse();
uint32_t GetStatusCode() const
{
return mStatusCode;
}
const cdstring& GetStatusReason() const
{
return mStatusReason;
}
bool GetConnectionClose() const
{
return mConnectionClose;
}
virtual uint32_t GetContentLength() const
{
return mContentLength;
}
virtual bool GetChunked() const
{
return mChunked;
}
void SetComplete()
{
mCompleted = true;
}
bool GetCompleted() const
{
return mCompleted;
}
const cdstrmultimapcasei& GetResponseHeaders() const
{
return mHeaders;
}
const cdstring& GetResponseHeader(const cdstring& hdr) const;
void DoRequestSync();
bool IsRedirect() const;
protected:
const CHTTPSession* mSession;
CHTTPInputData* mRequestData;
CHTTPOutputData* mResponseData;
// Request items
ERequestMethod mMethod;
cdstring mURI;
cdstring mETag;
bool mETagMatch;
// Response items
uint32_t mStatusCode;
cdstring mStatusReason;
cdstrmultimapcasei mHeaders;
bool mConnectionClose;
uint32_t mContentLength;
bool mChunked;
bool mCompleted;
virtual void WriteHeaderToStream(ostream& os);
virtual void WriteContentHeaderToStream(ostream& os);
private:
void InitResponse();
void ParseStatusLine(cdstring& line);
bool ReadFoldedLine(istream& is, cdstring& line1, cdstring& line2, ostream* log) const;
void CacheHeaders();
};
} // namespace http
#endif // CHTTPRequestResponse_H
| [
"svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132"
] | svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132 |
a705f7c3d2dd188e9b083600c802d3d284f498f1 | 629ca14b68ad60ff69bb5c07dccc87ec36b57920 | /Mutex/incrementworker.cpp | 42d16426ea9d20f43c1525b23da7ad33ba3bdf1f | [] | no_license | djhamo/UDEMY_curso_Multi-Threading_IPC_Qt_C | b7d54965e080052af8679156db291602775eb250 | 52263e8c75eea9d570109bea44d4ee0237f885a8 | refs/heads/main | 2023-03-28T05:56:14.621716 | 2021-03-15T17:01:38 | 2021-03-15T17:01:38 | 348,054,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | cpp | #include "incrementworker.h"
IncrementWorker::IncrementWorker(bool *stop, PrintDevice *print_device, QObject *parent):
QThread(parent), m_stop(stop), m_print_device(print_device)
{
}
void IncrementWorker::run()
{
while(!(* m_stop)) {
msleep(1500);
m_print_device->increment();
}
}
| [
"djhamo@gmail.com"
] | djhamo@gmail.com |
a21ddc7dbf58456a6b4a6e8bfe713497c07a01e4 | 5f9872ab687193d58145d05fedfa196c8184551a | /include/grpc_cb/server.h | 8457df2485b88a71c31dd6cd894c16fd70f89a5e | [
"Apache-2.0"
] | permissive | parkheeyoung/grpc_cb | aa03f8fff908bc2d490a44c0dd75f0013b3ddc2a | 1c666f9a9d8757585274984eaaaad1211769486a | refs/heads/master | 2020-06-14T01:37:16.133440 | 2016-12-04T08:23:23 | 2016-12-04T08:23:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,180 | h | // Licensed under the Apache License, Version 2.0.
// Author: Jin Qing (http://blog.csdn.net/jq0123)
#ifndef GRPC_CB_SERVER_H
#define GRPC_CB_SERVER_H
#include <unordered_map>
#include <vector>
#include <grpc/support/time.h> // for gpr_inf_future()
#include <grpc_cb/impl/completion_queue_sptr.h> // for CompletionQueueSptr
#include <grpc_cb/impl/grpc_library.h> // for GrpcLibrary
#include <grpc_cb/support/config.h> // for GRPC_FINAL
#include <grpc_cb/support/time.h> // for TimePoint
struct grpc_server;
namespace grpc_cb {
class InsecureServerCredentials;
class ServerCredentials;
class Service;
/// Models a gRPC server.
class Server GRPC_FINAL : public GrpcLibrary {
public:
Server();
~Server();
/// Shutdown the server, blocking until all rpc processing finishes.
/// Forcefully terminate pending calls after \a deadline expires.
///
/// \param deadline How long to wait until pending rpcs are forcefully
/// terminated.
template <class T>
void Shutdown(const T& deadline) {
ShutdownInternal(TimePoint<T>(deadline).raw_time());
}
/// Shutdown the server, waiting for all rpc processing to finish.
void Shutdown() { ShutdownInternal(gpr_inf_future(GPR_CLOCK_MONOTONIC)); }
/// Block waiting for all work to complete.
///
/// \warning The server must be either shutting down or some other thread must
/// call \a Shutdown for this function to ever return.
void BlockingRun();
/// Register a service. This call does not take ownership of the service.
/// The service must exist for the lifetime of the Server instance.
// bool RegisterService(/*const std::string* host, RpcService* service*/);
void RegisterService(Service& service);
/// Tries to bind \a server to the given \a addr.
///
/// It can be invoked multiple times.
///
/// \param addr The address to try to bind to the server (eg, localhost:1234,
/// 192.168.1.1:31416, [::1]:27182, etc.).
/// \params creds The credentials associated with the server.
///
/// \return bound port number on sucess, 0 on failure.
///
/// \warning It's an error to call this method on an already started server.
int AddListeningPort(const std::string& addr,
const ServerCredentials& creds);
int AddListeningPort(const std::string& addr); // with InsecureServerCredentials
private:
using RegisteredMethodVec = std::vector<void*>;
struct RegisteredService {
Service* service; // Borrowed.
RegisteredMethodVec registered_methods;
};
private:
void ShutdownInternal(gpr_timespec deadline);
void RequestMethodsCalls() const;
void RequestServiceMethodsCalls(const RegisteredService& rs) const;
private:
using GrpcServerUptr = std::unique_ptr<grpc_server, void (*)(grpc_server*)>;
static GrpcServerUptr MakeUniqueGrpcServer();
private:
// Completion queue.
const CompletionQueueSptr cq_sptr_;
// Sever status
bool started_;
bool shutdown_;
// Pointer to the c grpc server. Owned.
const std::unique_ptr<grpc_server, void (*)(grpc_server*)> c_server_uptr_;
std::unordered_map<std::string, RegisteredService> service_map_;
};
} // namespace grpc_cb
#endif // GRPC_CB_SERVER_H
| [
"jinq0123@163.com"
] | jinq0123@163.com |
03cf2d230d5c1c383e4086c5f90c154d3f7cf618 | c2d270aff0a4d939f43b6359ac2c564b2565be76 | /src/components/variations/service/variations_service.cc | cfe54772e8feb7514488b8403e90007781c1da48 | [
"BSD-3-Clause"
] | permissive | bopopescu/QuicDep | dfa5c2b6aa29eb6f52b12486ff7f3757c808808d | bc86b705a6cf02d2eade4f3ea8cf5fe73ef52aa0 | refs/heads/master | 2022-04-26T04:36:55.675836 | 2020-04-29T21:29:26 | 2020-04-29T21:29:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,966 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/variations/service/variations_service.h"
#include <stddef.h>
#include <stdint.h>
#include <utility>
#include <vector>
#include "base/base64.h"
#include "base/base_switches.h"
#include "base/build_time.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/sys_info.h"
#include "base/task_runner_util.h"
#include "base/task_scheduler/post_task.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/timer/elapsed_timer.h"
#include "base/values.h"
#include "base/version.h"
#include "build/build_config.h"
#include "components/data_use_measurement/core/data_use_user_data.h"
#include "components/encrypted_messages/encrypted_message.pb.h"
#include "components/encrypted_messages/message_encrypter.h"
#include "components/metrics/clean_exit_beacon.h"
#include "components/metrics/metrics_state_manager.h"
#include "components/network_time/network_time_tracker.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/variations/pref_names.h"
#include "components/variations/proto/variations_seed.pb.h"
#include "components/variations/variations_seed_processor.h"
#include "components/variations/variations_seed_simulator.h"
#include "components/variations/variations_switches.h"
#include "components/variations/variations_url_constants.h"
#include "components/version_info/version_info.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/network_change_notifier.h"
#include "net/base/url_util.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request_status.h"
#include "ui/base/device_form_factor.h"
#include "url/gurl.h"
namespace variations {
namespace {
const base::Feature kHttpRetryFeature{"VariationsHttpRetry",
base::FEATURE_DISABLED_BY_DEFAULT};
// Constants used for encrypting the if-none-match header if we are retrieving a
// seed over http.
const char kEncryptedMessageLabel[] = "chrome variations";
// TODO(crbug.com/792239): Change this key to a unique VariationsService one,
// once the matching private key is changed server side.
// Key is used to encrypt headers in seed retrieval requests that happen over
// HTTP connections (when retrying after an unsuccessful HTTPS retrieval
// attempt).
const uint8_t kServerPublicKey[] = {
0x51, 0xcc, 0x52, 0x67, 0x42, 0x47, 0x3b, 0x10, 0xe8, 0x63, 0x18,
0x3c, 0x61, 0xa7, 0x96, 0x76, 0x86, 0x91, 0x40, 0x71, 0x39, 0x5f,
0x31, 0x1a, 0x39, 0x5b, 0x76, 0xb1, 0x6b, 0x3d, 0x6a, 0x2b};
const uint32_t kServerPublicKeyVersion = 1;
// TODO(mad): To be removed when we stop updating the NetworkTimeTracker.
// For the HTTP date headers, the resolution of the server time is 1 second.
const int64_t kServerTimeResolutionMs = 1000;
// Whether the VariationsService should always be created, even in Chromium
// builds.
bool g_enabled_for_testing = false;
// Returns a string that will be used for the value of the 'osname' URL param
// to the variations server.
std::string GetPlatformString() {
#if defined(OS_WIN)
return "win";
#elif defined(OS_IOS)
return "ios";
#elif defined(OS_MACOSX)
return "mac";
#elif defined(OS_CHROMEOS)
return "chromeos";
#elif defined(OS_ANDROID)
return "android";
#elif defined(OS_LINUX) || defined(OS_BSD) || defined(OS_SOLARIS)
// Default BSD and SOLARIS to Linux to not break those builds, although these
// platforms are not officially supported by Chrome.
return "linux";
#else
#error Unknown platform
#endif
}
// Gets the restrict parameter from either the client or |policy_pref_service|.
std::string GetRestrictParameterPref(VariationsServiceClient* client,
PrefService* policy_pref_service) {
std::string parameter;
if (client->OverridesRestrictParameter(¶meter) || !policy_pref_service)
return parameter;
return policy_pref_service->GetString(prefs::kVariationsRestrictParameter);
}
enum ResourceRequestsAllowedState {
RESOURCE_REQUESTS_ALLOWED,
RESOURCE_REQUESTS_NOT_ALLOWED,
RESOURCE_REQUESTS_ALLOWED_NOTIFIED,
RESOURCE_REQUESTS_NOT_ALLOWED_EULA_NOT_ACCEPTED,
RESOURCE_REQUESTS_NOT_ALLOWED_NETWORK_DOWN,
RESOURCE_REQUESTS_NOT_ALLOWED_COMMAND_LINE_DISABLED,
RESOURCE_REQUESTS_ALLOWED_ENUM_SIZE,
};
// Records UMA histogram with the current resource requests allowed state.
void RecordRequestsAllowedHistogram(ResourceRequestsAllowedState state) {
UMA_HISTOGRAM_ENUMERATION("Variations.ResourceRequestsAllowed", state,
RESOURCE_REQUESTS_ALLOWED_ENUM_SIZE);
}
enum VariationsSeedExpiry {
VARIATIONS_SEED_EXPIRY_NOT_EXPIRED,
VARIATIONS_SEED_EXPIRY_FETCH_TIME_MISSING,
VARIATIONS_SEED_EXPIRY_EXPIRED,
VARIATIONS_SEED_EXPIRY_ENUM_SIZE,
};
// Converts ResourceRequestAllowedNotifier::State to the corresponding
// ResourceRequestsAllowedState value.
ResourceRequestsAllowedState ResourceRequestStateToHistogramValue(
web_resource::ResourceRequestAllowedNotifier::State state) {
using web_resource::ResourceRequestAllowedNotifier;
switch (state) {
case ResourceRequestAllowedNotifier::DISALLOWED_EULA_NOT_ACCEPTED:
return RESOURCE_REQUESTS_NOT_ALLOWED_EULA_NOT_ACCEPTED;
case ResourceRequestAllowedNotifier::DISALLOWED_NETWORK_DOWN:
return RESOURCE_REQUESTS_NOT_ALLOWED_NETWORK_DOWN;
case ResourceRequestAllowedNotifier::DISALLOWED_COMMAND_LINE_DISABLED:
return RESOURCE_REQUESTS_NOT_ALLOWED_COMMAND_LINE_DISABLED;
case ResourceRequestAllowedNotifier::ALLOWED:
return RESOURCE_REQUESTS_ALLOWED;
}
NOTREACHED();
return RESOURCE_REQUESTS_NOT_ALLOWED;
}
// Returns the header value for |name| from |headers| or an empty string if not
// set.
std::string GetHeaderValue(const net::HttpResponseHeaders* headers,
const base::StringPiece& name) {
std::string value;
headers->EnumerateHeader(nullptr, name, &value);
return value;
}
// Returns the list of values for |name| from |headers|. If the header in not
// set, return an empty list.
std::vector<std::string> GetHeaderValuesList(
const net::HttpResponseHeaders* headers,
const base::StringPiece& name) {
std::vector<std::string> values;
size_t iter = 0;
std::string value;
while (headers->EnumerateHeader(&iter, name, &value)) {
values.push_back(value);
}
return values;
}
// Looks for delta and gzip compression instance manipulation flags set by the
// server in |headers|. Checks the order of flags and presence of unknown
// instance manipulations. If successful, |is_delta_compressed| and
// |is_gzip_compressed| contain compression flags and true is returned.
bool GetInstanceManipulations(const net::HttpResponseHeaders* headers,
bool* is_delta_compressed,
bool* is_gzip_compressed) {
std::vector<std::string> ims = GetHeaderValuesList(headers, "IM");
const auto delta_im = std::find(ims.begin(), ims.end(), "x-bm");
const auto gzip_im = std::find(ims.begin(), ims.end(), "gzip");
*is_delta_compressed = delta_im != ims.end();
*is_gzip_compressed = gzip_im != ims.end();
// The IM field should not have anything but x-bm and gzip.
size_t im_count = (*is_delta_compressed ? 1 : 0) +
(*is_gzip_compressed ? 1 : 0);
if (im_count != ims.size()) {
DVLOG(1) << "Unrecognized instance manipulations in "
<< base::JoinString(ims, ",")
<< "; only x-bm and gzip are supported";
return false;
}
// The IM field defines order in which instance manipulations were applied.
// The client requests and supports gzip-compressed delta-compressed seeds,
// but not vice versa.
if (*is_delta_compressed && *is_gzip_compressed && delta_im > gzip_im) {
DVLOG(1) << "Unsupported instance manipulations order: "
<< "requested x-bm,gzip but received gzip,x-bm";
return false;
}
return true;
}
// Variations seed fetching is only enabled in official Chrome builds, if a URL
// is specified on the command line, and for testing.
bool IsFetchingEnabled() {
#if !defined(GOOGLE_CHROME_BUILD)
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kVariationsServerURL) &&
!g_enabled_for_testing) {
DVLOG(1)
<< "Not performing repeated fetching in unofficial build without --"
<< switches::kVariationsServerURL << " specified.";
return false;
}
#endif
return true;
}
} // namespace
VariationsService::VariationsService(
std::unique_ptr<VariationsServiceClient> client,
std::unique_ptr<web_resource::ResourceRequestAllowedNotifier> notifier,
PrefService* local_state,
metrics::MetricsStateManager* state_manager,
const UIStringOverrider& ui_string_overrider)
: client_(std::move(client)),
local_state_(local_state),
state_manager_(state_manager),
policy_pref_service_(local_state),
initial_request_completed_(false),
disable_deltas_for_next_request_(false),
resource_request_allowed_notifier_(std::move(notifier)),
request_count_(0),
safe_seed_manager_(state_manager->clean_exit_beacon()->exited_cleanly(),
local_state),
field_trial_creator_(local_state, client_.get(), ui_string_overrider),
weak_ptr_factory_(this) {
DCHECK(client_.get());
DCHECK(resource_request_allowed_notifier_.get());
resource_request_allowed_notifier_->Init(this);
}
VariationsService::~VariationsService() {
}
void VariationsService::PerformPreMainMessageLoopStartup() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!IsFetchingEnabled())
return;
StartRepeatedVariationsSeedFetch();
}
std::string VariationsService::LoadPermanentConsistencyCountry(
const base::Version& version,
const std::string& latest_country) {
return field_trial_creator_.LoadPermanentConsistencyCountry(version,
latest_country);
}
bool VariationsService::EncryptString(const std::string& plaintext,
std::string* encrypted) {
encrypted_messages::EncryptedMessage encrypted_message;
if (!encrypted_messages::EncryptSerializedMessage(
kServerPublicKey, kServerPublicKeyVersion, kEncryptedMessageLabel,
plaintext, &encrypted_message) ||
!encrypted_message.SerializeToString(encrypted)) {
return false;
}
return true;
}
void VariationsService::AddObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
observer_list_.AddObserver(observer);
}
void VariationsService::RemoveObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
observer_list_.RemoveObserver(observer);
}
void VariationsService::OnAppEnterForeground() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!IsFetchingEnabled())
return;
// On mobile platforms, initialize the fetch scheduler when we receive the
// first app foreground notification.
if (!request_scheduler_)
StartRepeatedVariationsSeedFetch();
request_scheduler_->OnAppEnterForeground();
}
void VariationsService::SetRestrictMode(const std::string& restrict_mode) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// This should be called before the server URL has been computed.
DCHECK(variations_server_url_.is_empty());
restrict_mode_ = restrict_mode;
}
void VariationsService::SetCreateTrialsFromSeedCalledForTesting(bool called) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
field_trial_creator_.SetCreateTrialsFromSeedCalledForTesting(called);
}
GURL VariationsService::GetVariationsServerURL(
PrefService* policy_pref_service,
const std::string& restrict_mode_override,
HttpOptions http_options) {
bool secure = http_options == USE_HTTPS;
std::string server_url_string(
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
secure ? switches::kVariationsServerURL
: switches::kVariationsInsecureServerURL));
if (server_url_string.empty())
server_url_string = secure ? kDefaultServerUrl : kDefaultInsecureServerUrl;
GURL server_url = GURL(server_url_string);
if (secure) {
const std::string restrict_param =
!restrict_mode_override.empty()
? restrict_mode_override
: GetRestrictParameterPref(client_.get(), policy_pref_service);
if (!restrict_param.empty()) {
server_url = net::AppendOrReplaceQueryParameter(server_url, "restrict",
restrict_param);
}
}
server_url = net::AppendOrReplaceQueryParameter(server_url, "osname",
GetPlatformString());
// Add channel to the request URL.
version_info::Channel channel = client_->GetChannel();
if (channel != version_info::Channel::UNKNOWN) {
server_url = net::AppendOrReplaceQueryParameter(
server_url, "channel", version_info::GetChannelString(channel));
}
// Add milestone to the request URL.
std::string version = version_info::GetVersionNumber();
std::vector<std::string> version_parts = base::SplitString(
version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
if (version_parts.size() > 0) {
server_url = net::AppendOrReplaceQueryParameter(server_url, "milestone",
version_parts[0]);
}
DCHECK(server_url.is_valid());
return server_url;
}
// static
std::string VariationsService::GetDefaultVariationsServerURLForTesting() {
return kDefaultServerUrl;
}
// static
void VariationsService::RegisterPrefs(PrefRegistrySimple* registry) {
SafeSeedManager::RegisterPrefs(registry);
VariationsSeedStore::RegisterPrefs(registry);
registry->RegisterInt64Pref(prefs::kVariationsLastFetchTime, 0);
// This preference will only be written by the policy service, which will fill
// it according to a value stored in the User Policy.
registry->RegisterStringPref(prefs::kVariationsRestrictParameter,
std::string());
// This preference keeps track of the country code used to filter
// permanent-consistency studies.
registry->RegisterListPref(prefs::kVariationsPermanentConsistencyCountry);
}
// static
void VariationsService::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
// This preference will only be written by the policy service, which will fill
// it according to a value stored in the User Policy.
registry->RegisterStringPref(prefs::kVariationsRestrictParameter,
std::string());
}
// static
std::unique_ptr<VariationsService> VariationsService::Create(
std::unique_ptr<VariationsServiceClient> client,
PrefService* local_state,
metrics::MetricsStateManager* state_manager,
const char* disable_network_switch,
const UIStringOverrider& ui_string_overrider) {
std::unique_ptr<VariationsService> result;
result.reset(new VariationsService(
std::move(client),
base::MakeUnique<web_resource::ResourceRequestAllowedNotifier>(
local_state, disable_network_switch),
local_state, state_manager, ui_string_overrider));
return result;
}
// static
void VariationsService::EnableForTesting() {
g_enabled_for_testing = true;
}
void VariationsService::DoActualFetch() {
DoFetchFromURL(variations_server_url_);
}
bool VariationsService::StoreSeed(const std::string& seed_data,
const std::string& seed_signature,
const std::string& country_code,
base::Time date_fetched,
bool is_delta_compressed,
bool is_gzip_compressed,
bool fetched_insecurely) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
std::unique_ptr<VariationsSeed> seed(new VariationsSeed);
if (!field_trial_creator_.seed_store()->StoreSeedData(
seed_data, seed_signature, country_code, date_fetched,
is_delta_compressed, is_gzip_compressed, fetched_insecurely,
seed.get())) {
return false;
}
RecordSuccessfulFetch();
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
client_->GetVersionForSimulationCallback(),
base::Bind(&VariationsService::PerformSimulationWithVersion,
weak_ptr_factory_.GetWeakPtr(), base::Passed(&seed)));
return true;
}
std::unique_ptr<const base::FieldTrial::EntropyProvider>
VariationsService::CreateLowEntropyProvider() {
return state_manager_->CreateLowEntropyProvider();
}
bool VariationsService::DoFetchFromURL(const GURL& url) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(IsFetchingEnabled());
safe_seed_manager_.RecordFetchStarted();
// Normally, there shouldn't be a |pending_request_| when this fires. However
// it's not impossible - for example if Chrome was paused (e.g. in a debugger
// or if the machine was suspended) and OnURLFetchComplete() hasn't had a
// chance to run yet from the previous request. In this case, don't start a
// new request and just let the previous one finish.
if (pending_seed_request_)
return false;
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("chrome_variations_service", R"(
semantics {
sender: "Chrome Variations Service"
description:
"Retrieves the list of Google Chrome's Variations from the server, "
"which will apply to the next Chrome session upon a restart."
trigger:
"Requests are made periodically while Google Chrome is running."
data: "The operating system name."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting: "This feature cannot be disabled by settings."
policy_exception_justification:
"Not implemented, considered not required."
})");
pending_seed_request_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET,
this, traffic_annotation);
data_use_measurement::DataUseUserData::AttachToFetcher(
pending_seed_request_.get(),
data_use_measurement::DataUseUserData::VARIATIONS);
pending_seed_request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA |
net::LOAD_DO_NOT_SAVE_COOKIES);
pending_seed_request_->SetRequestContext(client_->GetURLRequestContext());
bool enable_deltas = false;
if (!field_trial_creator_.seed_store()->variations_serial_number().empty() &&
!disable_deltas_for_next_request_) {
// Tell the server that delta-compressed seeds are supported.
enable_deltas = true;
// Get the seed only if its serial number doesn't match what we have.
// If the fetch is being done over HTTP, encrypt the If-None-Match header.
const std::string& original_sn =
field_trial_creator_.seed_store()->variations_serial_number();
if (!url.SchemeIs(url::kHttpsScheme) &&
base::FeatureList::IsEnabled(kHttpRetryFeature)) {
std::string encrypted_sn;
std::string encoded_sn;
if (!EncryptString(original_sn, &encrypted_sn)) {
pending_seed_request_.reset();
return false;
}
base::Base64Encode(encrypted_sn, &encoded_sn);
pending_seed_request_->AddExtraRequestHeader("If-None-Match:" +
encoded_sn);
} else {
pending_seed_request_->AddExtraRequestHeader("If-None-Match:" +
original_sn);
}
}
// Tell the server that delta-compressed and gzipped seeds are supported.
const char* supported_im = enable_deltas ? "A-IM:x-bm,gzip" : "A-IM:gzip";
pending_seed_request_->AddExtraRequestHeader(supported_im);
pending_seed_request_->Start();
const base::TimeTicks now = base::TimeTicks::Now();
base::TimeDelta time_since_last_fetch;
// Record a time delta of 0 (default value) if there was no previous fetch.
if (!last_request_started_time_.is_null())
time_since_last_fetch = now - last_request_started_time_;
UMA_HISTOGRAM_CUSTOM_COUNTS("Variations.TimeSinceLastFetchAttempt",
time_since_last_fetch.InMinutes(), 1,
base::TimeDelta::FromDays(7).InMinutes(), 50);
UMA_HISTOGRAM_COUNTS_100("Variations.RequestCount", request_count_);
++request_count_;
last_request_started_time_ = now;
disable_deltas_for_next_request_ = false;
return true;
}
void VariationsService::StartRepeatedVariationsSeedFetch() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Initialize the Variations server URL.
variations_server_url_ =
GetVariationsServerURL(policy_pref_service_, restrict_mode_, USE_HTTPS);
// Initialize the fallback HTTP URL if the HTTP retry feature is enabled.
if (base::FeatureList::IsEnabled(kHttpRetryFeature)) {
insecure_variations_server_url_ =
GetVariationsServerURL(policy_pref_service_, restrict_mode_, USE_HTTP);
}
// Check that |CreateTrialsFromSeed| was called, which is necessary to
// retrieve the serial number that will be sent to the server.
DCHECK(field_trial_creator_.create_trials_from_seed_called());
DCHECK(!request_scheduler_.get());
request_scheduler_.reset(VariationsRequestScheduler::Create(
base::Bind(&VariationsService::FetchVariationsSeed,
weak_ptr_factory_.GetWeakPtr()),
local_state_));
// Note that the act of starting the scheduler will start the fetch, if the
// scheduler deems appropriate.
request_scheduler_->Start();
}
void VariationsService::FetchVariationsSeed() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const web_resource::ResourceRequestAllowedNotifier::State state =
resource_request_allowed_notifier_->GetResourceRequestsAllowedState();
RecordRequestsAllowedHistogram(ResourceRequestStateToHistogramValue(state));
if (state != web_resource::ResourceRequestAllowedNotifier::ALLOWED) {
DVLOG(1) << "Resource requests were not allowed. Waiting for notification.";
return;
}
DoActualFetch();
}
void VariationsService::NotifyObservers(
const VariationsSeedSimulator::Result& result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (result.kill_critical_group_change_count > 0) {
for (auto& observer : observer_list_)
observer.OnExperimentChangesDetected(Observer::CRITICAL);
} else if (result.kill_best_effort_group_change_count > 0) {
for (auto& observer : observer_list_)
observer.OnExperimentChangesDetected(Observer::BEST_EFFORT);
}
}
void VariationsService::OnURLFetchComplete(const net::URLFetcher* source) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_EQ(pending_seed_request_.get(), source);
const bool is_first_request = !initial_request_completed_;
initial_request_completed_ = true;
// The fetcher will be deleted when the request is handled.
std::unique_ptr<const net::URLFetcher> request(
pending_seed_request_.release());
const net::URLRequestStatus& status = request->GetStatus();
const int response_code = request->GetResponseCode();
bool was_https = request->GetURL().SchemeIs(url::kHttpsScheme);
if (was_https) {
base::UmaHistogramSparse(
"Variations.SeedFetchResponseOrErrorCode",
status.is_success() ? response_code : status.error());
} else {
base::UmaHistogramSparse(
"Variations.SeedFetchResponseOrErrorCode.HTTP",
status.is_success() ? response_code : status.error());
}
if (status.status() != net::URLRequestStatus::SUCCESS) {
DVLOG(1) << "Variations server request failed with error: "
<< status.error() << ": " << net::ErrorToString(status.error());
// If the current fetch attempt was over an HTTPS connection, retry the
// fetch immediately over an HTTP connection.
// Currently we only do this if if the 'VariationsHttpRetry' feature is
// enabled.
if (was_https && !insecure_variations_server_url_.is_empty()) {
// When re-trying via HTTP, return immediately. OnURLFetchComplete() will
// be called with the result of that retry.
if (DoFetchFromURL(insecure_variations_server_url_))
return;
}
// It's common for the very first fetch attempt to fail (e.g. the network
// may not yet be available). In such a case, try again soon, rather than
// waiting the full time interval.
if (is_first_request)
request_scheduler_->ScheduleFetchShortly();
return;
}
const base::TimeDelta latency =
base::TimeTicks::Now() - last_request_started_time_;
base::Time response_date;
if (response_code == net::HTTP_OK ||
response_code == net::HTTP_NOT_MODIFIED) {
bool success = request->GetResponseHeaders()->GetDateValue(&response_date);
DCHECK(success || response_date.is_null());
if (!response_date.is_null()) {
client_->GetNetworkTimeTracker()->UpdateNetworkTime(
response_date,
base::TimeDelta::FromMilliseconds(kServerTimeResolutionMs), latency,
base::TimeTicks::Now());
}
}
if (response_code != net::HTTP_OK) {
DVLOG(1) << "Variations server request returned non-HTTP_OK response code: "
<< response_code;
if (response_code == net::HTTP_NOT_MODIFIED) {
RecordSuccessfulFetch();
// Update the seed date value in local state (used for expiry check on
// next start up), since 304 is a successful response.
field_trial_creator_.seed_store()->UpdateSeedDateAndLogDayChange(
response_date);
}
return;
}
std::string seed_data;
bool success = request->GetResponseAsString(&seed_data);
DCHECK(success);
net::HttpResponseHeaders* headers = request->GetResponseHeaders();
bool is_delta_compressed;
bool is_gzip_compressed;
if (!GetInstanceManipulations(headers, &is_delta_compressed,
&is_gzip_compressed)) {
// The header does not specify supported instance manipulations, unable to
// process data. Details of errors were logged by GetInstanceManipulations.
field_trial_creator_.seed_store()->ReportUnsupportedSeedFormatError();
return;
}
const std::string signature = GetHeaderValue(headers, "X-Seed-Signature");
const std::string country_code = GetHeaderValue(headers, "X-Country");
const bool store_success =
StoreSeed(seed_data, signature, country_code, response_date,
is_delta_compressed, is_gzip_compressed, !was_https);
if (!store_success && is_delta_compressed) {
disable_deltas_for_next_request_ = true;
request_scheduler_->ScheduleFetchShortly();
}
}
void VariationsService::OnResourceRequestsAllowed() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Note that this only attempts to fetch the seed at most once per period
// (kSeedFetchPeriodHours). This works because
// |resource_request_allowed_notifier_| only calls this method if an
// attempt was made earlier that fails (which implies that the period had
// elapsed). After a successful attempt is made, the notifier will know not
// to call this method again until another failed attempt occurs.
RecordRequestsAllowedHistogram(RESOURCE_REQUESTS_ALLOWED_NOTIFIED);
DVLOG(1) << "Retrying fetch.";
DoActualFetch();
// This service must have created a scheduler in order for this to be called.
DCHECK(request_scheduler_.get());
request_scheduler_->Reset();
}
void VariationsService::PerformSimulationWithVersion(
std::unique_ptr<VariationsSeed> seed,
const base::Version& version) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!version.IsValid())
return;
const base::ElapsedTimer timer;
std::unique_ptr<const base::FieldTrial::EntropyProvider> default_provider =
state_manager_->CreateDefaultEntropyProvider();
std::unique_ptr<const base::FieldTrial::EntropyProvider> low_provider =
state_manager_->CreateLowEntropyProvider();
VariationsSeedSimulator seed_simulator(*default_provider, *low_provider);
std::unique_ptr<ClientFilterableState> client_state =
field_trial_creator_.GetClientFilterableStateForVersion(version);
const VariationsSeedSimulator::Result result =
seed_simulator.SimulateSeedStudies(*seed, *client_state);
UMA_HISTOGRAM_COUNTS_100("Variations.SimulateSeed.NormalChanges",
result.normal_group_change_count);
UMA_HISTOGRAM_COUNTS_100("Variations.SimulateSeed.KillBestEffortChanges",
result.kill_best_effort_group_change_count);
UMA_HISTOGRAM_COUNTS_100("Variations.SimulateSeed.KillCriticalChanges",
result.kill_critical_group_change_count);
UMA_HISTOGRAM_TIMES("Variations.SimulateSeed.Duration", timer.Elapsed());
NotifyObservers(result);
}
void VariationsService::RecordSuccessfulFetch() {
field_trial_creator_.RecordLastFetchTime();
safe_seed_manager_.RecordSuccessfulFetch();
}
void VariationsService::GetClientFilterableStateForVersionCalledForTesting() {
const base::Version current_version(version_info::GetVersionNumber());
if (!current_version.IsValid())
return;
field_trial_creator_.GetClientFilterableStateForVersion(current_version);
}
std::string VariationsService::GetLatestCountry() const {
return field_trial_creator_.GetLatestCountry();
}
bool VariationsService::SetupFieldTrials(
const char* kEnableGpuBenchmarking,
const char* kEnableFeatures,
const char* kDisableFeatures,
const std::set<std::string>& unforceable_field_trials,
std::unique_ptr<base::FeatureList> feature_list,
std::vector<std::string>* variation_ids,
variations::PlatformFieldTrials* platform_field_trials) {
return field_trial_creator_.SetupFieldTrials(
kEnableGpuBenchmarking, kEnableFeatures, kDisableFeatures,
unforceable_field_trials, CreateLowEntropyProvider(),
std::move(feature_list), variation_ids, platform_field_trials);
}
std::string VariationsService::GetStoredPermanentCountry() {
const base::ListValue* list_value =
local_state_->GetList(prefs::kVariationsPermanentConsistencyCountry);
std::string stored_country;
if (list_value->GetSize() == 2) {
list_value->GetString(1, &stored_country);
}
return stored_country;
}
bool VariationsService::OverrideStoredPermanentCountry(
const std::string& country_override) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (country_override.empty())
return false;
const base::ListValue* list_value =
local_state_->GetList(prefs::kVariationsPermanentConsistencyCountry);
std::string stored_country;
const bool got_stored_country =
list_value->GetSize() == 2 && list_value->GetString(1, &stored_country);
if (got_stored_country && stored_country == country_override)
return false;
base::Version version(version_info::GetVersionNumber());
field_trial_creator_.StorePermanentCountry(version, country_override);
return true;
}
} // namespace variations
| [
"rdeshm0@aptvm070-6.apt.emulab.net"
] | rdeshm0@aptvm070-6.apt.emulab.net |
539a947abcff63eca30c7f836e023cc842a54bfa | 8663abfc8bbaf09af99dcba5ec88aac752d2e28e | /DP_speed_planner/include/DP_speed_planner.h | 9c5655a0032e48cb3741042caad4a2c03c107a52 | [] | no_license | owenliu-rdc/apollo_and_-autoware_path_planner | 7a393cd581fccde13a2fc53a2cebdb0aef44b1b0 | 762c06b71cfb848e314e2d8ea3ace4b37083a109 | refs/heads/master | 2023-08-27T04:54:56.708092 | 2020-09-27T01:43:08 | 2020-09-27T01:43:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,989 | h |
#include <array>
#include <vector>
#include <iostream>
#include <limits>
#include <algorithm>
#include <unordered_map>
#include <string>
#include <memory>
#include <future> // std::async, std::future
#include <chrono> // std::chrono::milliseconds
class Box2d
{
public:
Box2d(const std::vector<double> ¢er, const double heading, const double length,
const double width)
{
// std::cout << "Box2d " << center[0] << " " << center[1] << std::endl;
center_ = (center);
length_ = (length);
width_ = (width);
half_length_ = (length / 2.0);
half_width_ = (width / 2.0);
heading_ = (heading);
cos_heading_ = (cos(heading));
sin_heading_ = (sin(heading));
InitCorners();
}
double center_x()
{
return center_[0];
}
double center_y()
{
return center_[1];
}
bool HasOverlap(Box2d box)
{
}
double DistanceTo(Box2d &point)
{
double x_diff = center_[0] - point.center_[0];
double y_diff = center_[1] - point.center_[1];
double distance = hypot(y_diff, x_diff);
// distance = 0.5;
return distance;
}
void InitCorners()
{
const double dx1 = cos_heading_ * half_length_;
const double dy1 = sin_heading_ * half_length_;
const double dx2 = sin_heading_ * half_width_;
const double dy2 = -cos_heading_ * half_width_;
corners_.clear();
std::vector<double> corner_point_1{center_[0] + dx1 + dx2, center_[1] + dy1 + dy2};
std::vector<double> corner_point_2{center_[0] + dx1 - dx2, center_[1] + dy1 - dy2};
std::vector<double> corner_point_3{center_[0] - dx1 - dx2, center_[1] - dy1 - dy2};
std::vector<double> corner_point_4{center_[0] - dx1 + dx2, center_[1] - dy1 + dy2};
corners_.push_back(corner_point_1);
corners_.push_back(corner_point_2);
corners_.push_back(corner_point_3);
corners_.push_back(corner_point_4);
for (auto &corner : corners_)
{
max_x_ = std::fmax(corner[0], max_x_);
min_x_ = std::fmin(corner[0], min_x_);
max_y_ = std::fmax(corner[1], max_y_);
min_y_ = std::fmin(corner[1], min_y_);
}
}
std::vector<double> center_;
double length_ = 0.0;
double width_ = 0.0;
double half_length_ = 0.0;
double half_width_ = 0.0;
double heading_ = 0.0;
double cos_heading_ = 1.0;
double sin_heading_ = 0.0;
double max_x_ = std::numeric_limits<double>::lowest();
double min_x_ = std::numeric_limits<double>::max();
double max_y_ = std::numeric_limits<double>::lowest();
double min_y_ = std::numeric_limits<double>::max();
std::vector<std::vector<double>> corners_;
};
// 数据部分
struct Waypoint
{
Waypoint(const double _x, const double _y, const double _theta, const double _s)
: x(_x), y(_y), theta(_theta), s(_s)
{
}
double x;
double y;
double theta;
double s;
};
struct DiscretizedPath
{
explicit DiscretizedPath(const std::vector<Waypoint> &_waypoints) : points(_waypoints)
{
}
DiscretizedPath() = default;
std::vector<Waypoint> points;
};
struct TrajectoryPoint
{
TrajectoryPoint(const Waypoint &_waypoint, const double _v, const double _relative_time)
: waypoint(_waypoint), v(_v), relative_time(_relative_time)
{
}
Waypoint waypoint;
double v;
double relative_time;
};
struct DiscretizedTrajectory
{
explicit DiscretizedTrajectory(const std::vector<TrajectoryPoint> &_traj_points)
: traj_points(_traj_points)
{
}
DiscretizedTrajectory() = default;
std::vector<TrajectoryPoint> traj_points;
};
// 障碍物
struct Obstacle
{
Obstacle(const std::string &_id, const Box2d &_bounding_box, const bool _is_static,
const DiscretizedTrajectory &_trajectory)
: id(_id), bounding_box(_bounding_box), is_static(_is_static), trajectory(_trajectory)
{
}
Obstacle(const std::string &_id, const Box2d &_bounding_box, const bool _is_static)
: id(_id), bounding_box(_bounding_box), is_static(_is_static)
{
}
std::string id;
Box2d bounding_box;
bool is_static;
DiscretizedTrajectory trajectory;
};
// StBoundary
struct SpeedPoint
{
SpeedPoint(const double _t, const double _s, double _v) : t(_t), s(_s), v(_v)
{
}
void set_s(std::uint32_t s_)
{
s = s_;
}
void set_t(std::uint32_t t_)
{
t = t_;
}
void set_v(std::uint32_t v_)
{
v = v_;
}
double t;
double s;
double v;
};
// StBoundary
struct StPoint
{
StPoint(float _t, float _s) : t(_t), s(_s)
{
}
void set_s(float s_)
{
s = s_;
}
void set_t(float t_)
{
t = t_;
}
float t;
float s;
};
struct SlPoint
{
SlPoint(float _s, float _l) : s(_s), l(_l)
{
}
float s;
float l;
};
struct StGraphPoint
{
StGraphPoint(StPoint &_st_point)
: st_point(_st_point), cost(std::numeric_limits<double>::max())
{
}
void Init(float index_t,
float index_s, StPoint st_point)
{
index_t_ = index_t;
index_s_ = index_s;
st_point = st_point;
}
void SetPreNode(StGraphPoint pre_node_)
{
pre_node = &pre_node_;
}
StPoint st_point;
// , pre_node(nullptr)
StGraphPoint *pre_node = nullptr;
void SetTotalCost(double cost_)
{
cost = cost_;
}
double cost;
void SetObstacleCost(double ObstacleCost_)
{
ObstacleCost = ObstacleCost_;
}
double ObstacleCost;
void SetSpatialPotentialCost(double SpatialPotentialCost_)
{
ObstacleCost = SpatialPotentialCost_;
}
double SpatialPotentialCost;
float index_s_ = 0;
float index_t_ = 0;
double crusie_velocity;
double current_velocity;
void SetCruiseSpeed(double crusie_velocity_)
{
crusie_velocity = crusie_velocity_;
}
void SetCurrentSpeed(double current_velocity_)
{
current_velocity = current_velocity_;
}
};
class StBoundary
{
public:
StBoundary();
void Init(std::string obs_id, std::vector<StPoint> lower_points,
std::vector<StPoint> upper_points);
bool Evaluate(const double t, double *const lower_s, double *const upper_s) const;
std::string id() const
{
return obs_id_;
}
public:
bool is_init_ = false;
std::string obs_id_;
std::vector<StPoint> lower_points_;
std::vector<StPoint> upper_points_;
};
StBoundary::StBoundary()
{
is_init_ = false;
}
void StBoundary::Init(std::string obs_id, std::vector<StPoint> lower_points,
std::vector<StPoint> upper_points)
{
// CHECK_EQ(lower_points.size(), upper_points.size());
// CHECK_GE(lower_points.size(), 2);
obs_id_ = obs_id;
lower_points_ = lower_points;
upper_points_ = upper_points;
is_init_ = true;
}
bool StBoundary::Evaluate(const double t, double *const lower_s, double *const upper_s) const
{
// CHECK_NOTNULL(lower_s);
// CHECK_NOTNULL(upper_s);
// CHECK(is_init_);
if (t < lower_points_.front().t)
{
return false;
}
if (t > lower_points_.back().t)
{
return false;
}
auto func = [](const StPoint &st_point, const double t) { return st_point.t < t; };
const auto &lower_iter = std::lower_bound(lower_points_.begin(), lower_points_.end(), t, func);
if (lower_iter != lower_points_.end())
{
*lower_s = lower_iter->s;
}
else
{
return false;
}
const auto &upper_iter = std::lower_bound(upper_points_.begin(), upper_points_.end(), t, func);
if (upper_iter != upper_points_.end())
{
*upper_s = upper_iter->s;
}
else
{
return false;
}
return true;
}
// S-T Graph
class StGraph final
{
public:
StGraph(const DiscretizedPath &path, const std::vector<Obstacle> &obstacles);
bool GetAllObstacleStBoundary(std::vector<StBoundary> *const st_boundaries) const;
bool GetObstacleStBoundary(const std::string &obs_id, StBoundary *const st_boundary) const;
bool GetAllBlockedSRangesByT(const double t,
std::vector<std::pair<double, double>> *const blocked_ranges) const;
bool GetBlockedSRangeByT(const double t, const StBoundary &st_boundary,
std::pair<double, double> *blocked_range) const;
private:
void CalculateAllObstacleStBoundary(const std::vector<Obstacle> &obstacles);
bool CalculateObstacleStBoundary(const Obstacle &obs, StBoundary *const st_boundary) const;
bool CalculateStaticObstacleStBoundary(const std::string &obs_id, const Box2d &obs_box,
StBoundary *const st_boundary) const;
bool CalculateDynamicObstacleStBoundary(const Obstacle &obs, StBoundary *const st_boundary) const;
std::vector<Waypoint> GetWaypointsWithinDistance(const double x, const double y,
const double radius) const;
bool GetBlockedSRange(const Box2d &obs_box, double *const lower_s, double *const upper_s) const;
private:
std::unordered_map<std::string, StBoundary> obs_st_boundary_;
DiscretizedPath discretized_path_;
const double veh_heading_ = M_PI / 4.0;
const double veh_length_ = 2.0;
const double veh_width_ = 1.0;
const double time_range_ = 4.0;
};
StGraph::StGraph(const DiscretizedPath &path, const std::vector<Obstacle> &obstacles)
: discretized_path_(path)
{
// CHECK_GE(discretized_path_.points.size(), 2);
obs_st_boundary_.clear();
CalculateAllObstacleStBoundary(obstacles);
}
bool StGraph::GetAllObstacleStBoundary(std::vector<StBoundary> *const st_boundaries) const
{
// CHECK_NOTNULL(st_boundaries);
for (auto iter = obs_st_boundary_.begin(); iter != obs_st_boundary_.end(); ++iter)
{
st_boundaries->emplace_back(iter->second);
}
return true;
}
bool StGraph::GetObstacleStBoundary(const std::string &obs_id,
StBoundary *const st_boundary) const
{
// CHECK_NOTNULL(st_boundary);
const auto &iter = obs_st_boundary_.find(obs_id);
if (iter == obs_st_boundary_.end())
{
return false;
}
*st_boundary = iter->second;
return true;
}
bool StGraph::GetAllBlockedSRangesByT(
const double t, std::vector<std::pair<double, double>> *const blocked_ranges) const
{
// CHECK_NOTNULL(blocked_ranges);
std::vector<StBoundary> st_boundaries;
GetAllObstacleStBoundary(&st_boundaries);
for (const auto &st_boundary : st_boundaries)
{
std::pair<double, double> blocked_range;
if (GetBlockedSRangeByT(t, st_boundary, &blocked_range))
{
blocked_ranges->emplace_back(blocked_range);
}
}
return true;
}
bool StGraph::GetBlockedSRangeByT(const double t, const StBoundary &st_boundary,
std::pair<double, double> *blocked_range) const
{
// CHECK_NOTNULL(blocked_range);
double lower_s = 0.0;
double upper_s = 0.0;
if (st_boundary.Evaluate(t, &lower_s, &upper_s))
{
*blocked_range = std::make_pair(lower_s, upper_s);
return true;
}
return false;
}
void StGraph::CalculateAllObstacleStBoundary(const std::vector<Obstacle> &obstacles)
{
for (const auto &obstacle : obstacles)
{
const auto &iter = obs_st_boundary_.find(obstacle.id);
// CHECK(iter == obs_st_boundary_.end());
StBoundary st_boundary;
if (!CalculateObstacleStBoundary(obstacle, &st_boundary))
{
// AWARN << "Failed to get obstacle: " << obstacle.id << " st_boundary. ";
continue;
}
obs_st_boundary_.insert(std::make_pair(obstacle.id, st_boundary));
}
}
bool StGraph::CalculateObstacleStBoundary(const Obstacle &obstacle,
StBoundary *const st_boundary) const
{
// CHECK_NOTNULL(st_boundary);
if (obstacle.is_static)
{
return CalculateStaticObstacleStBoundary(obstacle.id, obstacle.bounding_box, st_boundary);
}
else
{
return CalculateDynamicObstacleStBoundary(obstacle, st_boundary);
}
}
bool StGraph::CalculateStaticObstacleStBoundary(const std::string &obs_id, const Box2d &obs_box,
StBoundary *const st_boundary) const
{
// CHECK_NOTNULL(st_boundary);
double lower_s = 0.0;
double upper_s = 0.0;
if (!GetBlockedSRange(obs_box, &lower_s, &upper_s))
{
return false;
}
std::vector<StPoint> lower_points{StPoint(0.0, lower_s), StPoint(time_range_, lower_s)};
std::vector<StPoint> upper_points{StPoint(0.0, upper_s), StPoint(time_range_, upper_s)};
st_boundary->Init(obs_id, lower_points, upper_points);
return true;
}
bool StGraph::GetBlockedSRange(const Box2d &obs_box, double *const lower_s,
double *const upper_s) const
{
// CHECK_NOTNULL(lower_s);
// CHECK_NOTNULL(upper_s);
const double radius = 5.0;
double radiAus = 2;
const auto &points = GetWaypointsWithinDistance(obs_box.center_[0], obs_box.center_[1], radiAus);
if (points.empty())
{
// ADEBUG << "Obstacle is not on the path. ";
return false;
}
bool is_updated = false;
for (auto iter = points.begin(); iter != points.end(); ++iter)
{
Box2d veh_box({iter->x, iter->y}, veh_heading_, veh_length_, veh_width_);
if (veh_box.HasOverlap(obs_box))
{
iter = iter == points.begin() ? iter : iter - 1;
*lower_s = iter->s;
is_updated = true;
break;
}
}
if (!is_updated)
{
// ADEBUG << "There is no collision with obstacle. ";
return false;
}
for (auto iter = points.rbegin(); iter != points.rend(); ++iter)
{
Box2d veh_box({iter->x, iter->y}, veh_heading_, veh_length_, veh_width_);
if (veh_box.HasOverlap(obs_box))
{
iter = iter == points.rbegin() ? iter : iter - 1;
*upper_s = iter->s;
break;
}
}
// CHECK_GE(*upper_s, *lower_s) << "upper_s: " << *upper_s << ", lower_s: " << *lower_s;
return true;
}
bool StGraph::CalculateDynamicObstacleStBoundary(const Obstacle &obstacle,
StBoundary *const st_boundary) const
{
// CHECK_NOTNULL(st_boundary);
// CHECK_GE(obstacle.trajectory.traj_points.size(), 2);
bool has_st_boundary = false;
std::vector<StPoint> lower_points;
std::vector<StPoint> upper_points;
for (const auto &p : obstacle.trajectory.traj_points)
{
Box2d obs_box({p.waypoint.x, p.waypoint.y}, p.waypoint.theta, obstacle.bounding_box.length_,
obstacle.bounding_box.width_);
double lower_s = 0.0;
double upper_s = 0.0;
if (GetBlockedSRange(obs_box, &lower_s, &upper_s))
{
lower_points.emplace_back(p.relative_time, lower_s);
upper_points.emplace_back(p.relative_time, upper_s);
has_st_boundary = true;
}
}
st_boundary->Init(obstacle.id, lower_points, upper_points);
return has_st_boundary;
}
std::vector<Waypoint> StGraph::GetWaypointsWithinDistance(const double x, const double y,
const double radius) const
{
std::vector<Waypoint> nearest_points;
for (const auto &p : discretized_path_.points)
{
if (std::hypot(p.x - x, p.y - y) < radius)
{
nearest_points.emplace_back(p);
}
}
return nearest_points;
}
void DisplayStGraph(const std::vector<StBoundary> &st_boundaries)
{
}
| [
"373605178@qq.com"
] | 373605178@qq.com |
17c58a2d16ab716e76504594e711fdb4c2a7d566 | 6460d398e781345c129b960bbc338aa3973e50bf | /Server/CommandSystem/CommandCharacter/CommandCharacterDrop.cpp | 85c524669c4abd1d0884d2cb291c69020c9576c8 | [] | no_license | gaoyang853/Mahjong_Server | 2d1f8bfe72ba63b681f0a4ecfeee41aa6f777c69 | 86df209d45671c52c2a146437affc9e30f66d742 | refs/heads/master | 2021-06-22T01:39:05.546585 | 2017-08-23T16:24:43 | 2017-08-23T16:24:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 821 | cpp | #include "CommandHeader.h"
#include "CharacterPlayer.h"
#include "PacketHeader.h"
#include "NetServer.h"
#include "CharacterData.h"
void CommandCharacterDrop::execute()
{
CharacterPlayer* player = static_cast<CharacterPlayer*>(mReceiver);
player->dropMahjong(mIndex);
SCRequestDropRet* requestDropRet = static_cast<SCRequestDropRet*>(mNetServer->createPacket(PT_SC_REQUEST_DROP_RET));
requestDropRet->mIndex = mIndex;
requestDropRet->mMahjong = mMahjong;
mNetServer->sendMessage(requestDropRet, player->getClientGUID());
// 打出一张牌后,需要重新排列
CommandCharacterReorderMahjong cmdReorder(CMD_PARAM);
mCommandSystem->pushCommand(&cmdReorder, player);
}
std::string CommandCharacterDrop::showDebugInfo()
{
COMMAND_DEBUG("index : %d, mahjong : %s", mIndex, MAHJONG_NAME[mMahjong].c_str());
} | [
"785130190@qq.com"
] | 785130190@qq.com |
022922e7433d7f4aacf7c6b84284f2130c070355 | 55d560fe6678a3edc9232ef14de8fafd7b7ece12 | /boost/circular_buffer/base.hpp | 756bd13eb0408123ac460c1a7fc1f1443f74b1eb | [
"BSL-1.0"
] | permissive | stardog-union/boost | ec3abeeef1b45389228df031bf25b470d3d123c5 | caa4a540db892caa92e5346e0094c63dea51cbfb | refs/heads/stardog/develop | 2021-06-25T02:15:10.697006 | 2020-11-17T19:50:35 | 2020-11-17T19:50:35 | 148,681,713 | 0 | 0 | BSL-1.0 | 2020-11-17T19:50:36 | 2018-09-13T18:38:54 | C++ | UTF-8 | C++ | false | false | 157,279 | hpp | // Implementation of the base circular buffer.
// Copyright (c) 2003-2008 Jan Gaspar
// Copyright (c) 2013 Paul A. Bristow // Doxygen comments changed.
// Copyright (c) 2013 Antony Polukhin // Move semantics implementation.
// Copyright (c) 2014 Glen Fernandes // C++11 allocator model support.
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#if !defined(BOOST_CIRCULAR_BUFFER_BASE_HPP)
#define BOOST_CIRCULAR_BUFFER_BASE_HPP
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/config.hpp>
#include <boost/call_traits.hpp>
#include <boost/concept_check.hpp>
#include <boost/limits.hpp>
#include <boost/container/allocator_traits.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <boost/iterator/iterator_traits.hpp>
#include <boost/type_traits/is_stateless.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/type_traits/is_scalar.hpp>
#include <boost/type_traits/is_nothrow_move_constructible.hpp>
#include <boost/type_traits/is_nothrow_move_assignable.hpp>
#include <boost/type_traits/is_copy_constructible.hpp>
#include <boost/type_traits/conditional.hpp>
#include <boost/move/adl_move_swap.hpp>
#include <boost/move/move.hpp>
#include <boost/utility/addressof.hpp>
#include <algorithm>
#include <utility>
#include <deque>
#include <stdexcept>
#if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3205))
#include <stddef.h>
#endif
namespace boost {
/*!
\class circular_buffer
\brief Circular buffer - a STL compliant container.
\tparam T The type of the elements stored in the <code>circular_buffer</code>.
\par Type Requirements T
The <code>T</code> has to be <a href="http://www.sgi.com/tech/stl/Assignable.html">
SGIAssignable</a> (SGI STL defined combination of <a href="../../../utility/Assignable.html">
Assignable</a> and <a href="../../../utility/CopyConstructible.html">CopyConstructible</a>).
Moreover <code>T</code> has to be <a href="http://www.sgi.com/tech/stl/DefaultConstructible.html">
DefaultConstructible</a> if supplied as a default parameter when invoking some of the
<code>circular_buffer</code>'s methods e.g.
<code>insert(iterator pos, const value_type& item = %value_type())</code>. And
<a href="http://www.sgi.com/tech/stl/EqualityComparable.html">EqualityComparable</a> and/or
<a href="../../../utility/LessThanComparable.html">LessThanComparable</a> if the <code>circular_buffer</code>
will be compared with another container.
\tparam Alloc The allocator type used for all internal memory management.
\par Type Requirements Alloc
The <code>Alloc</code> has to meet the allocator requirements imposed by STL.
\par Default Alloc
std::allocator<T>
For detailed documentation of the circular_buffer visit:
http://www.boost.org/libs/circular_buffer/doc/circular_buffer.html
*/
template <class T, class Alloc>
class circular_buffer
/*! \cond */
#if BOOST_CB_ENABLE_DEBUG
: public cb_details::debug_iterator_registry
#endif
/*! \endcond */
{
// Requirements
//BOOST_CLASS_REQUIRE(T, boost, SGIAssignableConcept);
//BOOST_CONCEPT_ASSERT((Assignable<T>));
//BOOST_CONCEPT_ASSERT((CopyConstructible<T>));
//BOOST_CONCEPT_ASSERT((DefaultConstructible<T>));
// Required if the circular_buffer will be compared with anther container.
//BOOST_CONCEPT_ASSERT((EqualityComparable<T>));
//BOOST_CONCEPT_ASSERT((LessThanComparable<T>));
public:
// Basic types
//! The type of this <code>circular_buffer</code>.
typedef circular_buffer<T, Alloc> this_type;
//! The type of elements stored in the <code>circular_buffer</code>.
typedef typename boost::container::allocator_traits<Alloc>::value_type value_type;
//! A pointer to an element.
typedef typename boost::container::allocator_traits<Alloc>::pointer pointer;
//! A const pointer to the element.
typedef typename boost::container::allocator_traits<Alloc>::const_pointer const_pointer;
//! A reference to an element.
typedef typename boost::container::allocator_traits<Alloc>::reference reference;
//! A const reference to an element.
typedef typename boost::container::allocator_traits<Alloc>::const_reference const_reference;
//! The distance type.
/*!
(A signed integral type used to represent the distance between two iterators.)
*/
typedef typename boost::container::allocator_traits<Alloc>::difference_type difference_type;
//! The size type.
/*!
(An unsigned integral type that can represent any non-negative value of the container's distance type.)
*/
typedef typename boost::container::allocator_traits<Alloc>::size_type size_type;
//! The type of an allocator used in the <code>circular_buffer</code>.
typedef Alloc allocator_type;
// Iterators
//! A const (random access) iterator used to iterate through the <code>circular_buffer</code>.
typedef cb_details::iterator< circular_buffer<T, Alloc>, cb_details::const_traits<boost::container::allocator_traits<Alloc> > > const_iterator;
//! A (random access) iterator used to iterate through the <code>circular_buffer</code>.
typedef cb_details::iterator< circular_buffer<T, Alloc>, cb_details::nonconst_traits<boost::container::allocator_traits<Alloc> > > iterator;
//! A const iterator used to iterate backwards through a <code>circular_buffer</code>.
typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;
//! An iterator used to iterate backwards through a <code>circular_buffer</code>.
typedef boost::reverse_iterator<iterator> reverse_iterator;
// Container specific types
//! An array range.
/*!
(A typedef for the <a href="http://www.sgi.com/tech/stl/pair.html"><code>std::pair</code></a> where
its first element is a pointer to a beginning of an array and its second element represents
a size of the array.)
*/
typedef std::pair<pointer, size_type> array_range;
//! A range of a const array.
/*!
(A typedef for the <a href="http://www.sgi.com/tech/stl/pair.html"><code>std::pair</code></a> where
its first element is a pointer to a beginning of a const array and its second element represents
a size of the const array.)
*/
typedef std::pair<const_pointer, size_type> const_array_range;
//! The capacity type.
/*!
(Same as <code>size_type</code> - defined for consistency with the __cbso class.
*/
// <a href="space_optimized.html"><code>circular_buffer_space_optimized</code></a>.)
typedef size_type capacity_type;
// Helper types
//! A type representing the "best" way to pass the value_type to a method.
typedef const value_type& param_value_type;
//! A type representing rvalue from param type.
//! On compilers without rvalue references support this type is the Boost.Moves type used for emulation.
typedef BOOST_RV_REF(value_type) rvalue_type;
private:
// Member variables
//! The internal buffer used for storing elements in the circular buffer.
pointer m_buff;
//! The internal buffer's end (end of the storage space).
pointer m_end;
//! The virtual beginning of the circular buffer.
pointer m_first;
//! The virtual end of the circular buffer (one behind the last element).
pointer m_last;
//! The number of items currently stored in the circular buffer.
size_type m_size;
//! The allocator.
allocator_type m_alloc;
// Friends
#if defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
friend iterator;
friend const_iterator;
#else
template <class Buff, class Traits> friend struct cb_details::iterator;
#endif
public:
// Allocator
//! Get the allocator.
/*!
\return The allocator.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>get_allocator()</code> for obtaining an allocator %reference.
*/
allocator_type get_allocator() const BOOST_NOEXCEPT { return m_alloc; }
//! Get the allocator reference.
/*!
\return A reference to the allocator.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\note This method was added in order to optimize obtaining of the allocator with a state,
although use of stateful allocators in STL is discouraged.
\sa <code>get_allocator() const</code>
*/
allocator_type& get_allocator() BOOST_NOEXCEPT { return m_alloc; }
// Element access
//! Get the iterator pointing to the beginning of the <code>circular_buffer</code>.
/*!
\return A random access iterator pointing to the first element of the <code>circular_buffer</code>. If the
<code>circular_buffer</code> is empty it returns an iterator equal to the one returned by
<code>end()</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>end()</code>, <code>rbegin()</code>, <code>rend()</code>
*/
iterator begin() BOOST_NOEXCEPT { return iterator(this, empty() ? 0 : m_first); }
//! Get the iterator pointing to the end of the <code>circular_buffer</code>.
/*!
\return A random access iterator pointing to the element "one behind" the last element of the <code>
circular_buffer</code>. If the <code>circular_buffer</code> is empty it returns an iterator equal to
the one returned by <code>begin()</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>begin()</code>, <code>rbegin()</code>, <code>rend()</code>
*/
iterator end() BOOST_NOEXCEPT { return iterator(this, 0); }
//! Get the const iterator pointing to the beginning of the <code>circular_buffer</code>.
/*!
\return A const random access iterator pointing to the first element of the <code>circular_buffer</code>. If
the <code>circular_buffer</code> is empty it returns an iterator equal to the one returned by
<code>end() const</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>end() const</code>, <code>rbegin() const</code>, <code>rend() const</code>
*/
const_iterator begin() const BOOST_NOEXCEPT { return const_iterator(this, empty() ? 0 : m_first); }
//! Get the const iterator pointing to the end of the <code>circular_buffer</code>.
/*!
\return A const random access iterator pointing to the element "one behind" the last element of the <code>
circular_buffer</code>. If the <code>circular_buffer</code> is empty it returns an iterator equal to
the one returned by <code>begin() const</code> const.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>begin() const</code>, <code>rbegin() const</code>, <code>rend() const</code>
*/
const_iterator end() const BOOST_NOEXCEPT { return const_iterator(this, 0); }
//! Get the iterator pointing to the beginning of the "reversed" <code>circular_buffer</code>.
/*!
\return A reverse random access iterator pointing to the last element of the <code>circular_buffer</code>.
If the <code>circular_buffer</code> is empty it returns an iterator equal to the one returned by
<code>rend()</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>rend()</code>, <code>begin()</code>, <code>end()</code>
*/
reverse_iterator rbegin() BOOST_NOEXCEPT { return reverse_iterator(end()); }
//! Get the iterator pointing to the end of the "reversed" <code>circular_buffer</code>.
/*!
\return A reverse random access iterator pointing to the element "one before" the first element of the <code>
circular_buffer</code>. If the <code>circular_buffer</code> is empty it returns an iterator equal to
the one returned by <code>rbegin()</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>rbegin()</code>, <code>begin()</code>, <code>end()</code>
*/
reverse_iterator rend() BOOST_NOEXCEPT { return reverse_iterator(begin()); }
//! Get the const iterator pointing to the beginning of the "reversed" <code>circular_buffer</code>.
/*!
\return A const reverse random access iterator pointing to the last element of the
<code>circular_buffer</code>. If the <code>circular_buffer</code> is empty it returns an iterator equal
to the one returned by <code>rend() const</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>rend() const</code>, <code>begin() const</code>, <code>end() const</code>
*/
const_reverse_iterator rbegin() const BOOST_NOEXCEPT { return const_reverse_iterator(end()); }
//! Get the const iterator pointing to the end of the "reversed" <code>circular_buffer</code>.
/*!
\return A const reverse random access iterator pointing to the element "one before" the first element of the
<code>circular_buffer</code>. If the <code>circular_buffer</code> is empty it returns an iterator equal
to the one returned by <code>rbegin() const</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>rbegin() const</code>, <code>begin() const</code>, <code>end() const</code>
*/
const_reverse_iterator rend() const BOOST_NOEXCEPT { return const_reverse_iterator(begin()); }
//! Get the element at the <code>index</code> position.
/*!
\pre <code>0 \<= index \&\& index \< size()</code>
\param index The position of the element.
\return A reference to the element at the <code>index</code> position.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>at()</code>
*/
reference operator [] (size_type index) {
BOOST_CB_ASSERT(index < size()); // check for invalid index
return *add(m_first, index);
}
//! Get the element at the <code>index</code> position.
/*!
\pre <code>0 \<= index \&\& index \< size()</code>
\param index The position of the element.
\return A const reference to the element at the <code>index</code> position.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>\link at(size_type)const at() const \endlink</code>
*/
const_reference operator [] (size_type index) const {
BOOST_CB_ASSERT(index < size()); // check for invalid index
return *add(m_first, index);
}
//! Get the element at the <code>index</code> position.
/*!
\param index The position of the element.
\return A reference to the element at the <code>index</code> position.
\throws <code>std::out_of_range</code> when the <code>index</code> is invalid (when
<code>index >= size()</code>).
\par Exception Safety
Strong.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>\link operator[](size_type) operator[] \endlink</code>
*/
reference at(size_type index) {
check_position(index);
return (*this)[index];
}
//! Get the element at the <code>index</code> position.
/*!
\param index The position of the element.
\return A const reference to the element at the <code>index</code> position.
\throws <code>std::out_of_range</code> when the <code>index</code> is invalid (when
<code>index >= size()</code>).
\par Exception Safety
Strong.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>\link operator[](size_type)const operator[] const \endlink</code>
*/
const_reference at(size_type index) const {
check_position(index);
return (*this)[index];
}
//! Get the first element.
/*!
\pre <code>!empty()</code>
\return A reference to the first element of the <code>circular_buffer</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>back()</code>
*/
reference front() {
BOOST_CB_ASSERT(!empty()); // check for empty buffer (front element not available)
return *m_first;
}
//! Get the last element.
/*!
\pre <code>!empty()</code>
\return A reference to the last element of the <code>circular_buffer</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>front()</code>
*/
reference back() {
BOOST_CB_ASSERT(!empty()); // check for empty buffer (back element not available)
return *((m_last == m_buff ? m_end : m_last) - 1);
}
//! Get the first element.
/*!
\pre <code>!empty()</code>
\return A const reference to the first element of the <code>circular_buffer</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>back() const</code>
*/
const_reference front() const {
BOOST_CB_ASSERT(!empty()); // check for empty buffer (front element not available)
return *m_first;
}
//! Get the last element.
/*!
\pre <code>!empty()</code>
\return A const reference to the last element of the <code>circular_buffer</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>front() const</code>
*/
const_reference back() const {
BOOST_CB_ASSERT(!empty()); // check for empty buffer (back element not available)
return *((m_last == m_buff ? m_end : m_last) - 1);
}
//! Get the first continuous array of the internal buffer.
/*!
This method in combination with <code>array_two()</code> can be useful when passing the stored data into
a legacy C API as an array. Suppose there is a <code>circular_buffer</code> of capacity 10, containing 7
characters <code>'a', 'b', ..., 'g'</code> where <code>buff[0] == 'a'</code>, <code>buff[1] == 'b'</code>,
... and <code>buff[6] == 'g'</code>:<br><br>
<code>circular_buffer<char> buff(10);</code><br><br>
The internal representation is often not linear and the state of the internal buffer may look like this:<br>
<br><code>
|e|f|g| | | |a|b|c|d|<br>
end ___^<br>
begin _______^</code><br><br>
where <code>|a|b|c|d|</code> represents the "array one", <code>|e|f|g|</code> represents the "array two" and
<code>| | | |</code> is a free space.<br>
Now consider a typical C style function for writing data into a file:<br><br>
<code>int write(int file_desc, char* buff, int num_bytes);</code><br><br>
There are two ways how to write the content of the <code>circular_buffer</code> into a file. Either relying
on <code>array_one()</code> and <code>array_two()</code> methods and calling the write function twice:<br><br>
<code>array_range ar = buff.array_one();<br>
write(file_desc, ar.first, ar.second);<br>
ar = buff.array_two();<br>
write(file_desc, ar.first, ar.second);</code><br><br>
Or relying on the <code>linearize()</code> method:<br><br><code>
write(file_desc, buff.linearize(), buff.size());</code><br><br>
Since the complexity of <code>array_one()</code> and <code>array_two()</code> methods is constant the first
option is suitable when calling the write method is "cheap". On the other hand the second option is more
suitable when calling the write method is more "expensive" than calling the <code>linearize()</code> method
whose complexity is linear.
\return The array range of the first continuous array of the internal buffer. In the case the
<code>circular_buffer</code> is empty the size of the returned array is <code>0</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\warning In general invoking any method which modifies the internal state of the circular_buffer may
delinearize the internal buffer and invalidate the array ranges returned by <code>array_one()</code>
and <code>array_two()</code> (and their const versions).
\note In the case the internal buffer is linear e.g. <code>|a|b|c|d|e|f|g| | | |</code> the "array one" is
represented by <code>|a|b|c|d|e|f|g|</code> and the "array two" does not exist (the
<code>array_two()</code> method returns an array with the size <code>0</code>).
\sa <code>array_two()</code>, <code>linearize()</code>
*/
array_range array_one() {
return array_range(m_first, (m_last <= m_first && !empty() ? m_end : m_last) - m_first);
}
//! Get the second continuous array of the internal buffer.
/*!
This method in combination with <code>array_one()</code> can be useful when passing the stored data into
a legacy C API as an array.
\return The array range of the second continuous array of the internal buffer. In the case the internal buffer
is linear or the <code>circular_buffer</code> is empty the size of the returned array is
<code>0</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>array_one()</code>
*/
array_range array_two() {
return array_range(m_buff, m_last <= m_first && !empty() ? m_last - m_buff : 0);
}
//! Get the first continuous array of the internal buffer.
/*!
This method in combination with <code>array_two() const</code> can be useful when passing the stored data into
a legacy C API as an array.
\return The array range of the first continuous array of the internal buffer. In the case the
<code>circular_buffer</code> is empty the size of the returned array is <code>0</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>array_two() const</code>; <code>array_one()</code> for more details how to pass data into a legacy C
API.
*/
const_array_range array_one() const {
return const_array_range(m_first, (m_last <= m_first && !empty() ? m_end : m_last) - m_first);
}
//! Get the second continuous array of the internal buffer.
/*!
This method in combination with <code>array_one() const</code> can be useful when passing the stored data into
a legacy C API as an array.
\return The array range of the second continuous array of the internal buffer. In the case the internal buffer
is linear or the <code>circular_buffer</code> is empty the size of the returned array is
<code>0</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>array_one() const</code>
*/
const_array_range array_two() const {
return const_array_range(m_buff, m_last <= m_first && !empty() ? m_last - m_buff : 0);
}
//! Linearize the internal buffer into a continuous array.
/*!
This method can be useful when passing the stored data into a legacy C API as an array.
\post <code>\&(*this)[0] \< \&(*this)[1] \< ... \< \&(*this)[size() - 1]</code>
\return A pointer to the beginning of the array or <code>0</code> if empty.
\throws <a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operations in the <i>Throws</i> section do not throw anything.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (except iterators equal to
<code>end()</code>); does not invalidate any iterators if the postcondition (the <i>Effect</i>) is already
met prior calling this method.
\par Complexity
Linear (in the size of the <code>circular_buffer</code>); constant if the postcondition (the
<i>Effect</i>) is already met.
\warning In general invoking any method which modifies the internal state of the <code>circular_buffer</code>
may delinearize the internal buffer and invalidate the returned pointer.
\sa <code>array_one()</code> and <code>array_two()</code> for the other option how to pass data into a legacy
C API; <code>is_linearized()</code>, <code>rotate(const_iterator)</code>
*/
pointer linearize() {
if (empty())
return 0;
if (m_first < m_last || m_last == m_buff)
return m_first;
pointer src = m_first;
pointer dest = m_buff;
size_type moved = 0;
size_type constructed = 0;
BOOST_TRY {
for (pointer first = m_first; dest < src; src = first) {
for (size_type ii = 0; src < m_end; ++src, ++dest, ++moved, ++ii) {
if (moved == size()) {
first = dest;
break;
}
if (dest == first) {
first += ii;
break;
}
if (is_uninitialized(dest)) {
boost::container::allocator_traits<Alloc>::construct(m_alloc, boost::to_address(dest), boost::move_if_noexcept(*src));
++constructed;
} else {
value_type tmp = boost::move_if_noexcept(*src);
replace(src, boost::move_if_noexcept(*dest));
replace(dest, boost::move(tmp));
}
}
}
} BOOST_CATCH(...) {
m_last += constructed;
m_size += constructed;
BOOST_RETHROW
}
BOOST_CATCH_END
for (src = m_end - constructed; src < m_end; ++src)
destroy_item(src);
m_first = m_buff;
m_last = add(m_buff, size());
#if BOOST_CB_ENABLE_DEBUG
invalidate_iterators_except(end());
#endif
return m_buff;
}
//! Is the <code>circular_buffer</code> linearized?
/*!
\return <code>true</code> if the internal buffer is linearized into a continuous array (i.e. the
<code>circular_buffer</code> meets a condition
<code>\&(*this)[0] \< \&(*this)[1] \< ... \< \&(*this)[size() - 1]</code>);
<code>false</code> otherwise.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>linearize()</code>, <code>array_one()</code>, <code>array_two()</code>
*/
bool is_linearized() const BOOST_NOEXCEPT { return m_first < m_last || m_last == m_buff; }
//! Rotate elements in the <code>circular_buffer</code>.
/*!
A more effective implementation of
<code><a href="http://www.sgi.com/tech/stl/rotate.html">std::rotate</a></code>.
\pre <code>new_begin</code> is a valid iterator pointing to the <code>circular_buffer</code> <b>except</b> its
end.
\post Before calling the method suppose:<br><br>
<code>m == std::distance(new_begin, end())</code><br><code>n == std::distance(begin(), new_begin)</code>
<br><code>val_0 == *new_begin, val_1 == *(new_begin + 1), ... val_m == *(new_begin + m)</code><br>
<code>val_r1 == *(new_begin - 1), val_r2 == *(new_begin - 2), ... val_rn == *(new_begin - n)</code><br>
<br>then after call to the method:<br><br>
<code>val_0 == (*this)[0] \&\& val_1 == (*this)[1] \&\& ... \&\& val_m == (*this)[m - 1] \&\& val_r1 ==
(*this)[m + n - 1] \&\& val_r2 == (*this)[m + n - 2] \&\& ... \&\& val_rn == (*this)[m]</code>
\param new_begin The new beginning.
\throws See <a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the <code>circular_buffer</code> is full or <code>new_begin</code> points to
<code>begin()</code> or if the operations in the <i>Throws</i> section do not throw anything.
\par Iterator Invalidation
If <code>m \< n</code> invalidates iterators pointing to the last <code>m</code> elements
(<b>including</b> <code>new_begin</code>, but not iterators equal to <code>end()</code>) else invalidates
iterators pointing to the first <code>n</code> elements; does not invalidate any iterators if the
<code>circular_buffer</code> is full.
\par Complexity
Linear (in <code>(std::min)(m, n)</code>); constant if the <code>circular_buffer</code> is full.
\sa <code><a href="http://www.sgi.com/tech/stl/rotate.html">std::rotate</a></code>
*/
void rotate(const_iterator new_begin) {
BOOST_CB_ASSERT(new_begin.is_valid(this)); // check for uninitialized or invalidated iterator
BOOST_CB_ASSERT(new_begin.m_it != 0); // check for iterator pointing to end()
if (full()) {
m_first = m_last = const_cast<pointer>(new_begin.m_it);
} else {
difference_type m = end() - new_begin;
difference_type n = new_begin - begin();
if (m < n) {
for (; m > 0; --m) {
push_front(boost::move_if_noexcept(back()));
pop_back();
}
} else {
for (; n > 0; --n) {
push_back(boost::move_if_noexcept(front()));
pop_front();
}
}
}
}
// Size and capacity
//! Get the number of elements currently stored in the <code>circular_buffer</code>.
/*!
\return The number of elements stored in the <code>circular_buffer</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>capacity()</code>, <code>max_size()</code>, <code>reserve()</code>,
<code>\link resize() resize(size_type, const_reference)\endlink</code>
*/
size_type size() const BOOST_NOEXCEPT { return m_size; }
/*! \brief Get the largest possible size or capacity of the <code>circular_buffer</code>. (It depends on
allocator's %max_size()).
\return The maximum size/capacity the <code>circular_buffer</code> can be set to.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>size()</code>, <code>capacity()</code>, <code>reserve()</code>
*/
size_type max_size() const BOOST_NOEXCEPT {
return (std::min<size_type>)(boost::container::allocator_traits<Alloc>::max_size(m_alloc), (std::numeric_limits<difference_type>::max)());
}
//! Is the <code>circular_buffer</code> empty?
/*!
\return <code>true</code> if there are no elements stored in the <code>circular_buffer</code>;
<code>false</code> otherwise.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>full()</code>
*/
bool empty() const BOOST_NOEXCEPT { return size() == 0; }
//! Is the <code>circular_buffer</code> full?
/*!
\return <code>true</code> if the number of elements stored in the <code>circular_buffer</code>
equals the capacity of the <code>circular_buffer</code>; <code>false</code> otherwise.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>empty()</code>
*/
bool full() const BOOST_NOEXCEPT { return capacity() == size(); }
/*! \brief Get the maximum number of elements which can be inserted into the <code>circular_buffer</code> without
overwriting any of already stored elements.
\return <code>capacity() - size()</code>
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>capacity()</code>, <code>size()</code>, <code>max_size()</code>
*/
size_type reserve() const BOOST_NOEXCEPT { return capacity() - size(); }
//! Get the capacity of the <code>circular_buffer</code>.
/*!
\return The maximum number of elements which can be stored in the <code>circular_buffer</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Does not invalidate any iterators.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>reserve()</code>, <code>size()</code>, <code>max_size()</code>,
<code>set_capacity(capacity_type)</code>
*/
capacity_type capacity() const BOOST_NOEXCEPT { return m_end - m_buff; }
//! Change the capacity of the <code>circular_buffer</code>.
/*!
\pre If <code>T</code> is a move only type, then compiler shall support <code>noexcept</code> modifiers
and move constructor of <code>T</code> must be marked with it (must not throw exceptions).
\post <code>capacity() == new_capacity \&\& size() \<= new_capacity</code><br><br>
If the current number of elements stored in the <code>circular_buffer</code> is greater than the desired
new capacity then number of <code>[size() - new_capacity]</code> <b>last</b> elements will be removed and
the new size will be equal to <code>new_capacity</code>.
\param new_capacity The new capacity.
\throws "An allocation error" if memory is exhausted, (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws or nothing if <code>T::T(T&&)</code> is noexcept.
\par Exception Safety
Strong.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (except iterators equal to
<code>end()</code>) if the new capacity is different from the original.
\par Complexity
Linear (in <code>min[size(), new_capacity]</code>).
\sa <code>rset_capacity(capacity_type)</code>,
<code>\link resize() resize(size_type, const_reference)\endlink</code>
*/
void set_capacity(capacity_type new_capacity) {
if (new_capacity == capacity())
return;
pointer buff = allocate(new_capacity);
iterator b = begin();
BOOST_TRY {
reset(buff,
cb_details::uninitialized_move_if_noexcept(b, b + (std::min)(new_capacity, size()), buff, m_alloc),
new_capacity);
} BOOST_CATCH(...) {
deallocate(buff, new_capacity);
BOOST_RETHROW
}
BOOST_CATCH_END
}
//! Change the size of the <code>circular_buffer</code>.
/*!
\post <code>size() == new_size \&\& capacity() >= new_size</code><br><br>
If the new size is greater than the current size, copies of <code>item</code> will be inserted at the
<b>back</b> of the of the <code>circular_buffer</code> in order to achieve the desired size. In the case
the resulting size exceeds the current capacity the capacity will be set to <code>new_size</code>.<br>
If the current number of elements stored in the <code>circular_buffer</code> is greater than the desired
new size then number of <code>[size() - new_size]</code> <b>last</b> elements will be removed. (The
capacity will remain unchanged.)
\param new_size The new size.
\param item The element the <code>circular_buffer</code> will be filled with in order to gain the requested
size. (See the <i>Effect</i>.)
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws or nothing if <code>T::T(T&&)</code> is noexcept.
\par Exception Safety
Basic.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (except iterators equal to
<code>end()</code>) if the new size is greater than the current capacity. Invalidates iterators pointing
to the removed elements if the new size is lower that the original size. Otherwise it does not invalidate
any iterator.
\par Complexity
Linear (in the new size of the <code>circular_buffer</code>).
\sa <code>\link rresize() rresize(size_type, const_reference)\endlink</code>,
<code>set_capacity(capacity_type)</code>
*/
void resize(size_type new_size, param_value_type item = value_type()) {
if (new_size > size()) {
if (new_size > capacity())
set_capacity(new_size);
insert(end(), new_size - size(), item);
} else {
iterator e = end();
erase(e - (size() - new_size), e);
}
}
//! Change the capacity of the <code>circular_buffer</code>.
/*!
\pre If <code>T</code> is a move only type, then compiler shall support <code>noexcept</code> modifiers
and move constructor of <code>T</code> must be marked with it (must not throw exceptions).
\post <code>capacity() == new_capacity \&\& size() \<= new_capacity</code><br><br>
If the current number of elements stored in the <code>circular_buffer</code> is greater than the desired
new capacity then number of <code>[size() - new_capacity]</code> <b>first</b> elements will be removed
and the new size will be equal to <code>new_capacity</code>.
\param new_capacity The new capacity.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws or nothing if <code>T::T(T&&)</code> is noexcept.
\par Exception Safety
Strong.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (except iterators equal to
<code>end()</code>) if the new capacity is different from the original.
\par Complexity
Linear (in <code>min[size(), new_capacity]</code>).
\sa <code>set_capacity(capacity_type)</code>,
<code>\link rresize() rresize(size_type, const_reference)\endlink</code>
*/
void rset_capacity(capacity_type new_capacity) {
if (new_capacity == capacity())
return;
pointer buff = allocate(new_capacity);
iterator e = end();
BOOST_TRY {
reset(buff, cb_details::uninitialized_move_if_noexcept(e - (std::min)(new_capacity, size()),
e, buff, m_alloc), new_capacity);
} BOOST_CATCH(...) {
deallocate(buff, new_capacity);
BOOST_RETHROW
}
BOOST_CATCH_END
}
//! Change the size of the <code>circular_buffer</code>.
/*!
\post <code>size() == new_size \&\& capacity() >= new_size</code><br><br>
If the new size is greater than the current size, copies of <code>item</code> will be inserted at the
<b>front</b> of the of the <code>circular_buffer</code> in order to achieve the desired size. In the case
the resulting size exceeds the current capacity the capacity will be set to <code>new_size</code>.<br>
If the current number of elements stored in the <code>circular_buffer</code> is greater than the desired
new size then number of <code>[size() - new_size]</code> <b>first</b> elements will be removed. (The
capacity will remain unchanged.)
\param new_size The new size.
\param item The element the <code>circular_buffer</code> will be filled with in order to gain the requested
size. (See the <i>Effect</i>.)
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws or nothing if <code>T::T(T&&)</code> is noexcept.
\par Exception Safety
Basic.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (except iterators equal to
<code>end()</code>) if the new size is greater than the current capacity. Invalidates iterators pointing
to the removed elements if the new size is lower that the original size. Otherwise it does not invalidate
any iterator.
\par Complexity
Linear (in the new size of the <code>circular_buffer</code>).
\sa <code>\link resize() resize(size_type, const_reference)\endlink</code>,
<code>rset_capacity(capacity_type)</code>
*/
void rresize(size_type new_size, param_value_type item = value_type()) {
if (new_size > size()) {
if (new_size > capacity())
set_capacity(new_size);
rinsert(begin(), new_size - size(), item);
} else {
rerase(begin(), end() - new_size);
}
}
// Construction/Destruction
//! Create an empty <code>circular_buffer</code> with zero capacity.
/*!
\post <code>capacity() == 0 \&\& size() == 0</code>
\param alloc The allocator.
\throws Nothing.
\par Complexity
Constant.
\warning Since Boost version 1.36 the behaviour of this constructor has changed. Now the constructor does not
allocate any memory and both capacity and size are set to zero. Also note when inserting an element
into a <code>circular_buffer</code> with zero capacity (e.g. by
<code>\link push_back() push_back(const_reference)\endlink</code> or
<code>\link insert(iterator, param_value_type) insert(iterator, value_type)\endlink</code>) nothing
will be inserted and the size (as well as capacity) remains zero.
\note You can explicitly set the capacity by calling the <code>set_capacity(capacity_type)</code> method or you
can use the other constructor with the capacity specified.
\sa <code>circular_buffer(capacity_type, const allocator_type& alloc)</code>,
<code>set_capacity(capacity_type)</code>
*/
explicit circular_buffer(const allocator_type& alloc = allocator_type()) BOOST_NOEXCEPT
: m_buff(0), m_end(0), m_first(0), m_last(0), m_size(0), m_alloc(alloc) {}
//! Create an empty <code>circular_buffer</code> with the specified capacity.
/*!
\post <code>capacity() == buffer_capacity \&\& size() == 0</code>
\param buffer_capacity The maximum number of elements which can be stored in the <code>circular_buffer</code>.
\param alloc The allocator.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
\par Complexity
Constant.
*/
explicit circular_buffer(capacity_type buffer_capacity, const allocator_type& alloc = allocator_type())
: m_size(0), m_alloc(alloc) {
initialize_buffer(buffer_capacity);
m_first = m_last = m_buff;
}
/*! \brief Create a full <code>circular_buffer</code> with the specified capacity and filled with <code>n</code>
copies of <code>item</code>.
\post <code>capacity() == n \&\& full() \&\& (*this)[0] == item \&\& (*this)[1] == item \&\& ... \&\&
(*this)[n - 1] == item </code>
\param n The number of elements the created <code>circular_buffer</code> will be filled with.
\param item The element the created <code>circular_buffer</code> will be filled with.
\param alloc The allocator.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws.
\par Complexity
Linear (in the <code>n</code>).
*/
circular_buffer(size_type n, param_value_type item, const allocator_type& alloc = allocator_type())
: m_size(n), m_alloc(alloc) {
initialize_buffer(n, item);
m_first = m_last = m_buff;
}
/*! \brief Create a <code>circular_buffer</code> with the specified capacity and filled with <code>n</code>
copies of <code>item</code>.
\pre <code>buffer_capacity >= n</code>
\post <code>capacity() == buffer_capacity \&\& size() == n \&\& (*this)[0] == item \&\& (*this)[1] == item
\&\& ... \&\& (*this)[n - 1] == item</code>
\param buffer_capacity The capacity of the created <code>circular_buffer</code>.
\param n The number of elements the created <code>circular_buffer</code> will be filled with.
\param item The element the created <code>circular_buffer</code> will be filled with.
\param alloc The allocator.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws.
\par Complexity
Linear (in the <code>n</code>).
*/
circular_buffer(capacity_type buffer_capacity, size_type n, param_value_type item,
const allocator_type& alloc = allocator_type())
: m_size(n), m_alloc(alloc) {
BOOST_CB_ASSERT(buffer_capacity >= size()); // check for capacity lower than size
initialize_buffer(buffer_capacity, item);
m_first = m_buff;
m_last = buffer_capacity == n ? m_buff : m_buff + n;
}
//! The copy constructor.
/*!
Creates a copy of the specified <code>circular_buffer</code>.
\post <code>*this == cb</code>
\param cb The <code>circular_buffer</code> to be copied.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws.
\par Complexity
Linear (in the size of <code>cb</code>).
*/
circular_buffer(const circular_buffer<T, Alloc>& cb)
:
#if BOOST_CB_ENABLE_DEBUG
debug_iterator_registry(),
#endif
m_size(cb.size()), m_alloc(cb.get_allocator()) {
initialize_buffer(cb.capacity());
m_first = m_buff;
BOOST_TRY {
m_last = cb_details::uninitialized_copy(cb.begin(), cb.end(), m_buff, m_alloc);
} BOOST_CATCH(...) {
deallocate(m_buff, cb.capacity());
BOOST_RETHROW
}
BOOST_CATCH_END
if (m_last == m_end)
m_last = m_buff;
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
//! The move constructor.
/*! \brief Move constructs a <code>circular_buffer</code> from <code>cb</code>, leaving <code>cb</code> empty.
\pre C++ compiler with rvalue references support.
\post <code>cb.empty()</code>
\param cb <code>circular_buffer</code> to 'steal' value from.
\throws Nothing.
\par Constant.
*/
circular_buffer(circular_buffer<T, Alloc>&& cb) BOOST_NOEXCEPT
: m_buff(0), m_end(0), m_first(0), m_last(0), m_size(0), m_alloc(cb.get_allocator()) {
cb.swap(*this);
}
#endif // BOOST_NO_CXX11_RVALUE_REFERENCES
//! Create a full <code>circular_buffer</code> filled with a copy of the range.
/*!
\pre Valid range <code>[first, last)</code>.<br>
<code>first</code> and <code>last</code> have to meet the requirements of
<a href="http://www.sgi.com/tech/stl/InputIterator.html">InputIterator</a>.
\post <code>capacity() == std::distance(first, last) \&\& full() \&\& (*this)[0]== *first \&\&
(*this)[1] == *(first + 1) \&\& ... \&\& (*this)[std::distance(first, last) - 1] == *(last - 1)</code>
\param first The beginning of the range to be copied.
\param last The end of the range to be copied.
\param alloc The allocator.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws.
\par Complexity
Linear (in the <code>std::distance(first, last)</code>).
*/
template <class InputIterator>
circular_buffer(InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type())
: m_alloc(alloc) {
initialize(first, last, is_integral<InputIterator>());
}
//! Create a <code>circular_buffer</code> with the specified capacity and filled with a copy of the range.
/*!
\pre Valid range <code>[first, last)</code>.<br>
<code>first</code> and <code>last</code> have to meet the requirements of
<a href="http://www.sgi.com/tech/stl/InputIterator.html">InputIterator</a>.
\post <code>capacity() == buffer_capacity \&\& size() \<= std::distance(first, last) \&\&
(*this)[0]== *(last - buffer_capacity) \&\& (*this)[1] == *(last - buffer_capacity + 1) \&\& ... \&\&
(*this)[buffer_capacity - 1] == *(last - 1)</code><br><br>
If the number of items to be copied from the range <code>[first, last)</code> is greater than the
specified <code>buffer_capacity</code> then only elements from the range
<code>[last - buffer_capacity, last)</code> will be copied.
\param buffer_capacity The capacity of the created <code>circular_buffer</code>.
\param first The beginning of the range to be copied.
\param last The end of the range to be copied.
\param alloc The allocator.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws.
\par Complexity
Linear (in <code>std::distance(first, last)</code>; in
<code>min[capacity, std::distance(first, last)]</code> if the <code>InputIterator</code> is a
<a href="http://www.sgi.com/tech/stl/RandomAccessIterator.html">RandomAccessIterator</a>).
*/
template <class InputIterator>
circular_buffer(capacity_type buffer_capacity, InputIterator first, InputIterator last,
const allocator_type& alloc = allocator_type())
: m_alloc(alloc) {
initialize(buffer_capacity, first, last, is_integral<InputIterator>());
}
//! The destructor.
/*!
Destroys the <code>circular_buffer</code>.
\throws Nothing.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (including iterators equal to
<code>end()</code>).
\par Complexity
Constant (in the size of the <code>circular_buffer</code>) for scalar types; linear for other types.
\sa <code>clear()</code>
*/
~circular_buffer() BOOST_NOEXCEPT {
destroy();
#if BOOST_CB_ENABLE_DEBUG
invalidate_all_iterators();
#endif
}
public:
// Assign methods
//! The assign operator.
/*!
Makes this <code>circular_buffer</code> to become a copy of the specified <code>circular_buffer</code>.
\post <code>*this == cb</code>
\param cb The <code>circular_buffer</code> to be copied.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws.
\par Exception Safety
Strong.
\par Iterator Invalidation
Invalidates all iterators pointing to this <code>circular_buffer</code> (except iterators equal to
<code>end()</code>).
\par Complexity
Linear (in the size of <code>cb</code>).
\sa <code>\link assign(size_type, param_value_type) assign(size_type, const_reference)\endlink</code>,
<code>\link assign(capacity_type, size_type, param_value_type)
assign(capacity_type, size_type, const_reference)\endlink</code>,
<code>assign(InputIterator, InputIterator)</code>,
<code>assign(capacity_type, InputIterator, InputIterator)</code>
*/
circular_buffer<T, Alloc>& operator = (const circular_buffer<T, Alloc>& cb) {
if (this == &cb)
return *this;
pointer buff = allocate(cb.capacity());
BOOST_TRY {
reset(buff, cb_details::uninitialized_copy(cb.begin(), cb.end(), buff, m_alloc), cb.capacity());
} BOOST_CATCH(...) {
deallocate(buff, cb.capacity());
BOOST_RETHROW
}
BOOST_CATCH_END
return *this;
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
/*! \brief Move assigns content of <code>cb</code> to <code>*this</code>, leaving <code>cb</code> empty.
\pre C++ compiler with rvalue references support.
\post <code>cb.empty()</code>
\param cb <code>circular_buffer</code> to 'steal' value from.
\throws Nothing.
\par Complexity
Constant.
*/
circular_buffer<T, Alloc>& operator = (circular_buffer<T, Alloc>&& cb) BOOST_NOEXCEPT {
cb.swap(*this); // now `this` holds `cb`
circular_buffer<T, Alloc>(get_allocator()) // temprary that holds initial `cb` allocator
.swap(cb); // makes `cb` empty
return *this;
}
#endif // BOOST_NO_CXX11_RVALUE_REFERENCES
//! Assign <code>n</code> items into the <code>circular_buffer</code>.
/*!
The content of the <code>circular_buffer</code> will be removed and replaced with <code>n</code> copies of the
<code>item</code>.
\post <code>capacity() == n \&\& size() == n \&\& (*this)[0] == item \&\& (*this)[1] == item \&\& ... \&\&
(*this) [n - 1] == item</code>
\param n The number of elements the <code>circular_buffer</code> will be filled with.
\param item The element the <code>circular_buffer</code> will be filled with.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws.
\par Exception Safety
Basic.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (except iterators equal to
<code>end()</code>).
\par Complexity
Linear (in the <code>n</code>).
\sa <code>\link operator=(const circular_buffer&) operator=\endlink</code>,
<code>\link assign(capacity_type, size_type, param_value_type)
assign(capacity_type, size_type, const_reference)\endlink</code>,
<code>assign(InputIterator, InputIterator)</code>,
<code>assign(capacity_type, InputIterator, InputIterator)</code>
*/
void assign(size_type n, param_value_type item) {
assign_n(n, n, cb_details::assign_n<param_value_type, allocator_type>(n, item, m_alloc));
}
//! Assign <code>n</code> items into the <code>circular_buffer</code> specifying the capacity.
/*!
The capacity of the <code>circular_buffer</code> will be set to the specified value and the content of the
<code>circular_buffer</code> will be removed and replaced with <code>n</code> copies of the <code>item</code>.
\pre <code>capacity >= n</code>
\post <code>capacity() == buffer_capacity \&\& size() == n \&\& (*this)[0] == item \&\& (*this)[1] == item
\&\& ... \&\& (*this) [n - 1] == item </code>
\param buffer_capacity The new capacity.
\param n The number of elements the <code>circular_buffer</code> will be filled with.
\param item The element the <code>circular_buffer</code> will be filled with.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws.
\par Exception Safety
Basic.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (except iterators equal to
<code>end()</code>).
\par Complexity
Linear (in the <code>n</code>).
\sa <code>\link operator=(const circular_buffer&) operator=\endlink</code>,
<code>\link assign(size_type, param_value_type) assign(size_type, const_reference)\endlink</code>,
<code>assign(InputIterator, InputIterator)</code>,
<code>assign(capacity_type, InputIterator, InputIterator)</code>
*/
void assign(capacity_type buffer_capacity, size_type n, param_value_type item) {
BOOST_CB_ASSERT(buffer_capacity >= n); // check for new capacity lower than n
assign_n(buffer_capacity, n, cb_details::assign_n<param_value_type, allocator_type>(n, item, m_alloc));
}
//! Assign a copy of the range into the <code>circular_buffer</code>.
/*!
The content of the <code>circular_buffer</code> will be removed and replaced with copies of elements from the
specified range.
\pre Valid range <code>[first, last)</code>.<br>
<code>first</code> and <code>last</code> have to meet the requirements of
<a href="http://www.sgi.com/tech/stl/InputIterator.html">InputIterator</a>.
\post <code>capacity() == std::distance(first, last) \&\& size() == std::distance(first, last) \&\&
(*this)[0]== *first \&\& (*this)[1] == *(first + 1) \&\& ... \&\& (*this)[std::distance(first, last) - 1]
== *(last - 1)</code>
\param first The beginning of the range to be copied.
\param last The end of the range to be copied.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws.
\par Exception Safety
Basic.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (except iterators equal to
<code>end()</code>).
\par Complexity
Linear (in the <code>std::distance(first, last)</code>).
\sa <code>\link operator=(const circular_buffer&) operator=\endlink</code>,
<code>\link assign(size_type, param_value_type) assign(size_type, const_reference)\endlink</code>,
<code>\link assign(capacity_type, size_type, param_value_type)
assign(capacity_type, size_type, const_reference)\endlink</code>,
<code>assign(capacity_type, InputIterator, InputIterator)</code>
*/
template <class InputIterator>
void assign(InputIterator first, InputIterator last) {
assign(first, last, is_integral<InputIterator>());
}
//! Assign a copy of the range into the <code>circular_buffer</code> specifying the capacity.
/*!
The capacity of the <code>circular_buffer</code> will be set to the specified value and the content of the
<code>circular_buffer</code> will be removed and replaced with copies of elements from the specified range.
\pre Valid range <code>[first, last)</code>.<br>
<code>first</code> and <code>last</code> have to meet the requirements of
<a href="http://www.sgi.com/tech/stl/InputIterator.html">InputIterator</a>.
\post <code>capacity() == buffer_capacity \&\& size() \<= std::distance(first, last) \&\&
(*this)[0]== *(last - buffer_capacity) \&\& (*this)[1] == *(last - buffer_capacity + 1) \&\& ... \&\&
(*this)[buffer_capacity - 1] == *(last - 1)</code><br><br>
If the number of items to be copied from the range <code>[first, last)</code> is greater than the
specified <code>buffer_capacity</code> then only elements from the range
<code>[last - buffer_capacity, last)</code> will be copied.
\param buffer_capacity The new capacity.
\param first The beginning of the range to be copied.
\param last The end of the range to be copied.
\throws "An allocation error" if memory is exhausted (<code>std::bad_alloc</code> if the standard allocator is
used).
Whatever <code>T::T(const T&)</code> throws.
\par Exception Safety
Basic.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (except iterators equal to
<code>end()</code>).
\par Complexity
Linear (in <code>std::distance(first, last)</code>; in
<code>min[capacity, std::distance(first, last)]</code> if the <code>InputIterator</code> is a
<a href="http://www.sgi.com/tech/stl/RandomAccessIterator.html">RandomAccessIterator</a>).
\sa <code>\link operator=(const circular_buffer&) operator=\endlink</code>,
<code>\link assign(size_type, param_value_type) assign(size_type, const_reference)\endlink</code>,
<code>\link assign(capacity_type, size_type, param_value_type)
assign(capacity_type, size_type, const_reference)\endlink</code>,
<code>assign(InputIterator, InputIterator)</code>
*/
template <class InputIterator>
void assign(capacity_type buffer_capacity, InputIterator first, InputIterator last) {
assign(buffer_capacity, first, last, is_integral<InputIterator>());
}
//! Swap the contents of two <code>circular_buffer</code>s.
/*!
\post <code>this</code> contains elements of <code>cb</code> and vice versa; the capacity of <code>this</code>
equals to the capacity of <code>cb</code> and vice versa.
\param cb The <code>circular_buffer</code> whose content will be swapped.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Invalidates all iterators of both <code>circular_buffer</code>s. (On the other hand the iterators still
point to the same elements but within another container. If you want to rely on this feature you have to
turn the <a href="#debug">Debug Support</a> off otherwise an assertion will report an error if such
invalidated iterator is used.)
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>swap(circular_buffer<T, Alloc>&, circular_buffer<T, Alloc>&)</code>
*/
void swap(circular_buffer<T, Alloc>& cb) BOOST_NOEXCEPT {
swap_allocator(cb, is_stateless<allocator_type>());
adl_move_swap(m_buff, cb.m_buff);
adl_move_swap(m_end, cb.m_end);
adl_move_swap(m_first, cb.m_first);
adl_move_swap(m_last, cb.m_last);
adl_move_swap(m_size, cb.m_size);
#if BOOST_CB_ENABLE_DEBUG
invalidate_all_iterators();
cb.invalidate_all_iterators();
#endif
}
// push and pop
private:
template <class ValT>
void push_back_impl(ValT item) {
if (full()) {
if (empty())
return;
replace(m_last, static_cast<ValT>(item));
increment(m_last);
m_first = m_last;
} else {
boost::container::allocator_traits<Alloc>::construct(m_alloc, boost::to_address(m_last), static_cast<ValT>(item));
increment(m_last);
++m_size;
}
}
template <class ValT>
void push_front_impl(ValT item) {
BOOST_TRY {
if (full()) {
if (empty())
return;
decrement(m_first);
replace(m_first, static_cast<ValT>(item));
m_last = m_first;
} else {
decrement(m_first);
boost::container::allocator_traits<Alloc>::construct(m_alloc, boost::to_address(m_first), static_cast<ValT>(item));
++m_size;
}
} BOOST_CATCH(...) {
increment(m_first);
BOOST_RETHROW
}
BOOST_CATCH_END
}
public:
//! Insert a new element at the end of the <code>circular_buffer</code>.
/*!
\post if <code>capacity() > 0</code> then <code>back() == item</code><br>
If the <code>circular_buffer</code> is full, the first element will be removed. If the capacity is
<code>0</code>, nothing will be inserted.
\param item The element to be inserted.
\throws Whatever <code>T::T(const T&)</code> throws.
Whatever <code>T::operator = (const T&)</code> throws.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Does not invalidate any iterators with the exception of iterators pointing to the overwritten element.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>\link push_front() push_front(const_reference)\endlink</code>,
<code>pop_back()</code>, <code>pop_front()</code>
*/
void push_back(param_value_type item) {
push_back_impl<param_value_type>(item);
}
//! Insert a new element at the end of the <code>circular_buffer</code> using rvalue references or rvalues references emulation.
/*!
\post if <code>capacity() > 0</code> then <code>back() == item</code><br>
If the <code>circular_buffer</code> is full, the first element will be removed. If the capacity is
<code>0</code>, nothing will be inserted.
\param item The element to be inserted.
\throws Whatever <code>T::T(T&&)</code> throws.
Whatever <code>T::operator = (T&&)</code> throws.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Does not invalidate any iterators with the exception of iterators pointing to the overwritten element.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>\link push_front() push_front(const_reference)\endlink</code>,
<code>pop_back()</code>, <code>pop_front()</code>
*/
void push_back(rvalue_type item) {
push_back_impl<rvalue_type>(boost::move(item));
}
//! Insert a new default-constructed element at the end of the <code>circular_buffer</code>.
/*!
\post if <code>capacity() > 0</code> then <code>back() == item</code><br>
If the <code>circular_buffer</code> is full, the first element will be removed. If the capacity is
<code>0</code>, nothing will be inserted.
\throws Whatever <code>T::T()</code> throws.
Whatever <code>T::T(T&&)</code> throws.
Whatever <code>T::operator = (T&&)</code> throws.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Does not invalidate any iterators with the exception of iterators pointing to the overwritten element.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>\link push_front() push_front(const_reference)\endlink</code>,
<code>pop_back()</code>, <code>pop_front()</code>
*/
void push_back() {
value_type temp;
push_back(boost::move(temp));
}
//! Insert a new element at the beginning of the <code>circular_buffer</code>.
/*!
\post if <code>capacity() > 0</code> then <code>front() == item</code><br>
If the <code>circular_buffer</code> is full, the last element will be removed. If the capacity is
<code>0</code>, nothing will be inserted.
\param item The element to be inserted.
\throws Whatever <code>T::T(const T&)</code> throws.
Whatever <code>T::operator = (const T&)</code> throws.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Does not invalidate any iterators with the exception of iterators pointing to the overwritten element.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>\link push_back() push_back(const_reference)\endlink</code>,
<code>pop_back()</code>, <code>pop_front()</code>
*/
void push_front(param_value_type item) {
push_front_impl<param_value_type>(item);
}
//! Insert a new element at the beginning of the <code>circular_buffer</code> using rvalue references or rvalues references emulation.
/*!
\post if <code>capacity() > 0</code> then <code>front() == item</code><br>
If the <code>circular_buffer</code> is full, the last element will be removed. If the capacity is
<code>0</code>, nothing will be inserted.
\param item The element to be inserted.
\throws Whatever <code>T::T(T&&)</code> throws.
Whatever <code>T::operator = (T&&)</code> throws.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Does not invalidate any iterators with the exception of iterators pointing to the overwritten element.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>\link push_back() push_back(const_reference)\endlink</code>,
<code>pop_back()</code>, <code>pop_front()</code>
*/
void push_front(rvalue_type item) {
push_front_impl<rvalue_type>(boost::move(item));
}
//! Insert a new default-constructed element at the beginning of the <code>circular_buffer</code>.
/*!
\post if <code>capacity() > 0</code> then <code>front() == item</code><br>
If the <code>circular_buffer</code> is full, the last element will be removed. If the capacity is
<code>0</code>, nothing will be inserted.
\throws Whatever <code>T::T()</code> throws.
Whatever <code>T::T(T&&)</code> throws.
Whatever <code>T::operator = (T&&)</code> throws.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Does not invalidate any iterators with the exception of iterators pointing to the overwritten element.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>\link push_back() push_back(const_reference)\endlink</code>,
<code>pop_back()</code>, <code>pop_front()</code>
*/
void push_front() {
value_type temp;
push_front(boost::move(temp));
}
//! Remove the last element from the <code>circular_buffer</code>.
/*!
\pre <code>!empty()</code>
\post The last element is removed from the <code>circular_buffer</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Invalidates only iterators pointing to the removed element.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>pop_front()</code>, <code>\link push_back() push_back(const_reference)\endlink</code>,
<code>\link push_front() push_front(const_reference)\endlink</code>
*/
void pop_back() {
BOOST_CB_ASSERT(!empty()); // check for empty buffer (back element not available)
decrement(m_last);
destroy_item(m_last);
--m_size;
}
//! Remove the first element from the <code>circular_buffer</code>.
/*!
\pre <code>!empty()</code>
\post The first element is removed from the <code>circular_buffer</code>.
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Invalidates only iterators pointing to the removed element.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>).
\sa <code>pop_back()</code>, <code>\link push_back() push_back(const_reference)\endlink</code>,
<code>\link push_front() push_front(const_reference)\endlink</code>
*/
void pop_front() {
BOOST_CB_ASSERT(!empty()); // check for empty buffer (front element not available)
destroy_item(m_first);
increment(m_first);
--m_size;
}
private:
template <class ValT>
iterator insert_impl(iterator pos, ValT item) {
BOOST_CB_ASSERT(pos.is_valid(this)); // check for uninitialized or invalidated iterator
iterator b = begin();
if (full() && pos == b)
return b;
return insert_item<ValT>(pos, static_cast<ValT>(item));
}
public:
// Insert
//! Insert an element at the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> or its end.
\post The <code>item</code> will be inserted at the position <code>pos</code>.<br>
If the <code>circular_buffer</code> is full, the first element will be overwritten. If the
<code>circular_buffer</code> is full and the <code>pos</code> points to <code>begin()</code>, then the
<code>item</code> will not be inserted. If the capacity is <code>0</code>, nothing will be inserted.
\param pos An iterator specifying the position where the <code>item</code> will be inserted.
\param item The element to be inserted.
\return Iterator to the inserted element or <code>begin()</code> if the <code>item</code> is not inserted. (See
the <i>Effect</i>.)
\throws Whatever <code>T::T(const T&)</code> throws.
Whatever <code>T::operator = (const T&)</code> throws.
<a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the elements at the insertion point (including <code>pos</code>) and
iterators behind the insertion point (towards the end; except iterators equal to <code>end()</code>). It
also invalidates iterators pointing to the overwritten element.
\par Complexity
Linear (in <code>std::distance(pos, end())</code>).
\sa <code>\link insert(iterator, size_type, param_value_type)
insert(iterator, size_type, value_type)\endlink</code>,
<code>insert(iterator, InputIterator, InputIterator)</code>,
<code>\link rinsert(iterator, param_value_type) rinsert(iterator, value_type)\endlink</code>,
<code>\link rinsert(iterator, size_type, param_value_type)
rinsert(iterator, size_type, value_type)\endlink</code>,
<code>rinsert(iterator, InputIterator, InputIterator)</code>
*/
iterator insert(iterator pos, param_value_type item) {
return insert_impl<param_value_type>(pos, item);
}
//! Insert an element at the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> or its end.
\post The <code>item</code> will be inserted at the position <code>pos</code>.<br>
If the <code>circular_buffer</code> is full, the first element will be overwritten. If the
<code>circular_buffer</code> is full and the <code>pos</code> points to <code>begin()</code>, then the
<code>item</code> will not be inserted. If the capacity is <code>0</code>, nothing will be inserted.
\param pos An iterator specifying the position where the <code>item</code> will be inserted.
\param item The element to be inserted.
\return Iterator to the inserted element or <code>begin()</code> if the <code>item</code> is not inserted. (See
the <i>Effect</i>.)
\throws Whatever <code>T::T(T&&)</code> throws.
Whatever <code>T::operator = (T&&)</code> throws.
<a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the elements at the insertion point (including <code>pos</code>) and
iterators behind the insertion point (towards the end; except iterators equal to <code>end()</code>). It
also invalidates iterators pointing to the overwritten element.
\par Complexity
Linear (in <code>std::distance(pos, end())</code>).
\sa <code>\link insert(iterator, size_type, param_value_type)
insert(iterator, size_type, value_type)\endlink</code>,
<code>insert(iterator, InputIterator, InputIterator)</code>,
<code>\link rinsert(iterator, param_value_type) rinsert(iterator, value_type)\endlink</code>,
<code>\link rinsert(iterator, size_type, param_value_type)
rinsert(iterator, size_type, value_type)\endlink</code>,
<code>rinsert(iterator, InputIterator, InputIterator)</code>
*/
iterator insert(iterator pos, rvalue_type item) {
return insert_impl<rvalue_type>(pos, boost::move(item));
}
//! Insert a default-constructed element at the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> or its end.
\post The <code>item</code> will be inserted at the position <code>pos</code>.<br>
If the <code>circular_buffer</code> is full, the first element will be overwritten. If the
<code>circular_buffer</code> is full and the <code>pos</code> points to <code>begin()</code>, then the
<code>item</code> will not be inserted. If the capacity is <code>0</code>, nothing will be inserted.
\param pos An iterator specifying the position where the <code>item</code> will be inserted.
\return Iterator to the inserted element or <code>begin()</code> if the <code>item</code> is not inserted. (See
the <i>Effect</i>.)
\throws Whatever <code>T::T()</code> throws.
Whatever <code>T::T(T&&)</code> throws.
Whatever <code>T::operator = (T&&)</code> throws.
<a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the elements at the insertion point (including <code>pos</code>) and
iterators behind the insertion point (towards the end; except iterators equal to <code>end()</code>). It
also invalidates iterators pointing to the overwritten element.
\par Complexity
Linear (in <code>std::distance(pos, end())</code>).
\sa <code>\link insert(iterator, size_type, param_value_type)
insert(iterator, size_type, value_type)\endlink</code>,
<code>insert(iterator, InputIterator, InputIterator)</code>,
<code>\link rinsert(iterator, param_value_type) rinsert(iterator, value_type)\endlink</code>,
<code>\link rinsert(iterator, size_type, param_value_type)
rinsert(iterator, size_type, value_type)\endlink</code>,
<code>rinsert(iterator, InputIterator, InputIterator)</code>
*/
iterator insert(iterator pos) {
value_type temp;
return insert(pos, boost::move(temp));
}
//! Insert <code>n</code> copies of the <code>item</code> at the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> or its end.
\post The number of <code>min[n, (pos - begin()) + reserve()]</code> elements will be inserted at the position
<code>pos</code>.<br>The number of <code>min[pos - begin(), max[0, n - reserve()]]</code> elements will
be overwritten at the beginning of the <code>circular_buffer</code>.<br>(See <i>Example</i> for the
explanation.)
\param pos An iterator specifying the position where the <code>item</code>s will be inserted.
\param n The number of <code>item</code>s the to be inserted.
\param item The element whose copies will be inserted.
\throws Whatever <code>T::T(const T&)</code> throws.
Whatever <code>T::operator = (const T&)</code> throws.
<a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operations in the <i>Throws</i> section do not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the elements at the insertion point (including <code>pos</code>) and
iterators behind the insertion point (towards the end; except iterators equal to <code>end()</code>). It
also invalidates iterators pointing to the overwritten elements.
\par Complexity
Linear (in <code>min[capacity(), std::distance(pos, end()) + n]</code>).
\par Example
Consider a <code>circular_buffer</code> with the capacity of 6 and the size of 4. Its internal buffer may
look like the one below.<br><br>
<code>|1|2|3|4| | |</code><br>
<code>p ___^</code><br><br>After inserting 5 elements at the position <code>p</code>:<br><br>
<code>insert(p, (size_t)5, 0);</code><br><br>actually only 4 elements get inserted and elements
<code>1</code> and <code>2</code> are overwritten. This is due to the fact the insert operation preserves
the capacity. After insertion the internal buffer looks like this:<br><br><code>|0|0|0|0|3|4|</code><br>
<br>For comparison if the capacity would not be preserved the internal buffer would then result in
<code>|1|2|0|0|0|0|0|3|4|</code>.
\sa <code>\link insert(iterator, param_value_type) insert(iterator, value_type)\endlink</code>,
<code>insert(iterator, InputIterator, InputIterator)</code>,
<code>\link rinsert(iterator, param_value_type) rinsert(iterator, value_type)\endlink</code>,
<code>\link rinsert(iterator, size_type, param_value_type)
rinsert(iterator, size_type, value_type)\endlink</code>,
<code>rinsert(iterator, InputIterator, InputIterator)</code>
*/
void insert(iterator pos, size_type n, param_value_type item) {
BOOST_CB_ASSERT(pos.is_valid(this)); // check for uninitialized or invalidated iterator
if (n == 0)
return;
size_type copy = capacity() - (end() - pos);
if (copy == 0)
return;
if (n > copy)
n = copy;
insert_n(pos, n, cb_details::item_wrapper<const_pointer, param_value_type>(item));
}
//! Insert the range <code>[first, last)</code> at the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> or its end.<br>
Valid range <code>[first, last)</code> where <code>first</code> and <code>last</code> meet the
requirements of an <a href="http://www.sgi.com/tech/stl/InputIterator.html">InputIterator</a>.
\post Elements from the range
<code>[first + max[0, distance(first, last) - (pos - begin()) - reserve()], last)</code> will be
inserted at the position <code>pos</code>.<br>The number of <code>min[pos - begin(), max[0,
distance(first, last) - reserve()]]</code> elements will be overwritten at the beginning of the
<code>circular_buffer</code>.<br>(See <i>Example</i> for the explanation.)
\param pos An iterator specifying the position where the range will be inserted.
\param first The beginning of the range to be inserted.
\param last The end of the range to be inserted.
\throws Whatever <code>T::T(const T&)</code> throws if the <code>InputIterator</code> is not a move iterator.
Whatever <code>T::operator = (const T&)</code> throws if the <code>InputIterator</code> is not a move iterator.
Whatever <code>T::T(T&&)</code> throws if the <code>InputIterator</code> is a move iterator.
Whatever <code>T::operator = (T&&)</code> throws if the <code>InputIterator</code> is a move iterator.
\par Exception Safety
Basic; no-throw if the operations in the <i>Throws</i> section do not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the elements at the insertion point (including <code>pos</code>) and
iterators behind the insertion point (towards the end; except iterators equal to <code>end()</code>). It
also invalidates iterators pointing to the overwritten elements.
\par Complexity
Linear (in <code>[std::distance(pos, end()) + std::distance(first, last)]</code>; in
<code>min[capacity(), std::distance(pos, end()) + std::distance(first, last)]</code> if the
<code>InputIterator</code> is a
<a href="http://www.sgi.com/tech/stl/RandomAccessIterator.html">RandomAccessIterator</a>).
\par Example
Consider a <code>circular_buffer</code> with the capacity of 6 and the size of 4. Its internal buffer may
look like the one below.<br><br>
<code>|1|2|3|4| | |</code><br>
<code>p ___^</code><br><br>After inserting a range of elements at the position <code>p</code>:<br><br>
<code>int array[] = { 5, 6, 7, 8, 9 };</code><br><code>insert(p, array, array + 5);</code><br><br>
actually only elements <code>6</code>, <code>7</code>, <code>8</code> and <code>9</code> from the
specified range get inserted and elements <code>1</code> and <code>2</code> are overwritten. This is due
to the fact the insert operation preserves the capacity. After insertion the internal buffer looks like
this:<br><br><code>|6|7|8|9|3|4|</code><br><br>For comparison if the capacity would not be preserved the
internal buffer would then result in <code>|1|2|5|6|7|8|9|3|4|</code>.
\sa <code>\link insert(iterator, param_value_type) insert(iterator, value_type)\endlink</code>,
<code>\link insert(iterator, size_type, param_value_type)
insert(iterator, size_type, value_type)\endlink</code>, <code>\link rinsert(iterator, param_value_type)
rinsert(iterator, value_type)\endlink</code>, <code>\link rinsert(iterator, size_type, param_value_type)
rinsert(iterator, size_type, value_type)\endlink</code>,
<code>rinsert(iterator, InputIterator, InputIterator)</code>
*/
template <class InputIterator>
void insert(iterator pos, InputIterator first, InputIterator last) {
BOOST_CB_ASSERT(pos.is_valid(this)); // check for uninitialized or invalidated iterator
insert(pos, first, last, is_integral<InputIterator>());
}
private:
template <class ValT>
iterator rinsert_impl(iterator pos, ValT item) {
BOOST_CB_ASSERT(pos.is_valid(this)); // check for uninitialized or invalidated iterator
if (full() && pos.m_it == 0)
return end();
if (pos == begin()) {
BOOST_TRY {
decrement(m_first);
construct_or_replace(!full(), m_first, static_cast<ValT>(item));
} BOOST_CATCH(...) {
increment(m_first);
BOOST_RETHROW
}
BOOST_CATCH_END
pos.m_it = m_first;
} else {
pointer src = m_first;
pointer dest = m_first;
decrement(dest);
pos.m_it = map_pointer(pos.m_it);
bool construct = !full();
BOOST_TRY {
while (src != pos.m_it) {
construct_or_replace(construct, dest, boost::move_if_noexcept(*src));
increment(src);
increment(dest);
construct = false;
}
decrement(pos.m_it);
replace(pos.m_it, static_cast<ValT>(item));
} BOOST_CATCH(...) {
if (!construct && !full()) {
decrement(m_first);
++m_size;
}
BOOST_RETHROW
}
BOOST_CATCH_END
decrement(m_first);
}
if (full())
m_last = m_first;
else
++m_size;
return iterator(this, pos.m_it);
}
public:
//! Insert an element before the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> or its end.
\post The <code>item</code> will be inserted before the position <code>pos</code>.<br>
If the <code>circular_buffer</code> is full, the last element will be overwritten. If the
<code>circular_buffer</code> is full and the <code>pos</code> points to <code>end()</code>, then the
<code>item</code> will not be inserted. If the capacity is <code>0</code>, nothing will be inserted.
\param pos An iterator specifying the position before which the <code>item</code> will be inserted.
\param item The element to be inserted.
\return Iterator to the inserted element or <code>end()</code> if the <code>item</code> is not inserted. (See
the <i>Effect</i>.)
\throws Whatever <code>T::T(const T&)</code> throws.
Whatever <code>T::operator = (const T&)</code> throws.
<a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operations in the <i>Throws</i> section do not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the elements before the insertion point (towards the beginning and
excluding <code>pos</code>). It also invalidates iterators pointing to the overwritten element.
\par Complexity
Linear (in <code>std::distance(begin(), pos)</code>).
\sa <code>\link rinsert(iterator, size_type, param_value_type)
rinsert(iterator, size_type, value_type)\endlink</code>,
<code>rinsert(iterator, InputIterator, InputIterator)</code>,
<code>\link insert(iterator, param_value_type) insert(iterator, value_type)\endlink</code>,
<code>\link insert(iterator, size_type, param_value_type)
insert(iterator, size_type, value_type)\endlink</code>,
<code>insert(iterator, InputIterator, InputIterator)</code>
*/
iterator rinsert(iterator pos, param_value_type item) {
return rinsert_impl<param_value_type>(pos, item);
}
//! Insert an element before the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> or its end.
\post The <code>item</code> will be inserted before the position <code>pos</code>.<br>
If the <code>circular_buffer</code> is full, the last element will be overwritten. If the
<code>circular_buffer</code> is full and the <code>pos</code> points to <code>end()</code>, then the
<code>item</code> will not be inserted. If the capacity is <code>0</code>, nothing will be inserted.
\param pos An iterator specifying the position before which the <code>item</code> will be inserted.
\param item The element to be inserted.
\return Iterator to the inserted element or <code>end()</code> if the <code>item</code> is not inserted. (See
the <i>Effect</i>.)
\throws Whatever <code>T::T(T&&)</code> throws.
Whatever <code>T::operator = (T&&)</code> throws.
<a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operations in the <i>Throws</i> section do not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the elements before the insertion point (towards the beginning and
excluding <code>pos</code>). It also invalidates iterators pointing to the overwritten element.
\par Complexity
Linear (in <code>std::distance(begin(), pos)</code>).
\sa <code>\link rinsert(iterator, size_type, param_value_type)
rinsert(iterator, size_type, value_type)\endlink</code>,
<code>rinsert(iterator, InputIterator, InputIterator)</code>,
<code>\link insert(iterator, param_value_type) insert(iterator, value_type)\endlink</code>,
<code>\link insert(iterator, size_type, param_value_type)
insert(iterator, size_type, value_type)\endlink</code>,
<code>insert(iterator, InputIterator, InputIterator)</code>
*/
iterator rinsert(iterator pos, rvalue_type item) {
return rinsert_impl<rvalue_type>(pos, boost::move(item));
}
//! Insert an element before the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> or its end.
\post The <code>item</code> will be inserted before the position <code>pos</code>.<br>
If the <code>circular_buffer</code> is full, the last element will be overwritten. If the
<code>circular_buffer</code> is full and the <code>pos</code> points to <code>end()</code>, then the
<code>item</code> will not be inserted. If the capacity is <code>0</code>, nothing will be inserted.
\param pos An iterator specifying the position before which the <code>item</code> will be inserted.
\return Iterator to the inserted element or <code>end()</code> if the <code>item</code> is not inserted. (See
the <i>Effect</i>.)
\throws Whatever <code>T::T()</code> throws.
Whatever <code>T::T(T&&)</code> throws.
Whatever <code>T::operator = (T&&)</code> throws.
<a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operations in the <i>Throws</i> section do not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the elements before the insertion point (towards the beginning and
excluding <code>pos</code>). It also invalidates iterators pointing to the overwritten element.
\par Complexity
Linear (in <code>std::distance(begin(), pos)</code>).
\sa <code>\link rinsert(iterator, size_type, param_value_type)
rinsert(iterator, size_type, value_type)\endlink</code>,
<code>rinsert(iterator, InputIterator, InputIterator)</code>,
<code>\link insert(iterator, param_value_type) insert(iterator, value_type)\endlink</code>,
<code>\link insert(iterator, size_type, param_value_type)
insert(iterator, size_type, value_type)\endlink</code>,
<code>insert(iterator, InputIterator, InputIterator)</code>
*/
iterator rinsert(iterator pos) {
value_type temp;
return rinsert(pos, boost::move(temp));
}
//! Insert <code>n</code> copies of the <code>item</code> before the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> or its end.
\post The number of <code>min[n, (end() - pos) + reserve()]</code> elements will be inserted before the
position <code>pos</code>.<br>The number of <code>min[end() - pos, max[0, n - reserve()]]</code> elements
will be overwritten at the end of the <code>circular_buffer</code>.<br>(See <i>Example</i> for the
explanation.)
\param pos An iterator specifying the position where the <code>item</code>s will be inserted.
\param n The number of <code>item</code>s the to be inserted.
\param item The element whose copies will be inserted.
\throws Whatever <code>T::T(const T&)</code> throws.
Whatever <code>T::operator = (const T&)</code> throws.
<a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operations in the <i>Throws</i> section do not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the elements before the insertion point (towards the beginning and
excluding <code>pos</code>). It also invalidates iterators pointing to the overwritten elements.
\par Complexity
Linear (in <code>min[capacity(), std::distance(begin(), pos) + n]</code>).
\par Example
Consider a <code>circular_buffer</code> with the capacity of 6 and the size of 4. Its internal buffer may
look like the one below.<br><br>
<code>|1|2|3|4| | |</code><br>
<code>p ___^</code><br><br>After inserting 5 elements before the position <code>p</code>:<br><br>
<code>rinsert(p, (size_t)5, 0);</code><br><br>actually only 4 elements get inserted and elements
<code>3</code> and <code>4</code> are overwritten. This is due to the fact the rinsert operation preserves
the capacity. After insertion the internal buffer looks like this:<br><br><code>|1|2|0|0|0|0|</code><br>
<br>For comparison if the capacity would not be preserved the internal buffer would then result in
<code>|1|2|0|0|0|0|0|3|4|</code>.
\sa <code>\link rinsert(iterator, param_value_type) rinsert(iterator, value_type)\endlink</code>,
<code>rinsert(iterator, InputIterator, InputIterator)</code>,
<code>\link insert(iterator, param_value_type) insert(iterator, value_type)\endlink</code>,
<code>\link insert(iterator, size_type, param_value_type)
insert(iterator, size_type, value_type)\endlink</code>,
<code>insert(iterator, InputIterator, InputIterator)</code>
*/
void rinsert(iterator pos, size_type n, param_value_type item) {
BOOST_CB_ASSERT(pos.is_valid(this)); // check for uninitialized or invalidated iterator
rinsert_n(pos, n, cb_details::item_wrapper<const_pointer, param_value_type>(item));
}
//! Insert the range <code>[first, last)</code> before the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> or its end.<br>
Valid range <code>[first, last)</code> where <code>first</code> and <code>last</code> meet the
requirements of an <a href="http://www.sgi.com/tech/stl/InputIterator.html">InputIterator</a>.
\post Elements from the range
<code>[first, last - max[0, distance(first, last) - (end() - pos) - reserve()])</code> will be inserted
before the position <code>pos</code>.<br>The number of <code>min[end() - pos, max[0,
distance(first, last) - reserve()]]</code> elements will be overwritten at the end of the
<code>circular_buffer</code>.<br>(See <i>Example</i> for the explanation.)
\param pos An iterator specifying the position where the range will be inserted.
\param first The beginning of the range to be inserted.
\param last The end of the range to be inserted.
\throws Whatever <code>T::T(const T&)</code> throws if the <code>InputIterator</code> is not a move iterator.
Whatever <code>T::operator = (const T&)</code> throws if the <code>InputIterator</code> is not a move iterator.
Whatever <code>T::T(T&&)</code> throws if the <code>InputIterator</code> is a move iterator.
Whatever <code>T::operator = (T&&)</code> throws if the <code>InputIterator</code> is a move iterator.
\par Exception Safety
Basic; no-throw if the operations in the <i>Throws</i> section do not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the elements before the insertion point (towards the beginning and
excluding <code>pos</code>). It also invalidates iterators pointing to the overwritten elements.
\par Complexity
Linear (in <code>[std::distance(begin(), pos) + std::distance(first, last)]</code>; in
<code>min[capacity(), std::distance(begin(), pos) + std::distance(first, last)]</code> if the
<code>InputIterator</code> is a
<a href="http://www.sgi.com/tech/stl/RandomAccessIterator.html">RandomAccessIterator</a>).
\par Example
Consider a <code>circular_buffer</code> with the capacity of 6 and the size of 4. Its internal buffer may
look like the one below.<br><br>
<code>|1|2|3|4| | |</code><br>
<code>p ___^</code><br><br>After inserting a range of elements before the position <code>p</code>:<br><br>
<code>int array[] = { 5, 6, 7, 8, 9 };</code><br><code>insert(p, array, array + 5);</code><br><br>
actually only elements <code>5</code>, <code>6</code>, <code>7</code> and <code>8</code> from the
specified range get inserted and elements <code>3</code> and <code>4</code> are overwritten. This is due
to the fact the rinsert operation preserves the capacity. After insertion the internal buffer looks like
this:<br><br><code>|1|2|5|6|7|8|</code><br><br>For comparison if the capacity would not be preserved the
internal buffer would then result in <code>|1|2|5|6|7|8|9|3|4|</code>.
\sa <code>\link rinsert(iterator, param_value_type) rinsert(iterator, value_type)\endlink</code>,
<code>\link rinsert(iterator, size_type, param_value_type)
rinsert(iterator, size_type, value_type)\endlink</code>, <code>\link insert(iterator, param_value_type)
insert(iterator, value_type)\endlink</code>, <code>\link insert(iterator, size_type, param_value_type)
insert(iterator, size_type, value_type)\endlink</code>,
<code>insert(iterator, InputIterator, InputIterator)</code>
*/
template <class InputIterator>
void rinsert(iterator pos, InputIterator first, InputIterator last) {
BOOST_CB_ASSERT(pos.is_valid(this)); // check for uninitialized or invalidated iterator
rinsert(pos, first, last, is_integral<InputIterator>());
}
// Erase
//! Remove an element at the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> (but not an
<code>end()</code>).
\post The element at the position <code>pos</code> is removed.
\param pos An iterator pointing at the element to be removed.
\return Iterator to the first element remaining beyond the removed element or <code>end()</code> if no such
element exists.
\throws <a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the erased element and iterators pointing to the elements behind
the erased element (towards the end; except iterators equal to <code>end()</code>).
\par Complexity
Linear (in <code>std::distance(pos, end())</code>).
\sa <code>erase(iterator, iterator)</code>, <code>rerase(iterator)</code>,
<code>rerase(iterator, iterator)</code>, <code>erase_begin(size_type)</code>,
<code>erase_end(size_type)</code>, <code>clear()</code>
*/
iterator erase(iterator pos) {
BOOST_CB_ASSERT(pos.is_valid(this)); // check for uninitialized or invalidated iterator
BOOST_CB_ASSERT(pos.m_it != 0); // check for iterator pointing to end()
pointer next = pos.m_it;
increment(next);
for (pointer p = pos.m_it; next != m_last; p = next, increment(next))
replace(p, boost::move_if_noexcept(*next));
decrement(m_last);
destroy_item(m_last);
--m_size;
#if BOOST_CB_ENABLE_DEBUG
return m_last == pos.m_it ? end() : iterator(this, pos.m_it);
#else
return m_last == pos.m_it ? end() : pos;
#endif
}
//! Erase the range <code>[first, last)</code>.
/*!
\pre Valid range <code>[first, last)</code>.
\post The elements from the range <code>[first, last)</code> are removed. (If <code>first == last</code>
nothing is removed.)
\param first The beginning of the range to be removed.
\param last The end of the range to be removed.
\return Iterator to the first element remaining beyond the removed elements or <code>end()</code> if no such
element exists.
\throws <a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the erased elements and iterators pointing to the elements behind
the erased range (towards the end; except iterators equal to <code>end()</code>).
\par Complexity
Linear (in <code>std::distance(first, end())</code>).
\sa <code>erase(iterator)</code>, <code>rerase(iterator)</code>, <code>rerase(iterator, iterator)</code>,
<code>erase_begin(size_type)</code>, <code>erase_end(size_type)</code>, <code>clear()</code>
*/
iterator erase(iterator first, iterator last) {
BOOST_CB_ASSERT(first.is_valid(this)); // check for uninitialized or invalidated iterator
BOOST_CB_ASSERT(last.is_valid(this)); // check for uninitialized or invalidated iterator
BOOST_CB_ASSERT(first <= last); // check for wrong range
if (first == last)
return first;
pointer p = first.m_it;
while (last.m_it != 0)
replace((first++).m_it, boost::move_if_noexcept(*last++));
do {
decrement(m_last);
destroy_item(m_last);
--m_size;
} while(m_last != first.m_it);
return m_last == p ? end() : iterator(this, p);
}
//! Remove an element at the specified position.
/*!
\pre <code>pos</code> is a valid iterator pointing to the <code>circular_buffer</code> (but not an
<code>end()</code>).
\post The element at the position <code>pos</code> is removed.
\param pos An iterator pointing at the element to be removed.
\return Iterator to the first element remaining in front of the removed element or <code>begin()</code> if no
such element exists.
\throws <a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the erased element and iterators pointing to the elements in front of
the erased element (towards the beginning).
\par Complexity
Linear (in <code>std::distance(begin(), pos)</code>).
\note This method is symetric to the <code>erase(iterator)</code> method and is more effective than
<code>erase(iterator)</code> if the iterator <code>pos</code> is close to the beginning of the
<code>circular_buffer</code>. (See the <i>Complexity</i>.)
\sa <code>erase(iterator)</code>, <code>erase(iterator, iterator)</code>,
<code>rerase(iterator, iterator)</code>, <code>erase_begin(size_type)</code>,
<code>erase_end(size_type)</code>, <code>clear()</code>
*/
iterator rerase(iterator pos) {
BOOST_CB_ASSERT(pos.is_valid(this)); // check for uninitialized or invalidated iterator
BOOST_CB_ASSERT(pos.m_it != 0); // check for iterator pointing to end()
pointer prev = pos.m_it;
pointer p = prev;
for (decrement(prev); p != m_first; p = prev, decrement(prev))
replace(p, boost::move_if_noexcept(*prev));
destroy_item(m_first);
increment(m_first);
--m_size;
#if BOOST_CB_ENABLE_DEBUG
return p == pos.m_it ? begin() : iterator(this, pos.m_it);
#else
return p == pos.m_it ? begin() : pos;
#endif
}
//! Erase the range <code>[first, last)</code>.
/*!
\pre Valid range <code>[first, last)</code>.
\post The elements from the range <code>[first, last)</code> are removed. (If <code>first == last</code>
nothing is removed.)
\param first The beginning of the range to be removed.
\param last The end of the range to be removed.
\return Iterator to the first element remaining in front of the removed elements or <code>begin()</code> if no
such element exists.
\throws <a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything.
\par Iterator Invalidation
Invalidates iterators pointing to the erased elements and iterators pointing to the elements in front of
the erased range (towards the beginning).
\par Complexity
Linear (in <code>std::distance(begin(), last)</code>).
\note This method is symetric to the <code>erase(iterator, iterator)</code> method and is more effective than
<code>erase(iterator, iterator)</code> if <code>std::distance(begin(), first)</code> is lower that
<code>std::distance(last, end())</code>.
\sa <code>erase(iterator)</code>, <code>erase(iterator, iterator)</code>, <code>rerase(iterator)</code>,
<code>erase_begin(size_type)</code>, <code>erase_end(size_type)</code>, <code>clear()</code>
*/
iterator rerase(iterator first, iterator last) {
BOOST_CB_ASSERT(first.is_valid(this)); // check for uninitialized or invalidated iterator
BOOST_CB_ASSERT(last.is_valid(this)); // check for uninitialized or invalidated iterator
BOOST_CB_ASSERT(first <= last); // check for wrong range
if (first == last)
return first;
pointer p = map_pointer(last.m_it);
last.m_it = p;
while (first.m_it != m_first) {
decrement(first.m_it);
decrement(p);
replace(p, boost::move_if_noexcept(*first.m_it));
}
do {
destroy_item(m_first);
increment(m_first);
--m_size;
} while(m_first != p);
if (m_first == last.m_it)
return begin();
decrement(last.m_it);
return iterator(this, last.m_it);
}
//! Remove first <code>n</code> elements (with constant complexity for scalar types).
/*!
\pre <code>n \<= size()</code>
\post The <code>n</code> elements at the beginning of the <code>circular_buffer</code> will be removed.
\param n The number of elements to be removed.
\throws <a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything. (I.e. no throw in
case of scalars.)
\par Iterator Invalidation
Invalidates iterators pointing to the first <code>n</code> erased elements.
\par Complexity
Constant (in <code>n</code>) for scalar types; linear for other types.
\note This method has been specially designed for types which do not require an explicit destructruction (e.g.
integer, float or a pointer). For these scalar types a call to a destructor is not required which makes
it possible to implement the "erase from beginning" operation with a constant complexity. For non-sacalar
types the complexity is linear (hence the explicit destruction is needed) and the implementation is
actually equivalent to
<code>\link circular_buffer::rerase(iterator, iterator) rerase(begin(), begin() + n)\endlink</code>.
\sa <code>erase(iterator)</code>, <code>erase(iterator, iterator)</code>,
<code>rerase(iterator)</code>, <code>rerase(iterator, iterator)</code>,
<code>erase_end(size_type)</code>, <code>clear()</code>
*/
void erase_begin(size_type n) {
BOOST_CB_ASSERT(n <= size()); // check for n greater than size
#if BOOST_CB_ENABLE_DEBUG
erase_begin(n, false_type());
#else
erase_begin(n, is_scalar<value_type>());
#endif
}
//! Remove last <code>n</code> elements (with constant complexity for scalar types).
/*!
\pre <code>n \<= size()</code>
\post The <code>n</code> elements at the end of the <code>circular_buffer</code> will be removed.
\param n The number of elements to be removed.
\throws <a href="circular_buffer/implementation.html#circular_buffer.implementation.exceptions_of_move_if_noexcept_t">Exceptions of move_if_noexcept(T&)</a>.
\par Exception Safety
Basic; no-throw if the operation in the <i>Throws</i> section does not throw anything. (I.e. no throw in
case of scalars.)
\par Iterator Invalidation
Invalidates iterators pointing to the last <code>n</code> erased elements.
\par Complexity
Constant (in <code>n</code>) for scalar types; linear for other types.
\note This method has been specially designed for types which do not require an explicit destructruction (e.g.
integer, float or a pointer). For these scalar types a call to a destructor is not required which makes
it possible to implement the "erase from end" operation with a constant complexity. For non-sacalar
types the complexity is linear (hence the explicit destruction is needed) and the implementation is
actually equivalent to
<code>\link circular_buffer::erase(iterator, iterator) erase(end() - n, end())\endlink</code>.
\sa <code>erase(iterator)</code>, <code>erase(iterator, iterator)</code>,
<code>rerase(iterator)</code>, <code>rerase(iterator, iterator)</code>,
<code>erase_begin(size_type)</code>, <code>clear()</code>
*/
void erase_end(size_type n) {
BOOST_CB_ASSERT(n <= size()); // check for n greater than size
#if BOOST_CB_ENABLE_DEBUG
erase_end(n, false_type());
#else
erase_end(n, is_scalar<value_type>());
#endif
}
//! Remove all stored elements from the <code>circular_buffer</code>.
/*!
\post <code>size() == 0</code>
\throws Nothing.
\par Exception Safety
No-throw.
\par Iterator Invalidation
Invalidates all iterators pointing to the <code>circular_buffer</code> (except iterators equal to
<code>end()</code>).
\par Complexity
Constant (in the size of the <code>circular_buffer</code>) for scalar types; linear for other types.
\sa <code>~circular_buffer()</code>, <code>erase(iterator)</code>, <code>erase(iterator, iterator)</code>,
<code>rerase(iterator)</code>, <code>rerase(iterator, iterator)</code>,
<code>erase_begin(size_type)</code>, <code>erase_end(size_type)</code>
*/
void clear() BOOST_NOEXCEPT {
destroy_content();
m_size = 0;
}
private:
// Helper methods
//! Check if the <code>index</code> is valid.
void check_position(size_type index) const {
if (index >= size())
throw_exception(std::out_of_range("circular_buffer"));
}
//! Increment the pointer.
template <class Pointer>
void increment(Pointer& p) const {
if (++p == m_end)
p = m_buff;
}
//! Decrement the pointer.
template <class Pointer>
void decrement(Pointer& p) const {
if (p == m_buff)
p = m_end;
--p;
}
//! Add <code>n</code> to the pointer.
template <class Pointer>
Pointer add(Pointer p, difference_type n) const {
return p + (n < (m_end - p) ? n : n - capacity());
}
//! Subtract <code>n</code> from the pointer.
template <class Pointer>
Pointer sub(Pointer p, difference_type n) const {
return p - (n > (p - m_buff) ? n - capacity() : n);
}
//! Map the null pointer to virtual end of circular buffer.
pointer map_pointer(pointer p) const { return p == 0 ? m_last : p; }
//! Allocate memory.
pointer allocate(size_type n) {
if (n > max_size())
throw_exception(std::length_error("circular_buffer"));
#if BOOST_CB_ENABLE_DEBUG
pointer p = (n == 0) ? 0 : m_alloc.allocate(n);
cb_details::do_fill_uninitialized_memory(p, sizeof(value_type) * n);
return p;
#else
return (n == 0) ? 0 : m_alloc.allocate(n);
#endif
}
//! Deallocate memory.
void deallocate(pointer p, size_type n) {
if (p != 0)
m_alloc.deallocate(p, n);
}
//! Does the pointer point to the uninitialized memory?
bool is_uninitialized(const_pointer p) const BOOST_NOEXCEPT {
return p >= m_last && (m_first < m_last || p < m_first);
}
//! Replace an element.
void replace(pointer pos, param_value_type item) {
*pos = item;
#if BOOST_CB_ENABLE_DEBUG
invalidate_iterators(iterator(this, pos));
#endif
}
//! Replace an element.
void replace(pointer pos, rvalue_type item) {
*pos = boost::move(item);
#if BOOST_CB_ENABLE_DEBUG
invalidate_iterators(iterator(this, pos));
#endif
}
//! Construct or replace an element.
/*!
<code>construct</code> has to be set to <code>true</code> if and only if
<code>pos</code> points to an uninitialized memory.
*/
void construct_or_replace(bool construct, pointer pos, param_value_type item) {
if (construct)
boost::container::allocator_traits<Alloc>::construct(m_alloc, boost::to_address(pos), item);
else
replace(pos, item);
}
//! Construct or replace an element.
/*!
<code>construct</code> has to be set to <code>true</code> if and only if
<code>pos</code> points to an uninitialized memory.
*/
void construct_or_replace(bool construct, pointer pos, rvalue_type item) {
if (construct)
boost::container::allocator_traits<Alloc>::construct(m_alloc, boost::to_address(pos), boost::move(item));
else
replace(pos, boost::move(item));
}
//! Destroy an item.
void destroy_item(pointer p) {
boost::container::allocator_traits<Alloc>::destroy(m_alloc, boost::to_address(p));
#if BOOST_CB_ENABLE_DEBUG
invalidate_iterators(iterator(this, p));
cb_details::do_fill_uninitialized_memory(p, sizeof(value_type));
#endif
}
//! Destroy an item only if it has been constructed.
void destroy_if_constructed(pointer pos) {
if (is_uninitialized(pos))
destroy_item(pos);
}
//! Destroy the whole content of the circular buffer.
void destroy_content() {
#if BOOST_CB_ENABLE_DEBUG
destroy_content(false_type());
#else
destroy_content(is_scalar<value_type>());
#endif
}
//! Specialized destroy_content method.
void destroy_content(const true_type&) {
m_first = add(m_first, size());
}
//! Specialized destroy_content method.
void destroy_content(const false_type&) {
for (size_type ii = 0; ii < size(); ++ii, increment(m_first))
destroy_item(m_first);
}
//! Destroy content and free allocated memory.
void destroy() BOOST_NOEXCEPT {
destroy_content();
deallocate(m_buff, capacity());
#if BOOST_CB_ENABLE_DEBUG
m_buff = 0;
m_first = 0;
m_last = 0;
m_end = 0;
#endif
}
//! Initialize the internal buffer.
void initialize_buffer(capacity_type buffer_capacity) {
m_buff = allocate(buffer_capacity);
m_end = m_buff + buffer_capacity;
}
//! Initialize the internal buffer.
void initialize_buffer(capacity_type buffer_capacity, param_value_type item) {
initialize_buffer(buffer_capacity);
BOOST_TRY {
cb_details::uninitialized_fill_n_with_alloc(m_buff, size(), item, m_alloc);
} BOOST_CATCH(...) {
deallocate(m_buff, size());
BOOST_RETHROW
}
BOOST_CATCH_END
}
//! Specialized initialize method.
template <class IntegralType>
void initialize(IntegralType n, IntegralType item, const true_type&) {
m_size = static_cast<size_type>(n);
initialize_buffer(size(), item);
m_first = m_last = m_buff;
}
//! Specialized initialize method.
template <class Iterator>
void initialize(Iterator first, Iterator last, const false_type&) {
BOOST_CB_IS_CONVERTIBLE(Iterator, value_type); // check for invalid iterator type
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x581))
initialize(first, last, iterator_category<Iterator>::type());
#else
initialize(first, last, BOOST_DEDUCED_TYPENAME iterator_category<Iterator>::type());
#endif
}
//! Specialized initialize method.
template <class InputIterator>
void initialize(InputIterator first, InputIterator last, const std::input_iterator_tag&) {
BOOST_CB_ASSERT_TEMPLATED_ITERATOR_CONSTRUCTORS // check if the STL provides templated iterator constructors
// for containers
std::deque<value_type, allocator_type> tmp(first, last, m_alloc);
size_type distance = tmp.size();
initialize(distance, boost::make_move_iterator(tmp.begin()), boost::make_move_iterator(tmp.end()), distance);
}
//! Specialized initialize method.
template <class ForwardIterator>
void initialize(ForwardIterator first, ForwardIterator last, const std::forward_iterator_tag&) {
BOOST_CB_ASSERT(std::distance(first, last) >= 0); // check for wrong range
size_type distance = std::distance(first, last);
initialize(distance, first, last, distance);
}
//! Specialized initialize method.
template <class IntegralType>
void initialize(capacity_type buffer_capacity, IntegralType n, IntegralType item, const true_type&) {
BOOST_CB_ASSERT(buffer_capacity >= static_cast<size_type>(n)); // check for capacity lower than n
m_size = static_cast<size_type>(n);
initialize_buffer(buffer_capacity, item);
m_first = m_buff;
m_last = buffer_capacity == size() ? m_buff : m_buff + size();
}
//! Specialized initialize method.
template <class Iterator>
void initialize(capacity_type buffer_capacity, Iterator first, Iterator last, const false_type&) {
BOOST_CB_IS_CONVERTIBLE(Iterator, value_type); // check for invalid iterator type
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x581))
initialize(buffer_capacity, first, last, iterator_category<Iterator>::type());
#else
initialize(buffer_capacity, first, last, BOOST_DEDUCED_TYPENAME iterator_category<Iterator>::type());
#endif
}
//! Specialized initialize method.
template <class InputIterator>
void initialize(capacity_type buffer_capacity,
InputIterator first,
InputIterator last,
const std::input_iterator_tag&) {
initialize_buffer(buffer_capacity);
m_first = m_last = m_buff;
m_size = 0;
if (buffer_capacity == 0)
return;
while (first != last && !full()) {
boost::container::allocator_traits<Alloc>::construct(m_alloc, boost::to_address(m_last), *first++);
increment(m_last);
++m_size;
}
while (first != last) {
replace(m_last, *first++);
increment(m_last);
m_first = m_last;
}
}
//! Specialized initialize method.
template <class ForwardIterator>
void initialize(capacity_type buffer_capacity,
ForwardIterator first,
ForwardIterator last,
const std::forward_iterator_tag&) {
BOOST_CB_ASSERT(std::distance(first, last) >= 0); // check for wrong range
initialize(buffer_capacity, first, last, std::distance(first, last));
}
//! Initialize the circular buffer.
template <class ForwardIterator>
void initialize(capacity_type buffer_capacity,
ForwardIterator first,
ForwardIterator last,
size_type distance) {
initialize_buffer(buffer_capacity);
m_first = m_buff;
if (distance > buffer_capacity) {
std::advance(first, distance - buffer_capacity);
m_size = buffer_capacity;
} else {
m_size = distance;
}
BOOST_TRY {
m_last = cb_details::uninitialized_copy(first, last, m_buff, m_alloc);
} BOOST_CATCH(...) {
deallocate(m_buff, buffer_capacity);
BOOST_RETHROW
}
BOOST_CATCH_END
if (m_last == m_end)
m_last = m_buff;
}
//! Reset the circular buffer.
void reset(pointer buff, pointer last, capacity_type new_capacity) {
destroy();
m_size = last - buff;
m_first = m_buff = buff;
m_end = m_buff + new_capacity;
m_last = last == m_end ? m_buff : last;
}
//! Specialized method for swapping the allocator.
void swap_allocator(circular_buffer<T, Alloc>&, const true_type&) {
// Swap is not needed because allocators have no state.
}
//! Specialized method for swapping the allocator.
void swap_allocator(circular_buffer<T, Alloc>& cb, const false_type&) {
adl_move_swap(m_alloc, cb.m_alloc);
}
//! Specialized assign method.
template <class IntegralType>
void assign(IntegralType n, IntegralType item, const true_type&) {
assign(static_cast<size_type>(n), static_cast<value_type>(item));
}
//! Specialized assign method.
template <class Iterator>
void assign(Iterator first, Iterator last, const false_type&) {
BOOST_CB_IS_CONVERTIBLE(Iterator, value_type); // check for invalid iterator type
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x581))
assign(first, last, iterator_category<Iterator>::type());
#else
assign(first, last, BOOST_DEDUCED_TYPENAME iterator_category<Iterator>::type());
#endif
}
//! Specialized assign method.
template <class InputIterator>
void assign(InputIterator first, InputIterator last, const std::input_iterator_tag&) {
BOOST_CB_ASSERT_TEMPLATED_ITERATOR_CONSTRUCTORS // check if the STL provides templated iterator constructors
// for containers
std::deque<value_type, allocator_type> tmp(first, last, m_alloc);
size_type distance = tmp.size();
assign_n(distance, distance,
cb_details::make_assign_range
(boost::make_move_iterator(tmp.begin()), boost::make_move_iterator(tmp.end()), m_alloc));
}
//! Specialized assign method.
template <class ForwardIterator>
void assign(ForwardIterator first, ForwardIterator last, const std::forward_iterator_tag&) {
BOOST_CB_ASSERT(std::distance(first, last) >= 0); // check for wrong range
size_type distance = std::distance(first, last);
assign_n(distance, distance, cb_details::make_assign_range(first, last, m_alloc));
}
//! Specialized assign method.
template <class IntegralType>
void assign(capacity_type new_capacity, IntegralType n, IntegralType item, const true_type&) {
assign(new_capacity, static_cast<size_type>(n), static_cast<value_type>(item));
}
//! Specialized assign method.
template <class Iterator>
void assign(capacity_type new_capacity, Iterator first, Iterator last, const false_type&) {
BOOST_CB_IS_CONVERTIBLE(Iterator, value_type); // check for invalid iterator type
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x581))
assign(new_capacity, first, last, iterator_category<Iterator>::type());
#else
assign(new_capacity, first, last, BOOST_DEDUCED_TYPENAME iterator_category<Iterator>::type());
#endif
}
//! Specialized assign method.
template <class InputIterator>
void assign(capacity_type new_capacity, InputIterator first, InputIterator last, const std::input_iterator_tag&) {
if (new_capacity == capacity()) {
clear();
insert(begin(), first, last);
} else {
circular_buffer<value_type, allocator_type> tmp(new_capacity, first, last, m_alloc);
tmp.swap(*this);
}
}
//! Specialized assign method.
template <class ForwardIterator>
void assign(capacity_type new_capacity, ForwardIterator first, ForwardIterator last,
const std::forward_iterator_tag&) {
BOOST_CB_ASSERT(std::distance(first, last) >= 0); // check for wrong range
size_type distance = std::distance(first, last);
if (distance > new_capacity) {
std::advance(first, distance - new_capacity);
distance = new_capacity;
}
assign_n(new_capacity, distance,
cb_details::make_assign_range(first, last, m_alloc));
}
//! Helper assign method.
template <class Functor>
void assign_n(capacity_type new_capacity, size_type n, const Functor& fnc) {
if (new_capacity == capacity()) {
destroy_content();
BOOST_TRY {
fnc(m_buff);
} BOOST_CATCH(...) {
m_size = 0;
BOOST_RETHROW
}
BOOST_CATCH_END
} else {
pointer buff = allocate(new_capacity);
BOOST_TRY {
fnc(buff);
} BOOST_CATCH(...) {
deallocate(buff, new_capacity);
BOOST_RETHROW
}
BOOST_CATCH_END
destroy();
m_buff = buff;
m_end = m_buff + new_capacity;
}
m_size = n;
m_first = m_buff;
m_last = add(m_buff, size());
}
//! Helper insert method.
template <class ValT>
iterator insert_item(const iterator& pos, ValT item) {
pointer p = pos.m_it;
if (p == 0) {
construct_or_replace(!full(), m_last, static_cast<ValT>(item));
p = m_last;
} else {
pointer src = m_last;
pointer dest = m_last;
bool construct = !full();
BOOST_TRY {
while (src != p) {
decrement(src);
construct_or_replace(construct, dest, boost::move_if_noexcept(*src));
decrement(dest);
construct = false;
}
replace(p, static_cast<ValT>(item));
} BOOST_CATCH(...) {
if (!construct && !full()) {
increment(m_last);
++m_size;
}
BOOST_RETHROW
}
BOOST_CATCH_END
}
increment(m_last);
if (full())
m_first = m_last;
else
++m_size;
return iterator(this, p);
}
//! Specialized insert method.
template <class IntegralType>
void insert(const iterator& pos, IntegralType n, IntegralType item, const true_type&) {
insert(pos, static_cast<size_type>(n), static_cast<value_type>(item));
}
//! Specialized insert method.
template <class Iterator>
void insert(const iterator& pos, Iterator first, Iterator last, const false_type&) {
BOOST_CB_IS_CONVERTIBLE(Iterator, value_type); // check for invalid iterator type
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x581))
insert(pos, first, last, iterator_category<Iterator>::type());
#else
insert(pos, first, last, BOOST_DEDUCED_TYPENAME iterator_category<Iterator>::type());
#endif
}
//! Specialized insert method.
template <class InputIterator>
void insert(iterator pos, InputIterator first, InputIterator last, const std::input_iterator_tag&) {
if (!full() || pos != begin()) {
for (;first != last; ++pos)
pos = insert(pos, *first++);
}
}
//! Specialized insert method.
template <class ForwardIterator>
void insert(const iterator& pos, ForwardIterator first, ForwardIterator last, const std::forward_iterator_tag&) {
BOOST_CB_ASSERT(std::distance(first, last) >= 0); // check for wrong range
size_type n = std::distance(first, last);
if (n == 0)
return;
size_type copy = capacity() - (end() - pos);
if (copy == 0)
return;
if (n > copy) {
std::advance(first, n - copy);
n = copy;
}
insert_n(pos, n, cb_details::iterator_wrapper<ForwardIterator>(first));
}
//! Helper insert method.
template <class Wrapper>
void insert_n(const iterator& pos, size_type n, const Wrapper& wrapper) {
size_type construct = reserve();
if (construct > n)
construct = n;
if (pos.m_it == 0) {
size_type ii = 0;
pointer p = m_last;
BOOST_TRY {
for (; ii < construct; ++ii, increment(p))
boost::container::allocator_traits<Alloc>::construct(m_alloc, boost::to_address(p), *wrapper());
for (;ii < n; ++ii, increment(p))
replace(p, *wrapper());
} BOOST_CATCH(...) {
size_type constructed = (std::min)(ii, construct);
m_last = add(m_last, constructed);
m_size += constructed;
BOOST_RETHROW
}
BOOST_CATCH_END
} else {
pointer src = m_last;
pointer dest = add(m_last, n - 1);
pointer p = pos.m_it;
size_type ii = 0;
BOOST_TRY {
while (src != pos.m_it) {
decrement(src);
construct_or_replace(is_uninitialized(dest), dest, *src);
decrement(dest);
}
for (; ii < n; ++ii, increment(p))
construct_or_replace(is_uninitialized(p), p, *wrapper());
} BOOST_CATCH(...) {
for (p = add(m_last, n - 1); p != dest; decrement(p))
destroy_if_constructed(p);
for (n = 0, p = pos.m_it; n < ii; ++n, increment(p))
destroy_if_constructed(p);
BOOST_RETHROW
}
BOOST_CATCH_END
}
m_last = add(m_last, n);
m_first = add(m_first, n - construct);
m_size += construct;
}
//! Specialized rinsert method.
template <class IntegralType>
void rinsert(const iterator& pos, IntegralType n, IntegralType item, const true_type&) {
rinsert(pos, static_cast<size_type>(n), static_cast<value_type>(item));
}
//! Specialized rinsert method.
template <class Iterator>
void rinsert(const iterator& pos, Iterator first, Iterator last, const false_type&) {
BOOST_CB_IS_CONVERTIBLE(Iterator, value_type); // check for invalid iterator type
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x581))
rinsert(pos, first, last, iterator_category<Iterator>::type());
#else
rinsert(pos, first, last, BOOST_DEDUCED_TYPENAME iterator_category<Iterator>::type());
#endif
}
//! Specialized insert method.
template <class InputIterator>
void rinsert(iterator pos, InputIterator first, InputIterator last, const std::input_iterator_tag&) {
if (!full() || pos.m_it != 0) {
for (;first != last; ++pos) {
pos = rinsert(pos, *first++);
if (pos.m_it == 0)
break;
}
}
}
//! Specialized rinsert method.
template <class ForwardIterator>
void rinsert(const iterator& pos, ForwardIterator first, ForwardIterator last, const std::forward_iterator_tag&) {
BOOST_CB_ASSERT(std::distance(first, last) >= 0); // check for wrong range
rinsert_n(pos, std::distance(first, last), cb_details::iterator_wrapper<ForwardIterator>(first));
}
//! Helper rinsert method.
template <class Wrapper>
void rinsert_n(const iterator& pos, size_type n, const Wrapper& wrapper) {
if (n == 0)
return;
iterator b = begin();
size_type copy = capacity() - (pos - b);
if (copy == 0)
return;
if (n > copy)
n = copy;
size_type construct = reserve();
if (construct > n)
construct = n;
if (pos == b) {
pointer p = sub(m_first, n);
size_type ii = n;
BOOST_TRY {
for (;ii > construct; --ii, increment(p))
replace(p, *wrapper());
for (; ii > 0; --ii, increment(p))
boost::container::allocator_traits<Alloc>::construct(m_alloc, boost::to_address(p), *wrapper());
} BOOST_CATCH(...) {
size_type constructed = ii < construct ? construct - ii : 0;
m_last = add(m_last, constructed);
m_size += constructed;
BOOST_RETHROW
}
BOOST_CATCH_END
} else {
pointer src = m_first;
pointer dest = sub(m_first, n);
pointer p = map_pointer(pos.m_it);
BOOST_TRY {
while (src != p) {
construct_or_replace(is_uninitialized(dest), dest, *src);
increment(src);
increment(dest);
}
for (size_type ii = 0; ii < n; ++ii, increment(dest))
construct_or_replace(is_uninitialized(dest), dest, *wrapper());
} BOOST_CATCH(...) {
for (src = sub(m_first, n); src != dest; increment(src))
destroy_if_constructed(src);
BOOST_RETHROW
}
BOOST_CATCH_END
}
m_first = sub(m_first, n);
m_last = sub(m_last, n - construct);
m_size += construct;
}
//! Specialized erase_begin method.
void erase_begin(size_type n, const true_type&) {
m_first = add(m_first, n);
m_size -= n;
}
//! Specialized erase_begin method.
void erase_begin(size_type n, const false_type&) {
iterator b = begin();
rerase(b, b + n);
}
//! Specialized erase_end method.
void erase_end(size_type n, const true_type&) {
m_last = sub(m_last, n);
m_size -= n;
}
//! Specialized erase_end method.
void erase_end(size_type n, const false_type&) {
iterator e = end();
erase(e - n, e);
}
};
// Non-member functions
//! Compare two <code>circular_buffer</code>s element-by-element to determine if they are equal.
/*!
\param lhs The <code>circular_buffer</code> to compare.
\param rhs The <code>circular_buffer</code> to compare.
\return <code>lhs.\link circular_buffer::size() size()\endlink == rhs.\link circular_buffer::size() size()\endlink
&& <a href="http://www.sgi.com/tech/stl/equal.html">std::equal</a>(lhs.\link circular_buffer::begin()
begin()\endlink, lhs.\link circular_buffer::end() end()\endlink,
rhs.\link circular_buffer::begin() begin()\endlink)</code>
\throws Nothing.
\par Complexity
Linear (in the size of the <code>circular_buffer</code>s).
\par Iterator Invalidation
Does not invalidate any iterators.
*/
template <class T, class Alloc>
inline bool operator == (const circular_buffer<T, Alloc>& lhs, const circular_buffer<T, Alloc>& rhs) {
return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
/*!
\brief Compare two <code>circular_buffer</code>s element-by-element to determine if the left one is lesser than the
right one.
\param lhs The <code>circular_buffer</code> to compare.
\param rhs The <code>circular_buffer</code> to compare.
\return <code><a href="http://www.sgi.com/tech/stl/lexicographical_compare.html">
std::lexicographical_compare</a>(lhs.\link circular_buffer::begin() begin()\endlink,
lhs.\link circular_buffer::end() end()\endlink, rhs.\link circular_buffer::begin() begin()\endlink,
rhs.\link circular_buffer::end() end()\endlink)</code>
\throws Nothing.
\par Complexity
Linear (in the size of the <code>circular_buffer</code>s).
\par Iterator Invalidation
Does not invalidate any iterators.
*/
template <class T, class Alloc>
inline bool operator < (const circular_buffer<T, Alloc>& lhs, const circular_buffer<T, Alloc>& rhs) {
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
#if !defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING) || defined(BOOST_MSVC)
//! Compare two <code>circular_buffer</code>s element-by-element to determine if they are non-equal.
/*!
\param lhs The <code>circular_buffer</code> to compare.
\param rhs The <code>circular_buffer</code> to compare.
\return <code>!(lhs == rhs)</code>
\throws Nothing.
\par Complexity
Linear (in the size of the <code>circular_buffer</code>s).
\par Iterator Invalidation
Does not invalidate any iterators.
\sa <code>operator==(const circular_buffer<T,Alloc>&, const circular_buffer<T,Alloc>&)</code>
*/
template <class T, class Alloc>
inline bool operator != (const circular_buffer<T, Alloc>& lhs, const circular_buffer<T, Alloc>& rhs) {
return !(lhs == rhs);
}
/*!
\brief Compare two <code>circular_buffer</code>s element-by-element to determine if the left one is greater than
the right one.
\param lhs The <code>circular_buffer</code> to compare.
\param rhs The <code>circular_buffer</code> to compare.
\return <code>rhs \< lhs</code>
\throws Nothing.
\par Complexity
Linear (in the size of the <code>circular_buffer</code>s).
\par Iterator Invalidation
Does not invalidate any iterators.
\sa <code>operator<(const circular_buffer<T,Alloc>&, const circular_buffer<T,Alloc>&)</code>
*/
template <class T, class Alloc>
inline bool operator > (const circular_buffer<T, Alloc>& lhs, const circular_buffer<T, Alloc>& rhs) {
return rhs < lhs;
}
/*!
\brief Compare two <code>circular_buffer</code>s element-by-element to determine if the left one is lesser or equal
to the right one.
\param lhs The <code>circular_buffer</code> to compare.
\param rhs The <code>circular_buffer</code> to compare.
\return <code>!(rhs \< lhs)</code>
\throws Nothing.
\par Complexity
Linear (in the size of the <code>circular_buffer</code>s).
\par Iterator Invalidation
Does not invalidate any iterators.
\sa <code>operator<(const circular_buffer<T,Alloc>&, const circular_buffer<T,Alloc>&)</code>
*/
template <class T, class Alloc>
inline bool operator <= (const circular_buffer<T, Alloc>& lhs, const circular_buffer<T, Alloc>& rhs) {
return !(rhs < lhs);
}
/*!
\brief Compare two <code>circular_buffer</code>s element-by-element to determine if the left one is greater or
equal to the right one.
\param lhs The <code>circular_buffer</code> to compare.
\param rhs The <code>circular_buffer</code> to compare.
\return <code>!(lhs < rhs)</code>
\throws Nothing.
\par Complexity
Linear (in the size of the <code>circular_buffer</code>s).
\par Iterator Invalidation
Does not invalidate any iterators.
\sa <code>operator<(const circular_buffer<T,Alloc>&, const circular_buffer<T,Alloc>&)</code>
*/
template <class T, class Alloc>
inline bool operator >= (const circular_buffer<T, Alloc>& lhs, const circular_buffer<T, Alloc>& rhs) {
return !(lhs < rhs);
}
//! Swap the contents of two <code>circular_buffer</code>s.
/*!
\post <code>lhs</code> contains elements of <code>rhs</code> and vice versa.
\param lhs The <code>circular_buffer</code> whose content will be swapped with <code>rhs</code>.
\param rhs The <code>circular_buffer</code> whose content will be swapped with <code>lhs</code>.
\throws Nothing.
\par Complexity
Constant (in the size of the <code>circular_buffer</code>s).
\par Iterator Invalidation
Invalidates all iterators of both <code>circular_buffer</code>s. (On the other hand the iterators still
point to the same elements but within another container. If you want to rely on this feature you have to
turn the <a href="#debug">Debug Support</a> off otherwise an assertion will report an error if such
invalidated iterator is used.)
\sa <code>\link circular_buffer::swap(circular_buffer<T, Alloc>&) swap(circular_buffer<T, Alloc>&)\endlink</code>
*/
template <class T, class Alloc>
inline void swap(circular_buffer<T, Alloc>& lhs, circular_buffer<T, Alloc>& rhs) BOOST_NOEXCEPT {
lhs.swap(rhs);
}
#endif // #if !defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING) || defined(BOOST_MSVC)
} // namespace boost
#endif // #if !defined(BOOST_CIRCULAR_BUFFER_BASE_HPP)
| [
"james.pack@stardog.com"
] | james.pack@stardog.com |
d463eaf0fd8aebb08432c4ba8e805402b1e539be | f4043b2fb90fe7f956d959df8c421760ef1d5fab | /ch11/copy2.cpp | 08af757eeb3b4f74598655b6ab0884ff22a631d0 | [
"MIT"
] | permissive | bashell/CppStandardLibrary | 41de8c71e119521b3f878eb24dbf6b8daba1c1e0 | 2aae03019288132c911036aeb9ba36edc56e510b | refs/heads/master | 2020-12-30T22:09:10.049502 | 2017-02-15T07:11:13 | 2017-02-15T07:11:13 | 68,666,712 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | cpp | #include "algostuff.hpp"
using namespace std;
int main()
{
vector<char> source(10, '.');
for(int c = 'a'; c <= 'f'; ++c)
source.push_back(c);
source.insert(source.end(), 10, '.');
PRINT_ELEMENTS(source, "source: ");
vector<char> c1(source.cbegin(), source.cend());
copy(c1.cbegin()+10, c1.cbegin()+16, c1.begin()+7);
PRINT_ELEMENTS(c1, "c1: ");
vector<char> c2(source.cbegin(), source.cend());
copy_backward(c2.cbegin()+10, c2.cbegin()+16, c2.begin()+19);
PRINT_ELEMENTS(c2, "c2: ");
return 0;
}
| [
"nju.liuc@gmail.com"
] | nju.liuc@gmail.com |
f01f0ea50771b5771121435d720705730402d4d3 | a17207bda73fe017746b90f1d85e96f0326454aa | /week_01/code_wars/myeong/200828_GetMiddle.cpp | fb1b94234dbbad922b167b630436aac4ce7a1d08 | [] | no_license | st102/2020-1st-St102-Algorithm-Sprint | 6ad494edb626b63533c8ac00f23d1a16f913bd2b | 85a9d961895170f47da85df84dde99ea5a545861 | refs/heads/master | 2022-12-20T16:12:58.098292 | 2020-10-06T07:52:44 | 2020-10-06T07:52:44 | 289,298,228 | 0 | 1 | null | 2020-10-10T06:28:17 | 2020-08-21T15:07:03 | C++ | UTF-8 | C++ | false | false | 302 | cpp | std::string get_middle(std::string input)
{
int mid;
mid=input.length()/2;
if ( input.length()==1 ) {
return input;
}
else if ( input.length()%2==1 && input.length()!=1 ) {
return input.substr(mid,1);
}
else if ( input.length()%2==0 ) {
return input.substr(mid-1,2);
}
} | [
"mg0454@naver.com"
] | mg0454@naver.com |
d461d590c669d3556b8d5dd8b6c8202348640933 | de75637338706776f8770c9cd169761cec128579 | /VHFOS/Viet heroes - Fight or Surrender/RealisticWater.h | dc0520c7d725002b13d58b08bfb4f9b145268dce | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | huytd/fosengine | e018957abb7b2ea2c4908167ec83cb459c3de716 | 1cebb1bec49720a8e9ecae1c3d0c92e8d16c27c5 | refs/heads/master | 2021-01-18T23:47:32.402023 | 2008-07-12T07:20:10 | 2008-07-12T07:20:10 | 38,933,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,041 | h | /*
* Copyright (c) 2007, elvman
* All rights reserved.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY elvman ``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 <copyright holder> 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.
*/
#define REALISIC_WATER_IN_USED 1;
#ifdef REALISIC_WATER_IN_USED
#pragma once
#include <string>
#include <irrlicht.h>
using namespace irr;
class RealisticWaterSceneNode: public scene::ISceneNode, video::IShaderConstantSetCallBack
{
public:
RealisticWaterSceneNode(scene::ISceneManager* sceneManager, f32 width, f32 height, video::ITexture* bumpTexture, ITimer* timer,
core::dimension2di renderTargetSize=core::dimension2di(512,512),scene::ISceneNode* parent = 0, s32 id = -1);
virtual ~RealisticWaterSceneNode();
// frame
virtual void OnRegisterSceneNode();
virtual void OnAnimate(u32 timeMs);
// renders terrain
virtual void render();
// returns the axis aligned bounding box of terrain
virtual const core::aabbox3d<f32>& getBoundingBox() const;
virtual void OnSetConstants(video::IMaterialRendererServices* services, s32 userData);
virtual void setWindForce(const f32 windForce);
virtual void setWindDirection(const core::vector2df& windDirection);
virtual void setWaveHeight(const f32 waveHeight);
virtual void setWaterColor(const video::SColorf& waterColor);
virtual void setColorBlendFactor(const f32 colorBlendFactor);
private:
scene::ICameraSceneNode* Camera;
scene::ISceneNode* WaterSceneNode;
video::IVideoDriver* VideoDriver;
scene::ISceneManager* SceneManager;
ITimer* Timer;
core::dimension2d<f32> Size;
s32 ShaderMaterial;
video::ITexture* RefractionMap;
video::ITexture* ReflectionMap;
f32 WindForce;
core::vector2df WindDirection;
f32 WaveHeight;
video::SColorf WaterColor;
f32 ColorBlendFactor;
};
#endif | [
"doqkhanh@52f955dd-904d-0410-b1ed-9fe3d3cbfe06"
] | doqkhanh@52f955dd-904d-0410-b1ed-9fe3d3cbfe06 |
e094d503e9bf5dc846fb0b53226eb1006a622981 | e1831f6315475599eff1d05b20e44f7b9413517f | /SafeComplan/src/utils/generatetrajectory.cpp | ac6d02cc947f56688c68201213f959901566142e | [
"BSD-3-Clause"
] | permissive | vighv/mae6770project | bf2ba350bd73a08aa72a334c87babf9346966100 | 091c518292b3363fce56f9015d4ef4a979f9a60c | refs/heads/master | 2021-08-28T03:03:18.094703 | 2017-12-11T04:30:07 | 2017-12-11T04:30:07 | 111,724,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,847 | cpp | #include <iostream>
#include <fstream>
#include <sys/time.h>
#include "stdlib.h"
#include "primitive.h"
#include "readinputs.h"
#include "extractoutput.h"
unsigned int max_traj_length = 30;
void generateZ3File(prim_vec_t , pos_vec_t , workspace_t );
void printTimeDifference(double wcts, double wcte)
{
double duration;
int hr, min;
double sec;
duration = wcte - wcts;
hr = duration / 3600;
min = (duration / 60) - (hr * 60) ;
sec = duration - hr * 3600 - min * 60;
cout << endl << duration << "s" << endl;
cout << endl << hr << "h " << min << "m " << (((sec - int(sec)) > 0.5) ? (int(sec) + 1) : int(sec)) << "s" << endl << endl;
ofstream ofp;
ofp.open("result", fstream::app);
ofp << hr << "h " << min << "m " << (((sec - int(sec)) > 0.5) ? (int(sec) + 1) : int(sec)) << "s" << endl << endl;
ofp.close();
}
int generateTrajectory(prim_vec_t primitives, prim_cost_t prim_cost, pos_vec_t obstacles, workspace_t workspace)
{
ifstream ifp;
string line;
unsigned int count;
char buffer[100];
float cost;
char command[100];
float max_total_cost, min_total_cost;
struct timeval tm;
double wcts, wcte;
ofstream ofp;
//count = 26;
count = workspace.number_of_points;
::max_traj_length = workspace.number_of_points;
while (1)
{
gettimeofday( &tm, NULL );
wcts = (double)tm.tv_sec + (double)tm.tv_usec * .000001;
workspace.number_of_points = count;
cost = count * workspace.number_of_uavs * prim_cost.max_cost;
sprintf(buffer, "%f", cost);
cout << "Cost =" << cost << endl;
workspace.total_cost = string(buffer);
//sprintf(command, "time ./constraints_generator output %d", workspace.number_of_points - 1);
//system(command);
generateZ3File(primitives, obstacles, workspace);
//cout << endl << "Timeout is set at 3600s." << endl;
//system("timeout 7200s z3 constraints.smt2 > z3_output");
system("time z3 constraints.smt2 > z3_output");
ifp.open("z3_output");
if (ifp.is_open())
{
getline(ifp, line);
ifp.close();
}
cout << "$$$$$$$$ " << count << " " << line << endl;
if (line == "unsat")
{
count = count + 1;
if (count > max_traj_length)
{
cout << "Trajectory does not exist.." << endl;
exit(0);
}
}
else if (line == "sat")
{
system("cp z3_output z3_output_sat");
gettimeofday( &tm, NULL );
wcte = (double)tm.tv_sec + (double)tm.tv_usec * .000001;
ofp.open("result");
ofp << "Trajectory Length = " << count << endl << endl;
ofp.close();
ofp.open("result", fstream::app);
ofp << "Final Iteration Time = ";
ofp.close();
printTimeDifference(wcts, wcte);
break;
}
else
{
cout << "unknown output from z3.." << endl;
count = count + 1;
if (count > max_traj_length)
{
exit(0);
}
}
if (count > max_traj_length)
break;
}
system("perl processoutputfile.pl");
system("mv planner_output plan_noopt");
max_total_cost = count * workspace.number_of_uavs * prim_cost.max_cost;
min_total_cost = count * workspace.number_of_uavs * prim_cost.min_cost;
cout << "max_total_cost = " << max_total_cost << endl;
cout << "min_total_cost = " << min_total_cost << endl;
ofp.open("result", fstream::app);
ofp << "max_total_cost = " << max_total_cost << endl;
ofp << "min_total_cost = " << min_total_cost << endl;
ofp << "Cost Before Optimization = " << extractTrajectoryCostInformation() << endl << endl;
ofp.close();
cout << "Cost = " << extractTrajectoryCostInformation() << endl << endl;
return count;
}
void optimizeTrajectory(prim_vec_t primitives, prim_cost_t prim_cost, pos_vec_t obstacles, workspace_t workspace, int trajectory_length)
{
float max_total_cost, min_total_cost, current_cost;
ifstream ifp;
string line;
char buffer[100];
ofstream ofp;
workspace.number_of_points = trajectory_length;
max_total_cost = extractTrajectoryCostInformation();
min_total_cost = trajectory_length * workspace.number_of_uavs * prim_cost.min_cost;
current_cost = (max_total_cost + min_total_cost) / 2;
cout << "min2_min_cost_diff = " << prim_cost.min2_min_cost_diff << endl << endl;
cout << "max_total_cost = " << max_total_cost << endl;
cout << "min_total_cost = " << min_total_cost << endl;
cout << "current_cost = " << current_cost << endl;
system("mv z3_output z3_output_sat");
while (max_total_cost - min_total_cost > prim_cost.min2_min_cost_diff)
{
sprintf(buffer, "%f", current_cost);
workspace.total_cost = string(buffer);
generateZ3File(primitives, obstacles, workspace);
cout << endl << "Timeout is set at 7200s." << endl;
system("time z3 constraints.smt2 > z3_output");
ifp.open("z3_output");
getline(ifp, line);
ifp.close();
cout << "$$$$$$$$ " << trajectory_length << " " << line << endl;
if (line == "unsat")
{
min_total_cost = current_cost;
}
else if (line == "sat")
{
max_total_cost = extractTrajectoryCostInformation();
system("mv z3_output z3_output_sat");
}
else
{
cout << "unknown output from z3.." << endl;
min_total_cost = current_cost;
//break;
}
current_cost = (max_total_cost + min_total_cost) / 2;
cout << "max_total_cost = " << max_total_cost << endl;
cout << "min_total_cost = " << min_total_cost << endl;
cout << "current_cost = " << current_cost << endl;
}
system("mv z3_output_sat z3_output");
system("perl processoutputfile.pl");
system("mv planner_output plan_opt");
ofp.open("result", fstream::app);
ofp << "Cost After Optimization = " << extractTrajectoryCostInformation() << endl << endl;
ofp.close();
cout << "Cost = " << extractTrajectoryCostInformation() << endl << endl;
}
| [
"vv94@cornell.edu"
] | vv94@cornell.edu |
e841c39c39cefc5defb130beca93aef20ef20766 | 5fafb2bdfa0b886a51b35b6414b694ae7e78c811 | /src/test/script_P2PKH_tests.cpp | 31e78566339ecc884fb688226dea5691f4529c3c | [
"MIT"
] | permissive | ahayder/Wolfcoin | 0dcc2322a19136a211360e8eea68d28495eba7d1 | 3bf0122e2bdd242af8c0e4435372874abe867194 | refs/heads/master | 2020-04-23T17:48:42.224491 | 2019-03-04T12:29:58 | 2019-03-04T12:29:58 | 171,345,315 | 1 | 0 | MIT | 2019-02-18T19:42:21 | 2019-02-18T19:42:20 | null | UTF-8 | C++ | false | false | 2,245 | 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 "script/script.h"
#include "test/test_wolfcoin.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(script_P2PKH_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(IsPayToPublicKeyHash)
{
// Test CScript::IsPayToPublicKeyHash()
uint160 dummy;
CScript p2pkh;
p2pkh << OP_DUP << OP_HASH160 << ToByteVector(dummy) << OP_EQUALVERIFY << OP_CHECKSIG;
BOOST_CHECK(p2pkh.IsPayToPublicKeyHash());
static const unsigned char direct[] = {
OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG
};
BOOST_CHECK(CScript(direct, direct+sizeof(direct)).IsPayToPublicKeyHash());
static const unsigned char notp2pkh1[] = {
OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG, OP_CHECKSIG
};
BOOST_CHECK(!CScript(notp2pkh1, notp2pkh1+sizeof(notp2pkh1)).IsPayToPublicKeyHash());
static const unsigned char p2sh[] = {
OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL
};
BOOST_CHECK(!CScript(p2sh, p2sh+sizeof(p2sh)).IsPayToPublicKeyHash());
static const unsigned char extra[] = {
OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG, OP_CHECKSIG
};
BOOST_CHECK(!CScript(extra, extra+sizeof(extra)).IsPayToPublicKeyHash());
static const unsigned char missing[] = {
OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG, OP_RETURN
};
BOOST_CHECK(!CScript(missing, missing+sizeof(missing)).IsPayToPublicKeyHash());
static const unsigned char missing2[] = {
OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
BOOST_CHECK(!CScript(missing2, missing2+sizeof(missing2)).IsPayToPublicKeyHash());
static const unsigned char tooshort[] = {
OP_DUP, OP_HASH160, 2, 0,0, OP_EQUALVERIFY, OP_CHECKSIG
};
BOOST_CHECK(!CScript(tooshort, tooshort+sizeof(tooshort)).IsPayToPublicKeyHash());
}
BOOST_AUTO_TEST_SUITE_END()
| [
"BigBitsCode@gmail.com"
] | BigBitsCode@gmail.com |
c32854d6d41becd5870954b3bb9c228c3d371587 | 5d01a2a16078b78fbb7380a6ee548fc87a80e333 | /ETS/EtsEod/EtsEodManager/EodCommandLineInfo.h | 838b8fba3df80e1fcab8ddb9c112e9c5dcee5101 | [] | no_license | WilliamQf-AI/IVRMstandard | 2fd66ae6e81976d39705614cfab3dbfb4e8553c5 | 761bbdd0343012e7367ea111869bb6a9d8f043c0 | refs/heads/master | 2023-04-04T22:06:48.237586 | 2013-04-17T13:56:40 | 2013-04-17T13:56:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 398 | h | #pragma once
#include "afxwin.h"
class CEodCommandLineInfo :
public CCommandLineInfo
{
public:
CEodCommandLineInfo(void) : m_bIsBackground(false) {};
~CEodCommandLineInfo(void) {};
virtual void ParseParam(const TCHAR* pszParam, BOOL bFlag, BOOL bLast);
#ifdef _UNICODE
virtual void ParseParam(const char* pszParam, BOOL bFlag, BOOL bLast);
#endif
bool m_bIsBackground;
};
| [
"chuchev@egartech.com"
] | chuchev@egartech.com |
b21c63d75dd48118d04938eb57f2680c00fb43d7 | f9276bd683b37570f26483b32652e1d6816940b2 | /server/sawa_admin.h | b9b83b12329dc237ae8a36f8014d344f8bf68c30 | [] | no_license | lpoulain/SaWa | 81d73f39b64f69436ec4c5206afcb3f74b2bd65a | 1994be6c1620c5286468c8e0ac700219c34d60af | refs/heads/master | 2020-03-09T22:00:24.231423 | 2018-06-18T03:04:12 | 2018-06-18T03:04:12 | 129,024,473 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | h | class AdminInterface {
int socket_desc;
pthread_t *thread;
void statCommand(int);
void processCommand(int, uint8_t *, int);
void readCommand(int);
static void *connectionHandler(void *);
public:
AdminInterface();
~AdminInterface();
};
extern AdminInterface *admin;
| [
"laurent.poulain@gmail.com"
] | laurent.poulain@gmail.com |
cab372c10a75c89a03d7702b271ca2c2b7422a1a | fbc3b7b48bdcc58bdcad5cdc70835939cc5e8d63 | /Projects/MasterMindConsole/MastermindGameApp.cpp | 25ad7f9b73af53bd5460f8eb606207c094dc02a4 | [] | no_license | cyrjac/CppExample | 39d1e734e89bf432d8ba27ae85dd0468ddc70bf5 | d8b0027ef38ed897e63750d5e4bd78f2237ed88e | refs/heads/main | 2023-02-13T05:26:25.582074 | 2021-01-04T18:57:16 | 2021-01-04T18:57:16 | 313,106,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,136 | cpp | // MastermindGameApp.cpp : Ce fichier contient la fonction 'main'. L'exécution du programme commence et se termine à cet endroit.
//
#include <iostream>
#include <string>
#include "MastermindUserPlays.h"
#include "MastermindAlgoPlays.h"
#include "MastermindGameApp.h"
int main()
{
bool wIsRunning = true;
std::cout << "Jeu de MasterMind\n";
MastermindUserPlays wUserPlayObject;
MastermindAlgoPlays uComputerPlayObject;
while (wIsRunning)
{
std::cout << "Vos options\n";
std::cout << "[1] Vous devinez la combinaison secrete\n";
std::cout << "[2] l'algorithme tente de deviner la combinaison secrete\n";
std::cout << "[3] Aide\n";
std::cout << "[4] Quitter\n";
std::string wAnswer = "";
std::cin >> wAnswer;
switch (wAnswer.at(0))
{
case '1':
wUserPlayObject.play();
break;
case '2':
uComputerPlayObject.play();
break;
case '3':
std::cout << "Aide\n";
std::cout << "Une combinaison comporte 4 caracteres\n";
std::cout << "Les caracteres sont 1, 2, 3 ou 4\n";
break;
case '4':
wIsRunning = false;
break;
};
}
}
// Exécuter le programme : Ctrl+F5 ou menu Déboguer > Exécuter sans débogage
// Déboguer le programme : F5 ou menu Déboguer > Démarrer le débogage
// Astuces pour bien démarrer :
// 1. Utilisez la fenêtre Explorateur de solutions pour ajouter des fichiers et les gérer.
// 2. Utilisez la fenêtre Team Explorer pour vous connecter au contrôle de code source.
// 3. Utilisez la fenêtre Sortie pour voir la sortie de la génération et d'autres messages.
// 4. Utilisez la fenêtre Liste d'erreurs pour voir les erreurs.
// 5. Accédez à Projet > Ajouter un nouvel élément pour créer des fichiers de code, ou à Projet > Ajouter un élément existant pour ajouter des fichiers de code existants au projet.
// 6. Pour rouvrir ce projet plus tard, accédez à Fichier > Ouvrir > Projet et sélectionnez le fichier .sln.
| [
"cyrjac@outlook.com"
] | cyrjac@outlook.com |
503c533d95c0af5ff01aca4d25eea660cca19fcc | 783be3f6e5147efa8f1b415776cbab70dc481a03 | /torch/csrc/distributed/c10d/reducer.h | 6606cf6488e3cae9728f00455450746dcb42b9e9 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | mkolod/pytorch | d6a5fc5336adc15cca6243554083970d1dde8ae5 | 7ae0263e1bf1482cba79361f991d11a85b35cde6 | refs/heads/master | 2020-05-04T19:03:05.751038 | 2019-04-03T21:37:54 | 2019-04-03T21:43:07 | 179,377,415 | 0 | 0 | NOASSERTION | 2019-04-03T22:08:22 | 2019-04-03T22:08:22 | null | UTF-8 | C++ | false | false | 5,285 | h | #pragma once
#include <atomic>
#include <memory>
#include <mutex>
#include <tuple>
#include <unordered_map>
#include <vector>
#include <c10d/ProcessGroup.hpp>
#include <torch/csrc/autograd/function.h>
#include <torch/csrc/autograd/variable.h>
namespace c10d {
class Reducer {
public:
// The constructor takes a vector<Variable> with model parameters for
// every model replica, hence the vector<vector<>>.
explicit Reducer(
std::vector<std::vector<torch::autograd::Variable>> variables,
std::shared_ptr<c10d::ProcessGroup> process_group);
// To (re-)initialize bucket assignment, pass a list of buckets, each
// of which is specified by a list of indices in the variables list.
// This function performs validation that the variables within a bucket
// all live on the same device and have the same dimensionality.
void initialize_buckets(std::vector<std::vector<size_t>> indices);
// This function is called when the forward function has produced an output,
// and the user wishes to reduce gradients in the backwards pass.
// If they don't, and wish to accumulate gradients before reducing them,
// a call to this function can simply be omitted.
void prepare_for_backward(
const std::vector<torch::autograd::Variable>& outputs);
// Returns the relative time in nanoseconds when gradients were ready,
// with respect to the time `prepare_for_backward` was called. The outer
// vector is for model replicas and the inner vector is for parameters.
std::vector<std::vector<int64_t>> get_backward_stats() const {
return backward_stats_;
}
protected:
std::mutex mutex_;
std::vector<std::vector<torch::autograd::Variable>> variables_;
std::shared_ptr<c10d::ProcessGroup> process_group_;
std::vector<std::vector<std::shared_ptr<torch::autograd::Function>>>
grad_accumulators_;
std::unordered_map<torch::autograd::Function*, std::tuple<int, int>> func_;
bool expect_autograd_hooks_;
bool has_queued_final_callback_;
size_t next_bucket_;
void mark_variable_ready(size_t replica_index, size_t variable_index);
void mark_bucket_ready(size_t bucket_index);
void finalize_backward();
// A bucket replica represents [1..N] gradients to be reduced,
// with the same dtype, on the same device.
//
// Batching gradients together before reducing them can result in lower
// overhead and/or faster time to completion. Only gradients of the same type
// and on the same device can be batched. The tensor that represents the
// flattened gradient uses the same type and is placed on the same device.
// Buckets are filled as the gradients they hold are computed (triggered by
// autograd hooks). Buckets are reduced in a predetemined order that is
// identical across processes.
//
struct BucketReplica {
// Flattened (1 dimensional) contents of bucket.
at::Tensor contents;
// Variables that contribute to this bucket replica. Use refcounted value
// here so that we can easily unflatten the bucket contents into the
// participating variables after reduction has completed.
std::vector<torch::autograd::Variable> variables;
// Per-variable offset/length into the flat bucket contents tensor.
std::vector<size_t> offsets;
std::vector<size_t> lengths;
// Number of tensors to be added before this bucket is complete.
// This is reset to `variables.size()` every iteration.
size_t pending;
// TODO(@pietern)
// Memory copies from gradient tensors into the bucket are potentially
// done on different CUDA streams. We record an event for every copy
// so that we can synchronize with them prior to kicking off the reduction.
// std::vector<at::cuda::CUDAEvent> events;
};
// A bucket holds N bucket replicas (1 per model replica).
//
// If every bucket in this struct is ready, the reduction can be kicked off.
// One bucket per replica. Reduction is kicked off when every bucket is ready.
//
struct Bucket {
std::vector<BucketReplica> replicas;
// Number of replicas to be marked done before this bucket is ready.
size_t pending;
// Keep work handle around when this set of buckets is being reduced.
std::shared_ptr<c10d::ProcessGroup::Work> work;
};
std::vector<Bucket> buckets_;
// A bucket index locates the position of a particular variable in the bucket
// structure. The `bucket_index` field points to the bucket in the `buckets_`
// vector. The `intra_bucket_index` field points to the index of the variable
// in any of the vector fields in the bucket replica.
struct BucketIndex {
// Index into the `buckets_` variable.
size_t bucket_index;
// Index of parameter in single bucket replica.
size_t intra_bucket_index;
};
// Maps variable index to bucket indices. Bucketing across replicas is
// identical so no need to include the replica index here.
std::vector<BucketIndex> bucket_indices_;
// We collect the relative timestamp of every gradient being ready
// when executing autograd. This can be used to derive a timeline of
// the point in time buckets were ready, or ideal bucket assignment/ordering.
int64_t backward_stats_base_;
std::vector<std::vector<int64_t>> backward_stats_;
};
} // namespace c10d
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
14d17c5fedb2495a290a39b5e6e8208f4f44629f | ac28172d0892a8c5f71f7d037687854dc2315b48 | /src/qt/coincontroldialog.cpp | e5e3072f19761605461649cd4a895fc2e62d45bf | [
"MIT"
] | permissive | biyanzu029201/ASEAN-Coin-Cash | d7005b2df21b722c8cd48ea0a0f3d4181e7ac64e | fd51982ffb12e3604acbefb1e9673f9a5e72d4d4 | refs/heads/master | 2020-04-02T03:57:35.217521 | 2018-10-21T09:38:03 | 2018-10-21T09:38:03 | 153,991,195 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,916 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coincontroldialog.h"
#include "ui_coincontroldialog.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "init.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "coincontrol.h"
#include "main.h"
#include "wallet.h"
#include "multisigdialog.h"
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <QApplication>
#include <QCheckBox>
#include <QCursor>
#include <QDialogButtonBox>
#include <QFlags>
#include <QIcon>
#include <QSettings>
#include <QString>
#include <QTreeWidget>
#include <QTreeWidgetItem>
using namespace std;
QList<CAmount> CoinControlDialog::payAmounts;
int CoinControlDialog::nSplitBlockDummy;
CCoinControl* CoinControlDialog::coinControl = new CCoinControl();
CoinControlDialog::CoinControlDialog(QWidget* parent, bool fMultisigEnabled) : QDialog(parent),
ui(new Ui::CoinControlDialog),
model(0)
{
ui->setupUi(this);
this->fMultisigEnabled = fMultisigEnabled;
/* Open CSS when configured */
this->setStyleSheet(GUIUtil::loadStyleSheet());
// context menu actions
QAction* copyAddressAction = new QAction(tr("Copy address"), this);
QAction* copyLabelAction = new QAction(tr("Copy label"), this);
QAction* copyAmountAction = new QAction(tr("Copy amount"), this);
copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this
lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this
unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this
// context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(copyTransactionHashAction);
contextMenu->addSeparator();
contextMenu->addAction(lockAction);
contextMenu->addAction(unlockAction);
// context menu signals
connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash()));
connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin()));
connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin()));
// clipboard actions
QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction* clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction* clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction* clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction* clipboardPriorityAction = new QAction(tr("Copy priority"), this);
QAction* clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
QAction* clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes()));
connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// toggle tree/list mode
connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool)));
connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool)));
// click on checkbox
connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int)));
// click on header
#if QT_VERSION < 0x050000
ui->treeWidget->header()->setClickable(true);
#else
ui->treeWidget->header()->setSectionsClickable(true);
#endif
connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int)));
// ok button
connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
// (un)select all
connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked()));
// Toggle lock state
connect(ui->pushButtonToggleLock, SIGNAL(clicked()), this, SLOT(buttonToggleLockClicked()));
// change coin control first column label due Qt4 bug.
// see https://github.com/bitcoin/bitcoin/issues/5716
ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString());
ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100);
ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170);
ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 190);
ui->treeWidget->setColumnWidth(COLUMN_DATE, 80);
ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100);
ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100);
ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64 in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64 in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_DATE_INT64, true); // store date int64 in this column, but dont show it
// default view is sorted by amount desc
sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder);
// restore list mode and sortorder as a convenience feature
QSettings settings;
if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool())
ui->radioTreeMode->click();
if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder"))
sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt()));
}
CoinControlDialog::~CoinControlDialog()
{
QSettings settings;
settings.setValue("nCoinControlMode", ui->radioListMode->isChecked());
settings.setValue("nCoinControlSortColumn", sortColumn);
settings.setValue("nCoinControlSortOrder", (int)sortOrder);
delete ui;
}
void CoinControlDialog::setModel(WalletModel* model)
{
this->model = model;
if (model && model->getOptionsModel() && model->getAddressTableModel()) {
updateView();
updateLabelLocked();
CoinControlDialog::updateLabels(model, this);
updateDialogLabels();
}
}
// helper function str_pad
QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding)
{
while (s.length() < nPadLength)
s = sPadding + s;
return s;
}
// ok button
void CoinControlDialog::buttonBoxClicked(QAbstractButton* button)
{
if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
done(QDialog::Accepted); // closes the dialog
}
// (un)select all
void CoinControlDialog::buttonSelectAllClicked()
{
Qt::CheckState state = Qt::Checked;
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) {
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) {
state = Qt::Unchecked;
break;
}
}
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state)
ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state);
ui->treeWidget->setEnabled(true);
if (state == Qt::Unchecked)
coinControl->UnSelectAll(); // just to be sure
CoinControlDialog::updateLabels(model, this);
updateDialogLabels();
}
// Toggle lock state
void CoinControlDialog::buttonToggleLockClicked()
{
QTreeWidgetItem* item;
// Works in list-mode only
if (ui->radioListMode->isChecked()) {
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) {
item = ui->treeWidget->topLevelItem(i);
if (item->text(COLUMN_TYPE) == "MultiSig")
continue;
COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) {
model->unlockCoin(outpt);
item->setDisabled(false);
item->setIcon(COLUMN_CHECKBOX, QIcon());
} else {
model->lockCoin(outpt);
item->setDisabled(true);
item->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
}
updateLabelLocked();
}
ui->treeWidget->setEnabled(true);
CoinControlDialog::updateLabels(model, this);
updateDialogLabels();
} else {
QMessageBox msgBox;
msgBox.setObjectName("lockMessageBox");
msgBox.setStyleSheet(GUIUtil::loadStyleSheet());
msgBox.setText(tr("Please switch to \"List mode\" to use this function."));
msgBox.exec();
}
}
// context menu
void CoinControlDialog::showMenu(const QPoint& point)
{
QTreeWidgetItem* item = ui->treeWidget->itemAt(point);
if (item) {
contextMenuItem = item;
// disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
copyTransactionHashAction->setEnabled(true);
if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) {
lockAction->setEnabled(false);
unlockAction->setEnabled(true);
} else {
lockAction->setEnabled(true);
unlockAction->setEnabled(false);
}
} else // this means click on parent node in tree mode -> disable all
{
copyTransactionHashAction->setEnabled(false);
lockAction->setEnabled(false);
unlockAction->setEnabled(false);
}
// show context menu
contextMenu->exec(QCursor::pos());
}
}
// context menu action: copy amount
void CoinControlDialog::copyAmount()
{
GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT)));
}
// context menu action: copy label
void CoinControlDialog::copyLabel()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL));
}
// context menu action: copy address
void CoinControlDialog::copyAddress()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS));
}
// context menu action: copy transaction id
void CoinControlDialog::copyTransactionHash()
{
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH));
}
// context menu action: lock coin
void CoinControlDialog::lockCoin()
{
if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked)
contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->lockCoin(outpt);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
updateLabelLocked();
}
// context menu action: unlock coin
void CoinControlDialog::unlockCoin()
{
COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->unlockCoin(outpt);
contextMenuItem->setDisabled(false);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon());
updateLabelLocked();
}
// copy label "Quantity" to clipboard
void CoinControlDialog::clipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// copy label "Amount" to clipboard
void CoinControlDialog::clipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// copy label "Fee" to clipboard
void CoinControlDialog::clipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace("~", ""));
}
// copy label "After fee" to clipboard
void CoinControlDialog::clipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", ""));
}
// copy label "Bytes" to clipboard
void CoinControlDialog::clipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace("~", ""));
}
// copy label "Priority" to clipboard
void CoinControlDialog::clipboardPriority()
{
GUIUtil::setClipboard(ui->labelCoinControlPriority->text());
}
// copy label "Dust" to clipboard
void CoinControlDialog::clipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// copy label "Change" to clipboard
void CoinControlDialog::clipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace("~", ""));
}
// treeview: sort
void CoinControlDialog::sortView(int column, Qt::SortOrder order)
{
sortColumn = column;
sortOrder = order;
ui->treeWidget->sortItems(column, order);
ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder);
}
// treeview: clicked on header
void CoinControlDialog::headerSectionClicked(int logicalIndex)
{
if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing
{
ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder);
} else {
logicalIndex = getMappedColumn(logicalIndex, false);
if (sortColumn == logicalIndex)
sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder);
else {
sortColumn = logicalIndex;
sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc
}
sortView(sortColumn, sortOrder);
}
}
// toggle tree mode
void CoinControlDialog::radioTreeMode(bool checked)
{
if (checked && model)
updateView();
}
// toggle list mode
void CoinControlDialog::radioListMode(bool checked)
{
if (checked && model)
updateView();
}
// checkbox clicked by user
void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
{
if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked)
coinControl->UnSelect(outpt);
else if (item->isDisabled()) // locked (this happens if "check all" through parent node)
item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
else {
coinControl->Select(outpt);
}
// selection changed -> update labels
if (ui->treeWidget->isEnabled()){ // do not update on every click for (un)select all
CoinControlDialog::updateLabels(model, this);
updateDialogLabels();
}
}
// todo: this is a temporary qt5 fix: when clicking a parent node in tree mode, the parent node
// including all childs are partially selected. But the parent node should be fully selected
// as well as the childs. Childs should never be partially selected in the first place.
// Please remove this ugly fix, once the bug is solved upstream.
#if QT_VERSION >= 0x050000
else if (column == COLUMN_CHECKBOX && item->childCount() > 0) {
if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
item->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
#endif
}
// return human readable label for priority number
QString CoinControlDialog::getPriorityLabel(double dPriority, double mempoolEstimatePriority)
{
double dPriorityMedium = mempoolEstimatePriority;
if (dPriorityMedium <= 0)
dPriorityMedium = AllowFreeThreshold(); // not enough data, back to hard-coded
if (dPriority / 1000000 > dPriorityMedium)
return tr("highest");
else if (dPriority / 100000 > dPriorityMedium)
return tr("higher");
else if (dPriority / 10000 > dPriorityMedium)
return tr("high");
else if (dPriority / 1000 > dPriorityMedium)
return tr("medium-high");
else if (dPriority > dPriorityMedium)
return tr("medium");
else if (dPriority * 10 > dPriorityMedium)
return tr("low-medium");
else if (dPriority * 100 > dPriorityMedium)
return tr("low");
else if (dPriority * 1000 > dPriorityMedium)
return tr("lower");
else
return tr("lowest");
}
// shows count of locked unspent outputs
void CoinControlDialog::updateLabelLocked()
{
vector<COutPoint> vOutpts;
model->listLockedCoins(vOutpts);
if (vOutpts.size() > 0) {
ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size()));
ui->labelLocked->setVisible(true);
} else
ui->labelLocked->setVisible(false);
}
void CoinControlDialog::updateDialogLabels()
{
if (this->parentWidget() == nullptr) {
CoinControlDialog::updateLabels(model, this);
return;
}
vector<COutPoint> vCoinControl;
vector<COutput> vOutputs;
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
CAmount nAmount = 0;
unsigned int nQuantity = 0;
for (const COutput& out : vOutputs) {
// unselect already spent, very unlikely scenario, this could happen
// when selected are spent elsewhere, like rpc or another computer
uint256 txhash = out.tx->GetHash();
COutPoint outpt(txhash, out.i);
if(model->isSpent(outpt)) {
coinControl->UnSelect(outpt);
continue;
}
// Quantity
nQuantity++;
// Amount
nAmount += out.tx->vout[out.i].nValue;
}
MultisigDialog* multisigDialog = (MultisigDialog*)this->parentWidget();
multisigDialog->updateCoinControl(nAmount, nQuantity);
}
void CoinControlDialog::updateLabels(WalletModel* model, QDialog* dialog)
{
if (!model)
return;
// nPayAmount
CAmount nPayAmount = 0;
bool fDust = false;
CMutableTransaction txDummy;
foreach (const CAmount& amount, CoinControlDialog::payAmounts) {
nPayAmount += amount;
if (amount > 0) {
CTxOut txout(amount, (CScript)vector<unsigned char>(24, 0));
txDummy.vout.push_back(txout);
if (txout.IsDust(::minRelayTxFee))
fDust = true;
}
}
QString sPriorityLabel = tr("none");
CAmount nAmount = 0;
CAmount nPayFee = 0;
CAmount nAfterFee = 0;
CAmount nChange = 0;
unsigned int nBytes = 0;
unsigned int nBytesInputs = 0;
double dPriority = 0;
double dPriorityInputs = 0;
unsigned int nQuantity = 0;
int nQuantityUncompressed = 0;
bool fAllowFree = false;
vector<COutPoint> vCoinControl;
vector<COutput> vOutputs;
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
BOOST_FOREACH (const COutput& out, vOutputs) {
// unselect already spent, very unlikely scenario, this could happen
// when selected are spent elsewhere, like rpc or another computer
uint256 txhash = out.tx->GetHash();
COutPoint outpt(txhash, out.i);
if (model->isSpent(outpt)) {
coinControl->UnSelect(outpt);
continue;
}
// Quantity
nQuantity++;
// Amount
nAmount += out.tx->vout[out.i].nValue;
// Priority
dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth + 1);
// Bytes
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
CPubKey pubkey;
CKeyID* keyid = boost::get<CKeyID>(&address);
if (keyid && model->getPubKey(*keyid, pubkey)) {
nBytesInputs += (pubkey.IsCompressed() ? 148 : 180);
if (!pubkey.IsCompressed())
nQuantityUncompressed++;
} else
nBytesInputs += 148; // in all error cases, simply assume 148 here
} else
nBytesInputs += 148;
}
// calculation
if (nQuantity > 0) {
// Bytes
nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + max(1, CoinControlDialog::nSplitBlockDummy) : 2) * 34) + 10; // always assume +1 output for change here
// Priority
double mempoolEstimatePriority = mempool.estimatePriority(nTxConfirmTarget);
dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority)
sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority);
// Fee
nPayFee = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
// IX Fee
if (coinControl->useSwiftTX) nPayFee = max(nPayFee, CENT);
// Allow free?
double dPriorityNeeded = mempoolEstimatePriority;
if (dPriorityNeeded <= 0)
dPriorityNeeded = AllowFreeThreshold(); // not enough data, back to hard-coded
fAllowFree = (dPriority >= dPriorityNeeded);
if (fSendFreeTransactions)
if (fAllowFree && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
nPayFee = 0;
if (nPayAmount > 0) {
nChange = nAmount - nPayFee - nPayAmount;
// Never create dust outputs; if we would, just add the dust to the fee.
if (nChange > 0 && nChange < CENT) {
CTxOut txout(nChange, (CScript)vector<unsigned char>(24, 0));
if (txout.IsDust(::minRelayTxFee)) {
nPayFee += nChange;
nChange = 0;
}
}
if (nChange == 0)
nBytes -= 34;
}
// after fee
nAfterFee = nAmount - nPayFee;
if (nAfterFee < 0)
nAfterFee = 0;
}
// actually update labels
int nDisplayUnit = BitcoinUnits::ACCH;
if (model && model->getOptionsModel())
nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
QLabel* l1 = dialog->findChild<QLabel*>("labelCoinControlQuantity");
QLabel* l2 = dialog->findChild<QLabel*>("labelCoinControlAmount");
QLabel* l3 = dialog->findChild<QLabel*>("labelCoinControlFee");
QLabel* l4 = dialog->findChild<QLabel*>("labelCoinControlAfterFee");
QLabel* l5 = dialog->findChild<QLabel*>("labelCoinControlBytes");
QLabel* l6 = dialog->findChild<QLabel*>("labelCoinControlPriority");
QLabel* l7 = dialog->findChild<QLabel*>("labelCoinControlLowOutput");
QLabel* l8 = dialog->findChild<QLabel*>("labelCoinControlChange");
// enable/disable "dust" and "change"
dialog->findChild<QLabel*>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel*>("labelCoinControlLowOutput")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel*>("labelCoinControlChangeText")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel*>("labelCoinControlChange")->setEnabled(nPayAmount > 0);
// stats
l1->setText(QString::number(nQuantity)); // Quantity
l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount
l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee
l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee
l5->setText(((nBytes > 0) ? "~" : "") + QString::number(nBytes)); // Bytes
l6->setText(sPriorityLabel); // Priority
l7->setText(fDust ? tr("yes") : tr("no")); // Dust
l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change
if (nPayFee > 0 && !(payTxFee.GetFeePerK() > 0 && fPayAtLeastCustomFee && nBytes < 1000)) {
l3->setText("~" + l3->text());
l4->setText("~" + l4->text());
if (nChange > 0)
l8->setText("~" + l8->text());
}
// turn labels "red"
l5->setStyleSheet((nBytes >= MAX_FREE_TRANSACTION_CREATE_SIZE) ? "color:red;" : ""); // Bytes >= 1000
l6->setStyleSheet((dPriority > 0 && !fAllowFree) ? "color:red;" : ""); // Priority < "medium"
l7->setStyleSheet((fDust) ? "color:red;" : ""); // Dust = "yes"
// tool tips
QString toolTip1 = tr("This label turns red, if the transaction size is greater than 1000 bytes.") + "<br /><br />";
toolTip1 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CWallet::minTxFee.GetFeePerK())) + "<br /><br />";
toolTip1 += tr("Can vary +/- 1 byte per input.");
QString toolTip2 = tr("Transactions with higher priority are more likely to get included into a block.") + "<br /><br />";
toolTip2 += tr("This label turns red, if the priority is smaller than \"medium\".") + "<br /><br />";
toolTip2 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CWallet::minTxFee.GetFeePerK()));
QString toolTip3 = tr("This label turns red, if any recipient receives an amount smaller than %1.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, ::minRelayTxFee.GetFee(546)));
// how many satoshis the estimated fee can vary per byte we guess wrong
double dFeeVary;
if (payTxFee.GetFeePerK() > 0)
dFeeVary = (double)std::max(CWallet::minTxFee.GetFeePerK(), payTxFee.GetFeePerK()) / 1000;
else
dFeeVary = (double)std::max(CWallet::minTxFee.GetFeePerK(), mempool.estimateFee(nTxConfirmTarget).GetFeePerK()) / 1000;
QString toolTip4 = tr("Can vary +/- %1 ubitg per input.").arg(dFeeVary);
l3->setToolTip(toolTip4);
l4->setToolTip(toolTip4);
l5->setToolTip(toolTip1);
l6->setToolTip(toolTip2);
l7->setToolTip(toolTip3);
l8->setToolTip(toolTip4);
dialog->findChild<QLabel*>("labelCoinControlFeeText")->setToolTip(l3->toolTip());
dialog->findChild<QLabel*>("labelCoinControlAfterFeeText")->setToolTip(l4->toolTip());
dialog->findChild<QLabel*>("labelCoinControlBytesText")->setToolTip(l5->toolTip());
dialog->findChild<QLabel*>("labelCoinControlPriorityText")->setToolTip(l6->toolTip());
dialog->findChild<QLabel*>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip());
dialog->findChild<QLabel*>("labelCoinControlChangeText")->setToolTip(l8->toolTip());
// Insufficient funds
QLabel* label = dialog->findChild<QLabel*>("labelCoinControlInsuffFunds");
if (label)
label->setVisible(nChange < 0);
}
void CoinControlDialog::updateView()
{
if (!model || !model->getOptionsModel() || !model->getAddressTableModel())
return;
bool treeMode = ui->radioTreeMode->isChecked();
ui->treeWidget->clear();
ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox
ui->treeWidget->setAlternatingRowColors(!treeMode);
QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
int nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
double mempoolEstimatePriority = mempool.estimatePriority(nTxConfirmTarget);
map<QString, vector<COutput>> mapCoins;
model->listCoins(mapCoins);
BOOST_FOREACH (PAIRTYPE(QString, vector<COutput>) coins, mapCoins) {
QTreeWidgetItem* itemWalletAddress = new QTreeWidgetItem();
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
QString sWalletAddress = coins.first;
QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress);
if (sWalletLabel.isEmpty())
sWalletLabel = tr("(no label)");
if (treeMode) {
// wallet address
ui->treeWidget->addTopLevelItem(itemWalletAddress);
itemWalletAddress->setFlags(flgTristate);
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
// label
itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel);
itemWalletAddress->setToolTip(COLUMN_LABEL, sWalletLabel);
// address
itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress);
itemWalletAddress->setToolTip(COLUMN_ADDRESS, sWalletAddress);
}
CAmount nSum = 0;
double dPrioritySum = 0;
int nChildren = 0;
int nInputSum = 0;
for(const COutput& out: coins.second) {
isminetype mine = pwalletMain->IsMine(out.tx->vout[out.i]);
bool fMultiSigUTXO = (mine & ISMINE_MULTISIG);
// when multisig is enabled, it will only display outputs from multisig addresses
if (fMultisigEnabled && !fMultiSigUTXO)
continue;
int nInputSize = 0;
nSum += out.tx->vout[out.i].nValue;
nChildren++;
QTreeWidgetItem* itemOutput;
if (treeMode)
itemOutput = new QTreeWidgetItem(itemWalletAddress);
else
itemOutput = new QTreeWidgetItem(ui->treeWidget);
itemOutput->setFlags(flgCheckbox);
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
//MultiSig
if (fMultiSigUTXO) {
itemOutput->setText(COLUMN_TYPE, "MultiSig");
if (!fMultisigEnabled) {
COutPoint outpt(out.tx->GetHash(), out.i);
coinControl->UnSelect(outpt); // just to be sure
itemOutput->setDisabled(true);
itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
}
} else {
itemOutput->setText(COLUMN_TYPE, "Personal");
}
// address
CTxDestination outputAddress;
QString sAddress = "";
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) {
sAddress = QString::fromStdString(CBitcoinAddress(outputAddress).ToString());
// if listMode or change => show ACCH address. In tree mode, address is not shown again for direct wallet address outputs
if (!treeMode || (!(sAddress == sWalletAddress)))
itemOutput->setText(COLUMN_ADDRESS, sAddress);
itemOutput->setToolTip(COLUMN_ADDRESS, sAddress);
CPubKey pubkey;
CKeyID* keyid = boost::get<CKeyID>(&outputAddress);
if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed())
nInputSize = 29; // 29 = 180 - 151 (public key is 180 bytes, priority free area is 151 bytes)
}
// label
if (!(sAddress == sWalletAddress)) // change
{
// tooltip from where the change comes from
itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress));
itemOutput->setText(COLUMN_LABEL, tr("(change)"));
} else if (!treeMode) {
QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress);
if (sLabel.isEmpty())
sLabel = tr("(no label)");
itemOutput->setText(COLUMN_LABEL, sLabel);
}
// amount
itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue));
itemOutput->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue));
itemOutput->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(out.tx->vout[out.i].nValue), 15, " ")); // padding so that sorting works correctly
// date
itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
itemOutput->setToolTip(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
itemOutput->setText(COLUMN_DATE_INT64, strPad(QString::number(out.tx->GetTxTime()), 20, " "));
// confirmations
itemOutput->setText(COLUMN_CONFIRMATIONS, strPad(QString::number(out.nDepth), 8, " "));
// priority
double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth + 1); // 78 = 2 * 34 + 10
itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority));
itemOutput->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPriority), 20, " "));
dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth + 1);
nInputSum += nInputSize;
// transaction hash
uint256 txhash = out.tx->GetHash();
itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex()));
// vout index
itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i));
// disable locked coins
if (model->isLockedCoin(txhash, out.i)) {
COutPoint outpt(txhash, out.i);
coinControl->UnSelect(outpt); // just to be sure
itemOutput->setDisabled(true);
itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
}
// set checkbox
if (coinControl->IsSelected(txhash, out.i))
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
// amount
if (treeMode) {
dPrioritySum = dPrioritySum / (nInputSum + 78);
itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")");
itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(nSum), 15, " "));
itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum, mempoolEstimatePriority));
itemWalletAddress->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPrioritySum), 20, " "));
}
}
// expand all partially selected
if (treeMode) {
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
ui->treeWidget->topLevelItem(i)->setExpanded(true);
}
// sort view
sortView(sortColumn, sortOrder);
ui->treeWidget->setEnabled(true);
}
| [
"ernestovps@gmail.com"
] | ernestovps@gmail.com |
18123968ff62c75ddb1b746f088b5c8b757f50bc | eac24bb9ac49967d531dda4e169664e74e85d2ba | /a_motor_Temp.h | e4074c80b8cb138f12b52b7981f1cd087a8e5d2f | [] | no_license | AlfredoBalli/TexasStateSeniorDesign | c8a1158a6afc8af84f4638adaa293b1814485c90 | 9fa5ce10ac1c73903b33761e206becfe80d09c1a | refs/heads/master | 2020-04-09T06:38:23.374673 | 2018-12-03T04:02:47 | 2018-12-03T04:02:47 | 160,121,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | h |
#ifndef m_Temp_h
#define m_Temp_h
#include "Arduino.h"
class a_motor_Temp
{
private:
bool _temp_Flag1;
bool _temp_Flag2;
int _temp_Counter1;
int _temp_Counter2;
int _temp_Sample_Ammt;
float _temp_Cumalitive_Sample;
float _temp_Inital_Sample;
float _temp_Average1;
float _temp_boundC;
float _bound_tempF;
int _pin;
unsigned long _temp_Sample_mSecs;
unsigned long _temp_Timer;
public:
a_motor_Temp(int pin, float bound);
void mTemp_Test(float tC, unsigned long milli);
bool flag1_Test();
bool flag2_Test();
void flag2_Set(bool flag);
void counter2_Set(int cnt);
};
#endif
| [
"noreply@github.com"
] | AlfredoBalli.noreply@github.com |
d918db38cc7db42472ad10908cd7d52963d36992 | 3333edce8305b199431da4ed1e2bbe9bf5aef175 | /BOJ/1000~/1978/src.cpp | a10109cccec6939e8839a1387a18854eef9c4298 | [] | no_license | suhyunch/shalstd | d208ba10ab16c3f904de9148e4fa11f243148c03 | 85ede530ebe01d1fffc3b5e2df5eee1fa88feaf0 | refs/heads/master | 2021-06-07T10:45:58.181997 | 2019-08-11T13:14:48 | 2019-08-11T13:14:48 | 110,432,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | cpp | #include <iostream>
using namespace std;
int num[1001];
int main(){
for(int i=2; i<=1000; i++){
for(int j=1; i*j<=1000; j++){
num[i*j]++;
}
}
int N;
cin >> N;
int ans=0;
while(N-->0){
int tmp;
cin >>tmp;
if(num[tmp]==1) ans++;
}
cout << ans;
}
| [
"b215220@daum.net"
] | b215220@daum.net |
9f1d4695e3636b450d3a55af18ddd46dedf63995 | 2e62eded4a05a565aa67c2557fed94d2dd2965cf | /Telemed测温监控系统设备配置/Telemed测温监控系统设备配置/common.cpp | 2b1c5cf54211fd73a42f1c80851d86541bce5081 | [] | no_license | jielmn/MyProjects | f34b308a1495f02e1cdbd887ee0faf3f103a8df8 | 0f0519991d0fdbb98ad0ef86e8bd472c2176a2aa | refs/heads/master | 2021-06-03T11:56:40.884186 | 2020-05-29T09:47:55 | 2020-05-29T09:47:55 | 110,639,886 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,474 | cpp | #include <time.h>
#include "common.h"
#include <setupapi.h>
CGlobalData g_data;
IConfig * g_cfg_area = 0;
std::vector<TArea *> g_vArea;
// The following define is from ntddser.h in the DDK. It is also
// needed for serial port enumeration.
#ifndef GUID_CLASS_COMPORT
DEFINE_GUID(GUID_CLASS_COMPORT, 0x86e0d1e0L, 0x8089, 0x11d0, 0x9c, 0xe4, \
0x08, 0x00, 0x3e, 0x30, 0x1f, 0x73);
#endif
BOOL EnumPortsWdm(std::vector<std::string> & v)
{
// Create a device information set that will be the container for
// the device interfaces.
GUID *guidDev = (GUID*)&GUID_CLASS_COMPORT;
HDEVINFO hDevInfo = INVALID_HANDLE_VALUE;
SP_DEVICE_INTERFACE_DETAIL_DATA *pDetData = NULL;
hDevInfo = SetupDiGetClassDevs(guidDev,
NULL,
NULL,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE
);
if (INVALID_HANDLE_VALUE == hDevInfo)
{
return FALSE;
}
// Enumerate the serial ports
BOOL bOk = TRUE;
SP_DEVICE_INTERFACE_DATA ifcData;
DWORD dwDetDataSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + 256;
pDetData = (SP_DEVICE_INTERFACE_DETAIL_DATA*)new char[dwDetDataSize];
if (!pDetData)
{
return FALSE;
}
// This is required, according to the documentation. Yes,
// it's weird.
ifcData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
pDetData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
for (DWORD ii = 0; bOk; ii++)
{
bOk = SetupDiEnumDeviceInterfaces(hDevInfo,
NULL, guidDev, ii, &ifcData);
if (bOk)
{
// Got a device. Get the details.
SP_DEVINFO_DATA devdata = { sizeof(SP_DEVINFO_DATA) };
bOk = SetupDiGetDeviceInterfaceDetail(hDevInfo,
&ifcData, pDetData, dwDetDataSize, NULL, &devdata);
if (bOk) {
// Got a path to the device. Try to get some more info.
CHAR fname[256] = { 0 };
CHAR desc[256] = { 0 };
BOOL bSuccess = SetupDiGetDeviceRegistryProperty(
hDevInfo, &devdata, SPDRP_FRIENDLYNAME, NULL,
(PBYTE)fname, sizeof(fname), NULL);
bSuccess = bSuccess && SetupDiGetDeviceRegistryProperty(
hDevInfo, &devdata, SPDRP_DEVICEDESC, NULL,
(PBYTE)desc, sizeof(desc), NULL);
BOOL bUsbDevice = FALSE;
CHAR locinfo[256] = { 0 };
if (SetupDiGetDeviceRegistryProperty(
hDevInfo, &devdata, SPDRP_LOCATION_INFORMATION, NULL,
(PBYTE)locinfo, sizeof(locinfo), NULL))
{
bUsbDevice = (strncmp(locinfo, "USB", 3) == 0);
}
if (bSuccess)
{
//printf("FriendlyName = %S\r\n", fname);
//printf("Port Desc = %S\r\n", desc);
v.push_back(fname);
}
}
else
{
if (pDetData != NULL)
{
delete[](char*)pDetData;
}
if (hDevInfo != INVALID_HANDLE_VALUE)
{
SetupDiDestroyDeviceInfoList(hDevInfo);
}
return FALSE;
}
}
else
{
DWORD err = GetLastError();
if (err != ERROR_NO_MORE_ITEMS)
{
if (pDetData != NULL)
{
delete[](char*)pDetData;
}
if (hDevInfo != INVALID_HANDLE_VALUE)
{
SetupDiDestroyDeviceInfoList(hDevInfo);
}
return FALSE;
}
}
}
if (pDetData != NULL)
{
delete[](char*)pDetData;
}
if (hDevInfo != INVALID_HANDLE_VALUE)
{
SetupDiDestroyDeviceInfoList(hDevInfo);
}
return TRUE;
}
void SetComboCom(DuiLib::CComboUI * pCombo, std::vector<std::string> & vComPorts) {
pCombo->RemoveAll();
BOOL bFindReader = FALSE;
int nFindeIndex = -1;
std::vector<std::string>::iterator it;
int i = 0;
for (it = vComPorts.begin(); it != vComPorts.end(); it++, i++) {
std::string & s = *it;
CListLabelElementUI * pElement = new CListLabelElementUI;
pElement->SetText(s.c_str());
pCombo->Add(pElement);
int nComPort = 0;
const char * pFind = strstr(s.c_str(), "COM");
while (pFind) {
if (1 == sscanf(pFind + 3, "%d", &nComPort)) {
pElement->SetTag(nComPort);
break;
}
pFind = strstr(pFind + 3, "COM");
}
if (!bFindReader) {
char tmp[256];
Str2Lower(s.c_str(), tmp, sizeof(tmp));
if (0 != strstr(tmp, "usb-serial ch340")) {
bFindReader = TRUE;
nFindeIndex = i;
}
}
}
if ( pCombo->GetCount() > 0) {
if (nFindeIndex >= 0) {
pCombo->SelectItem(nFindeIndex);
}
else {
pCombo->SelectItem(0);
}
}
}
static DWORD FindMaxAreaId(const std::vector<TArea *> & v) {
DWORD dwMax = 0;
std::vector<TArea *>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it) {
TArea * pArea = *it;
if (pArea->dwAreaNo > dwMax) {
dwMax = pArea->dwAreaNo;
}
}
return dwMax + 1;
}
DWORD FindNewAreaId(const std::vector<TArea *> & v) {
DWORD dwMaxId = FindMaxAreaId(v);
if (dwMaxId <= 100) {
return dwMaxId;
}
for (DWORD i = 1; i <= 100; i++) {
std::vector<TArea *>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it) {
TArea * pArea = *it;
if (pArea->dwAreaNo == i) {
break;
}
}
// 如果没有找到相同的id,就用这个id
if (it == v.end()) {
return i;
}
}
return -1;
}
void SaveAreas() {
g_cfg_area->ClearConfig();
std::vector<TArea *>::iterator it;
int i = 0;
DuiLib::CDuiString strText;
for (it = g_vArea.begin(); it != g_vArea.end(); it++, i++) {
TArea * pArea = *it;
strText.Format("area no %d", i + 1);
g_cfg_area->SetConfig(strText, pArea->dwAreaNo);
strText.Format("area name %d", i + 1);
g_cfg_area->SetConfig(strText, pArea->szAreaName);
}
g_cfg_area->Save();
} | [
"jielmn@aliyun.com"
] | jielmn@aliyun.com |
3373a17045bddda81bc3269399975a1a58de4687 | 1151fbeca1fc58b83420de3b215da0ecc53d5fb6 | /src/include/io_tool.h | bb61b21a1442f39a8475960a10df51cc7437544e | [
"MIT"
] | permissive | junior-2016/lisp-simulator | b9b49e2352f19516c291426093044b3740664009 | e73c8819935f8d4d60cbf4ea4f4bca43c7b5db17 | refs/heads/master | 2020-05-20T23:33:22.196460 | 2019-05-29T17:29:13 | 2019-05-29T17:29:13 | 185,803,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | h | //
// Created by junior on 19-5-9.
//
#ifndef LISP_SIMULATOR_IO_H
#define LISP_SIMULATOR_IO_H
#include "lisp.h"
namespace lisp {
template<typename ... Args>
void output(FILE *file, const char *fmt, Args &&... args) noexcept {
if (file == STDERR) {
std::this_thread::sleep_for(DELAY_FOR_ERROR_OUTPUT);
std::fprintf(file, fmt, std::forward<Args>(args)...);
std::this_thread::sleep_for(DELAY_FOR_ERROR_OUTPUT);
// 因为错误输出和程序运行存在延时,所以这里将程序运行阻塞.
} else {
std::fprintf(file, fmt, std::forward<Args>(args)...);
}
}
template<typename ... Args>
void error_output(const char *fmt, Args &&... args) noexcept {
output(STDERR, fmt, args...);
}
template<typename ... Args>
void standard_output(const char *fmt, Args &&... args) noexcept {
output(STDOUT, fmt, args...);
}
}
#endif //LISP_SIMULATOR_IO_H
| [
"457030053@qq.com"
] | 457030053@qq.com |
0213a6061378a5d0bfff0b7a19957f25738da337 | c74d7751ef4f52980acb71536b66c840a31ddcda | /220d/WebKit-faust/WebKit-faust.app/Contents/Frameworks/10.6/WebCore.framework/Versions/A/PrivateHeaders/InspectorFrontend.h | e7adf1372115cd358f9b4b95a4d646068f28bbbe | [] | no_license | e7mac/Stanford | f0199a97e8cc9eb4d8e7619cc818d92bf3d8f38f | 52075da0a7a7bc893697ea213185ce6767726711 | refs/heads/master | 2020-03-20T07:34:34.277747 | 2020-01-16T01:05:12 | 2020-01-16T01:05:12 | 7,416,285 | 59 | 46 | null | null | null | null | UTF-8 | C++ | false | false | 20,612 | h | // File is generated by WebCore/WebCore/inspector/CodeGeneratorInspector.py
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef InspectorFrontend_h
#define InspectorFrontend_h
#include "InspectorTypeBuilder.h"
#include "InspectorValues.h"
#include <PlatformString.h>
#include <wtf/PassRefPtr.h>
namespace WebCore {
class InspectorFrontendChannel;
// Both InspectorObject and InspectorArray may or may not be declared at this point as defined by ENABLED_INSPECTOR.
// Double-check we have them at least as forward declaration.
class InspectorArray;
class InspectorObject;
typedef String ErrorString;
#if ENABLE(INSPECTOR)
class InspectorFrontend {
public:
InspectorFrontend(InspectorFrontendChannel*);
class Inspector {
public:
Inspector(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void evaluateForTestInFrontend(int testCallId, const String& script);
void inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> object, PassRefPtr<InspectorObject> hints);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Inspector* inspector() { return &m_inspector; }
class Memory {
public:
Memory(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Memory* memory() { return &m_memory; }
class Page {
public:
Page(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void domContentEventFired(double timestamp);
void loadEventFired(double timestamp);
void frameNavigated(PassRefPtr<TypeBuilder::Page::Frame> frame);
void frameDetached(const TypeBuilder::Network::FrameId& frameId);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Page* page() { return &m_page; }
class Runtime {
public:
Runtime(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void isolatedContextCreated(PassRefPtr<TypeBuilder::Runtime::ExecutionContextDescription> context);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Runtime* runtime() { return &m_runtime; }
class Console {
public:
Console(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void messageAdded(PassRefPtr<TypeBuilder::Console::ConsoleMessage> message);
void messageRepeatCountUpdated(int count);
void messagesCleared();
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Console* console() { return &m_console; }
class Network {
public:
Network(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void requestWillBeSent(const TypeBuilder::Network::RequestId& requestId, const TypeBuilder::Network::FrameId& frameId, const TypeBuilder::Network::LoaderId& loaderId, const String& documentURL, PassRefPtr<TypeBuilder::Network::Request> request, double timestamp, PassRefPtr<TypeBuilder::Network::Initiator> initiator, PassRefPtr<TypeBuilder::Network::Response> redirectResponse);
void requestServedFromCache(const TypeBuilder::Network::RequestId& requestId);
void responseReceived(const TypeBuilder::Network::RequestId& requestId, const TypeBuilder::Network::FrameId& frameId, const TypeBuilder::Network::LoaderId& loaderId, double timestamp, TypeBuilder::Page::ResourceType::Enum type, PassRefPtr<TypeBuilder::Network::Response> response);
void dataReceived(const TypeBuilder::Network::RequestId& requestId, double timestamp, int dataLength, int encodedDataLength);
void loadingFinished(const TypeBuilder::Network::RequestId& requestId, double timestamp);
void loadingFailed(const TypeBuilder::Network::RequestId& requestId, double timestamp, const String& errorText, const bool* const canceled);
void requestServedFromMemoryCache(const TypeBuilder::Network::RequestId& requestId, const TypeBuilder::Network::FrameId& frameId, const TypeBuilder::Network::LoaderId& loaderId, const String& documentURL, double timestamp, PassRefPtr<TypeBuilder::Network::Initiator> initiator, PassRefPtr<TypeBuilder::Network::CachedResource> resource);
void webSocketWillSendHandshakeRequest(const TypeBuilder::Network::RequestId& requestId, double timestamp, PassRefPtr<TypeBuilder::Network::WebSocketRequest> request);
void webSocketHandshakeResponseReceived(const TypeBuilder::Network::RequestId& requestId, double timestamp, PassRefPtr<TypeBuilder::Network::WebSocketResponse> response);
void webSocketCreated(const TypeBuilder::Network::RequestId& requestId, const String& url);
void webSocketClosed(const TypeBuilder::Network::RequestId& requestId, double timestamp);
void webSocketFrameReceived(const TypeBuilder::Network::RequestId& requestId, double timestamp, PassRefPtr<TypeBuilder::Network::WebSocketFrame> response);
void webSocketFrameError(const TypeBuilder::Network::RequestId& requestId, double timestamp, const String& errorMessage);
void webSocketFrameSent(const TypeBuilder::Network::RequestId& requestId, double timestamp, PassRefPtr<TypeBuilder::Network::WebSocketFrame> response);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Network* network() { return &m_network; }
#if ENABLE(SQL_DATABASE)
class Database {
public:
Database(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void addDatabase(PassRefPtr<TypeBuilder::Database::Database> database);
void sqlTransactionSucceeded(int transactionId, PassRefPtr<TypeBuilder::Array<String> > columnNames, PassRefPtr<TypeBuilder::Array<InspectorValue> > values);
void sqlTransactionFailed(int transactionId, PassRefPtr<InspectorObject> sqlError);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Database* database() { return &m_database; }
#endif // ENABLE(SQL_DATABASE)
#if ENABLE(INDEXED_DATABASE)
class IndexedDB {
public:
IndexedDB(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void databaseNamesLoaded(double requestId, PassRefPtr<TypeBuilder::IndexedDB::SecurityOriginWithDatabaseNames> securityOriginWithDatabaseNames);
void databaseLoaded(int requestId, PassRefPtr<TypeBuilder::IndexedDB::DatabaseWithObjectStores> databaseWithObjectStores);
void objectStoreDataLoaded(int requestId, PassRefPtr<TypeBuilder::Array<TypeBuilder::IndexedDB::DataEntry> > objectStoreDataEntries, bool hasMore);
void indexDataLoaded(int requestId, PassRefPtr<TypeBuilder::Array<TypeBuilder::IndexedDB::DataEntry> > indexDataEntries, bool hasMore);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
IndexedDB* indexeddb() { return &m_indexeddb; }
#endif // ENABLE(INDEXED_DATABASE)
class DOMStorage {
public:
DOMStorage(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void addDOMStorage(PassRefPtr<TypeBuilder::DOMStorage::Entry> storage);
void domStorageUpdated(const TypeBuilder::DOMStorage::StorageId& storageId);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
DOMStorage* domstorage() { return &m_domstorage; }
class ApplicationCache {
public:
ApplicationCache(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void applicationCacheStatusUpdated(const TypeBuilder::Network::FrameId& frameId, const String& manifestURL, int status);
void networkStateUpdated(bool isNowOnline);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
ApplicationCache* applicationcache() { return &m_applicationcache; }
#if ENABLE(FILE_SYSTEM)
class FileSystem {
public:
FileSystem(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void fileSystemRootReceived(int requestId, int errorCode, PassRefPtr<TypeBuilder::FileSystem::Entry> root);
void directoryContentReceived(int requestId, int errorCode, PassRefPtr<TypeBuilder::Array<TypeBuilder::FileSystem::Entry> > entries);
void metadataReceived(int requestId, int errorCode, PassRefPtr<TypeBuilder::FileSystem::Metadata> metadata);
void fileContentReceived(int requestId, int errorCode, const String* const content, const String* const charset);
void deletionCompleted(int requestId, int errorCode);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
FileSystem* filesystem() { return &m_filesystem; }
#endif // ENABLE(FILE_SYSTEM)
class DOM {
public:
DOM(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void documentUpdated();
void setChildNodes(int parentId, PassRefPtr<TypeBuilder::Array<TypeBuilder::DOM::Node> > nodes);
void attributeModified(int nodeId, const String& name, const String& value);
void attributeRemoved(int nodeId, const String& name);
void inlineStyleInvalidated(PassRefPtr<TypeBuilder::Array<int> > nodeIds);
void characterDataModified(int nodeId, const String& characterData);
void childNodeCountUpdated(int nodeId, int childNodeCount);
void childNodeInserted(int parentNodeId, int previousNodeId, PassRefPtr<TypeBuilder::DOM::Node> node);
void childNodeRemoved(int parentNodeId, int nodeId);
void shadowRootPushed(int hostId, PassRefPtr<TypeBuilder::DOM::Node> root);
void shadowRootPopped(int hostId, int rootId);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
DOM* dom() { return &m_dom; }
class CSS {
public:
CSS(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void mediaQueryResultChanged();
void styleSheetChanged(const TypeBuilder::CSS::StyleSheetId& styleSheetId);
void namedFlowCreated(int documentNodeId, const String& namedFlow);
void namedFlowRemoved(int documentNodeId, const String& namedFlow);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
CSS* css() { return &m_css; }
class Timeline {
public:
Timeline(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void eventRecorded(PassRefPtr<TypeBuilder::Timeline::TimelineEvent> record);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Timeline* timeline() { return &m_timeline; }
#if ENABLE(JAVASCRIPT_DEBUGGER)
class Debugger {
public:
Debugger(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void globalObjectCleared();
void scriptParsed(const TypeBuilder::Debugger::ScriptId& scriptId, const String& url, int startLine, int startColumn, int endLine, int endColumn, const bool* const isContentScript, const String* const sourceMapURL);
void scriptFailedToParse(const String& url, const String& scriptSource, int startLine, int errorLine, const String& errorMessage);
void breakpointResolved(const TypeBuilder::Debugger::BreakpointId& breakpointId, PassRefPtr<TypeBuilder::Debugger::Location> location);
// Named after parameter 'reason' while generating command/event paused.
struct Reason {
enum Enum {
XHR = 5,
DOM = 68,
EventListener = 69,
Exception = 70,
Other = 25,
};
}; // struct Reason
void paused(PassRefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> > callFrames, Reason::Enum reason, PassRefPtr<InspectorObject> data);
void resumed();
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Debugger* debugger() { return &m_debugger; }
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
#if ENABLE(JAVASCRIPT_DEBUGGER)
class DOMDebugger {
public:
DOMDebugger(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
DOMDebugger* domdebugger() { return &m_domdebugger; }
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
#if ENABLE(JAVASCRIPT_DEBUGGER)
class Profiler {
public:
Profiler(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void addProfileHeader(PassRefPtr<TypeBuilder::Profiler::ProfileHeader> header);
void addHeapSnapshotChunk(int uid, const String& chunk);
void finishHeapSnapshot(int uid);
void setRecordingProfile(bool isProfiling);
void resetProfiles();
void reportHeapSnapshotProgress(int done, int total);
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Profiler* profiler() { return &m_profiler; }
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
#if ENABLE(WORKERS)
class Worker {
public:
Worker(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void workerCreated(int workerId, const String& url, bool inspectorConnected);
void workerTerminated(int workerId);
void dispatchMessageFromWorker(int workerId, PassRefPtr<InspectorObject> message);
void disconnectedFromWorker();
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
Worker* worker() { return &m_worker; }
#endif // ENABLE(WORKERS)
#if ENABLE(WEBGL)
class WebGL {
public:
WebGL(InspectorFrontendChannel* inspectorFrontendChannel) : m_inspectorFrontendChannel(inspectorFrontendChannel) { }
void setInspectorFrontendChannel(InspectorFrontendChannel* inspectorFrontendChannel) { m_inspectorFrontendChannel = inspectorFrontendChannel; }
InspectorFrontendChannel* getInspectorFrontendChannel() { return m_inspectorFrontendChannel; }
private:
InspectorFrontendChannel* m_inspectorFrontendChannel;
};
WebGL* webgl() { return &m_webgl; }
#endif // ENABLE(WEBGL)
private:
Inspector m_inspector;
Memory m_memory;
Page m_page;
Runtime m_runtime;
Console m_console;
Network m_network;
#if ENABLE(SQL_DATABASE)
Database m_database;
#endif // ENABLE(SQL_DATABASE)
#if ENABLE(INDEXED_DATABASE)
IndexedDB m_indexeddb;
#endif // ENABLE(INDEXED_DATABASE)
DOMStorage m_domstorage;
ApplicationCache m_applicationcache;
#if ENABLE(FILE_SYSTEM)
FileSystem m_filesystem;
#endif // ENABLE(FILE_SYSTEM)
DOM m_dom;
CSS m_css;
Timeline m_timeline;
#if ENABLE(JAVASCRIPT_DEBUGGER)
Debugger m_debugger;
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
#if ENABLE(JAVASCRIPT_DEBUGGER)
DOMDebugger m_domdebugger;
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
#if ENABLE(JAVASCRIPT_DEBUGGER)
Profiler m_profiler;
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
#if ENABLE(WORKERS)
Worker m_worker;
#endif // ENABLE(WORKERS)
#if ENABLE(WEBGL)
WebGL m_webgl;
#endif // ENABLE(WEBGL)
};
#endif // ENABLE(INSPECTOR)
} // namespace WebCore
#endif // !defined(InspectorFrontend_h)
| [
"mayank.sanganeria@leanplum.com"
] | mayank.sanganeria@leanplum.com |
5e2cfe35e55d85d8cfebd2b4fa57f9c3a6aca03c | d2bb8b920f5d1d23f3db2d1256d1fd6213940014 | /engine/Engine.Core/src/core/window/WindowMessage.h | babcf00d4bbedba292f49af1a7845ddd2846f77c | [
"MIT"
] | permissive | ZieIony/Ghurund | 726672d56838d18b6dd675f304feee1d95a296bd | 0ce83cabd91f7ac71286dcd8e12d486bed2d75cf | refs/heads/master | 2023-08-17T08:14:19.548027 | 2022-02-12T16:33:32 | 2022-02-12T16:34:54 | 124,959,579 | 91 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 195 | h | #pragma once
#include <Windows.h>
namespace Ghurund::Core {
struct WindowMessage {
unsigned int code;
WPARAM wParam;
uint64_t time;
POINT mousePos;
};
}
| [
"niewartotupisac@gmail.com"
] | niewartotupisac@gmail.com |
b5c323b1e08f1070bdf77aef0bb082e37e951450 | 7db0da6d1182fe5514005f37a5bfd311f9c2467e | /July CookOff 2020/ORTHODOX.cpp | 7d285707da20bf929d73ce650d3d28be1fc4857e | [] | no_license | iamarjun45/codechef | bf8b8a6f1fb153d42858365f08f00e695f22a79c | 549b3810b12efc035c4a0dacaabacf745fdacd46 | refs/heads/master | 2023-01-01T08:42:45.709179 | 2020-10-26T18:22:07 | 2020-10-26T18:22:07 | 290,109,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | cpp | #include<bits/stdc++.h>
#define MOD 1000000007
#define int long long
using namespace std;
//#include <ext/pb_ds/assoc_container.hpp>
//using namespace __gnu_pbds;
//typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
int n;
vector<int> A;
void gogo() {
unordered_set<int> s;
set<int> t;
for (int i : A) {
set<int> r;
r.insert(i);
for (int j : t) r.insert(i | j);
t = r;
for (int j : t) s.insert(j);
}
if(s.size()==(n*(n+1)/2)){
cout<<"YES\n";
}else{
cout<<"NO\n";
}
}
void solve(){
cin>>n;
A=vector<int>(n);
for(int i=0;i<n;i++){
cin>>A[i];
}
gogo();
}
int32_t main(){
ios::sync_with_stdio(0);
cin.tie(0);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
int t;
cin>>t;
while(t--){
solve();
}
return 0;
}
| [
"noreply@github.com"
] | iamarjun45.noreply@github.com |
8a78873d06ebc6b85e857d220fd741a0fadde1a1 | 00844495757e7f6b05c8abf46eb131e4eee16ca9 | /PrintPDF/excel/CFont0.h | 0c4b30cab650bb75c8ce3f12c96be95b2464ab32 | [] | no_license | byaizz/PrintfPDF | f63048c407574ab18765498736536f41434a6a7f | 6b6af575f4f5bb28fe433190c43b77091b531d52 | refs/heads/master | 2020-07-03T23:58:45.462063 | 2019-06-03T03:00:55 | 2019-06-03T03:01:17 | 202,092,465 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,120 | h | #pragma once
// 从类型库向导中用“添加类”创建的计算机生成的 IDispatch 包装器类
//#import "C:\\Program Files\\Microsoft Office\\Office15\\EXCEL.EXE" no_namespace
// CFont0 包装器类
class CFont0 : public COleDispatchDriver
{
public:
CFont0() {} // 调用 COleDispatchDriver 默认构造函数
CFont0(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
CFont0(const CFont0& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// 特性
public:
// 操作
public:
// Font 方法
public:
LPDISPATCH get_Application()
{
LPDISPATCH result;
InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL);
return result;
}
long get_Creator()
{
long result;
InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
LPDISPATCH get_Parent()
{
LPDISPATCH result;
InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL);
return result;
}
VARIANT get_Background()
{
VARIANT result;
InvokeHelper(0xb4, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Background(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0xb4, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_Bold()
{
VARIANT result;
InvokeHelper(0x60, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Bold(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x60, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_Color()
{
VARIANT result;
InvokeHelper(0x63, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Color(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x63, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_ColorIndex()
{
VARIANT result;
InvokeHelper(0x61, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_ColorIndex(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x61, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_FontStyle()
{
VARIANT result;
InvokeHelper(0xb1, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_FontStyle(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0xb1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_Italic()
{
VARIANT result;
InvokeHelper(0x65, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Italic(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x65, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_Name()
{
VARIANT result;
InvokeHelper(0x6e, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Name(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x6e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_OutlineFont()
{
VARIANT result;
InvokeHelper(0xdd, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_OutlineFont(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0xdd, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_Shadow()
{
VARIANT result;
InvokeHelper(0x67, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Shadow(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x67, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_Size()
{
VARIANT result;
InvokeHelper(0x68, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Size(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x68, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_Strikethrough()
{
VARIANT result;
InvokeHelper(0x69, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Strikethrough(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x69, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_Subscript()
{
VARIANT result;
InvokeHelper(0xb3, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Subscript(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0xb3, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_Superscript()
{
VARIANT result;
InvokeHelper(0xb2, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Superscript(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0xb2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_Underline()
{
VARIANT result;
InvokeHelper(0x6a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_Underline(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x6a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_ThemeColor()
{
VARIANT result;
InvokeHelper(0x93d, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_ThemeColor(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x93d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
VARIANT get_TintAndShade()
{
VARIANT result;
InvokeHelper(0x93e, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL);
return result;
}
void put_TintAndShade(VARIANT& newValue)
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x93e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue);
}
long get_ThemeFont()
{
long result;
InvokeHelper(0x93f, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void put_ThemeFont(long newValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x93f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue);
}
// Font 属性
public:
};
| [
"410389821@qq.com"
] | 410389821@qq.com |
2357aee8715e195cdfffdf0ad1ffd3104fb1555b | 6f1a8bae3b7916b94bf0409288a3a80692d8e4d3 | /Arduino/CS362/rgenov2Lab5/rgenov2Lab5.ino | 4703b1d4c124e676ac7c4b271c3bacd67140eaa3 | [] | no_license | Rg3n0v4/schoolProjects | 8acf490abf9a5c0ecc840b41c4b55747765d81e8 | c959b7e31d8dd5b7ea8138dd66447e42907de85d | refs/heads/master | 2023-02-15T03:10:50.156762 | 2021-01-11T18:29:47 | 2021-01-11T18:29:47 | 286,540,842 | 0 | 0 | null | 2020-08-19T15:16:32 | 2020-08-10T17:40:13 | null | UTF-8 | C++ | false | false | 2,349 | ino | // Raphael Genova - 667495961
// Lab 5 - Multiple Inputs and Outputs
// Description - be able to have my Arduino have two unconnected things at te same time, using multiple inputs
// and outputs. Also be able to read and write analog inputs and outputs
// Assumption - being able to adjust the volume on a tuner and checking the lighting in the room
// References - looked up on the Internet and came across the Ardunio discussion boards about it,
// Arduino Reference sheet on
int value; //for storing the value of the photoresistor
int sensorVal; //for storing the value of the potentiometer
int volume; //for the volume of the buzzer
//for storing the values of the LEDs
int led1 = LOW;
int led2 = LOW;
int led3 = LOW;
int led4 = LOW;
void setup() {
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(11, OUTPUT);
pinMode(A1, INPUT);
pinMode(A2, INPUT);
//Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
value = analogRead(A2); //for reading the photoresistor value
sensorVal = analogRead(A1); //for reading the potentiometer
//Serial.println(sensorVal);
volume = map(sensorVal, 0, 1023, 100, 2000);
tone(11, volume); //analog output on a digital pin
//delay(1);
if(value <= 370) //for if the photoresistor is reading it's dark
{
led1 = HIGH;
led2 = HIGH;
led3 = HIGH;
led4 = HIGH;
}
else if(value > 370 && value <= 500)//for if the photoresistor is reading it's partially dark
{
led1 = LOW;
led2 = HIGH;
led3 = HIGH;
led4 = HIGH;
}
else if(value > 500 && value <= 700)//for if the photoresistor is reading it's half-dark and half-lit
{
led1 = LOW;
led2 = LOW;
led3 = HIGH;
led4 = HIGH;
}
else if(value > 700 && value <= 831)//for if the photoresistor is reading it's partially lit
{
led1 = LOW;
led2 = LOW;
led3 = LOW;
led4 = HIGH;
}
else //for if the photoresistor is reading it's fully lit
{
led1 = LOW;
led2 = LOW;
led3 = LOW;
led4 = LOW;
}
//updates the LEDs accordingly
digitalWrite(2, led1);
digitalWrite(3, led2);
digitalWrite(4, led3);
digitalWrite(5, led4);
}
| [
"rgenov2@uic.edu"
] | rgenov2@uic.edu |
2e96f77de6451921145cbc477dfec6844aa26c8b | c29752627f2ea11d293823bfdf8d3a6bd6f39c06 | /C Memory Management/C Memory Management.cpp | 8507eb933be7d6e33e8e272d25b6c1095492a669 | [] | no_license | lukaszbednarz/C_Memory_Management | 86fa3545911853c6e11a5dbcc493c0bfd07d4759 | 8082ddf4f4bf4946c7c84a22ca680c0664750480 | refs/heads/master | 2021-01-10T07:38:48.895808 | 2016-03-08T17:18:56 | 2016-03-08T17:18:56 | 53,431,054 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 161 | cpp | // C Memory Management.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| [
"lbednarz@qti.qualcomm.com"
] | lbednarz@qti.qualcomm.com |
e4676d80775a10853be8a9f27fd7cd2cebdb1476 | 69a0fc15ed9311fb4455b6ba09f205f0ac14ea2c | /modify.cpp | 7c4aa824eaa1aa96f7a0db329c8dfcf9e23b1b02 | [] | no_license | obourat/MaquetteMimosa | fda98733d2cfc6d2ee29741a9cda046940f5664f | 1034d847145add8f18e1711e2bc52c3c01665f73 | refs/heads/master | 2020-12-03T20:56:06.318974 | 2016-08-22T13:04:40 | 2016-08-22T13:04:40 | 66,273,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,651 | cpp | #include "modify.h"
#include "ui_modify.h"
#include "alllisting.h"
using namespace std;
Modify::Modify(AllListing *allListing,QWidget *parent) :
QDialog(parent),
ui(new Ui::Modify),
allListing(allListing)
{
ui->setupUi(this);
QString updateNom, updateEdition, updateSocPri;
updateNom = allListing->getDefaultNom();
updateEdition = allListing->getDefaultEdition();
updateSocPri = allListing->getDefaultSocPri();
ui->updateNom->setText(updateNom); //On rentre dans les input les valeurs connues des attributs
ui->updateEdition->setText(updateEdition);
ui->updateSocPri->setText(updateSocPri);
//this->allListing = allListing;
//ui->updateNom->text() = allListing.getDefaultNom();
}
Modify::~Modify()
{
delete ui;
}
void Modify::on_updateButtonBox_rejected() //Si on clique sur annuler
{
close();
}
void Modify::on_updateButtonBox_accepted() //Si on clique sur accepter
{
if(ui->updateNom->text() == allListing->getDefaultNom() && ui->updateEdition->text() == allListing->getDefaultEdition() && ui->updateSocPri->text() == allListing->getDefaultSocPri())
{
QMessageBox::information(this, "Information", "Aucun attribut n'a ete change, le document n'a pas ete modifie");
}
else if (ui->updateNom->text() == "")
{
QMessageBox::warning(this, "Erreur", "Veuillez donner un nom au document");
}
else
{
QDomDocument dom("GDOcopy2generated"); //Creation d'un QDomDocument à partir du fichier xml
QFile file("GDOcopy2.xml");
//QDomElement root = dom.documentElement();
//qDebug() << root.text();
//QString write_doc = dom.toString(); //Stockage du fichier mis à jour
if(!file.open(QIODevice::ReadOnly))
{
QMessageBox::critical(this, "Erreur", "Impossible d'ouvrir le fichier XML");
file.close();
return;
}
if(!dom.setContent(&file)) {
QMessageBox::critical(this, "erreur", "Impossible d'ouvrir le fichier XML");
file.close();
return;
}
file.close();
QDomNode docElem = dom.documentElement().firstChild(); //ListDoc -> Doc
while(!docElem.isNull())
{
QDomNode n = docElem.firstChild(); //Doc ->Num...
while (n.nodeName() != "id_CONST") //Tant que la balise est differente de id_const (bug XML mal formé)
{
QDomElement e = n.toElement(); //on stocke les valeurs de chaque balise
if(allListing->getDefaultNom() == e.text()) //Si on se trouve dans le bon doc :
{
if(ui->updateNom->text() != allListing->getDefaultNom()) //Si le nom a ete change :
{
QDomNode p = docElem.firstChild();
while ( p.nodeName() != "Titre")
{
p = p.nextSibling();
}
e = p.toElement();
QDomElement newTitre = dom.createElement("Titre");
newTitre.appendChild(dom.createTextNode(ui->updateNom->text()));
e.parentNode().replaceChild(newTitre,e);
}
if(ui->updateEdition->text() != allListing->getDefaultEdition()) //Si l'edition a ete change :
{
QDomNode q = docElem.firstChild();
while ( q.nodeName() != "Edition")
{
q = q.nextSibling();
}
e = q.toElement();
QDomElement newEdition = dom.createElement("Edition");
newEdition.appendChild((dom.createTextNode(ui->updateEdition->text())));
e.parentNode().replaceChild(newEdition,e);
}
if(ui->updateSocPri->text() != allListing->getDefaultSocPri()) //Si le SocPri a ete change :
{
QDomNode r = docElem.firstChild();
while ( r.nodeName() != "SocPri")
{
r = r.nextSibling();
}
e = r.toElement();
QDomElement newSocPri = dom.createElement("SocPri");
newSocPri.appendChild((dom.createTextNode(ui->updateSocPri->text())));
e.parentNode().replaceChild(newSocPri,e);
}
break; //On sors de la boucle si le bon doc a ete trouvé et traité
}
n = n.nextSibling(); //On passe à la prochaine balise d'un doc
}
docElem = docElem.nextSibling(); //On passe au prochain doc
}
file.open(QIODevice::WriteOnly);
file.write(dom.toByteArray());
file.close();
allListing->parser();
//QTextStream out(&file);
//out << dom.toString(); //ecriture du document
//file.close(); //fermeture du document
}
}
// while(!n.isNull())
// {
// QDomElement e=n.toElement();
// if(!e.isNull())
// {
// }
// }
//if(ui->updateNom->text() != allListing->getDefaultNom())
// }
//}
| [
"noreply@github.com"
] | obourat.noreply@github.com |
00fefab77d76f8fc926f6192c488a63dba76f85d | 6a2d1800e25e3624b315c21f9598b4442c8d80b6 | /sdk/core/azure-core/inc/azure/core/internal/log.hpp | 28a99bf1669ef296313f54d0dd9d9b26671911cb | [
"MIT",
"BSD-3-Clause",
"curl",
"LGPL-2.1-or-later",
"LicenseRef-scancode-generic-cla"
] | permissive | katmsft/azure-sdk-for-cpp | e3f76ebe9c1a176050f64b9fb0658031b95ec02b | d99f3ab8e62fff5c65c49aea91aba3c2a422a7d1 | refs/heads/master | 2021-09-11T14:52:51.875720 | 2021-01-28T09:21:59 | 2021-01-28T09:21:59 | 248,464,376 | 0 | 0 | MIT | 2020-08-27T05:37:44 | 2020-03-19T09:41:59 | C++ | UTF-8 | C++ | false | false | 418 | hpp | // Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#pragma once
#include "azure/core/logging/logging.hpp"
namespace Azure { namespace Core { namespace Logging { namespace Details {
bool ShouldWrite(LogClassification const& classification);
void Write(LogClassification const& classification, std::string const& message);
}}}} // namespace Azure::Core::Logging::Details
| [
"noreply@github.com"
] | katmsft.noreply@github.com |
b2ed0c60dd866038a13d6c37aaefcf71ec34915b | f043ac0aa15a28e9c9af1ab9f0b9a0dec02057a8 | /HugeCTR/include/data_readers/parquet_data_reader_worker.hpp | 40a16d0a00a7b9c5dfde62d602b00bb2bc7ee3e6 | [
"Apache-2.0"
] | permissive | dendisuhubdy/HugeCTR | 9fe1f1bedd13df6f64115c45a3282549c5c824c6 | 849be3fde24f91d2f0b389830a0d427617fd40b4 | refs/heads/master | 2022-12-29T08:44:09.244236 | 2020-10-05T12:10:38 | 2020-10-05T12:10:38 | 301,602,662 | 0 | 0 | Apache-2.0 | 2020-10-06T03:24:53 | 2020-10-06T03:23:14 | null | UTF-8 | C++ | false | false | 23,256 | hpp | /*
* Copyright (c) 2020, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "HugeCTR/include/common.hpp"
#include "HugeCTR/include/data_readers/data_reader_worker_interface.hpp"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wreorder"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#include <cudf/column/column.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/concatenate.hpp>
#include <cudf/io/functions.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <rmm/device_buffer.hpp>
#include <rmm/mr/device/cnmem_memory_resource.hpp>
#include <rmm/mr/device/cuda_memory_resource.hpp>
#include <rmm/mr/device/device_memory_resource.hpp>
#include <rmm/mr/device/pool_memory_resource.hpp>
#include <rmm/mr/device/thread_safe_resource_adaptor.hpp>
#include "data_readers/file_source_parquet.hpp"
#pragma GCC diagnostic pop
#pragma GCC diagnostic pop
#pragma GCC diagnostic pop
#include "data_readers/file_list.hpp"
#include "data_readers/metadata.hpp"
#include "data_readers/parquet_data_converter.hpp"
namespace HugeCTR {
template <class T>
class ParquetDataReaderWorker : public IDataReaderWorker {
private:
const unsigned int worker_id_{0};
const unsigned int worker_num_{0};
size_t buffer_length_; /**< buffer size for internal use */
std::shared_ptr<HeapEx<CSRChunk<T>>> csr_heap_; /**< heap to cache the data set */
std::vector<DataReaderSparseParam> params_; /**< configuration of data reader sparse input */
std::shared_ptr<ParquetFileSource> source_; /**< source: can be file or network */
bool skip_read_{false}; /**< set to true when you want to stop the data reading */
const int MAX_TRY = 10;
long long records_in_file_;
long long current_record_index_{0};
int slots_{0};
const std::vector<long long> slot_offset_;
std::vector<T> slot_offset_dtype_;
std::shared_ptr<rmm::mr::device_memory_resource>
memory_resource_; /**< RMM device memory resource object */
int device_id_{0}; /**< GPU id for execution */
cudaStream_t task_stream_; /**< Stream for Parquet to csr work */
cudaStream_t dense_stream_; /**< Stream for Parquet to dense work */
std::map<int, int> dense_idx_to_parquet_col_; /**< dense feature to parquet column idx */
std::map<int, int> categorical_idx_parquet_col_; /**< cat(slot) to parquet column idx */
std::shared_ptr<rmm::device_buffer> slot_offset_device_buf_; /**< GPU buffer w/ slot offset*/
bool thread_resource_allocated_{false}; /**< Flag to set/allocate worker thread resources */
std::unique_ptr<cudf::table> cached_df_; /**< Cached row_group from Parquet */
Tensor2<int64_t> host_memory_pointer_staging_;
/**< Pinned memory for async column dev ptr copy */
Tensor2<uint32_t> host_pinned_csr_inc_; /**< Pinned memory to copy csr push_back values */
long long row_group_size_;
long long row_group_index_;
long long row_group_carry_forward_;
long long view_offset_;
void read_new_file() {
for (int i = 0; i < MAX_TRY; i++) {
Error_t err = source_->next_source();
if (err == Error_t::Success) {
auto metadata = source_->get_file_metadata();
if (metadata.get_metadata_status()) {
auto label_col_names = metadata.get_label_names();
auto dense_col_names = metadata.get_cont_names();
if (dense_idx_to_parquet_col_.size() !=
(label_col_names.size() + dense_col_names.size())) {
dense_idx_to_parquet_col_.clear();
int i = 0;
for (auto& c : label_col_names) {
dense_idx_to_parquet_col_.insert(std::make_pair(i, c.index));
i++;
}
for (auto& c : dense_col_names) {
dense_idx_to_parquet_col_.insert(std::make_pair(i, c.index));
i++;
}
}
auto cat_col_names = metadata.get_cat_names();
if (categorical_idx_parquet_col_.size() != cat_col_names.size()) {
categorical_idx_parquet_col_.clear();
int i = 0;
for (auto& c : cat_col_names) {
categorical_idx_parquet_col_.insert(std::make_pair(i, c.index));
i++;
}
}
records_in_file_ = source_->get_num_rows();
current_record_index_ = 0;
} else {
// raise exception
CK_THROW_(Error_t::BrokenFile, "failed to read a file");
}
return;
}
}
CK_THROW_(Error_t::BrokenFile, "failed to read a file");
}
public:
/**
* Ctor
*/
ParquetDataReaderWorker(unsigned int worker_id, unsigned int worker_num,
const std::shared_ptr<HeapEx<CSRChunk<T>>>& csr_heap,
const std::string& file_list, size_t buffer_length,
const std::vector<DataReaderSparseParam>& params,
const std::vector<long long>& slot_offset,
const std::shared_ptr<rmm::mr::device_memory_resource>& mr)
: worker_id_(worker_id),
worker_num_(worker_num),
buffer_length_(buffer_length),
csr_heap_(csr_heap),
params_(params),
slot_offset_(slot_offset),
memory_resource_(mr),
row_group_carry_forward_(0) {
std::shared_ptr<GeneralBuffer2<CudaHostAllocator>> buff =
GeneralBuffer2<CudaHostAllocator>::create();
buff->reserve({1024}, &host_memory_pointer_staging_);
buff->reserve({32}, &host_pinned_csr_inc_);
buff->allocate();
device_id_ = worker_id_;
if (worker_id >= worker_num) {
CK_THROW_(Error_t::BrokenFile, "ParquetDataReaderWorker: worker_id >= worker_num");
}
slots_ = 0;
for (auto& p : params) {
slots_ += p.slot_num;
}
source_ = std::make_shared<ParquetFileSource>(worker_id, worker_num, file_list);
assert((int)slot_offset_.size() == slots_);
for (auto& c : slot_offset_) {
if ((c >= std::numeric_limits<T>::min()) && (c <= std::numeric_limits<T>::max()))
slot_offset_dtype_.push_back((T)c);
else
CK_THROW_(Error_t::DataCheckError, "Slot offset value exceed the key type range");
}
}
~ParquetDataReaderWorker() {
// dont have a good place to destroy resource - before worker threads exits
if (thread_resource_allocated_) {
CudaDeviceContext context(device_id_);
cudaStreamSynchronize(task_stream_);
cudaStreamSynchronize(dense_stream_);
cached_df_.reset();
slot_offset_device_buf_.reset();
source_.reset();
cudaStreamDestroy(task_stream_);
cudaStreamDestroy(dense_stream_);
}
}
/**
* read a batch of data from data set to heap.
*/
void read_a_batch();
/**
* skip data reading in read_a_batch()
*/
void skip_read() { skip_read_ = true; }
};
template <class T>
void ParquetDataReaderWorker<T>::read_a_batch() {
// get csr chunk
// staging on cpu csr_chunk heap in first prototype
// will shift to gpu tensors in next iteration - need collector changes
// and possible gpu location/memory issues??
using dtype_dense = float;
if (!thread_resource_allocated_) {
// cant allocate and set resources in constructor
CK_CUDA_THROW_(cudaSetDevice(device_id_)); // for multiple devices
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
rmm::mr::set_default_resource(memory_resource_.get());
#pragma GCC diagnostic pop
CK_CUDA_THROW_(cudaStreamCreateWithFlags(&task_stream_, cudaStreamNonBlocking));
CK_CUDA_THROW_(cudaStreamCreateWithFlags(&dense_stream_, cudaStreamNonBlocking));
size_t slot_offset_buf_size = sizeof(T) * slot_offset_dtype_.size();
slot_offset_device_buf_ = std::make_shared<rmm::device_buffer>(
slot_offset_buf_size, task_stream_, memory_resource_.get());
CK_CUDA_THROW_(cudaMemcpyAsync(slot_offset_device_buf_->data(), slot_offset_dtype_.data(),
slot_offset_buf_size, cudaMemcpyHostToDevice, task_stream_));
thread_resource_allocated_ = true;
}
try {
if (!source_->is_open()) {
read_new_file();
}
CSRChunk<T>* csr_chunk = nullptr;
csr_heap_->free_chunk_checkout(&csr_chunk, worker_id_);
if (!skip_read_) {
csr_chunk->set_current_batchsize(csr_chunk->get_batchsize());
int batch_size = csr_chunk->get_batchsize();
long long elements_to_read = batch_size;
std::vector<cudf::table_view> table_view_for_concat;
// have enough row inc row_group_index_ else slice and concat to next DF
while (elements_to_read > 0) {
if (!cached_df_ || (row_group_size_ == row_group_index_)) {
auto tbl_w_metadata = source_->read(-1, memory_resource_.get());
if (row_group_carry_forward_ > 0 && table_view_for_concat.size() > 0) {
std::vector<cudf::table_view> table_views_for_concat{table_view_for_concat[0],
tbl_w_metadata.tbl->view()};
// swap here will automatically release previous cached DF
(cudf::concatenate(table_views_for_concat, memory_resource_.get())).swap(cached_df_);
row_group_size_ = cached_df_->num_rows();
row_group_carry_forward_ = 0;
table_view_for_concat.clear();
} else {
cached_df_.reset();
tbl_w_metadata.tbl.swap(cached_df_);
row_group_size_ = cached_df_->num_rows();
}
row_group_index_ = 0;
view_offset_ = 0;
}
if ((row_group_size_ - row_group_index_) >= elements_to_read) {
row_group_index_ += elements_to_read;
current_record_index_ += elements_to_read;
elements_to_read = 0;
} else if (row_group_index_ < row_group_size_) {
long long avail_rows = (row_group_size_ - row_group_index_);
if (avail_rows < row_group_size_) {
// slice and add to concat queue
std::vector<cudf::size_type> slice_indices{
(cudf::size_type)row_group_index_,
(cudf::size_type)(row_group_index_ + avail_rows)};
table_view_for_concat = cudf::slice(cached_df_->view(), slice_indices);
} else {
table_view_for_concat.emplace_back(std::move(cached_df_->view()));
}
row_group_index_ += avail_rows;
current_record_index_ += avail_rows;
// elements_to_read -= avail_rows; //
row_group_carry_forward_ = avail_rows;
}
// read_next_file if needed
if (current_record_index_ >= records_in_file_) {
read_new_file(); // set current_record_index_ to zero
if (row_group_carry_forward_ > 0)
records_in_file_ += row_group_carry_forward_;
else if ((row_group_size_ - row_group_index_) > 0)
records_in_file_ += (row_group_size_ - row_group_index_);
}
}
cudf::table_view data_view = cached_df_->view();
Tensors2<float>& label_dense_buffers = csr_chunk->get_label_buffers(); // get_num_elements
const int label_dense_dim = csr_chunk->get_label_dense_dim();
int num_dense_buffers = label_dense_buffers.size();
int64_t num_of_pointer_staging =
2 * (csr_chunk->get_label_dense_dim() + num_dense_buffers) +
3 * (int)csr_chunk->get_csr_buffers().size() * params_.size() + slots_ +
+csr_chunk->get_num_devices();
// PinnedBuffer extend on unique_ptr cant realloc properly and safely (cudaContext)
if ((int64_t)host_memory_pointer_staging_.get_num_elements() < num_of_pointer_staging)
CK_THROW_(Error_t::UnspecificError, "Parquet reader worker: not enough pinned storge");
// calculate rows for each buffer
size_t device_staging_dense_size = ((batch_size - 1) / num_dense_buffers + 1);
device_staging_dense_size *= ((size_t)label_dense_dim * sizeof(dtype_dense));
std::vector<rmm::device_buffer> dense_data_buffers(num_dense_buffers);
for (int k = 0; k < num_dense_buffers; k++) {
dense_data_buffers[k] =
rmm::device_buffer(device_staging_dense_size, dense_stream_, memory_resource_.get());
}
std::vector<cudf::column_view> dense_columns_view_ref;
for (int k = 0; k < label_dense_dim; k++) {
dense_columns_view_ref.emplace_back(
std::move(data_view.column(dense_idx_to_parquet_col_[k])));
if (dense_columns_view_ref.back().type().id() != cudf::type_to_id<dtype_dense>()) {
CK_THROW_(Error_t::WrongInput,
"Parquet reader: Dense KeyType and Parquet column type don't match");
}
}
std::vector<dtype_dense*> dense_column_data_ptr;
for (int k = 0; k < label_dense_dim; k++) {
dtype_dense* column_ptr =
const_cast<dtype_dense*>(dense_columns_view_ref[k].data<dtype_dense>());
column_ptr =
reinterpret_cast<dtype_dense*>((size_t)column_ptr + sizeof(dtype_dense) * view_offset_);
dense_column_data_ptr.push_back(column_ptr);
}
std::deque<rmm::device_buffer> rmm_resources;
// kernel from dense_column_data_ptr to device_staging_dense_size with data transpose
convert_parquet_dense_columns(dense_column_data_ptr, label_dense_dim, batch_size,
num_dense_buffers, dense_data_buffers,
host_memory_pointer_staging_.get_ptr(), rmm_resources,
memory_resource_.get(), dense_stream_);
for (int k = 0; k < num_dense_buffers; k++) {
Tensor2<float>& buf = label_dense_buffers[k];
size_t copy_size = buf.get_num_elements() * sizeof(dtype_dense);
CK_CUDA_THROW_(cudaMemcpyAsync(buf.get_ptr(), dense_data_buffers[k].data(), copy_size,
cudaMemcpyDeviceToHost, dense_stream_));
}
// device/buffer wise distribution is important
// label device buffer - as many as csr buffers
// transpose on gpu kernel
// memcpy to csr label_dense_buffers
csr_chunk->apply_to_csr_buffers(&CSR<T>::reset);
csr_chunk->apply_to_csr_buffers(&CSR<T>::set_check_point);
auto& csr_buffers = csr_chunk->get_csr_buffers();
int num_csr_buffers = csr_buffers.size();
std::vector<rmm::device_buffer> device_csr_value_buffers(num_csr_buffers);
std::vector<rmm::device_buffer> device_csr_row_offset_buffers(num_csr_buffers);
// caution for mhot
// use nnz = 1, so device allocations needn't be variable length
// @future - parquet multi-hot change these allocation size
size_t size_of_csr_buffer = sizeof(T) * slots_ * batch_size;
size_t size_of_csr_roff_buffer = sizeof(T) * (slots_ * batch_size + 1);
for (int k = 0; k < num_csr_buffers; k++) {
device_csr_value_buffers[k] =
rmm::device_buffer(size_of_csr_buffer, task_stream_, memory_resource_.get());
device_csr_row_offset_buffers[k] =
rmm::device_buffer(size_of_csr_roff_buffer, task_stream_, memory_resource_.get());
// @todo: check if we need this really for localized, distributed not required
CK_CUDA_THROW_(cudaMemsetAsync(device_csr_row_offset_buffers[k].data(), 0,
size_of_csr_roff_buffer, task_stream_));
}
size_t embed_param_offset_buf_size = num_csr_buffers * sizeof(uint32_t);
rmm::device_buffer device_embed_param_start_offset(embed_param_offset_buf_size, task_stream_,
memory_resource_.get());
CK_CUDA_THROW_(cudaMemsetAsync(device_embed_param_start_offset.data(), 0,
embed_param_offset_buf_size, task_stream_));
// categoricals
// param_id unroll with param : params_ --> param.slot_num
int csr_chunk_devices = csr_chunk->get_num_devices();
int param_id = 0;
int df_column_id = 0;
int param_size = params_.size();
int64_t* pinned_staging_buffer = reinterpret_cast<int64_t*>(
(size_t)host_memory_pointer_staging_.get_ptr() +
sizeof(int64_t) * 2 * (csr_chunk->get_label_dense_dim() + num_dense_buffers));
size_t pinned_buffer_offset_count = 0;
for (auto& param : params_) {
bool distributed_slot = false;
int slot_count = param.slot_num;
std::vector<cudf::column_view> cat_columns_view_ref;
for (int k = 0; k < slot_count; k++) {
cat_columns_view_ref.emplace_back(
std::move(data_view.column(categorical_idx_parquet_col_[df_column_id + k])));
if (cudf::size_of(cat_columns_view_ref.back().type()) != sizeof(T)) {
CK_THROW_(Error_t::WrongInput,
"Parquet reader: Slot KeyType and Parquet column type don't match");
}
}
std::vector<T*> cat_column_data_ptr;
for (int k = 0; k < slot_count; k++) {
T* column_ptr = const_cast<T*>(cat_columns_view_ref[k].data<T>());
column_ptr = reinterpret_cast<T*>((size_t)column_ptr + sizeof(T) * view_offset_);
cat_column_data_ptr.push_back(column_ptr);
}
T* dev_slot_offset_ptr = reinterpret_cast<T*>((size_t)slot_offset_device_buf_->data() +
(df_column_id * sizeof(T)));
int64_t* pinned_staging_buffer_param = reinterpret_cast<int64_t*>(
(size_t)pinned_staging_buffer + pinned_buffer_offset_count * sizeof(int64_t));
if (param.type == DataReaderSparse_t::Distributed) {
distributed_slot = true;
// added row to all device csr buffer based on param_id
// distribute input based on input read feature % num_devices
// csr_chunk->get_csr_buffer(param_id, dev_id).push_back(local_id);
pinned_buffer_offset_count += convert_parquet_cat_columns(
cat_column_data_ptr, param_size, param_id, slot_count, batch_size, num_csr_buffers,
csr_chunk_devices, distributed_slot, device_csr_value_buffers,
device_csr_row_offset_buffers, pinned_staging_buffer_param,
(uint32_t*)device_embed_param_start_offset.data(), dev_slot_offset_ptr, rmm_resources,
memory_resource_.get(), task_stream_);
} else if (param.type == DataReaderSparse_t::Localized) {
// Add row to one buffer
// buffer select based on k % num_gpus k -> loop on slot_num
// csr_chunk->get_csr_buffer(param_id, dev_id).push_back(local_id);
// for all slots
// k is slot_id in current slot
// int dev_id = k % csr_chunk->get_num_devices();
// dev_id * num_params_ + param_id
// call GPU kernel to rearrage the value in individual buffers
// call GPU kernel for row_offset as well
// row_increments go for respective buffers that got data
pinned_buffer_offset_count += convert_parquet_cat_columns(
cat_column_data_ptr, param_size, param_id, slot_count, batch_size, num_csr_buffers,
csr_chunk_devices, distributed_slot, device_csr_value_buffers,
device_csr_row_offset_buffers, pinned_staging_buffer_param,
(uint32_t*)device_embed_param_start_offset.data(), dev_slot_offset_ptr, rmm_resources,
memory_resource_.get(), task_stream_);
} else {
CK_THROW_(Error_t::UnspecificError, "param.type is not defined");
}
df_column_id += param.slot_num;
param_id++;
}
assert((int)host_pinned_csr_inc_.get_num_elements() >= num_csr_buffers);
CK_CUDA_THROW_(
cudaMemcpyAsync(host_pinned_csr_inc_.get_ptr(), device_embed_param_start_offset.data(),
embed_param_offset_buf_size, cudaMemcpyDeviceToHost, task_stream_));
// need this sync here to adjust for memcpy size from D2H of csr bufs
CK_CUDA_THROW_(cudaStreamSynchronize(task_stream_));
// data copied to csr_chunk are based on valid-data
for (int param_idx = 0; param_idx < param_size; param_idx++) {
for (int device = 0; device < csr_chunk_devices; device++) {
int buf_id = device * param_size + param_idx;
size_t copy_size = host_pinned_csr_inc_.get_ptr()[buf_id] * sizeof(T);
CK_CUDA_THROW_(cudaMemcpyAsync(csr_chunk->get_csr_buffer(buf_id).get_value_buffer(),
device_csr_value_buffers[buf_id].data(), copy_size,
cudaMemcpyDeviceToHost, task_stream_));
if (params_[param_idx].type == DataReaderSparse_t::Distributed) {
copy_size = sizeof(T) * (batch_size * params_[param_idx].slot_num + 1);
} else {
copy_size += sizeof(T);
}
CK_CUDA_THROW_(cudaMemcpyAsync(csr_chunk->get_csr_buffer(buf_id).get_row_offset_buffer(),
device_csr_row_offset_buffers[buf_id].data(), copy_size,
cudaMemcpyDeviceToHost, task_stream_));
}
}
for (int param_idx = 0; param_idx < param_size; param_idx++) {
for (int device = 0; device < csr_chunk_devices; device++) {
int buf_id = device * param_size + param_idx;
csr_chunk->get_csr_buffer(buf_id).update_value_size(
host_pinned_csr_inc_.get_ptr()[buf_id]);
if (params_[param_idx].type == DataReaderSparse_t::Localized) {
csr_chunk->get_csr_buffer(buf_id).update_row_offset(
host_pinned_csr_inc_.get_ptr()[buf_id]);
} else if (params_[param_idx].type == DataReaderSparse_t::Distributed) {
csr_chunk->get_csr_buffer(buf_id).update_row_offset(batch_size *
params_[param_idx].slot_num);
}
}
}
CK_CUDA_THROW_(cudaStreamSynchronize(task_stream_));
CK_CUDA_THROW_(cudaStreamSynchronize(dense_stream_));
csr_chunk->apply_to_csr_buffers(&CSR<T>::new_row);
// caching index increment
view_offset_ = row_group_index_;
}
csr_heap_->chunk_write_and_checkin(worker_id_);
} catch (const std::runtime_error& rt_err) {
std::cerr << rt_err.what() << std::endl;
throw;
}
return;
}
} // namespace HugeCTR
| [
"zehuanw@nvidia.com"
] | zehuanw@nvidia.com |
3bc100abbd4f922896338eb98fd0ca6dff0f4389 | a36131551ca27e752372cd999eb51c29dcd501e1 | /SevSeg_Counter4.1.1.ino | ddffbfa48f3e98f71f419c1c38a5506acf0f1fd3 | [] | no_license | cshs20120831/Arduino_lab04 | 288f8da0afb24737b5dab11d57fce915b5b5cac2 | 79f5cfe826e2828a24a7172b4acfa81fb0fdf6f1 | refs/heads/master | 2021-01-19T07:16:19.809355 | 2017-04-10T11:37:10 | 2017-04-10T11:37:10 | 87,532,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,001 | ino | #include "SevSeg.h"
SevSeg sevseg;
float Analogin;
void setup()
{
byte numDigits = 4;
byte digitPins[] = {7,3,4,8};
byte segmentPins[] = {6,5,10,12,13,2,9,11};
pinMode(A0,INPUT_PULLUP);
pinMode(A1,INPUT_PULLUP);
bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
byte hardwareConfig = COMMON_CATHODE; // See README.md for options
bool updateWithDelays = false; // Default. Recommended
bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
sevseg.begin(COMMON_CATHODE, numDigits, digitPins,segmentPins);
sevseg.setBrightness(90);
}
void loop()
{
static unsigned long timer = millis();
static int minute=59;
static int hour=23;
if(millis()>=timer)
{
if (minute == 60)
{
if( ++minute>=60)
{
minute=0;
if( ++ hour >=24)
hour=0;
}
} // overflow
sevseg.setNumber(hour * 100 + minute, 4);
}
for(int i=0;i<10;i++)
sevseg.refreshDisplay();
}
| [
"noreply@github.com"
] | cshs20120831.noreply@github.com |
cd893903bbd00ac47444f9bff667d50e3b82b114 | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/chrome/browser/chromeos/chrome_browser_main_chromeos.h | df86349d1225e5ae57d647f16930f58dec1f107b | [
"BSD-3-Clause"
] | permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,233 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_CHROME_BROWSER_MAIN_CHROMEOS_H_
#define CHROME_BROWSER_CHROMEOS_CHROME_BROWSER_MAIN_CHROMEOS_H_
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/chrome_browser_main_linux.h"
#include "chrome/browser/chromeos/version_loader.h"
#include "chrome/common/cancelable_task_tracker.h"
namespace contacts {
class ContactManager;
}
namespace content {
class PowerSaveBlocker;
}
namespace chromeos {
class BrightnessObserver;
class DisplayConfigurationObserver;
class IdleActionWarningObserver;
class MagnificationManager;
class PeripheralBatteryObserver;
class PowerButtonObserver;
class PowerPrefs;
class ResumeObserver;
class ScreenLockObserver;
class ScreensaverController;
class SessionManagerObserver;
class SuspendObserver;
class SwapMetrics;
class UserActivityNotifier;
class VideoActivityNotifier;
namespace default_app_order {
class ExternalLoader;
}
namespace internal {
class DBusServices;
}
class ChromeBrowserMainPartsChromeos : public ChromeBrowserMainPartsLinux {
public:
explicit ChromeBrowserMainPartsChromeos(
const content::MainFunctionParams& parameters);
virtual ~ChromeBrowserMainPartsChromeos();
// ChromeBrowserMainParts overrides.
virtual void PreEarlyInitialization() OVERRIDE;
virtual void PreMainMessageLoopStart() OVERRIDE;
virtual void PostMainMessageLoopStart() OVERRIDE;
virtual void PreMainMessageLoopRun() OVERRIDE;
// Stages called from PreMainMessageLoopRun.
virtual void PreProfileInit() OVERRIDE;
virtual void PostProfileInit() OVERRIDE;
virtual void PreBrowserStart() OVERRIDE;
virtual void PostBrowserStart() OVERRIDE;
virtual void PostMainMessageLoopRun() OVERRIDE;
virtual void PostDestroyThreads() OVERRIDE;
virtual void SetupPlatformFieldTrials() OVERRIDE;
private:
scoped_ptr<contacts::ContactManager> contact_manager_;
scoped_ptr<BrightnessObserver> brightness_observer_;
scoped_ptr<DisplayConfigurationObserver> display_configuration_observer_;
scoped_ptr<default_app_order::ExternalLoader> app_order_loader_;
scoped_ptr<SuspendObserver> suspend_observer_;
scoped_ptr<ResumeObserver> resume_observer_;
scoped_ptr<ScreenLockObserver> screen_lock_observer_;
scoped_ptr<ScreensaverController> screensaver_controller_;
scoped_ptr<PeripheralBatteryObserver> peripheral_battery_observer_;
scoped_ptr<PowerPrefs> power_prefs_;
scoped_ptr<PowerButtonObserver> power_button_observer_;
scoped_ptr<content::PowerSaveBlocker> retail_mode_power_save_blocker_;
scoped_ptr<UserActivityNotifier> user_activity_notifier_;
scoped_ptr<VideoActivityNotifier> video_activity_notifier_;
scoped_ptr<IdleActionWarningObserver> idle_action_warning_observer_;
scoped_ptr<SwapMetrics> swap_metrics_;
scoped_ptr<internal::DBusServices> dbus_services_;
VersionLoader cros_version_loader_;
CancelableTaskTracker tracker_;
bool use_new_network_change_notifier_;
DISALLOW_COPY_AND_ASSIGN(ChromeBrowserMainPartsChromeos);
};
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_CHROME_BROWSER_MAIN_CHROMEOS_H_
| [
"ProjectRetroScope@gmail.com"
] | ProjectRetroScope@gmail.com |
5ea44edbf3e4a9209b8675eb1d364c0630c1a8a8 | 1b9b2f5733bd1f63f0a02367d85060ec8240007e | /server.cpp | 9ceb36e102131d8e8378d2bcf7398789e3328014 | [] | no_license | matiTechno/sockets | 5a8973ee585fe69ff82d1ad1403fadbeae488b71 | cc464f3bb9aeac74cefe583bd1012bdf301508b0 | refs/heads/master | 2020-03-14T14:20:02.845266 | 2018-10-04T08:50:59 | 2018-10-04T08:50:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,745 | cpp | #include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <netinet/tcp.h>
#include "Array.hpp"
template<typename T>
T min(T l, T r) {return l > r ? r : l;}
double getTimeSec()
{
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec / 1000000000.0;
}
const void* get_in_addr(const sockaddr* const sa)
{
if(sa->sa_family == AF_INET)
return &( ( (sockaddr_in*)sa )->sin_addr );
return &( ( (sockaddr_in6*)sa )->sin6_addr );
}
struct Cmd
{
enum
{
_nil,
Ping,
Pong,
Name,
Chat,
_count
};
};
const char* getCmdStr(int cmd)
{
switch(cmd)
{
case Cmd::Ping: return "PING";
case Cmd::Pong: return "PONG";
case Cmd::Name: return "NAME";
case Cmd::Chat: return "CHAT";
}
assert(false);
}
void addMsg(Array<char>& buffer, int cmd, const char* payload = "")
{
if(cmd)
{
const char* cmdStr = getCmdStr(cmd);
int len = strlen(cmdStr) + strlen(payload) + 2; // ' ' + '\0'
int prevSize = buffer.size();
buffer.resize(prevSize + len);
assert(snprintf(buffer.data() + prevSize, len, "%s %s", cmdStr, payload) == len - 1);
}
// special case for http response
else
{
int len = strlen(payload) + 1;
int prevSize = buffer.size();
buffer.resize(prevSize + len);
memcpy(buffer.data() + prevSize, payload, len);
}
}
enum class ClientStatus
{
Waiting,
Browser,
Player,
PlayerRename
};
struct Client
{
ClientStatus status = ClientStatus::Waiting;
char name[20] = "dummy";
int sockfd;
bool remove = false;
bool alive = true;
};
const char* getStatusStr(ClientStatus code)
{
switch(code)
{
case ClientStatus::Waiting: return "Waiting";
case ClientStatus::Browser: return "Browser";
case ClientStatus::Player: return "Player";
case ClientStatus::PlayerRename: return "PlayerRename";
}
assert(false);
}
static volatile int gExitLoop = false;
void sigHandler(int) {gExitLoop = true;}
int main()
{
signal(SIGINT, sigHandler);
signal(SIGTERM, sigHandler);
addrinfo hints = {};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
addrinfo* list;
{
// this blocks
const int ec = getaddrinfo(nullptr, "3000", &hints, &list);
if(ec != 0)
{
printf("getaddrinfo() failed: %s\n", gai_strerror(ec));
return 0;
}
}
int sockfd;
const addrinfo* it;
for(it = list; it != nullptr; it = it->ai_next)
{
sockfd = socket(it->ai_family, it->ai_socktype, it->ai_protocol);
if(sockfd == -1)
{
perror("socket() failed");
continue;
}
const int option = 1;
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) == -1)
{
close(sockfd);
perror("setsockopt() (SO_REUSEADDR) failed");
return 0;
}
if(fcntl(sockfd, F_SETFL, O_NONBLOCK) == -1)
{
close(sockfd);
perror("fcntl() failed");
return 0;
}
if(bind(sockfd, it->ai_addr, it->ai_addrlen) == -1)
{
close(sockfd);
perror("bind() failed");
continue;
}
break;
}
freeaddrinfo(list);
if(it == nullptr)
{
printf("binding procedure failed\n");
return 0;
}
if(listen(sockfd, 5) == -1)
{
perror("listen() failed");
close(sockfd);
return 0;
}
constexpr int maxClients = 10;
FixedArray<Client, maxClients> clients;
Array<char> sendBufs[maxClients];
Array<char> recvBufs[maxClients];
int recvBufsNumUsed[maxClients];
for(int i = 0; i < maxClients; ++i)
{
sendBufs[i].reserve(500);
recvBufs[i].resize(500);
}
double currentTime = getTimeSec();
float timer = 0.f;
// server loop
// note: don't change the order of operations
// (some logic is based on this)
while(gExitLoop == false)
{
// update clients
{
const double newTime = getTimeSec();
timer += newTime - currentTime;
currentTime = newTime;
if(timer > 5.f)
{
timer = 0.f;
for(int i = 0; i < clients.size(); ++i)
{
Client& client = clients[i];
if(client.alive == false)
{
printf("client '%s' (%s) will be removed (no PONG or init msg)\n",
client.name, getStatusStr(client.status));
client.remove = true;
}
else if(client.status != ClientStatus::Waiting)
addMsg(sendBufs[i], Cmd::Ping);
client.alive = false;
}
}
}
// handle new client
if(clients.size() < clients.maxSize())
{
sockaddr_storage clientAddr;
socklen_t clientAddrSize = sizeof(clientAddr);
const int clientSockfd = accept(sockfd, (sockaddr*)&clientAddr, &clientAddrSize);
if(clientSockfd == -1)
{
if(errno != EAGAIN || errno != EWOULDBLOCK)
{
perror("accept()");
break;
}
}
else
{
const int option = 1;
if(fcntl(clientSockfd, F_SETFL, O_NONBLOCK) == -1)
{
close(clientSockfd);
perror("fcntl() on client failed");
}
else if(setsockopt(clientSockfd, IPPROTO_TCP, TCP_NODELAY, &option,
sizeof(option)) == -1)
{
close(clientSockfd);
perror("setsockopt() (TCP_NODELAY) on client failed");
}
else
{
clients.pushBack(Client());
clients.back().sockfd = clientSockfd;
sendBufs[clients.size() - 1].clear();
recvBufsNumUsed[clients.size() - 1] = 0;
// print client ip
char ipStr[INET6_ADDRSTRLEN];
inet_ntop(clientAddr.ss_family, get_in_addr( (sockaddr*)&clientAddr ),
ipStr, sizeof(ipStr));
printf("accepted connection from %s\n", ipStr);
}
}
}
// receive
for(int i = 0; i < clients.size(); ++i)
{
Array<char>& recvBuf = recvBufs[i];
int& recvBufNumUsed = recvBufsNumUsed[i];
Client& client = clients[i];
while(true)
{
const int numFree = recvBuf.size() - recvBufNumUsed;
const int rc = recv(client.sockfd, recvBuf.data() + recvBufNumUsed,
numFree, 0);
if(rc == -1)
{
if(errno != EAGAIN || errno != EWOULDBLOCK)
{
perror("recv() failed");
client.remove = true;
}
break;
}
else if(rc == 0)
{
printf("client has closed the connection\n");
client.remove = true;
break;
}
else
{
recvBufNumUsed += rc;
if(recvBufNumUsed < recvBuf.size())
break;
recvBuf.resize(recvBuf.size() * 2);
if(recvBuf.size() > 10000)
{
printf("recvBuf big size issue, removing client: '%s' (%s)\n",
client.name, getStatusStr(client.status));
client.remove = true;
break;
}
}
}
}
// process received data
for(int i = 0; i < clients.size(); ++i)
{
Array<char>& sendBuf = sendBufs[i];
Array<char>& recvBuf = recvBufs[i];
int& recvBufNumUsed = recvBufsNumUsed[i];
Client& client = clients[i];
const char* end = recvBuf.data();
const char* begin;
// special case for http
if(recvBufNumUsed >= 3)
{
const char* const cmd = "GET";
if(strncmp(cmd, recvBuf.data(), strlen(cmd)) == 0)
{
client.status = ClientStatus::Browser;
addMsg(sendBuf, Cmd::_nil,
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n\r\n"
"<!DOCTYPE html>"
"<html>"
"<body>"
"<h1>Welcome to the cavetiles server!</h1>"
"<p><a href=\"https://github.com/m2games\">company</a></p>"
"</body>"
"</html>");
continue;
}
}
while(true)
{
begin = end;
{
const char* tmp = (const char*)memchr((const void*)end, '\0',
recvBuf.data() + recvBufNumUsed - end);
if(tmp == nullptr) break;
end = tmp;
}
++end;
printf("'%s' (%s) received msg: '%s'\n", client.name,
getStatusStr(client.status), begin);
int cmd = 0;
for(int i = 1; i < Cmd::_count; ++i)
{
const char* const cmdStr = getCmdStr(i);
const int cmdLen = strlen(cmdStr);
if(cmdLen > int(strlen(begin)))
continue;
if(strncmp(begin, cmdStr, cmdLen) == 0)
{
cmd = i;
begin += cmdLen + 1; // ' '
break;
}
}
switch(cmd)
{
case 0:
printf("WARNING unknown command received: '%s'\n", begin);
break;
case Cmd::Ping:
addMsg(sendBuf, Cmd::Pong);
break;
case Cmd::Pong:
client.alive = true;
break;
case Cmd::Name:
{
bool ok = true;
for(const Client& other: clients)
{
if(other.status == ClientStatus::Player &&
strcmp(other.name, begin) == 0)
{
ok = false;
break;
}
}
if(ok)
{
client.status = ClientStatus::Player;
const int maxSize = sizeof(client.name);
memcpy(client.name, begin, min(maxSize, int(strlen(begin)) + 1));
client.name[maxSize - 1] = '\0';
for(int i = 0; i < clients.size(); ++i)
{
if(clients[i].status == ClientStatus::Player)
{
char msg[64];
snprintf(msg, sizeof(msg), "'%s' has joined the game!",
client.name);
addMsg(sendBufs[i], Cmd::Chat, msg);
}
}
}
else
{
client.status = ClientStatus::PlayerRename;
addMsg(sendBuf, Cmd::Name);
}
break;
}
case Cmd::Chat:
for(int i = 0; i < clients.size(); ++i)
{
if(clients[i].status == ClientStatus::Player)
{
char msg[512];
snprintf(msg, sizeof(msg), "%s: %s", client.name, begin);
addMsg(sendBufs[i], Cmd::Chat, msg);
}
}
break;
}
}
const int numToFree = end - recvBuf.data();
memmove(recvBuf.data(), recvBuf.data() + numToFree, recvBufNumUsed - numToFree);
recvBufNumUsed -= numToFree;
}
// inform players if someone will leave the game
for(const Client& client: clients)
{
if(client.remove && client.status == ClientStatus::Player)
{
char buf[64];
snprintf(buf, sizeof(buf), "'%s' has left", client.name);
for(int i = 0; i < clients.size(); ++i)
{
if(clients[i].status == ClientStatus::Player && !clients[i].remove)
{
addMsg(sendBufs[i], Cmd::Chat, buf);
}
}
}
}
// send
for(int i = 0; i < clients.size(); ++i)
{
if(clients[i].remove)
continue;
Array<char>& buf = sendBufs[i];
if(buf.size())
{
const int rc = send(clients[i].sockfd, buf.data(), buf.size(), 0);
if(rc == -1)
{
perror("send() failed");
clients[i].remove = true;
}
else
buf.erase(0, rc);
}
}
// remove some clients
for(int i = 0; i < clients.size(); ++i)
{
Client& client = clients[i];
if(client.remove || client.status == ClientStatus::Browser)
{
printf("removing client '%s' (%s)\n", client.name,
getStatusStr(client.status));
close(client.sockfd);
client = clients.back();
const int lastIdx = clients.size() - 1;
sendBufs[i].swap(sendBufs[lastIdx]);
recvBufs[i].swap(recvBufs[lastIdx]);
recvBufsNumUsed[i] = recvBufsNumUsed[lastIdx];
clients.popBack();
--i;
}
}
// sleep for 10 ms
usleep(10000);
}
for(Client& client: clients)
close(client.sockfd);
close(sockfd);
printf("end of the main function\n");
return 0;
}
| [
"mateusz.macieja8@gmail.com"
] | mateusz.macieja8@gmail.com |
1becb4ec5854ca2271cf8938934b9446aadf54b7 | 29d7129d8459e751061e7f30582e5c8a009e85c1 | /loop-functions/gianduja/GiandujaBeaconAggregationLoopFunc.cpp | 093b9e0f1f6e62cc83d5970435682b4c6661fe0a | [
"MIT"
] | permissive | demiurge-project/experiments-loop-functions | 88ced1d0d1c42116f1338ec5015dd72dd7f23a08 | 02333bd2ee3a99cb31a1d7da5cb8067df79a4167 | refs/heads/master | 2023-08-14T10:24:00.161414 | 2022-11-16T16:48:11 | 2022-11-16T16:48:11 | 117,963,055 | 0 | 5 | MIT | 2020-10-19T09:15:24 | 2018-01-18T09:42:55 | C++ | UTF-8 | C++ | false | false | 7,675 | cpp | #include "GiandujaBeaconAggregationLoopFunc.h"
/****************************************/
/****************************************/
GiandujaBeaconAggregationLoopFunction::GiandujaBeaconAggregationLoopFunction() {
m_fRadius = 0.3;
m_cCoordSpot1 = CVector2(0.5,0.5);
m_cCoordSpot2 = CVector2(-0.5,0.5);
m_unCostSpot1 = 0;
m_unCostSpot2 = 0;
m_fObjectiveFunction = 0;
m_unTime = 0;
m_unMesParam = 0;
m_unMes = 0;
}
/****************************************/
/****************************************/
GiandujaBeaconAggregationLoopFunction::GiandujaBeaconAggregationLoopFunction(const GiandujaBeaconAggregationLoopFunction& orig) {}
/****************************************/
/****************************************/
GiandujaBeaconAggregationLoopFunction::~GiandujaBeaconAggregationLoopFunction() {}
/****************************************/
/****************************************/
void GiandujaBeaconAggregationLoopFunction::Destroy() {}
/****************************************/
/****************************************/
void GiandujaBeaconAggregationLoopFunction::Reset() {
CoreLoopFunctions::Reset();
m_unCostSpot1 = 0;
m_fObjectiveFunction = 0;
m_unMes = 0;
// if (m_unMesParam == 3) {
// m_unMes = m_pcRng->Uniform(CRange<UInt32>(0,2))*150+10;
// }
// else {
// m_unMes = m_unMesParam;
// }
PlaceBeacon();
ExtractMessage();
//SetMessageBeacon();
}
void GiandujaBeaconAggregationLoopFunction::Init(TConfigurationNode& t_tree) {
CoreLoopFunctions::Init(t_tree);
TConfigurationNode cParametersNode;
try {
cParametersNode = GetNode(t_tree, "params");
//GetNodeAttributeOrDefault(cParametersNode, "mes", m_unMesParam, (UInt32) 3);
} catch(std::exception e) {
LOGERR << e.what() << std::endl;
}
// if (m_unMesParam == 3) {
// m_unMes = m_pcRng->Uniform(CRange<UInt32>(0,2))*150+10;
// }
// else {
// m_unMes = m_unMesParam;
// }
m_unMes = 0;
m_unCostSpot1 = 0;
m_fObjectiveFunction = 0;
PlaceBeacon();
ExtractMessage();
//SetMessageBeacon();
}
/****************************************/
/****************************************/
argos::CColor GiandujaBeaconAggregationLoopFunction::GetFloorColor(const argos::CVector2& c_position_on_plane) {
CVector2 vCurrentPoint(c_position_on_plane.GetX(), c_position_on_plane.GetY());
Real d = (m_cCoordSpot1 - vCurrentPoint).Length();
if (d <= m_fRadius) {
return CColor::WHITE;
}
d = (m_cCoordSpot2 - vCurrentPoint).Length();
if (d <= m_fRadius) {
return CColor::BLACK;
}
return CColor::GRAY50;
}
void GiandujaBeaconAggregationLoopFunction::PlaceBeacon() {
try {
CEPuckEntity& cEpuck = dynamic_cast<CEPuckEntity&>(GetSpace().GetEntity("beacon0"));
MoveEntity(cEpuck.GetEmbodiedEntity(),
CVector3(0, 0.5, 0),
CQuaternion().FromEulerAngles(CRadians::ZERO,
CRadians::ZERO,CRadians::ZERO),false);
} catch (std::exception& ex) {
LOGERR << "Error while casting PlaceBeacon: " << ex.what() << std::endl;
}
}
void GiandujaBeaconAggregationLoopFunction::ExtractMessage() {
try {
CEPuckEntity& cEntity = dynamic_cast<CEPuckEntity&>(GetSpace().GetEntity("beacon0"));
CEPuckBeacon& cController = dynamic_cast<CEPuckBeacon&>(cEntity.GetControllableEntity().GetController());
m_unMes = cController.getMessage();
} catch (std::exception& ex) {
LOGERR << "Error while casting ExtractMessage: " << ex.what() << std::endl;
}
if (m_unMes==160) {
LOG << "Message=" << m_unMes << " blanc" << std::endl;
}
else if (m_unMes==10) {
LOG << "Message=" << m_unMes << " noir"<< std::endl;
}
}
void GiandujaBeaconAggregationLoopFunction::SetMessageBeacon() {
try {
CEPuckEntity& cEntity = dynamic_cast<CEPuckEntity&>(GetSpace().GetEntity("beacon0"));
CEPuckBeacon& cController = dynamic_cast<CEPuckBeacon&>(cEntity.GetControllableEntity().GetController());
cController.setMessage(m_unMes);
if (m_unMes==160) {
LOG << "Message=" << m_unMes << "blanc" << std::endl;
}
else if (m_unMes==10) {
LOG << "Message=" << m_unMes << "noir"<< std::endl;
}
} catch (std::exception& ex) {
LOGERR << "Error while casting SetMessageBeacon: " << ex.what() << std::endl;
}
}
CVector3 GiandujaBeaconAggregationLoopFunction::GetRandomPosition() {
Real a;
Real b;
a = m_pcRng->Uniform(CRange<Real>(0.0f, 1.0f));
b = m_pcRng->Uniform(CRange<Real>(0.0f, 1.0f));
Real fPosY = -1.0 + a * 0.8;
Real fPosX = -0.8 + b * 1.6;
return CVector3(fPosX, fPosY, 0);
}
/****************************************/
/****************************************/
void GiandujaBeaconAggregationLoopFunction::PostStep() {
CSpace::TMapPerType& tEpuckMap = GetSpace().GetEntitiesByType("epuck");
CVector2 cEpuckPosition(0,0);
for (CSpace::TMapPerType::iterator it = tEpuckMap.begin(); it != tEpuckMap.end(); ++it) {
CEPuckEntity* pcEpuck = any_cast<CEPuckEntity*>(it->second);
cEpuckPosition.Set(pcEpuck->GetEmbodiedEntity().GetOriginAnchor().Position.GetX(),
pcEpuck->GetEmbodiedEntity().GetOriginAnchor().Position.GetY());
Real fDistanceSpot;
if (m_unMes == 160) {
fDistanceSpot = (m_cCoordSpot1 - cEpuckPosition).Length();
}
else if (m_unMes == 10) {
fDistanceSpot = (m_cCoordSpot2 - cEpuckPosition).Length();
}
if (fDistanceSpot >= m_fRadius) {
m_unCostSpot1 += 1;
}
}
m_fObjectiveFunction = (Real) m_unCostSpot1;
m_unTime+=1;
}
/****************************************/
/****************************************/
void GiandujaBeaconAggregationLoopFunction::PostExperiment() {
// CSpace::TMapPerType& tEpuckMap = GetSpace().GetEntitiesByType("epuck");
// CVector2 cEpuckPosition(0,0);
//
// for (CSpace::TMapPerType::iterator it = tEpuckMap.begin(); it != tEpuckMap.end(); ++it) {
// CEPuckEntity* pcEpuck = any_cast<CEPuckEntity*>(it->second);
// cEpuckPosition.Set(pcEpuck->GetEmbodiedEntity().GetOriginAnchor().Position.GetX(),
// pcEpuck->GetEmbodiedEntity().GetOriginAnchor().Position.GetY());
//
// Real fDistanceSpot1;
// Real fDistanceSpot2;
// if (m_unMes == 0) {
// fDistanceSpot1 = (m_cCoordSpot1 - cEpuckPosition).Length();
// fDistanceSpot2 = (m_cCoordSpot2 - cEpuckPosition).Length();
// }
// else if (m_unMes == 1) {
// fDistanceSpot1 = (m_cCoordSpot2 - cEpuckPosition).Length();
// fDistanceSpot2 = (m_cCoordSpot1 - cEpuckPosition).Length();
// }
//
// if (fDistanceSpot1 <= m_fRadius) {
// m_unCostSpot1 += 1;
// }
// if ( fDistanceSpot2 <= m_fRadius ) {
// m_unCostSpot2 += 1;
// }
// }
//
// LOG << "1:" << m_unCostSpot1 << " 2:" << m_unCostSpot2 << std::endl;
// Real score = m_unCostSpot1 - m_unCostSpot2;
// if (score < 0) {
// score = 0;
// }
// m_fObjectiveFunction = (Real) score ;
m_fObjectiveFunction = (Real) 25201 - (m_unCostSpot1);
LOG<< "fit: " << m_fObjectiveFunction << std::endl;
}
Real GiandujaBeaconAggregationLoopFunction::GetObjectiveFunction() {
return m_fObjectiveFunction;
}
REGISTER_LOOP_FUNCTIONS(GiandujaBeaconAggregationLoopFunction, "gianduja_beacon_aggregation_loop_functions");
| [
"ken@kenh.fr"
] | ken@kenh.fr |
48384343c3c7dcfb7978531a3a21247bdba52af5 | 47bae215224de3df826ed22dae557315c7d48d73 | /C_OFFER/Chapter5_OptimizationSpaceTime/40_KLeastNumbers.cpp | 7c3eb0abf4342ee9ca542feda88a286280718cac | [] | no_license | lgtcarol/BasicAlgorithm | ba3d15f03274397e6b01038759c6c48c798e5f52 | a9db9824f2c08e5f3340c08efa497a77045eecc9 | refs/heads/master | 2020-03-28T18:40:10.528191 | 2019-09-10T03:47:10 | 2019-09-10T03:47:10 | 148,900,023 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,115 | cpp | // 面试题40:最小的k个数
// 题目:输入n个整数,找出其中最小的k个数。例如输入4、5、1、6、2、7、3、8
// 这8个数字,则最小的4个数字是1、2、3、4。
#include <cstdio>
#include "Utilities\Array.cpp"
#include <set>
#include <vector>
#include <iostream>
#include <functional>//该头文件中定义的两个结构greater和less都重载了操作符()
using namespace std;
/**
1. 比上题特征更明显适合快排
2. 同样确定到目标为k-1 即可返回分析达到目标要求
*/
// ====================方法1====================
void GetLeastNumbers_Solution1(int* input, int n, int* output, int k)
{
if(input == nullptr || output == nullptr || k > n || n <= 0 || k <= 0)
return;
int start = 0;
int end = n - 1;
int index = Partition(input, n, start, end);
while(index != k - 1)
{
if(index > k - 1)
{
end = index - 1;
index = Partition(input, n, start, end);
}
else
{
start = index + 1;
index = Partition(input, n, start, end);
}
}
for(int i = 0; i < k; ++i)
output[i] = input[i];
}
/**
STL中三个关键点:容器,迭代器,算法
*/
// ====================方法2====================
typedef multiset<int, std::greater<int> > intSet; //大顶堆
typedef multiset<int, std::greater<int> >::iterator setIterator; //本题使用迭代删除是multiset在删除值时会删多个相等值
typedef multiset
void GetLeastNumbers_Solution2(const vector<int>& data, intSet& leastNumbers, int k)
{
leastNumbers.clear();
if(k < 1 || data.size() < k)
return;
vector<int>::const_iterator iter = data.begin();
for(; iter != data.end(); ++ iter)
{
if((leastNumbers.size()) < k)
leastNumbers.insert(*iter);
else
{
//Note:因为迭代器是指针,故取容器中的值时注意
setIterator iterGreatest = leastNumbers.begin();////multiset访问必须定义迭代器,且begin()返回的不是值!
if(*iter < *(leastNumbers.begin()))
{
leastNumbers.erase(iterGreatest);
leastNumbers.insert(*iter);
}
}
}
}
// ====================测试代码====================
void Test(char* testName, int* data, int n, int* expectedResult, int k)
{
if(testName != nullptr)
printf("%s begins: \n", testName);
vector<int> vectorData;
for(int i = 0; i < n; ++ i)
vectorData.push_back(data[i]);
if(expectedResult == nullptr)
printf("The input is invalid, we don't expect any result.\n");
else
{
printf("Expected result: \n");
for(int i = 0; i < k; ++ i)
printf("%d\t", expectedResult[i]);
printf("\n");
}
printf("Result for solution1:\n");
int* output = new int[k];
GetLeastNumbers_Solution1(data, n, output, k);
if(expectedResult != nullptr)
{
for(int i = 0; i < k; ++ i)
printf("%d\t", output[i]);
printf("\n");
}
delete[] output;
printf("Result for solution2:\n");
intSet leastNumbers;
GetLeastNumbers_Solution2(vectorData, leastNumbers, k);
printf("The actual output numbers are:\n");
for(setIterator iter = leastNumbers.begin(); iter != leastNumbers.end(); ++iter)
printf("%d\t", *iter);
printf("\n\n");
}
// k小于数组的长度
void Test1()
{
int data[] = {4, 5, 1, 6, 2, 7, 3, 8};
int expected[] = {1, 2, 3, 4};
Test("Test1", data, sizeof(data) / sizeof(int), expected, sizeof(expected) / sizeof(int));
}
// k等于数组的长度
void Test2()
{
int data[] = {4, 5, 1, 6, 2, 7, 3, 8};
int expected[] = {1, 2, 3, 4, 5, 6, 7, 8};
Test("Test2", data, sizeof(data) / sizeof(int), expected, sizeof(expected) / sizeof(int));
}
// k大于数组的长度
void Test3()
{
int data[] = {4, 5, 1, 6, 2, 7, 3, 8};
int* expected = nullptr;
Test("Test3", data, sizeof(data) / sizeof(int), expected, 10);
}
// k等于1
void Test4()
{
int data[] = {4, 5, 1, 6, 2, 7, 3, 8};
int expected[] = {1};
Test("Test4", data, sizeof(data) / sizeof(int), expected, sizeof(expected) / sizeof(int));
}
// k等于0
void Test5()
{
int data[] = {4, 5, 1, 6, 2, 7, 3, 8};
int* expected = nullptr;
Test("Test5", data, sizeof(data) / sizeof(int), expected, 0);
}
// 数组中有相同的数字
void Test6()
{
int data[] = {4, 5, 1, 6, 2, 7, 2, 8};
int expected[] = {1, 2};
Test("Test6", data, sizeof(data) / sizeof(int), expected, sizeof(expected) / sizeof(int));
}
// 输入空指针
void Test7()
{
int* expected = nullptr;
Test("Test7", nullptr, 0, expected, 0);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
return 0;
}
| [
"noreply@github.com"
] | lgtcarol.noreply@github.com |
79af7938589ecbfaf8fa54c3626e987078a6385e | a0a620497a3c3d2676bdc8fa17ff51f59754f7b4 | /451B.cpp | f28463600c4d165ec84c523d099ffe071fba5248 | [] | no_license | Sahilkalamkar/Codeforces_Solutions | 3da7b79e5acad2189b8e7f662242040700e18f56 | b9045b13003ea80276900a068f120a5bbd8fbbde | refs/heads/master | 2021-10-27T07:18:46.664126 | 2020-10-31T16:38:19 | 2020-10-31T16:38:19 | 216,762,951 | 8 | 17 | null | 2020-10-31T16:38:20 | 2019-10-22T08:31:50 | C++ | UTF-8 | C++ | false | false | 1,167 | cpp | /*
* Author: Akansha(akansha_2202)
* Date : 22/10/2019
*/
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
int b[n];
int c[n];
for(int i=0;i<n;i++){
cin>>a[i];
c[i]=a[i];
}
for(int j=0;j<n;j++){
b[j]=0;
}
for(int i=0;i<n;i++){
if(i==0){
if(a[i]>a[i+1]){
b[i]=1;
continue;
}
}
else if(i==n-1){
if(a[i]<a[i-1]){
b[i]=1;
continue;
}
}
else if(a[i-1]>a[i]&&a[i]<a[i+1]){
b[i]=1;
continue;
}
else if(a[i-1]<a[i]&&a[i]>a[i+1]){
b[i]=1;
continue;
}
}
int x=1,y=1;
if(is_sorted(a,a+n)){
cout<<"yes"<<endl;
cout<<x<<" "<<y<<endl;
}
else{
int temp[n];
int k=0;
for(int i=0;i<n;i++){
if(b[i]==1){
temp[k]=i;
k++;
}
}
x=temp[0];
y=temp[1];
int m=x;
int l=y;
//swap(a[x],a[y]);
for(int i=x;i<=y;i++){
a[i]=c[l];
l--;
}
//for(int i=0;i<n;i++)
//cout<<a[i]<<" ";
if(is_sorted(a,a+n)){
cout<<"yes";
cout<<endl;
cout<<x+1<<" "<<y+1<<endl;
}
else
cout<<"no"<<endl;
//cout<<endl;
//cout<<temp[0]+1<<" "<<temp[1]+1<<endl;
}
/*for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}*/
return 0;
}
| [
"mini.akansha007@gmail.com"
] | mini.akansha007@gmail.com |
fc7bb753628476c653578af0c6d92f9bc94a0957 | 7c5930680d1e1c6baaa37c679929d35d38bdb27f | /vacancy_visualize_vtk.cpp | 31d347c0f8a391823904dfa958819b88d3ee41f3 | [] | no_license | divergentscott/ack | 60bedeb1e3e3293411c6e49c2589b074d185bf14 | d746d3a4726419240a19ff46878e9220b8cf5f51 | refs/heads/master | 2021-08-09T17:16:47.266238 | 2020-08-21T21:20:50 | 2020-08-21T21:20:50 | 215,874,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,711 | cpp | #include <vtkRenderer.h>
#include <vtkSmartPointer.h>
#include <vtkSVGExporter.h>
#include "vacancy_visualize_vtk.h"
#include <vtkActor.h>
#include <vtkCellArray.h>
#include <vtkNamedColors.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolygon.h>
#include <vtkProperty.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartPointer.h>
VacancyVisualizeVTK::VacancyVisualizeVTK(){
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
// Setup four points
vtkSmartPointer<vtkPoints> points =
vtkSmartPointer<vtkPoints>::New();
points->InsertNextPoint(0.0, 0.0, 0.0);
points->InsertNextPoint(1.0, 0.0, 0.0);
points->InsertNextPoint(1.0, 1.0, 0.0);
points->InsertNextPoint(0.0, 1.0, 0.0);
// Create the polygon
vtkSmartPointer<vtkPolygon> polygon =
vtkSmartPointer<vtkPolygon>::New();
polygon->GetPointIds()->SetNumberOfIds(4); //make a quad
polygon->GetPointIds()->SetId(0, 0);
polygon->GetPointIds()->SetId(1, 1);
polygon->GetPointIds()->SetId(2, 2);
polygon->GetPointIds()->SetId(3, 3);
// Add the polygon to a list of polygons
vtkSmartPointer<vtkCellArray> polygons =
vtkSmartPointer<vtkCellArray>::New();
polygons->InsertNextCell(polygon);
// Create a PolyData
vtkSmartPointer<vtkPolyData> polygonPolyData =
vtkSmartPointer<vtkPolyData>::New();
polygonPolyData->SetPoints(points);
polygonPolyData->SetPolys(polygons);
// Create a mapper and actor
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(polygonPolyData);
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
actor->GetProperty()->SetColor(
colors->GetColor3d("Silver").GetData());
// Visualize
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->SetWindowName("Polygon");
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor(actor);
renderer->SetBackground(colors->GetColor3d("Salmon").GetData());
renderWindow->Render();
renderWindowInteractor->Start();
};
//void VacancyVisualizeVTK::setStroke(const double &x){
// stroke_width_ = x;
//}
//
//void VacancyVisualizeVTK::setViewBox(const Eigen::Vector2d& position, const double& width0, const double& height0){
// min_x_ = position[0];
// min_y_ = -position[1];
// max_x_ = position[0] + width0;
// max_y_ = -position[1] + height0;
//};
//
void VacancyVisualizeVTK::addRectangle(const Eigen::Vector2d& position, const double& width, const double& height){
// context_->GetPen()->SetColor(0,0,0);
// context_->DrawRect(position[0], position[1], width, height);
};
//
//void VacancyVisualizeVTK::addRectangles(const std::vector<Eigen::Vector2d>& positions, const double& width, const double& height){
// for (const auto& p : positions){
// addRectangle(p,width,height);
// }
//};
//
//void VacancyVisualizeVTK::addCabbieCurveCollection(const CabbieCurveCollection& ccc){
// int n_components = ccc.get_number_of_components();
// for (int foo=0; foo < n_components; foo++){
// std::stringstream ss;
// ss << "<polyline points=\"";
// int basepoint = ccc.get_basepoint(foo);
// int bar = basepoint;
// Eigen::Vector2d pbar = ccc.get_point(bar);
// ss << pbar[0] << "," << -pbar[1] << " ";
// do {
// bar = ccc.get_next_point(bar);
// pbar = ccc.get_point(bar);
// ss << pbar[0] << "," << -pbar[1] << " ";
// min_x_ = std::min(pbar[0], min_x_);
// min_y_ = std::min(-pbar[1], min_y_);
// } while (bar != basepoint);
// ss << "\" stroke=\"black\" stroke-width=\""<< stroke_width_ << "\" fill=\"none\" />";
// topstack.push_back(ss.str());
// };
//}
//<polyline points="50,150 50,200 200,200 200,100" stroke="black" stroke-width="4" fill="none" />
//void VacancyVisualizeVTK::writeScalableVectorGraphics(const std::string& outfilepath){
// auto svger = vtkSmartPointer<vtkSVGExporter>::New();
// auto rendy = vtkSmartPointer<vtkRenderer>::New();
// rendy->AddActor2D();
// svger->SetInput(context_);
// svger->SetFileName(outfilepath.c_str());
// svger->WriteSVG();
//};
| [
"sscott@divergent3d.com"
] | sscott@divergent3d.com |
051c0ab4b7864637449c4f93f39fa5f240c4ad92 | 7cf5dc55a252076ab51a77ef5c4ea8ad3dbc5809 | /src/KMeans.cpp | 6147f99c88e58d74a5df42eaacd601e8360df00c | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | permissive | rmjarvis/TreeCorr | f607eca752de6f88b9a9625de61725f232d8d4e8 | 3b6b5b376e02cceac7f6c493c25cc397d8a41454 | refs/heads/releases/4.3 | 2023-09-01T05:27:54.309814 | 2023-04-12T18:33:35 | 2023-04-12T18:33:35 | 22,117,429 | 98 | 42 | NOASSERTION | 2023-08-11T23:18:20 | 2014-07-22T19:19:26 | Python | UTF-8 | C++ | false | false | 40,156 | cpp | /* Copyright (c) 2003-2019 by Mike Jarvis
*
* TreeCorr is free software: 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 disclaimer given in the accompanying LICENSE
* file.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions, and the disclaimer given in the documentation
* and/or other materials provided with the distribution.
*/
//#define DEBUGLOGGING
#include <vector>
#include <cmath>
#include "Field.h"
#include "Cell.h"
#include "dbg.h"
extern "C" {
#ifdef _WIN32
#define extern __declspec(dllexport)
#endif
#include "Field_C.h"
}
// In BinnedCorr2.cpp
extern void SelectRandomFrom(long m, std::vector<long>& selection);
template <int D, int C>
void InitializeCentersTree(std::vector<Position<C> >& centers, const Cell<D,C>* cell,
long first, int ncenters)
{
xdbg<<"Recursive InitializeCentersTree: "<<first<<" "<<ncenters<<std::endl;
xdbg<<"pos = "<<cell->getPos()<<std::endl;
if (ncenters == 1) {
xdbg<<"Only 1 center. Use this cell.\n";
Assert(first < long(centers.size()));
xdbg<<"initial center["<<first<<"] = "<<cell->getPos()<<std::endl;
centers[first] = cell->getPos();
} else if (cell->getLeft()) {
int m1 = ncenters / 2;
int m2 = ncenters - m1;
double urd = urand();
if (urd < 0.5) std::swap(m1,m2);
// Note: If ncenters is even, this doesn't do anything, but if odd, then 50% chance
// that left side will get the extra one and 50% chance that right side will get it.
xdbg<<"Recurse with m1,m2 = "<<m1<<','<<m2<<std::endl;
InitializeCentersTree(centers, cell->getLeft(), first, m1);
InitializeCentersTree(centers, cell->getRight(), first + m1, m2);
} else {
dbg<<"BAD! Shouldn't happen. Probably shouldn't be running kmeans on this field.\n";
// Shouldn't ever happen -- this means a leaf is very close to the top.
// But still, let's do soemthing at least vaguely sensible if it does.
for (int i=0; i<ncenters; ++i) {
Assert(first+i < long(centers.size()));
centers[first+i] = Position<C>(cell->getPos()*(1. + urand() * 1.e-8));
}
}
xdbg<<"End of Recursive InitializeCentersTree\n";
}
template <int D, int C>
void InitializeCentersTree(std::vector<Position<C> >& centers, const std::vector<Cell<D,C>*>& cells,
long long seed)
{
dbg<<"Initialize centers: "<<centers.size()<<" "<<cells.size()<<std::endl;
long ncenters = centers.size();
long ncells = cells.size();
urand(seed); // Make sure rand is seeded properly.
if (ncells > ncenters) {
dbg<<"More cells than centers. Pick from them randomly.\n";
std::vector<long> selection(ncenters);
SelectRandomFrom(ncells, selection);
for (long i=0; i<ncenters; ++i) {
Assert(selection[i] < long(cells.size()));
centers[i] = cells[selection[i]]->getPos();
}
} else {
dbg<<"Fewer cells than centers. Recurse to get more than one from each.\n";
long n1 = ncenters / ncells;
long k2 = ncenters % ncells;
long n2 = n1 + 1;
long k1 = ncells - k2;
xdbg<<"n1 = "<<n1<<" n2 = "<<n2<<std::endl;
xdbg<<"k1 = "<<k1<<" k2 = "<<k2<<std::endl;
Assert(n1 >= 1);
Assert(n1 * k1 + n2 * k2 == ncenters);
// Distribute n1 and n2 in list k1 and k2 times respectively.
std::vector<long> nvalues(ncells);
for (long k=0; k<k1; ++k) nvalues[k] = n1;
for (long k=k1; k<ncells; ++k) nvalues[k] = n2;
// Shuffle the locations of n1, n2
// (Fisher-Yates algorithm)
for (long k=ncells; k>1; --k) {
long j = int(urand() * k);
if (j != k-1) std::swap(nvalues[j], nvalues[k-1]);
}
// Do the recursive initialization for each value of n1 in the list.
long first=0;
for (long k=0; k<ncells; ++k) {
Assert(first < ncenters);
InitializeCentersTree(centers, cells[k], first, nvalues[k]);
first += nvalues[k];
}
Assert(first == ncenters);
}
xdbg<<"Done initializing centers\n";
}
template <int D, int C>
void InitializeCentersRand(std::vector<Position<C> >& centers, const std::vector<Cell<D,C>*>& cells,
long long seed)
{
dbg<<"Initialize centers (random): "<<centers.size()<<" "<<cells.size()<<std::endl;
// Pick npatch random numbers from the total number of objecst.
long ncenters = centers.size();
long ncells = cells.size();
long ntot = 0;
for (long k=0; k<ncells; ++k) ntot += cells[k]->getN();
xdbg<<"ntot = "<<ntot<<std::endl;
urand(seed); // Make sure rand is seeded properly.
// Find ncenters different indices from 0..ntot-1.
std::vector<long> index(ncenters);
SelectRandomFrom(ntot, index);
// Select the position of the leaf with this index.
// Note: these aren't the same as the "index" that is stored from the original catalog.
// These are the index in a kind of arbitrary ordering of the final tree structure.
for (long i=0; i<ncenters; ++i) {
dbg<<"Pick random center "<<i<<" index = "<<index[i]<<std::endl;
long m = index[i];
for (long k=0; k<ncells; ++k) {
if (m < cells[k]->getN()) {
const Cell<D,C>* c = cells[k]->getLeafNumber(m);
centers[i] = c->getPos();
xdbg<<" k = "<<k<<", m = "<<m<<" cen = "<<centers[i]<<std::endl;
break;
} else {
m -= cells[k]->getN();
xdbg<<" N["<<k<<"] = "<<cells[k]->getN()<<" m -> "<<m<<std::endl;
}
}
// It is technically possible that some centers will repeat if a leaf has multiple
// points in it. Then two different index values could both point to the same leaf.
// This should be rare, but guard against it by arbitrarily shifting the second value
// by a random small value.
for (long i1=0; i1<i; ++i1) {
if (centers[i1] == centers[i]) {
dbg<<"Found duplicate center!\n";
centers[i] *= (1. + urand() * 1.e-8);
}
}
}
}
template <int D, int C>
Position<C> InitializeCentersKMPP(const Cell<D,C>* cell,
const std::vector<Position<C> >& centers, long ncen)
{
struct LeafAlreadyUsed {};
xdbg<<"Start recursive InitializeCentersKMPP\n";
// If we are in a leaf, then return this position as the next center to use.
if (cell->getSize() == 0) {
// Check that we haven't already used this leaf as a center
for (long j=0; j<ncen; ++j) {
if (cell->getPos() == centers[j]) {
dbg<<"Already used this leaf as a center\n";
throw LeafAlreadyUsed();
}
}
return cell->getPos();
}
// If not, then we choose which subcell to recurse to based on the relative dsq values
// to each daughter's closest center.
const Cell<D,C>* left = cell->getLeft();
const Cell<D,C>* right = cell->getRight();
double dsq1 = (left->getPos() - centers[0]).normSq();
double dsq2 = (right->getPos() - centers[0]).normSq();
for (long j=1; j<ncen; ++j) {
double dsq1j = (left->getPos() - centers[j]).normSq();
double dsq2j = (right->getPos() - centers[j]).normSq();
if (dsq1j < dsq1) dsq1 = dsq1j;
if (dsq2j < dsq2) dsq2 = dsq2j;
}
xdbg<<"dsq1 = "<<dsq1<<", dsq2 = "<<dsq2<<std::endl;
if (dsq1 + dsq2 == 0.) {
dbg<<"All used. Throw exception and try other branch.\n";
xdbg<<"N1 = "<<left->getN()<<" N2 = "<<right->getN()<<std::endl;
throw LeafAlreadyUsed();
}
double u = urand() * (dsq1 + dsq2);
if (u < dsq1) {
xdbg<<"u = "<<u<<", recurse left\n";
try {
return InitializeCentersKMPP(left, centers, ncen);
} catch (LeafAlreadyUsed) {
dbg<<"Caught LeafAlreadyUsed.\n";
return InitializeCentersKMPP(right, centers, ncen);
}
} else {
xdbg<<"u = "<<u<<", recurse right\n";
try {
return InitializeCentersKMPP(right, centers, ncen);
} catch (LeafAlreadyUsed) {
dbg<<"Caught LeafAlreadyUsed.\n";
return InitializeCentersKMPP(left, centers, ncen);
}
}
}
template <int D, int C>
void InitializeCentersKMPP(std::vector<Position<C> >& centers, const std::vector<Cell<D,C>*>& cells,
long long seed)
{
// cf. https://en.wikipedia.org/wiki/K-means%2B%2B
// The basic KMeans++ algorithm is as follows:
// 1. Pick the first center at random.
// 2. For subsequent centers, calculate all d_i = the distance to the nearest center
// picked so far.
// 3. Select the next center randomly with probability proportional to d_i^2.
// 4. Repeat 2,3 until all centers are selected.
//
// We modify this algorithm slightly to make it reasonably efficient. Rather than actually
// calculating all the distances each time, we traverse the tree and pick the direction to
// go according to the distances to the centers of the cell at each point. It's not quite the
// same thing, but it's pretty close.
dbg<<"Initialize centers (kmeans++): "<<centers.size()<<" "<<cells.size()<<std::endl;
long ncenters = centers.size();
long ncells = cells.size();
urand(seed); // Make sure rand is seeded properly.
long ntot = 0;
for (long k=0; k<ncells; ++k) ntot += cells[k]->getN();
xdbg<<"ntot = "<<ntot<<std::endl;
// Keep track of how many centers are assigned from each cell.
std::vector<long> centers_per_cell(ncells, 0);
// Pick the first point
long m = long(urand() * ntot);
xdbg<<"m = "<<m<<std::endl;
for (long k=0; k<ncells; ++k) {
if (m < cells[k]->getN()) {
dbg<<"Pick first center from cell "<<k<<std::endl;
centers[0] = cells[k]->getLeafNumber(m)->getPos();
xdbg<<"center[0] = "<<centers[0]<<std::endl;
centers_per_cell[k] += 1;
break;
} else {
m -= cells[k]->getN();
}
}
// Pick the rest of the points
for (long i=1; i<ncenters; ++i) {
xdbg<<"Start work on center "<<i<<std::endl;
// Calculate the dsq for each top level cell, to calculate the probability of choosing it.
std::vector<double> p(ncells);
double sump=0.; // to normalize probabilities
for (long k=0; k<ncells; ++k) {
double dsq1 = (centers[0] - cells[k]->getPos()).normSq();
xdbg<<" dsq[0] = "<<dsq1<<std::endl;
for (long i1=1; i1<i; ++i1) {
double dsq2 = (centers[i1] - cells[k]->getPos()).normSq();
xdbg<<" dsq["<<i1<<"] = "<<dsq2<<std::endl;
if (dsq2 < dsq1) dsq1 = dsq2;
}
xdbg<<"Cell "<<k<<" has dsq = "<<dsq1<<std::endl;
// The probability of picking each point is proportional to its dsq.
// Approximate that all points in a cell are closest to the same center, and that
// the points are uniformly distibuted in either a circle or a sphere (according to C)
// Then the sum of all the dsq of a cell is
// dsq = N (d^2 + 1/2 s^2) for a circle
// = N (d^2 + 3/5 s^2) for a sphere
// If N is smallish, then we want to make sure we subtract off the number of centers
// that are already in the cell.
// TODO: This could be improved for the case where there is more than 1 center already
// in the cell. The current formula is a significant over-estimate in that case.
// Not sure how important it is though, since I think the Tree initialization is
// normally better, so this is not a very important use case.
const double coef = C == ThreeD ? 0.6 : 0.5;
p[k] = (cells[k]->getN() -
centers_per_cell[k]) * (dsq1 + coef * SQR(cells[k]->getSize()));
sump += p[k];
}
double u = urand();
xdbg<<"u = "<<u<<std::endl;
for (long k=0; k<ncells; ++k) {
p[k] /= sump;
xdbg<<"Prob("<<k<<") = "<<p[k]<<std::endl;
if (u < p[k]) {
dbg<<"Choose next center from cell "<<k<<std::endl;
xdbg<<"N = "<<cells[k]->getN()<<" ncen so far = "<<centers_per_cell[k]<<std::endl;
centers[i] = InitializeCentersKMPP(cells[k], centers, ncenters);
xdbg<<"center["<<i<<"] = "<<centers[i]<<std::endl;
centers_per_cell[k] += 1;
break;
} else {
u -= p[k];
xdbg<<"u -> "<<u<<std::endl;
Assert(k != ncells-1);
}
}
}
}
template <int D, int C>
struct StoreCells
{
int npatch;
std::vector<std::vector<const Cell<D,C>*> > cells_by_patch;
StoreCells(int _npatch) : npatch(_npatch), cells_by_patch(npatch) {}
void run(int patch_num, const Cell<D,C>* cell)
{
cells_by_patch[patch_num].push_back(cell);
}
void combineWith(const StoreCells<D,C>& rhs)
{
for (int i=0; i<npatch; ++i)
cells_by_patch[i].insert(cells_by_patch[i].end(),
rhs.cells_by_patch[i].begin(),
rhs.cells_by_patch[i].end());
}
void finalize() {}
void reset()
{
for (int i=0;i<npatch;++i) cells_by_patch[i].clear();
}
};
template <int D, int C>
struct UpdateCenters
{
int npatch;
std::vector<Position<C> > new_centers;
std::vector<double> w;
UpdateCenters(int _npatch) : npatch(_npatch), new_centers(npatch), w(npatch) {}
void run(int patch_num, const Cell<D,C>* cell)
{
new_centers[patch_num] += cell->getPos() * cell->getW();
w[patch_num] += cell->getW();
}
void combineWith(const UpdateCenters<D,C>& rhs)
{
for (int i=0; i<npatch; ++i) {
new_centers[i] += rhs.new_centers[i];
w[i] += rhs.w[i];
}
}
void finalize()
{
for (int i=0; i<npatch; ++i) {
if (w[i] > 0.) {
new_centers[i] /= w[i];
new_centers[i].normalize();
}
xdbg<<"New center = "<<new_centers[i]<<std::endl;
}
}
void reset()
{
for (int i=0;i<npatch;++i) new_centers[i] = Position<C>();
for (int i=0;i<npatch;++i) w[i] = 0.;
}
};
template <int D, int C>
struct CalculateInertia
{
int npatch;
std::vector<double> inertia;
double sumw;
const std::vector<Position<C> >& centers;
CalculateInertia(int _npatch, const std::vector<Position<C> >& _centers) :
npatch(_npatch), inertia(npatch,0.), sumw(0.), centers(_centers) {}
void run(int patch_num, const Cell<D,C>* cell)
{
double ssq = SQR(cell->getSize());
double w = cell->getW();
inertia[patch_num] += (cell->getPos() - centers[patch_num]).normSq() * w;
// Parallel axis theorem says we should add the inertia of this cell about its own
// centroid. We can calculate that with cell->calculateInertia(), but for small cells,
// it is close to I = w s^2, and for large cells (assuming uniform density of points)
// it is close to I = 0.5 w s^2. Splitting the difference works fairly well and is much
// faster than the full calculateInertia() method.
if (ssq > 0.) {
double I1 = 0.75 * ssq * w;
#ifdef DEBUGLOGGING
double I2 = cell->calculateInertia();
xdbg<<"ssq, I1, I2 = "<<ssq<<" "<<I1<<" "<<I2<<std::endl;
#endif
inertia[patch_num] += I1;
}
sumw += w;
}
void combineWith(const CalculateInertia<D,C>& rhs)
{
for (int i=0; i<npatch; ++i) {
inertia[i] += rhs.inertia[i];
}
sumw += rhs.sumw;
}
void finalize()
{
#ifdef DEBUGLOGGING
double mean=0.;
double rms=0.;
#endif
// The 3 here is empirical, but fairly good results were obtained with this factor
// being anywhere from 2 to 4. 4 was actually slgihtly better, but above 4, the
// iterations could turn unstable and neighboring patches could alternate grabbing
// more and more area back and forth until one patch had no points.
// So to avoid getting near this instability, we use 3 rather than 4, which we believe
// is usually safe.
double meanw = sumw / npatch / 3.;
for (int i=0; i<npatch; ++i) {
#ifdef DEBUGLOGGING
xdbg<<"Inertia["<<i<<"] = "<<inertia[i]<<std::endl;
mean += inertia[i];
rms += SQR(inertia[i]);
#endif
inertia[i] /= meanw;
}
#ifdef DEBUGLOGGING
mean /= npatch;
rms -= npatch * SQR(mean);
rms = sqrt(rms / npatch);
xdbg<<"mean inertia = "<<mean<<std::endl;
xdbg<<"rms inertia = "<<rms<<std::endl;
#endif
}
void reset()
{
for (int i=0;i<npatch;++i) inertia[i] = 0.;
sumw = 0.;
}
};
template <int D, int C>
struct AssignPatches
{
long* patches;
long n;
#ifdef DEBUGLOGGING
const std::vector<Position<C> >& centers;
std::vector<double> inertia;
#endif
AssignPatches(long* _patches, long _n, const std::vector<Position<C> >& _c) :
patches(_patches), n(_n)
#ifdef DEBUGLOGGING
, centers(_c), inertia(_c.size())
#endif
{}
void run(int patch_num, const Cell<D,C>* cell)
{
xdbg<<"Start AssignPatches "<<cell<<" "<<patch_num<<std::endl;
if (cell->getLeft()) {
xdbg<<"Not a leaf. Recurse\n";
run(patch_num, cell->getLeft());
run(patch_num, cell->getRight());
} else if (cell->getN() == 1) {
long index = cell->getInfo().index;
xdbg<<"N=1. index = "<<index<<std::endl;
Assert(index < n);
patches[index] = patch_num;
#ifdef DEBUGLOGGING
inertia[patch_num] += (cell->getPos() - centers[patch_num]).normSq() * cell->getW();
#endif
} else {
std::vector<long>* indices = cell->getListInfo().indices;
xdbg<<"Leaf with N>1. "<<indices->size()<<" indices\n";
for (size_t j=0; j<indices->size(); ++j) {
long index = (*indices)[j];
xdbg<<" index = "<<index<<std::endl;
Assert(index < n);
patches[index] = patch_num;
}
#ifdef DEBUGLOGGING
inertia[patch_num] += (cell->getPos() - centers[patch_num]).normSq() * cell->getW();
#endif
}
}
void combineWith(const AssignPatches<D,C>& rhs)
{
#ifdef DEBUGLOGGING
int npatch = centers.size();
for (int i=0; i<npatch; ++i) {
inertia[i] += rhs.inertia[i];
}
#endif
}
void finalize()
{
#ifdef DEBUGLOGGING
double mean=0.;
double rms=0.;
int npatch = centers.size();
dbg<<"Finalize AssignPatches\n";
for (int i=0; i<npatch; ++i) {
xdbg<<"Inertia["<<i<<"] = "<<inertia[i]<<std::endl;
mean += inertia[i];
rms += SQR(inertia[i]);
}
mean /= npatch;
rms -= npatch * SQR(mean);
rms = sqrt(rms / npatch);
dbg<<"mean inertia = "<<mean<<std::endl;
dbg<<"rms inertia = "<<rms<<std::endl;
#endif
}
void reset() {}
};
template <int D, int C, typename F>
void FindCellsInPatches(const std::vector<Position<C> >& centers,
const Cell<D,C>* cell, std::vector<long>& patches, long ncand,
std::vector<double>& saved_dsq, F& f,
const std::vector<double>* inertia)
{
//set_verbose(2);
xdbg<<"Start recursive FindCellsInPatches\n";
// First find the center that is closest to the current cell's center
const Position<C> cell_center = cell->getPos();
double s = cell->getSize();
xdbg<<"cell = "<<cell_center<<" "<<s<<" "<<cell->getN()<<std::endl;
// Start with a guess that the closest one is in the first position.
double closest_i = patches[0];
double min_dsq = (cell_center - centers[closest_i]).normSq();
saved_dsq[0] = min_dsq;
if (inertia) {
xdbg<<"Initial min_dsq = "<<min_dsq<<", I = "<<(*inertia)[closest_i]<<std::endl;
min_dsq += (*inertia)[closest_i];
xdbg<<" min_dsq => "<<min_dsq<<std::endl;
}
// Note: saved_dsq is really the d^2 values.
// min_dsq is the minimum value of the possibly modified distance:
// dsq for alt = False.
// dsq + I_i for alt = True.
// Look for closer center
for (long j=1; j<ncand; ++j) {
long i=patches[j];
double dsq = (cell_center - centers[i]).normSq();
saved_dsq[j] = dsq;
if (inertia) {
xdbg<<"dsq = "<<dsq<<", I = "<<(*inertia)[i]<<std::endl;
dsq += (*inertia)[i];
xdbg<<" dsq => "<<dsq<<std::endl;
}
xdbg<<"dsq["<<i<<"] = "<<dsq<<", min = "<<min_dsq<<std::endl;
if (dsq < min_dsq) {
std::swap(saved_dsq[0], saved_dsq[j]);
std::swap(patches[0], patches[j]);
closest_i = i;
min_dsq = dsq;
}
}
double min_d = sqrt(saved_dsq[0]);
xdbg<<"closest center = "<<closest_i<<" "<<centers[closest_i]<<std::endl;
xdbg<<"min_d = "<<min_d<<" min_dsq = "<<min_dsq<<std::endl;
double thresh_dsq;
if (!inertia) {
// Can remove any candidate with d - size > min_d + size
thresh_dsq = SQR(min_d + 2*s);
} else {
// When using inertia, it is slightly more complicated.
// (d_i-s)^2 + I_i > (min_d+s)^2 + I_0
// Since this involved the specific I_i in each step, it's simpler to just
// calculate the left side specifically for each patch.
thresh_dsq = SQR(min_d + s) + (*inertia)[closest_i];
}
xdbg<<"thresh_dsq = "<<thresh_dsq<<std::endl;
// Update patches to remove any that cannot be the right center from candidate section.
for (long j=ncand-1; j>0; --j) {
double dsq = saved_dsq[j];
if (inertia) {
double d = sqrt(dsq);
// If s > d, then the normal calculation doesn't apply. Use dsq = 0.
if (s > d)
dsq = 0.;
else
dsq = SQR(d-s) + (*inertia)[patches[j]];
}
xdbg<<"Check: "<<dsq<<" >? "<<thresh_dsq<<std::endl;
if (dsq > thresh_dsq) {
if (patches[j] < 2) {
xdbg<<"Remove cell with center "<<centers[patches[j]]<<std::endl;
xdbg<<"cell = "<<cell_center<<" "<<s<<" "<<cell->getN()<<std::endl;
xdbg<<dsq<<" > "<<thresh_dsq<<std::endl;
xdbg<<"min_d = "<<min_d<<std::endl;
}
--ncand;
if (j != ncand) {
std::swap(patches[j], patches[ncand]);
// Don't bother with saved_dsq, since don't need that anymore.
}
}
}
xdbg<<"There are "<<ncand<<" patches remaining\n";
//set_verbose(1);
if (ncand == 1 || s == 0.) {
// If we only have one candidate left, we're done. Use this cell to update this patch.
f.run(closest_i, cell);
} else {
// Otherwise, need to recurse to sub-cells.
FindCellsInPatches(centers, cell->getLeft(), patches, ncand, saved_dsq, f, inertia);
// Note: the above call might have swapped some patches around, but only within the
// first ncand values, so they are still valid for the next call.
FindCellsInPatches(centers, cell->getRight(), patches, ncand, saved_dsq, f, inertia);
}
}
// This recurses the tree until if finds a cell that completely belongs in only a single
// patch and then runs f, which can be any of the above function classes.
template <int D, int C, typename F>
void FindCellsInPatches(const std::vector<Position<C> >& centers,
const std::vector<Cell<D,C>*>& cells, F& f,
const std::vector<double>* inertia=0)
{
#ifdef _OPENMP
#pragma omp parallel
{
// Give each thread their own copy of f to use.
F f2 = f;
#else
F& f2 = f;
#endif
// We start with all patches as candidates.
int npatch = centers.size();
std::vector<long> patches(npatch);
for (int i=0; i<npatch; ++i) patches[i] = i;
// Set up a work space where we save dsq calculations.
std::vector<double> saved_dsq(npatch);
// Start a recursion for each top-level cell.
#ifdef _OPENMP
#pragma omp for schedule(static)
#endif
for (size_t k=0; k<cells.size(); ++k) {
FindCellsInPatches(centers, cells[k], patches, npatch, saved_dsq, f2, inertia);
}
#ifdef _OPENMP
// Combine the results
#pragma omp critical
{
f.combineWith(f2);
}
}
#endif
}
template <int C>
double CalculateShiftSq(const std::vector<Position<C> >& centers,
const std::vector<Position<C> >& new_centers)
{
xdbg<<"Start CalculateShiftSq\n";
double shiftsq=0.;
for (size_t i=0; i<centers.size(); ++i) {
double shiftsq_i = (centers[i] - new_centers[i]).normSq();
xdbg<<"Shift for "<<i<<" = "<<centers[i]<<" -> "<<new_centers[i]<<" d = "<<sqrt(shiftsq_i)<<std::endl;
shiftsq += shiftsq_i;
}
xdbg<<"Total shiftsq = "<<shiftsq<<std::endl;
return shiftsq;
}
// C = Threed or Sphere
template <int C>
void WriteCenters(const std::vector<Position<C> >& centers, double* pycenters, int npatch)
{
for(int i=0; i<npatch; ++i, pycenters+=3) {
pycenters[0] = centers[i].getX();
pycenters[1] = centers[i].getY();
pycenters[2] = centers[i].getZ();
}
}
template <int C>
void ReadCenters(std::vector<Position<C> >& centers, const double* pycenters, int npatch)
{
for(int i=0; i<npatch; ++i, pycenters+=3) {
centers[i] = Position<C>(pycenters[0], pycenters[1], pycenters[2]);
}
}
// C = Flat
template <>
void WriteCenters(const std::vector<Position<Flat> >& centers, double* pycenters, int npatch)
{
for(int i=0; i<npatch; ++i, pycenters+=2) {
pycenters[0] = centers[i].getX();
pycenters[1] = centers[i].getY();
}
}
template <>
void ReadCenters(std::vector<Position<Flat> >& centers, const double* pycenters, int npatch)
{
for(int i=0; i<npatch; ++i, pycenters+=2) {
centers[i] = Position<Flat>(pycenters[0], pycenters[1]);
}
}
template <int D, int C>
void KMeansInitTree2(Field<D,C>*field, double* pycenters, int npatch, long long seed)
{
dbg<<"Start KMeansInitTree for "<<npatch<<" patches\n";
const std::vector<Cell<D,C>*> cells = field->getCells();
std::vector<Position<C> > centers(npatch);
InitializeCentersTree(centers, cells, seed);
WriteCenters(centers, pycenters, npatch);
}
template <int D, int C>
void KMeansInitRand2(Field<D,C>*field, double* pycenters, int npatch, long long seed)
{
dbg<<"Start KMeansInitRand for "<<npatch<<" patches\n";
const std::vector<Cell<D,C>*> cells = field->getCells();
std::vector<Position<C> > centers(npatch);
InitializeCentersRand(centers, cells, seed);
WriteCenters(centers, pycenters, npatch);
}
template <int D, int C>
void KMeansInitKMPP2(Field<D,C>*field, double* pycenters, int npatch, long long seed)
{
dbg<<"Start KMeansInitKMPP for "<<npatch<<" patches\n";
const std::vector<Cell<D,C>*> cells = field->getCells();
std::vector<Position<C> > centers(npatch);
InitializeCentersKMPP(centers, cells, seed);
WriteCenters(centers, pycenters, npatch);
}
template <int D, int C>
void KMeansRun2(Field<D,C>*field, double* pycenters, int npatch, int max_iter, double tol,
bool alt)
{
dbg<<"Start KMeansRun for "<<npatch<<" patches\n";
const std::vector<Cell<D,C>*> cells = field->getCells();
// Initialize the centers of the patches smartly according to the tree structure.
std::vector<Position<C> > centers(npatch);
ReadCenters(centers, pycenters, npatch);
// We compare the total shift^2 to this number
// Want rms shift / field.size < tol
// So sqrt(total_shift^2 / npatch) / field.size < tol
// total_shift^2 < tol^2 * size^2 * npatch
double tolsq = SQR(tol * field->getSize()) * npatch;
xdbg<<"tolsq = "<<tolsq<<std::endl;
// The alt version needs to keep track of the inertia of each patch.
CalculateInertia<D,C> calculate_inertia(alt ? npatch : 0, centers);
std::vector<double>* pinertia = 0;
xdbg<<"Made calculate_inertia\n";
// Keep track of which cells belong to which patch.
UpdateCenters<D,C> update_centers(npatch);
xdbg<<"Made update_centers\n";
for(int iter=0; iter<max_iter; ++iter) {
xdbg<<"Start iter "<<iter<<std::endl;
// Update the inertia if we are doing the alternate version
if (alt) {
calculate_inertia.reset();
FindCellsInPatches(centers, cells, calculate_inertia);
calculate_inertia.finalize();
pinertia = &calculate_inertia.inertia;
}
// Figure out which cells belong to which patch according to the current centers.
// Note: clear leaves the previous capacity available, so usually won't need much
// in the way of allocation here.
update_centers.reset();
FindCellsInPatches(centers, cells, update_centers, pinertia);
update_centers.finalize();
xdbg<<"After UpdateCenters\n";
// Check for convergence
double shiftsq = CalculateShiftSq(centers, update_centers.new_centers);
centers = update_centers.new_centers;
xdbg<<"Iter "<<iter<<": shiftsq = "<<shiftsq<<" tolsq = "<<tolsq<<std::endl;
// Stop if (rms shift / size) < tol
if (shiftsq < tolsq) {
dbg<<"Stopping RunKMeans because rms shift = "<<sqrt(shiftsq/npatch)<<std::endl;
dbg<<"tol * size = "<<tol * field->getSize()<<std::endl;
break;
}
if (iter == max_iter-1) {
dbg<<"Stopping RunKMeans because hit maximum iterations = "<<max_iter<<std::endl;
}
}
WriteCenters(centers, pycenters, npatch);
}
template <int D, int C>
void KMeansAssign2(Field<D,C>*field, double* pycenters, int npatch, long* patches, long n)
{
dbg<<"Start KMeansAssign for "<<npatch<<" patches\n";
const std::vector<Cell<D,C>*> cells = field->getCells();
std::vector<Position<C> > centers(npatch);
ReadCenters(centers, pycenters, npatch);
xdbg<<"Start AssignPatches\n";
AssignPatches<D,C> assign_patches(patches, n, centers);
FindCellsInPatches(centers, cells, assign_patches);
assign_patches.finalize();
xdbg<<"After AssignPatches\n";
}
template <int D>
void KMeansInitTree1(void* field, double* centers, int npatch, int coords, long long seed)
{
switch(coords) {
case Flat:
KMeansInitTree2(static_cast<Field<D,Flat>*>(field), centers, npatch, seed);
break;
case Sphere:
KMeansInitTree2(static_cast<Field<D,Sphere>*>(field), centers, npatch, seed);
break;
case ThreeD:
KMeansInitTree2(static_cast<Field<D,ThreeD>*>(field), centers, npatch, seed);
break;
}
}
void KMeansInitTree(void* field, double* centers, int npatch, int d, int coords, long long seed)
{
switch(d) {
case NData:
KMeansInitTree1<NData>(field, centers, npatch, coords, seed);
break;
case KData:
KMeansInitTree1<KData>(field, centers, npatch, coords, seed);
break;
case GData:
KMeansInitTree1<GData>(field, centers, npatch, coords, seed);
break;
}
}
template <int D>
void KMeansInitRand1(void* field, double* centers, int npatch, int coords, long long seed)
{
switch(coords) {
case Flat:
KMeansInitRand2(static_cast<Field<D,Flat>*>(field), centers, npatch, seed);
break;
case Sphere:
KMeansInitRand2(static_cast<Field<D,Sphere>*>(field), centers, npatch, seed);
break;
case ThreeD:
KMeansInitRand2(static_cast<Field<D,ThreeD>*>(field), centers, npatch, seed);
break;
}
}
void KMeansInitRand(void* field, double* centers, int npatch, int d, int coords, long long seed)
{
switch(d) {
case NData:
KMeansInitRand1<NData>(field, centers, npatch, coords, seed);
break;
case KData:
KMeansInitRand1<KData>(field, centers, npatch, coords, seed);
break;
case GData:
KMeansInitRand1<GData>(field, centers, npatch, coords, seed);
break;
}
}
template <int D>
void KMeansInitKMPP1(void* field, double* centers, int npatch, int coords, long long seed)
{
switch(coords) {
case Flat:
KMeansInitKMPP2(static_cast<Field<D,Flat>*>(field), centers, npatch, seed);
break;
case Sphere:
KMeansInitKMPP2(static_cast<Field<D,Sphere>*>(field), centers, npatch, seed);
break;
case ThreeD:
KMeansInitKMPP2(static_cast<Field<D,ThreeD>*>(field), centers, npatch, seed);
break;
}
}
void KMeansInitKMPP(void* field, double* centers, int npatch, int d, int coords, long long seed)
{
switch(d) {
case NData:
KMeansInitKMPP1<NData>(field, centers, npatch, coords, seed);
break;
case KData:
KMeansInitKMPP1<KData>(field, centers, npatch, coords, seed);
break;
case GData:
KMeansInitKMPP1<GData>(field, centers, npatch, coords, seed);
break;
}
}
template <int D>
void KMeansRun1(void* field, double* centers, int npatch, int max_iter, double tol, bool alt,
int coords)
{
switch(coords) {
case Flat:
KMeansRun2(static_cast<Field<D,Flat>*>(field), centers, npatch, max_iter, tol, alt);
break;
case Sphere:
KMeansRun2(static_cast<Field<D,Sphere>*>(field), centers, npatch, max_iter, tol, alt);
break;
case ThreeD:
KMeansRun2(static_cast<Field<D,ThreeD>*>(field), centers, npatch, max_iter, tol, alt);
break;
}
}
void KMeansRun(void* field, double* centers, int npatch, int max_iter, double tol, int alt,
int d, int coords)
{
switch(d) {
case NData:
KMeansRun1<NData>(field, centers, npatch, max_iter, tol, bool(alt), coords);
break;
case KData:
KMeansRun1<KData>(field, centers, npatch, max_iter, tol, bool(alt), coords);
break;
case GData:
KMeansRun1<GData>(field, centers, npatch, max_iter, tol, bool(alt), coords);
break;
}
}
template <int D>
void KMeansAssign1(void* field, double* centers, int npatch, long* patches, long n, int coords)
{
switch(coords) {
case Flat:
KMeansAssign2(static_cast<Field<D,Flat>*>(field), centers, npatch, patches, n);
break;
case Sphere:
KMeansAssign2(static_cast<Field<D,Sphere>*>(field), centers, npatch, patches, n);
break;
case ThreeD:
KMeansAssign2(static_cast<Field<D,ThreeD>*>(field), centers, npatch, patches, n);
break;
}
}
void KMeansAssign(void* field, double* centers, int npatch, long* patches, long n,
int d, int coords)
{
switch(d) {
case NData:
KMeansAssign1<NData>(field, centers, npatch, patches, n, coords);
break;
case KData:
KMeansAssign1<KData>(field, centers, npatch, patches, n, coords);
break;
case GData:
KMeansAssign1<GData>(field, centers, npatch, patches, n, coords);
break;
}
}
void QuickAssign(double* centers, int npatch,
double* x, double* y, double* z, long* patches, long n)
{
if (z) {
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int i=0; i<n; ++i) {
int kmin = 0;
double min_rsq = SQR(x[i]-centers[0]) + SQR(y[i]-centers[1]) + SQR(z[i]-centers[2]);
for (int k=1; k<npatch; ++k) {
double rsq = SQR(x[i]-centers[3*k]) + SQR(y[i]-centers[3*k+1]) + SQR(z[i]-centers[3*k+2]);
if (rsq < min_rsq) {
kmin = k;
min_rsq = rsq;
}
}
patches[i] = kmin;
}
} else {
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int i=0; i<n; ++i) {
int kmin = 0;
double min_rsq = SQR(x[i]-centers[0]) + SQR(y[i]-centers[1]);
for (int k=1; k<npatch; ++k) {
double rsq = SQR(x[i]-centers[2*k]) + SQR(y[i]-centers[2*k+1]);
if (rsq < min_rsq) {
kmin = k;
min_rsq = rsq;
}
}
patches[i] = kmin;
}
}
}
void SelectPatch(int patch, double* centers, int npatch, double* x, double* y, double* z,
long* use, long n)
{
// Notation: p = the good patch we are looking for
// q = other patches
// if p is the closest, then use = 1, else use = 0.
if (z) {
// 3d version
double px = centers[3*patch];
double py = centers[3*patch+1];
double pz = centers[3*patch+2];
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int i=0; i<n; ++i) {
double p_dsq = SQR(x[i]-px) + SQR(y[i]-py) + SQR(z[i]-pz);
use[i] = 1;
for (int q=0; q<npatch; ++q) {
if (q == patch) continue;
double qx = centers[3*q];
double qy = centers[3*q+1];
double qz = centers[3*q+2];
double q_dsq = SQR(x[i]-qx) + SQR(y[i]-qy) + SQR(z[i]-qz);
if (q_dsq < p_dsq) {
use[i] = 0;
break;
}
}
}
} else {
// 2d version
double px = centers[2*patch];
double py = centers[2*patch+1];
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int i=0; i<n; ++i) {
double p_dsq = SQR(x[i]-px) + SQR(y[i]-py);
use[i] = 1;
for (int q=0; q<npatch; ++q) {
if (q == patch) continue;
double qx = centers[2*q];
double qy = centers[2*q+1];
double q_dsq = SQR(x[i]-qx) + SQR(y[i]-qy);
if (q_dsq < p_dsq) {
use[i] = 0;
break;
}
}
}
}
}
void GenerateXYZ(double* x, double* y, double* z, double* ra, double* dec, double* r, long n)
{
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int i=0; i<n; ++i) {
double sr, cr, sd, cd;
#ifdef _GLIBCXX_HAVE_SINCOS
::sincos(ra[i],&sr,&cr);
::sincos(dec[i],&sd,&cd);
#else
// If the native sincos function isn't available, then most compilers will still optimize
// these into a single trig call for each.
sr = std::sin(ra[i]);
cr = std::cos(ra[i]);
sd = std::sin(dec[i]);
cd = std::cos(dec[i]);
#endif
x[i] = cd * cr;
y[i] = cd * sr;
z[i] = sd;
if (r) {
x[i] *= r[i];
y[i] *= r[i];
z[i] *= r[i];
}
}
}
| [
"michael@jarvis.net"
] | michael@jarvis.net |
dcee1cc21e019322a95368c8b57bb19b8ff34b1d | 7cccf08fd75619d9edf7e4d651be7c17cb166717 | /DisplayImage.cpp | 6df3e1cfe3a70c9220d04cc1b2130415d9c65b6a | [] | no_license | skho513/Chocolate-Detection-and-Analysis | f4c2f190267da203afdf286993bef53b6c0cac46 | ae9f4780090ab84975fea55ba6b670fc4d648957 | refs/heads/master | 2021-01-02T09:21:30.291151 | 2017-08-03T06:26:11 | 2017-08-03T06:26:11 | 99,194,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,618 | cpp | #include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/opencv.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <vector>
#include <string>
#include <math.h>
using namespace cv;
using namespace std;
Mat src; Mat src_HSV;
Mat src2; Mat src2_gray;
RNG rng(12345);
void drawCircles(Mat red_hue_image, Mat green_hue_image, Mat white_hue_image, Mat yellow_hue_image, Mat blue_hue_image, Mat orig_image);
void thresh_callback(int, void*);
int main( int argc, char** argv )
{
/// Load source image
src = imread( argv[1], 1 );
src2 = imread( argv[2], 1);
cvtColor(src2, src2_gray, CV_BGR2GRAY);
blur(src2_gray, src2, Size(3,3));
thresh_callback(0, 0);
Mat copy_image = src.clone();
medianBlur(src, src, 3);
/// Convert image to HSV and blur it
cvtColor( src, src_HSV, CV_BGR2HSV );
/// Threshold the HSV image, keep only red pixels
Mat red_hue_image;
inRange(src_HSV, Scalar(1,100,100), Scalar(8,255,255), red_hue_image);
// Threshold the HSV image, keep only green pixels
Mat green_hue_image;
inRange(src_HSV, Scalar(50,100,100), Scalar(70,255,255), green_hue_image);
// Threshold the HSV image, keep only white pixels
Mat white_hue_image;
inRange(src_HSV, Scalar(0,0,200), Scalar(179,100,255), white_hue_image);
// Threshold the HSV image, keep only yellow pixels
Mat yellow_hue_image;
inRange(src_HSV, Scalar(20,100,100), Scalar(30,255,255), yellow_hue_image);
// Threshold the HSV image, keep only blue pixels
Mat blue_hue_image;
inRange(src_HSV, Scalar(90,50,50), Scalar(100,255,255), blue_hue_image);
GaussianBlur(red_hue_image, red_hue_image, Size(9, 9), 2, 2);
GaussianBlur(green_hue_image, green_hue_image, Size(9, 9), 2, 2);
GaussianBlur(white_hue_image, white_hue_image, Size(9, 9), 2, 2);
GaussianBlur(yellow_hue_image, yellow_hue_image, Size(9, 9), 2, 2);
GaussianBlur(blue_hue_image, blue_hue_image, Size(9, 9), 2, 2);
drawCircles(red_hue_image, green_hue_image, white_hue_image, yellow_hue_image, blue_hue_image, copy_image);
waitKey(0);
return(0);
}
void drawCircles(Mat red_hue_image, Mat green_hue_image, Mat white_hue_image, Mat yellow_hue_image, Mat blue_hue_image, Mat orig_image)
{
ofstream outputFile;
outputFile.open ("QuestionTwo_Output.txt");
// Use the Hough transform to detect circles in the combined threshold image
vector<Vec3f> circles;
// Red
HoughCircles(red_hue_image, circles, CV_HOUGH_GRADIENT, 1, red_hue_image.rows/20, 10, 20, 30, 60);
// Loop over all detected circles and outline them on the original image
for(size_t i = 0; i < circles.size(); ++i) {
Point center(round(circles[i][0]), round(circles[i][1]));
int radius = round(circles[i][2]);
// Circle outline
circle(orig_image, center, radius, Scalar(0, 0, 255), 5);
}
cout << "There are " << circles.size() << " red chocolate eggs" << endl;
outputFile << "There are " << circles.size() << " red chocolate eggs. \n" <<
endl;
// Green
HoughCircles(green_hue_image, circles, CV_HOUGH_GRADIENT, 1, green_hue_image.rows/11, 10, 20, 0, 100);
for(size_t i = 0; i < circles.size(); ++i) {
Point center(round(circles[i][0]), round(circles[i][1]));
int radius = round(circles[i][2]);
circle(orig_image, center, radius, Scalar(0, 255, 0), 5);
}
cout << "There are " << circles.size() << " green chocolate eggs" << endl;
outputFile << "\nThere are " << circles.size() << " green chocolate eggs. \n" << endl;
// White
HoughCircles(white_hue_image, circles, CV_HOUGH_GRADIENT, 1, white_hue_image.rows/15, 10, 20, 0, 100);
for(size_t i = 0; i < circles.size(); ++i) {
Point center(round(circles[i][0]), round(circles[i][1]));
int radius = round(circles[i][2]);
circle(orig_image, center, radius, Scalar(255, 255, 255), 5);
}
cout << "There are " << circles.size() << " white chocolate eggs" << endl;
outputFile << "There are " << circles.size() << " white chocolate eggs. \n" << endl;
// Yellow
HoughCircles(yellow_hue_image, circles, CV_HOUGH_GRADIENT, 1, yellow_hue_image.rows/11, 10, 20, 0, 100);
for(size_t i = 0; i < circles.size(); ++i) {
Point center(round(circles[i][0]), round(circles[i][1]));
int radius = round(circles[i][2]);
circle(orig_image, center, radius, Scalar(0, 255, 255), 5);
}
cout << "There are " << circles.size() << " yellow chocolate eggs" << endl;
outputFile << "There are " << circles.size() << " yellow chocolate eggs. \n" << endl;
// Blue
HoughCircles(blue_hue_image, circles, CV_HOUGH_GRADIENT, 1, blue_hue_image.rows/11, 10, 20, 0, 100);
for(size_t i = 0; i < circles.size(); ++i) {
Point center(round(circles[i][0]), round(circles[i][1]));
int radius = round(circles[i][2]);
circle(orig_image, center, radius, Scalar(255, 0, 0), 5);
}
cout << "There are " << circles.size() << " blue chocolate eggs" << endl;
outputFile << "There are " << circles.size() << " blue chocolate eggs. \n" << endl;
outputFile.close();
namedWindow("chocolate_eggs_marked", WINDOW_AUTOSIZE);
imshow("chocolate_eggs_marked", orig_image);
/// Save as JPG image file in the current directory
vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(95);
imwrite("chocolate_eggs_marked.jpg", orig_image, compression_params );
}
void thresh_callback(int, void* )
{
Mat threshold_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
/// Detect edges using Threshold
threshold( src2, threshold_output, 100, 255, THRESH_BINARY );
/// Find contours
findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
/// Find the rotated rectangles and ellipses for each contour
vector<RotatedRect> minRect( contours.size() );
vector<RotatedRect> minEllipse( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ minRect[i] = minAreaRect( Mat(contours[i]) );
// cout << minRect[i].points() "\n"<< endl;
if( contours[i].size() > 5 )
{ minEllipse[i] = fitEllipse( Mat(contours[i]) ); }
}
/// Draw contours + rotated rects + ellipses
Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
int width;
int hundred_pixels=(45000/450);
int good_eggs = 0;
int bad_eggs = 0;
for( int i = 0; i< contours.size(); i++ )
{
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
// contour
drawContours( drawing, contours, i, color, 1, 8, vector<Vec4i>(), 0, Point() );
// ellipse
ellipse( drawing, minEllipse[i], color, 2, 8 );
// rotated rectangle
Point2f rect_points[4];
minRect[i].points( rect_points );
for( int j = 0; j < 4; j++ )
{
line( drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8 );
// cout << rect_points[j].x << "," << rect_points[j].y << endl;
width = sqrt(pow(rect_points[(j+1)%4].x - rect_points[j].x, 2) + pow(rect_points[(j+1)%4].y - rect_points[j].y, 2));
// cout << width << endl;
// height = sqrt(pow(rect_points[(j+2)%4].x - rect_points[(j+1)%4].x, 2) + pow(rect_points[(j+2)%4].y - rect_points[(j+1)%4].y, 2));
if (width < hundred_pixels)
{
bad_eggs++;
}
else
{
good_eggs++;
}
}
}
cout << "There are "<< good_eggs <<" good eggs and " << bad_eggs << " bad_eggs" << endl;
char const* source_window = "Sorting objects by size";
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
imshow( source_window, drawing);
}
| [
"skho591@aucklanduni.ac.nz"
] | skho591@aucklanduni.ac.nz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.