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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8a3f19982f5084d19ca49a10930848a76f148de1 | 2780081bb046866b1449519cbe4dd78fbbf0719e | /XUL.framework/Versions/2.0/include/nsIDOMSVGAnimateTransformElement.h | 4d6df978eed9a2315bcffd9eef42d4e4e43a1399 | [] | no_license | edisonlee55/gluezilla-mac | d8b6535d2b36fc900eff837009372f033484a63f | 45d559edad7b5191430e139629d2aee918aa6654 | refs/heads/master | 2022-09-23T19:57:18.853517 | 2020-06-03T03:57:37 | 2020-06-03T03:57:37 | 267,499,676 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,416 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/rel-2.0-xr-osx64-bld/build/dom/interfaces/svg/nsIDOMSVGAnimateTransformElement.idl
*/
#ifndef __gen_nsIDOMSVGAnimateTransformElement_h__
#define __gen_nsIDOMSVGAnimateTransformElement_h__
#ifndef __gen_nsIDOMSVGAnimationElement_h__
#include "nsIDOMSVGAnimationElement.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIDOMSVGAnimateTransformElement */
#define NS_IDOMSVGANIMATETRANSFORMELEMENT_IID_STR "735e0f75-c6aa-4aee-bcd2-46426d6ac90c"
#define NS_IDOMSVGANIMATETRANSFORMELEMENT_IID \
{0x735e0f75, 0xc6aa, 0x4aee, \
{ 0xbc, 0xd2, 0x46, 0x42, 0x6d, 0x6a, 0xc9, 0x0c }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMSVGAnimateTransformElement : public nsIDOMSVGAnimationElement {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMSVGANIMATETRANSFORMELEMENT_IID)
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMSVGAnimateTransformElement, NS_IDOMSVGANIMATETRANSFORMELEMENT_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMSVGANIMATETRANSFORMELEMENT \
/* no methods! */
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMSVGANIMATETRANSFORMELEMENT(_to) \
/* no methods! */
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMSVGANIMATETRANSFORMELEMENT(_to) \
/* no methods! */
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMSVGAnimateTransformElement : public nsIDOMSVGAnimateTransformElement
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMSVGANIMATETRANSFORMELEMENT
nsDOMSVGAnimateTransformElement();
private:
~nsDOMSVGAnimateTransformElement();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMSVGAnimateTransformElement, nsIDOMSVGAnimateTransformElement)
nsDOMSVGAnimateTransformElement::nsDOMSVGAnimateTransformElement()
{
/* member initializers and constructor code */
}
nsDOMSVGAnimateTransformElement::~nsDOMSVGAnimateTransformElement()
{
/* destructor code */
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMSVGAnimateTransformElement_h__ */
| [
"edisonlee@edisonlee55.com"
] | edisonlee@edisonlee55.com |
273e75b669669937d9d3796ba75c6ce892c19874 | 94dcc118f9492896d6781e5a3f59867eddfbc78a | /llvm/include/llvm/DebugInfo/PDB/Raw/StreamReader.h | 1897dfe147452edf0c3e147cf920cb8e752b67d5 | [
"NCSA",
"Apache-2.0"
] | permissive | vusec/safeinit | 43fd500b5a832cce2bd87696988b64a718a5d764 | 8425bc49497684fe16e0063190dec8c3c58dc81a | refs/heads/master | 2021-07-07T11:46:25.138899 | 2021-05-05T10:40:52 | 2021-05-05T10:40:52 | 76,794,423 | 22 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,649 | h | //===- StreamReader.h - Reads bytes and objects from a stream ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_DEBUGINFO_PDB_RAW_STREAMREADER_H
#define LLVM_DEBUGINFO_PDB_RAW_STREAMREADER_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/DebugInfo/PDB/Raw/StreamInterface.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Error.h"
#include <string>
namespace llvm {
namespace pdb {
class StreamInterface;
class StreamReader {
public:
StreamReader(const StreamInterface &S);
Error readBytes(MutableArrayRef<uint8_t> Buffer);
Error readInteger(uint32_t &Dest);
Error readZeroString(std::string &Dest);
template <typename T> Error readObject(T *Dest) {
MutableArrayRef<uint8_t> Buffer(reinterpret_cast<uint8_t *>(Dest),
sizeof(T));
return readBytes(Buffer);
}
template <typename T> Error readArray(MutableArrayRef<T> Array) {
MutableArrayRef<uint8_t> Casted(reinterpret_cast<uint8_t*>(Array.data()), Array.size() * sizeof(T));
return readBytes(Casted);
}
Error getArrayRef(ArrayRef<uint8_t> &Array, uint32_t Length);
void setOffset(uint32_t Off) { Offset = Off; }
uint32_t getOffset() const { return Offset; }
uint32_t getLength() const { return Stream.getLength(); }
uint32_t bytesRemaining() const { return getLength() - getOffset(); }
private:
const StreamInterface &Stream;
uint32_t Offset;
};
}
}
#endif
| [
"fuzzie@fuzzie.org"
] | fuzzie@fuzzie.org |
82e03e9a6b39875f4c811c3a64be83218993d023 | bb4d0899650ec41875a93ce053b9854221283bba | /contests/paiza_s/002.cpp | 2b8f43b64fa141e5441ac49376abc5ccfd6390e3 | [] | no_license | moosan63/my_competitive_programmings | 9c41a9ac9a95c5f404b1e697c75650b4a0076a0f | e507b15659e9c629839165f0f265eb624df8bda2 | refs/heads/master | 2020-05-19T17:04:27.378309 | 2020-01-27T10:15:32 | 2020-01-27T10:15:32 | 185,125,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,241 | cpp | #include <algorithm>
#include <bitset>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define REP(i, b, n) for (Int i = b; i < Int(n); i++)
#define rep(i, n) REP(i, 0, n)
using namespace std;
using Int = long long;
Int inf = 1000000000000000001LL;
using vi = vector<Int>;
using vvi = vector<vi>;
int start_i, start_j;
int goal_i, goal_j;
int N,M;
vvi done_a;
vvi done_b;
vvi done_c;
vvi done_d;
vector<vector<char>> nm;
Int GCD(Int a, Int b){
if(b==0) return a;
if(a < b) return GCD(b, a);
unsigned r;
while ((r=a%b)) {
a = b;
b = r;
}
return b;
}
int dfs(int source_i, int source_j, int i, int j,Int cost){
if(i == goal_i && j == goal_j){
return cost;
}
if(nm[i][j]=='1'){
return 99999999;
}
int a=999999999,b=999999999,c=999999999,d=999999999;
if(i+1 != source_i && i<M-1 && done_a[i+1][j] != 1){
done_a[i+1][j] = 1;
a = dfs(i,j,i+1,j,cost+1);
}
if(i-1 != source_i && i>0 && done_b[i-1][j] != 1){
done_b[i-1][j] = 1;
b = dfs(i,j,i-1,j,cost+1);
}
if(j+1 != source_j && j<N-1 && done_c[i][j+1] != 1){
done_c[i][j+1] = 1;
c = dfs(i,j,i,j+1,cost+1);
}
if(j-1 != source_j && j>0 && done_d[i][j-1] != 1){
done_d[i][j-1] = 1;
d = dfs(i,j,i,j-1,cost+1);
}
return min(a,(min(b,min(c,d))));
}
int main() {
Int ans;
cin >> N >> M;
nm = vector<vector<char>>(M,vector<char>(N,'0'));
done_a = vvi(M,vi(N,0));
done_b = vvi(M,vi(N,0));
done_c = vvi(M,vi(N,0));
done_d = vvi(M,vi(N,0));
rep(i,M){
rep(j,N){
cin >> nm[i][j];
if(nm[i][j] == 's'){
start_i = i;
start_j = j;
}
if(nm[i][j] == 'g'){
goal_i = i;
goal_j = j;
}
}
}
ans = dfs(start_i,start_j,start_i,start_j,0);
if(ans != 99999999){
cout << ans;
}else{
cout << "Fail";
}
return 0;
}
| [
"moosan63@gmail.com"
] | moosan63@gmail.com |
364cca4f7c1a1bf798424fb91eddfee3d9d81739 | d7db098f4b1d1cd7d32952ebde8106e1f297252e | /CodeChef/d.cpp | d8ed0927c34b9bc5693171121c0ab3eecdc372e8 | [] | no_license | monman53/online_judge | d1d3ce50f5a8a3364a259a78bb89980ce05b9419 | dec972d2b2b3922227d9eecaad607f1d9cc94434 | refs/heads/master | 2021-01-16T18:36:27.455888 | 2019-05-26T14:03:14 | 2019-05-26T14:03:14 | 25,679,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,607 | cpp | // header {{{
#include <bits/stdc++.h>
using namespace std;
// {U}{INT,LONG,LLONG}_{MAX,MIN}
#define INF INT_MAX/3
#define LLINF LLONG_MAX/3
#define MOD (1000000007LL)
#define MODA(a, b) a=((a)+(b))%MOD
#define MODP(a, b) a=((a)*(b))%MOD
#define inc(i, l, r) for(int i=(l);i<(r);i++)
#define dec(i, l, r) for(int i=(r)-1;i>=(l);i--)
#define pb push_back
#define se second
#define fi first
#define mset(a, b) memset(a, b, sizeof(a))
using LL = long long;
using G = vector<vector<int>>;
int di[] = {0, -1, 0, 1};
int dj[] = {1, 0, -1, 0};
// }}}
struct Hoge {
int l, r;
vector<int> seq;
Hoge(char c, int l, int r){
this->l = l;
this->r = r;
int cnt = 0;
inc(i, 0, r-l){
seq.push_back(cnt);
if(c == 'I'){
cnt++;
}else{
cnt--;
}
}
}
int add(char c, int l, int r){
set<int> st;
int cnt = 0;
inc(i, l-this->l, this->r-this->l){
st.insert(seq[i]-cnt);
if(c == 'I'){
cnt++;
}else{
cnt--;
}
}
if(st.size() != 1){
return 1;
}else{
inc(i, this->r-this->l, r-this->l){
if(c == 'I'){
seq.push_back(seq[i-1]+1);
}else{
seq.push_back(seq[i-1]-1);
}
}
this->r = r;
return 0;
}
}
};
int solve() {
int n, m, k;
vector<int> a;
vector<pair<pair<int, int>, char>> lr;
vector<int> imos;
stack<Hoge> st;
LL ans = 1;
cin >> n >> m >> k;
a.resize(n);
lr.resize(m);
imos.resize(n+5, 0);
inc(i, 0, n) cin >> a[i];
inc(i, 0, m){
char c;
int l, r;
cin >> c >> l >> r;
l--;
imos[l]++;
imos[r]--;
lr[i] = {{l, r}, c};
}
inc(i, 1, n+4){
imos[i] = imos[i-1] + imos[i];
}
sort(lr.begin(), lr.end());
inc(i, 0, m){
char c = lr[i].se;
int l = lr[i].fi.fi;
int r = lr[i].fi.se;
if(st.size() == 0){
st.push(Hoge(c, l, r));
}else{
auto now = st.top();
st.pop();
if(now.r-l > 0){
if(now.add(c, l, r)){
return 1;
}
st.push(now);
}else{
st.push(now);
st.push(Hoge(c, l, r));
}
}
}
while(!st.empty()){
auto now = st.top();
st.pop();
int l = now.l;
int r = now.r;
set<int> ss;
int mmax = -INF;
int mmin = INF;
inc(i, l, r){
if(a[i] != -1){
ss.insert(now.seq[i-l]-a[i]);
}
mmax = max(now.seq[i-l], mmax);
mmin = min(now.seq[i-l], mmin);
}
//cout << "ss" << ss.size() << endl;
//cout << "a" << ans << endl;
if(ss.size() == 0){
if(k-(mmax-mmin) < 1){
return 1;
}
MODP(ans, k-(mmax-mmin));
}else{
if(ss.size() != 1) return 1;
}
}
inc(i, 0, n+5){
if(imos[i] == 0 && a[i] == -1){
MODP(ans, k);
}
}
cout << ans << endl;
return 0;
}
int main() {
cin.tie(0);ios::sync_with_stdio(false);
int t;cin >> t;
while(t--){
if(solve()){
cout << 0 << endl;
}
}
return 0;
}
| [
"monman.cs@gmail.com"
] | monman.cs@gmail.com |
534cf464c9107b394243d6d6315a879b5a608a94 | 698a11c977d074f3ab3f7d59883ba5e2e6f41002 | /src/language/stringdata.cpp | dcda38ce066a669fa6311d6842652fbeb910bf1e | [] | no_license | jeffmeese/tiberius | d0d92ebb69cd761baf2d79b75290e55cf21c70ec | 5a058cea86126d0b04b324830d757e7ece0fb497 | refs/heads/master | 2023-02-25T19:01:27.095207 | 2021-01-29T20:08:17 | 2021-01-29T20:08:17 | 306,618,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,380 | cpp | #include "stringdata.h"
#include "stringdatagroup.h"
#include <QDebug>
#include <QDir>
#include <QFile>
#include <sstream>
#include <stdexcept>
StringData::StringData()
{
}
StringData::~StringData()
{
}
void StringData::addGroup(std::unique_ptr<StringDataGroup> textGroup)
{
mGroups.push_back(std::move(textGroup));
}
QString StringData::getString(uint32_t groupId, uint32_t number) const
{
const StringDataGroup * textGoup = mGroups.at(groupId-1).get();
if (textGoup->totalStrings() <= number) {
return QString();
}
return mGroups.at(groupId-1)->stringAt(number);
}
void StringData::loadFromDataStream(QDataStream &dataStream)
{
mGroups.clear();
dataStream.setByteOrder(QDataStream::LittleEndian);
// Read the header data
Header header;
dataStream.readRawData(header.description, 16);
dataStream >> header.totalGroups;
dataStream >> header.totalStrings;
dataStream >> header.totalWords;
// Read index data
Index indexData[MAX_INDEX];
for (int32_t i = 0; i < MAX_INDEX; i++) {
dataStream >> indexData[i].offset;
dataStream >> indexData[i].numStrings;
}
// Read the string data
// Older versions only specified where the group was used
// while newer versions specified how many strings were in
// each group. The following assumes the old format and
// converts to the new format. For new format files this
// is unnecessary but it's only done once so the performance
// impact is minimal.
for (int32_t i = 0; i < MAX_INDEX-1; i++) {
uint32_t offset = indexData[i].offset;
uint32_t numStrings = indexData[i].numStrings;
if (numStrings > 0) {
StringDataGroupPtr group(new StringDataGroup(i+1));
// Read new strings until we hit the offset for the next group
uint32_t nextOffset = indexData[i+1].offset; // What if the next one isn't used?
QString currentString;
while (offset < nextOffset && !dataStream.atEnd()) {
offset++;
// Read characters until we find a null
char c;
dataStream.readRawData(&c, 1);
if (c == '\0') {
group->addString(currentString);
currentString.clear();
}
else {
currentString += c;
}
}
addGroup(std::move(group));
}
}
}
void StringData::loadFromFile(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
std::ostringstream oss;
oss << "Could not open language file " << fileName.toStdString();
throw std::invalid_argument(oss.str());
}
QDataStream dataStream(&file);
loadFromDataStream(dataStream);
}
void StringData::saveToDataStream(QDataStream & dataStream) const
{
// TODO: Implement
}
void StringData::saveToFile(const QString & fileName) const
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
std::ostringstream oss;
oss << "Could not open language file " << fileName.toStdString();
throw std::invalid_argument(oss.str());
}
}
std::size_t StringData::totalGroups() const
{
return mGroups.size();
}
std::size_t StringData::totalStrings() const
{
std::size_t total = 0;
for (std::size_t i = 0; i < mGroups.size(); i++) {
total += mGroups.at(i)->totalStrings();
}
return total;
}
| [
"jmeese@DESKTOP-8IUC6VI.attlocal.net"
] | jmeese@DESKTOP-8IUC6VI.attlocal.net |
b82a422506998aa858411bb7c6ef4de642ae32f6 | 282fa8dd9fd2e26b5ebf448c85121ed1bf873148 | /src/Common.h | fc2ccae7db358b3dd540ac093bb6215433e4d1ef | [] | no_license | fjgarciao/hustle_castle_bot_pack | ec8e71a1ea175a6790b187c64b0116f24b61d587 | 0ae16429e5da7d5bd69afdf1d28e15eaaa70e4d3 | refs/heads/master | 2020-04-20T17:15:36.817536 | 2019-02-03T21:32:10 | 2019-02-03T21:32:10 | 168,983,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 432 | h | #pragma once
#include "pch.h"
cv::Point MatchingMethod(const cv::Mat &src, const cv::Mat &templ);
void GenerateDataForTrain();
int TestWinApi();
double Compare(const cv::Mat &a, const cv::Mat &b);
bool CompareFromTemplate(const cv::Mat &src, const cv::Mat &sample, const cv::Mat &tmpl);
bool MaskToRect(const cv::Mat &img, cv::Rect &rect);
std::string type2str(int type);
void show_two(const cv::Mat &a, const cv::Mat &b);
| [
"denesic@gmail.com"
] | denesic@gmail.com |
e846e6d07b6a7d776186246dccaac4c9bca34dba | cce1863b204ae1ed76f0e2b54ec8a121ee83e4dc | /VimbaCPP/Examples/AsynchronousGrab/Qt/Source/CameraObserver.h | 25a9683cdf2e9535e742e52e2270af73d9830a62 | [] | no_license | quminhdo/vimba | 0c54366f00cd8df3139bcd7887dd6771bbdc25b4 | 1203f1809e00d9deab8705c5867b8425a22f6355 | refs/heads/master | 2023-05-08T04:46:46.626769 | 2021-06-01T15:54:52 | 2021-06-01T15:54:52 | 367,311,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,441 | h | /*=============================================================================
Copyright (C) 2012 - 2016 Allied Vision Technologies. All Rights Reserved.
Redistribution of this file, in original or modified form, without
prior written consent of Allied Vision Technologies is prohibited.
-------------------------------------------------------------------------------
File: CameraObserver.h
Description: The camera observer that is used for notifications from VimbaCPP
regarding a change in the camera list.
-------------------------------------------------------------------------------
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE,
NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 AVT_VMBAPI_EXAMPLES_CAMERAOBSERVER
#define AVT_VMBAPI_EXAMPLES_CAMERAOBSERVER
#include <QObject>
#include <VimbaCPP/Include/VimbaCPP.h>
namespace AVT {
namespace VmbAPI {
namespace Examples {
class CameraObserver : public QObject, public ICameraListObserver
{
Q_OBJECT
public:
//
// This is our callback routine that will be executed every time a camera was plugged in or out
//
// Parameters:
// [in] pCam The camera that triggered the callback
// [in] reason The reason why the callback was triggered
//
virtual void CameraListChanged( CameraPtr pCamera, UpdateTriggerType reason );
signals:
//
// The camera list changed event (Qt signal) that notifies about a camera change and its reason
//
// Parameters:
// [out] reason The reason why this event was fired
//
void CameraListChangedSignal( int reason );
};
}}} // namespace AVT::VmbAPI::Examples
#endif
| [
"quminh.do@gmail.com"
] | quminh.do@gmail.com |
582bb799285e8290274d2bfa819fc5cbbf134697 | 19048fa3c92b3a01209de30023afd9e82f19284d | /2018组队/2013-2014 ACM-ICPC Northeastern European Regional Contest (NEERC 13)/e.cpp | 07dbe7f78f8785ad53515c9cce5b007dd6ede895 | [] | no_license | fblogy/code | b73d1172f4e58f9ecbe1ffbcac925070cbd10881 | ae8bded0caced69d0248bfcbd2396d6aa745820a | refs/heads/master | 2020-03-25T16:53:03.864473 | 2019-07-01T07:57:31 | 2019-07-01T07:57:31 | 134,960,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,920 | cpp | #include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define rep(i, a, b) for(int i=(a); i<(b); i++)
#define per(i, a, b) for(int i=(b)-1; i>=(a); i--)
#define sz(a) (int)a.size()
#define de(a) cout << #a << " = " << a << endl
#define dd(a) cout << #a << " = " << a << " "
#define all(a) a.begin(), a.end()
#define pw(x) (1ll<<(x))
#define endl "\n"
typedef double db;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int P = 1e9 + 7;
int add(int a, int b) {if((a += b) >= P) a -= P; return a;}
int sub(int a, int b) {if((a -= b) < 0) a += P; return a;}
int mul(int a, int b) {return 1ll * a * b % P;}
int kpow(int a, int b) {int r=1;for(;b;b>>=1,a=mul(a,a)) {if(b&1)r=mul(r,a);}return r;}
//----
const int N = 100005;
int n, x[N], y[N], p1, p2, p;
vector<pair<db, db> > V[2];
db ansx, ansy1, ansy2, lo, ro, m1, m2, s1, s2;
db Y (db x, int p, int o) {
assert(p < sz(V[o]));
if (p == 0) return V[o][0].se;
if (V[o][p].fi != V[o][p-1].fi) {
return V[o][p-1].se + (x - V[o][p-1].fi) * (V[o][p].se - V[o][p-1].se) / (V[o][p].fi - V[o][p-1].fi);
}else return V[o][p].se;
}
db cal(db a, db b) {
if (b >= x[p2]) return -pw(60);
int t1 = lower_bound(all(V[0]), mp(a, 1.0 * pw(30))) - V[0].begin();
int t2 = lower_bound(all(V[0]), mp(b, 1.0 * pw(30))) - V[0].begin();
if (t1 == sz(V[0]) || t2 == sz(V[0])) return -pw(60);
db ma = min(Y(a, t1, 0), Y(b, t2, 0));
t1 = lower_bound(all(V[1]), mp(a, 1.0 * pw(30))) - V[1].begin();
t2 = lower_bound(all(V[1]), mp(b, 1.0 * pw(30))) - V[1].begin();
if (t1 == sz(V[1]) || t2 == sz(V[1])) return -pw(60);
db mi = max(Y(a, t1, 1), Y(b, t2, 1));
if (ma < mi) return -pw(60);
ansy1 = mi; ansy2 = ma;
return (b - a) * (ma - mi);
}
db solve(db w) {
db lo = x[p1], ro = x[p2], s1, s2;
rep(tim, 0, 100) {
db m1 = (lo + lo + ro) / 3, m2 = (lo + ro + ro) / 3;
s1 = cal(m1, m1 + w);
s2 = cal(m2, m2 + w);
//dd(m1);de(m2);dd(s1);de(s2);
if (s1 < s2) lo = m1; else ro = m2;
}
ansx = lo;
return s1;
}
int main() {
freopen("easy.in","r",stdin);
// freopen("easy.out","w",stdout);
std::ios::sync_with_stdio(false);
std::cin.tie(0);
cout << setiosflags(ios::fixed);
cout << setprecision(10);
cin >> n;
rep(i, 1, n+1) cin >> x[i] >> y[i];
p1 = min_element(x+1, x+n+1) - x;
p2 = max_element(x+1, x+n+1) - x;
p = p1;
while (p != p2) {
V[0].pb(mp(x[p], y[p])); p++;
if (p > n) p = 1;
}
V[0].pb(mp(x[p], y[p]));
while (p != p1) {
V[1].pb(mp(x[p], y[p])); p++;
if (p > n) p = 1;
}
V[1].pb(mp(x[p], y[p]));
reverse(all(V[1]));
//de(solve(2));
//return 0;
lo = 0; ro = x[p2] - x[p1];
rep(tim, 0, 100) {
m1 = (lo + lo + ro) / 3; m2 = (lo + ro + ro) / 3;
s1 = solve(m1);
s2 = solve(m2);
if (s1 < s2) lo = m1; else ro = m2;
}
cout << ansx << " " << ansy1 << " " << ansx + lo << " " << ansy2;
return 0;
}
| [
"39649744+fblogy@users.noreply.github.com"
] | 39649744+fblogy@users.noreply.github.com |
adae3f407367db6fc5eb491c20ea994749db384c | a0b5820634469419965dd6b2439f29f3603c4c8e | /Hobot_conf/driver/c++/src/driver_common.cc | 7dec67ee45bdc27b45612572c4a524932a65c5dc | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | zhuzy-xys/conf_schedule | 84ad343e36f2cadf030247962409ee3ac5f5206c | 1d5ca0e7f8e6131141b075d370f0e186401bb377 | refs/heads/master | 2020-03-16T21:23:46.170662 | 2018-06-04T14:59:13 | 2018-06-04T14:59:13 | 132,997,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 873 | cc | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hconf_errno.h"
#include "driver_common.h"
int init_hconf_batch_nodes(hconf_batch_nodes *bnodes)
{
if (NULL == bnodes) return HCONF_ERR_PARAM;
memset((void*)bnodes, 0, sizeof(hconf_batch_nodes));
return HCONF_OK;
}
int destroy_hconf_batch_nodes(hconf_batch_nodes *bnodes)
{
if (NULL == bnodes) return HCONF_ERR_PARAM;
free_hconf_batch_nodes(bnodes, bnodes->count);
return HCONF_OK;
}
void free_hconf_batch_nodes(hconf_batch_nodes *bnodes, size_t free_size)
{
if (NULL == bnodes) return;
for (size_t i = 0; i < free_size; ++i)
{
free(bnodes->nodes[i].key);
free(bnodes->nodes[i].value);
bnodes->nodes[i].key = NULL;
bnodes->nodes[i].value = NULL;
}
free(bnodes->nodes);
bnodes->nodes = NULL;
bnodes->count = 0;
}
| [
"17702514160@163.com"
] | 17702514160@163.com |
1187934589becdabe6e8787cef140290c7e1a622 | 563def4f397c5e130fb9282d72cbe9a942522f99 | /outdir/nv_small/spec/manual/NVDLA_GEC_reg_c/ordt_pio_common.cpp | 775d53d32f0ba515a915bc16636b5b7a7754e730 | [] | no_license | Allahfan/nvdla_change | 8311f581b6776cb531e504d6998ab8da583e36e2 | cadd45ead29ff7a11970dc3f3b19b22e84d43fcb | refs/heads/master | 2020-08-16T00:42:34.123345 | 2019-10-16T01:50:52 | 2019-10-16T01:50:52 | 215,432,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,107 | cpp | // Ordt 171103.01 autogenerated file
// Input: NVDLA_GEC.rdl
// Parms: opendla.parms
// Date: Tue Jun 25 16:49:26 CST 2019
//
#include "ordt_pio_common.hpp"
// ------------------ ordt_data methods ------------------
ordt_data::ordt_data()
: std::vector<uint32_t>() {
}
ordt_data::ordt_data(int _size, uint32_t _data)
: std::vector<uint32_t>(_size, _data) {
}
ordt_data::ordt_data(const ordt_data& _data)
: std::vector<uint32_t>(_data) {
}
void ordt_data::set_slice(int lobit, int size, const ordt_data& update) {
int data_size = this->size() * 32;
if ((lobit % 32) > 0) {
std::cout << "ERROR set_slice: non 32b aligned slices are not supported" << "\n";
return;
}
int hibit = lobit + size - 1;
int loword = lobit / 32;
int hiword = hibit / 32;
if (hibit > data_size - 1) {
std::cout << "ERROR set_slice: specified slice is not contained in data" << "\n";
return;
}
int update_idx=0;
for (int idx=loword; idx < hiword + 1; idx++) {
if (idx == hiword) {
int modsize = hibit - hiword*32 + 1;
uint32_t mask = (modsize == 32)? 0xffffffff : (1 << modsize) - 1;
this->at(idx) = (this->at(idx) & ~mask) ^ (update.at(update_idx) & mask);
}
else this->at(idx) = update.at(update_idx);
update_idx++;
}
}
void ordt_data::get_slice(int lobit, int size, ordt_data& slice_out) const {
int data_size = this->size() * 32;
if ((lobit % 32) > 0) {
std::cout << "ERROR set_slice: non 32b aligned large fields are not supported" << "\n";
return;
}
slice_out.clear();
int hibit = lobit + size - 1;
int loword = lobit / 32;
int hiword = hibit / 32;
if (hibit > data_size - 1) {
std::cout << "ERROR set_slice: specified slice is not contained in data" << "\n";
return;
}
int out_idx=0;
for (int idx=loword; idx < hiword + 1; idx++) {
if (idx == hiword) {
int modsize = hibit - hiword*32 + 1;
uint32_t mask = (modsize == 32)? 0xffffffff : (1 << modsize) - 1;
slice_out.at(out_idx) = (this->at(idx) & mask);
}
else slice_out.at(out_idx) = this->at(idx);
out_idx++;
}
return;
}
std::string ordt_data::to_string() const {
std::stringstream ss;
ss << "{" << std::hex << std::showbase;
for (int idx=this->size() - 1; idx >= 0; idx--)
ss << " " << this->at(idx);
ss << " }";
return ss.str();
}
ordt_data& ordt_data::operator=(const uint32_t rhs) {
this->assign(this->size(), rhs);
return *this;
}
ordt_data ordt_data::operator~() {
ordt_data temp;
for (int idx=0; idx<this->size(); idx++)
temp.at(idx) = ~ this->at(idx);
return temp;
}
ordt_data ordt_data::operator&(const ordt_data& rhs) {
ordt_data temp;
for (int idx=0; idx<this->size(); idx++)
if (idx < rhs.size()) temp.at(idx) = this->at(idx) & rhs.at(idx);
else temp.at(idx) = 0;
return temp;
}
ordt_data ordt_data::operator|(const ordt_data& rhs) {
ordt_data temp;
for (int idx=0; idx<this->size(); idx++)
if (idx < rhs.size()) temp.at(idx) = this->at(idx) | rhs.at(idx);
else temp.at(idx) = this->at(idx);
return temp;
}
| [
"1978573841@qq.com"
] | 1978573841@qq.com |
289ff4bd56770331322c3c04f4a1277d50d88e46 | c8958958e5802f3e04ce88bd4064eacb98ce2f97 | /森林中的兔子.cpp | f2ee5e95986e8944691d1c9096b268d5d495463c | [] | no_license | Kiids/OJ_Practice | 08e5ea99066421bfaf5b71e59eea24e282e39a24 | e7d36ddb1664635d27db3c37bec952970b77dcb0 | refs/heads/master | 2023-09-01T11:38:28.834187 | 2023-06-30T17:12:18 | 2023-06-30T17:12:18 | 217,068,695 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,641 | cpp | /*
森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 answers 数组里。
返回森林中兔子的最少数量。
示例:
输入: answers = [1, 1, 2]
输出: 5
解释:
两只回答了 "1" 的兔子可能有相同的颜色,设为红色。
之后回答了 "2" 的兔子不会是红色,否则他们的回答会相互矛盾。
设回答了 "2" 的兔子为蓝色。
此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。
因此森林中兔子的最少数量是 5: 3 只回答的和 2 只没有回答的。
输入: answers = [10, 10, 10]
输出: 11
输入: answers = []
输出: 0
说明:
answers 的长度最大为1000。
answers[i] 是在 [0, 999] 范围内的整数。
*/
class Solution {
public:
int numRabbits(vector<int>& answers) {
if (answers.empty())
return 0;
int ret = 0;
unordered_map<int, int> m; // <数字, 说了这个数字的兔子数量>
for (int e : answers)
{
if (!m.count(e) || m[e] == 0) // 没有记录或当前数字的兔子数量为0时
{
ret += e + 1;
m[e]++ ;
}
else if (m.count(e))
m[e] ++ ;
if (m[e] == e + 1) // 当兔子数量等于数字时,表示达到该种颜色所能代表的数量上限
m[e] = 0; // 重置兔子数量为零,若再遇到相同数字,需要开另一种颜色来存
}
return ret;
}
};
| [
"1980774293@qq.com"
] | 1980774293@qq.com |
2a27df84d68a1be1402d24d1f6ef7bf22d147f5b | b677894966f2ae2d0585a31f163a362e41a3eae0 | /ns3/ns-3.26/src/lte/model/epc-enb-s1-sap.h | 2d3224eb9bf808e04da6c80f787f2b7518c40345 | [
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | cyliustack/clusim | 667a9eef2e1ea8dad1511fd405f3191d150a04a8 | cbedcf671ba19fded26e4776c0e068f81f068dfd | refs/heads/master | 2022-10-06T20:14:43.052930 | 2022-10-01T19:42:19 | 2022-10-01T19:42:19 | 99,692,344 | 7 | 3 | Apache-2.0 | 2018-07-04T10:09:24 | 2017-08-08T12:51:33 | Python | UTF-8 | C++ | false | false | 6,292 | h | /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2012 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Nicola Baldo <nbaldo@cttc.es>
*/
#ifndef EPC_ENB_S1_SAP_H
#define EPC_ENB_S1_SAP_H
#include <list>
#include <stdint.h>
#include <ns3/eps-bearer.h>
#include <ns3/ipv4-address.h>
namespace ns3 {
/**
* This class implements the Service Access Point (SAP) between the
* LteEnbRrc and the EpcEnbApplication. In particular, this class implements the
* Provider part of the SAP, i.e., the methods exported by the
* EpcEnbApplication and called by the LteEnbRrc.
*
*/
class EpcEnbS1SapProvider
{
public:
virtual ~EpcEnbS1SapProvider ();
/**
*
*
* \param imsi
* \param rnti
*/
virtual void InitialUeMessage (uint64_t imsi, uint16_t rnti) = 0;
/**
* \brief Triggers epc-enb-application to send ERAB Release Indication message towards MME
* \param imsi the UE IMSI
* \param rnti the UE RNTI
* \param bearerId Bearer Identity which is to be de-activated
*/
virtual void DoSendReleaseIndication (uint64_t imsi, uint16_t rnti, uint8_t bearerId) = 0;
struct BearerToBeSwitched
{
uint8_t epsBearerId;
uint32_t teid;
};
struct PathSwitchRequestParameters
{
uint16_t rnti;
uint16_t cellId;
uint32_t mmeUeS1Id;
std::list<BearerToBeSwitched> bearersToBeSwitched;
};
virtual void PathSwitchRequest (PathSwitchRequestParameters params) = 0;
/**
* release UE context at the S1 Application of the source eNB after
* reception of the UE CONTEXT RELEASE X2 message from the target eNB
* during X2-based handover
*
* \param rnti
*/
virtual void UeContextRelease (uint16_t rnti) = 0;
};
/**
* This class implements the Service Access Point (SAP) between the
* LteEnbRrc and the EpcEnbApplication. In particular, this class implements the
* User part of the SAP, i.e., the methods exported by the LteEnbRrc
* and called by the EpcEnbApplication.
*
*/
class EpcEnbS1SapUser
{
public:
virtual ~EpcEnbS1SapUser ();
/**
* Parameters passed to DataRadioBearerSetupRequest ()
*
*/
struct DataRadioBearerSetupRequestParameters
{
uint16_t rnti; /**< the RNTI identifying the UE for which the
DataRadioBearer is to be created */
EpsBearer bearer; /**< the characteristics of the bearer to be set
up */
uint8_t bearerId; /**< the EPS Bearer Identifier */
uint32_t gtpTeid; /**< S1-bearer GTP tunnel endpoint identifier, see 36.423 9.2.1 */
Ipv4Address transportLayerAddress; /**< IP Address of the SGW, see 36.423 9.2.1 */
};
/**
* request the setup of a DataRadioBearer
*
*/
virtual void DataRadioBearerSetupRequest (DataRadioBearerSetupRequestParameters params) = 0;
struct PathSwitchRequestAcknowledgeParameters
{
uint16_t rnti;
};
virtual void PathSwitchRequestAcknowledge (PathSwitchRequestAcknowledgeParameters params) = 0;
};
/**
* Template for the implementation of the EpcEnbS1SapProvider as a member
* of an owner class of type C to which all methods are forwarded
*
*/
template <class C>
class MemberEpcEnbS1SapProvider : public EpcEnbS1SapProvider
{
public:
MemberEpcEnbS1SapProvider (C* owner);
// inherited from EpcEnbS1SapProvider
virtual void InitialUeMessage (uint64_t imsi, uint16_t rnti);
virtual void DoSendReleaseIndication (uint64_t imsi, uint16_t rnti, uint8_t bearerId);
virtual void PathSwitchRequest (PathSwitchRequestParameters params);
virtual void UeContextRelease (uint16_t rnti);
private:
MemberEpcEnbS1SapProvider ();
C* m_owner;
};
template <class C>
MemberEpcEnbS1SapProvider<C>::MemberEpcEnbS1SapProvider (C* owner)
: m_owner (owner)
{
}
template <class C>
MemberEpcEnbS1SapProvider<C>::MemberEpcEnbS1SapProvider ()
{
}
template <class C>
void MemberEpcEnbS1SapProvider<C>::InitialUeMessage (uint64_t imsi, uint16_t rnti)
{
m_owner->DoInitialUeMessage (imsi, rnti);
}
template <class C>
void MemberEpcEnbS1SapProvider<C>::DoSendReleaseIndication (uint64_t imsi, uint16_t rnti, uint8_t bearerId)
{
m_owner->DoReleaseIndication (imsi, rnti, bearerId);
}
template <class C>
void MemberEpcEnbS1SapProvider<C>::PathSwitchRequest (PathSwitchRequestParameters params)
{
m_owner->DoPathSwitchRequest (params);
}
template <class C>
void MemberEpcEnbS1SapProvider<C>::UeContextRelease (uint16_t rnti)
{
m_owner->DoUeContextRelease (rnti);
}
/**
* Template for the implementation of the EpcEnbS1SapUser as a member
* of an owner class of type C to which all methods are forwarded
*
*/
template <class C>
class MemberEpcEnbS1SapUser : public EpcEnbS1SapUser
{
public:
MemberEpcEnbS1SapUser (C* owner);
// inherited from EpcEnbS1SapUser
virtual void DataRadioBearerSetupRequest (DataRadioBearerSetupRequestParameters params);
virtual void PathSwitchRequestAcknowledge (PathSwitchRequestAcknowledgeParameters params);
private:
MemberEpcEnbS1SapUser ();
C* m_owner;
};
template <class C>
MemberEpcEnbS1SapUser<C>::MemberEpcEnbS1SapUser (C* owner)
: m_owner (owner)
{
}
template <class C>
MemberEpcEnbS1SapUser<C>::MemberEpcEnbS1SapUser ()
{
}
template <class C>
void MemberEpcEnbS1SapUser<C>::DataRadioBearerSetupRequest (DataRadioBearerSetupRequestParameters params)
{
m_owner->DoDataRadioBearerSetupRequest (params);
}
template <class C>
void MemberEpcEnbS1SapUser<C>::PathSwitchRequestAcknowledge (PathSwitchRequestAcknowledgeParameters params)
{
m_owner->DoPathSwitchRequestAcknowledge (params);
}
} // namespace ns3
#endif // EPC_ENB_S1_SAP_H
| [
"you@example.com"
] | you@example.com |
8c01e1827671e8f5b39071e4785552c7bfa695e0 | c0caed81b5b3e1498cbca4c1627513c456908e38 | /src/core/scoring/methods/PoissonBoltzmannEnergy.cc | 15662387c08a9b217a5d3ed6d2f661418a2dbc8c | [] | no_license | malaifa/source | 5b34ac0a4e7777265b291fc824da8837ecc3ee84 | fc0af245885de0fb82e0a1144422796a6674aeae | refs/heads/master | 2021-01-19T22:10:22.942155 | 2017-04-19T14:13:07 | 2017-04-19T14:13:07 | 88,761,668 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 14,744 | cc | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu.
/// @file core/scoring/methods/PoissonBoltzmannEnergy.cc
/// @brief Ramachandran energy method class implementation
/// @author Phil Bradley
/// @author Andrew Leaver-Fay (aleaverfay@gmail.com)
// Unit Headers
#include <core/scoring/methods/PoissonBoltzmannEnergy.hh>
#include <core/scoring/methods/PoissonBoltzmannEnergyCreator.hh>
// Package Headers
#include <core/scoring/PoissonBoltzmannPotential.hh>
#include <core/scoring/EnergyMap.hh>
#include <core/scoring/OneToAllEnergyContainer.hh>
#include <core/scoring/Energies.hh>
#include <core/scoring/methods/Methods.hh>
#include <core/scoring/ScoreFunction.hh>
#include <core/scoring/methods/EnergyMethodOptions.hh>
// Project headers
#include <core/pose/Pose.hh>
#include <core/pose/PDBInfo.hh>
#include <core/conformation/Residue.hh>
// Utility headers
#include <basic/Tracer.hh>
#include <basic/datacache/CacheableData.hh>
#include <basic/datacache/DataCache.hh>
#include <core/pose/datacache/CacheableDataType.hh>
// option
#include <basic/options/option.hh>
#include <basic/options/keys/pb_potential.OptionKeys.gen.hh>
// numeric
#include <numeric/xyzVector.hh>
#include <utility/vector1.hh>
static THREAD_LOCAL basic::Tracer TR( "core.scoring.methods.PoissonBoltzmannEnergy" );
namespace core {
namespace scoring {
namespace methods {
//*****************************************************************
//
// PBLifetimeCache: carries cache for the entire runtime cycle.
//
//*****************************************************************
PBLifetimeCache::PBLifetimeCache()
{}
PBLifetimeCache::~PBLifetimeCache()
{}
basic::datacache::CacheableDataOP
PBLifetimeCache::clone() const
{
return basic::datacache::CacheableDataOP( new PBLifetimeCache(*this) );
}
void
PBLifetimeCache::set_charged_residues_map( const std::map<std::string, bool> & charged_residues_map )
{
charged_residues_map_ = charged_residues_map;
}
void
PBLifetimeCache::set_energy_state( const std::string& energy_state )
{
energy_state_ = energy_state;
}
void
PBLifetimeCache::set_conformational_data( const std::string& energy_state,
const core::pose::Pose & pose,
PoissonBoltzmannPotentialOP pbp )
{
pose_by_state_[energy_state] = core::pose::PoseOP( new core::pose::Pose(pose) );
pb_by_state_[energy_state] = pbp;
}
std::map<std::string, bool> &
PBLifetimeCache::get_charged_residues_map()
{
return charged_residues_map_;
}
const std::string &
PBLifetimeCache::get_energy_state() const
{
return energy_state_;
}
core::pose::PoseCOP
PBLifetimeCache::get_pose( const std::string& energy_state )
{
//TR << "Looking for cached pose for state \"" << energy_state << "\" in PBLifetimeCache " << "{ ";
//std::map<std::string, pose::PoseCOP>::const_iterator itr = poses_by_state_.begin();
//for(; itr != poses_by_state_.end(); ++itr ){
// TR << "(key=" << itr->first << ": val=" << itr->second->pdb_info()->name() << "), ";
//}
//TR << " }" << std::endl;
return pose_by_state_[energy_state];
}
PoissonBoltzmannPotentialOP
PBLifetimeCache::get_pbp( const std::string& energy_state )
{
return pb_by_state_[energy_state];
}
bool
PBLifetimeCache::has_cache( const std::string& energy_state ) const
{
return pb_by_state_.count(energy_state) && pose_by_state_.count( energy_state);
}
//*****************************************************************
//
// PoissonBoltzmannEnergyCreator
//
//*****************************************************************
/// @details This must return a fresh instance of the PoissonBoltzmannEnergy class,
/// never an instance already in use
methods::EnergyMethodOP
PoissonBoltzmannEnergyCreator::create_energy_method(
methods::EnergyMethodOptions const &
) const {
return methods::EnergyMethodOP( new PoissonBoltzmannEnergy );
}
ScoreTypes
PoissonBoltzmannEnergyCreator::score_types_for_method() const {
ScoreTypes sts;
sts.push_back( PB_elec );
return sts;
}
//*****************************************************************
//
// PoissonBoltzmannEnergy
//
//*****************************************************************
/// ctor
PoissonBoltzmannEnergy::PoissonBoltzmannEnergy() :
parent( methods::EnergyMethodCreatorOP( new PoissonBoltzmannEnergyCreator ) ),
fixed_residue_(1),
epsilon_(2.0)
//,
//poisson_boltzmann_potential_( new scoring::PoissonBoltzmannPotential )
{
if ( basic::options::option[basic::options::OptionKeys::pb_potential::epsilon].user() ) {
epsilon_ = basic::options::option[basic::options::OptionKeys::pb_potential::epsilon];
}
}
/// clone
EnergyMethodOP
PoissonBoltzmannEnergy::clone() const
{
return EnergyMethodOP( new PoissonBoltzmannEnergy( *this ) );
}
methods::LongRangeEnergyType
PoissonBoltzmannEnergy::long_range_type() const { return methods::PB_elec_lr; }
void
PoissonBoltzmannEnergy::setup_for_scoring(
pose::Pose & pose,
ScoreFunction const & scorefxn
) const {
using namespace methods;
// If the cached object is not in the pose data-cache, it suggests that the setup protocol has not
// been called in prior. Warn and get out!
if ( ! pose.data().has( pose::datacache::CacheableDataType::PB_LIFETIME_CACHE ) ) {
TR << "PB_LIFETIME_CACHE object is not initialized. Did you call SetupPoissonBoltzmannPotential mover? Terminaing the program..." << std::endl;
TR.flush();
// Register the empty cache holder if not done so yet.
PoissonBoltzmannEnergy::PBLifetimeCacheOP new_cache( new PoissonBoltzmannEnergy::PBLifetimeCache() );
pose.data().set( pose::datacache::CacheableDataType::PB_LIFETIME_CACHE, new_cache );
//runtime_assert(false);
}
PBLifetimeCacheOP cached_data =
static_cast< PBLifetimeCacheOP > (pose.data().get_ptr< PBLifetimeCache >(pose::datacache::CacheableDataType::PB_LIFETIME_CACHE ));
// Do we have the map of charged residues by name?
charged_residues_ = cached_data->get_charged_residues_map();
if ( charged_residues_.size() == 0 ) {
utility::vector1<int> charged_chains
= basic::options::option[basic::options::OptionKeys::pb_potential::charged_chains];
TR << "Charged residues: [ ";
for ( Size i=1; i<= pose.total_residue(); ++i ) {
core::conformation::Residue const & rsd( pose.residue(i) );
bool residue_charged = false;
if ( std::find(charged_chains.begin(), charged_chains.end(), (int)rsd.chain()) != charged_chains.end() ) {
residue_charged = true;
TR << rsd.type().name() << ",";
}
charged_residues_[rsd.type().name()] = residue_charged;
}
cached_data->set_charged_residues_map( charged_residues_ );
TR << "]" << std::endl;
}
core::scoring::methods::EnergyMethodOptions emoptions = scorefxn.energy_method_options();
std::string energy_state = cached_data->get_energy_state();
if ( energy_state == "" ) {
energy_state = "stateless";
}
TR << "Energy state: \"" << energy_state << "\" for scorefxn: " << scorefxn.get_name() << std::endl;
const Size atom_index = 2; // alpha carbon
// Solve PB
//
// use cached data if the bound comformation hasn't changed.
if ( cached_data->has_cache( energy_state ) ) {
core::pose::PoseCOP prev_pose = cached_data->get_pose( energy_state );
// switch to the state's pb
poisson_boltzmann_potential_ = cached_data->get_pbp(energy_state);
debug_assert(poisson_boltzmann_potential_ != 0);
TR << "Found cached pose for state: " << energy_state << std::endl;
// re-evaluate only for bound-state.
if ( energy_state == emoptions.pb_bound_tag() ) {
if ( !protein_position_equal_within( pose, *prev_pose, atom_index, epsilon_ ) ) {
TR << "Atoms (" << atom_index << ") in charged chains moved more than " ;
TR << epsilon_ << "A" << std::endl;
poisson_boltzmann_potential_->solve_pb(pose, energy_state, charged_residues_);
}
}
} else {
TR << "No cached pose for state: " << energy_state << std::endl;
poisson_boltzmann_potential_ = scoring::PoissonBoltzmannPotentialOP( new PoissonBoltzmannPotential() );
poisson_boltzmann_potential_->solve_pb(pose, energy_state, charged_residues_);
}
// Update the cache
cached_data->set_conformational_data( energy_state, pose, poisson_boltzmann_potential_ );
// create LR energy container
LongRangeEnergyType const & lr_type( long_range_type() );
Energies & energies( pose.energies() );
bool create_new_lre_container( false );
if ( energies.long_range_container( lr_type ) == 0 ) {
create_new_lre_container = true;
} else {
LREnergyContainerOP lrc = energies.nonconst_long_range_container( lr_type );
OneToAllEnergyContainerOP dec( utility::pointer::static_pointer_cast< core::scoring::OneToAllEnergyContainer > ( lrc ) );
// make sure size or root did not change
if ( dec->size() != pose.total_residue() ) {
create_new_lre_container = true;
}
}
if ( create_new_lre_container ) {
TR << "Creating new one-to-all energy container (" << pose.total_residue() << ")" << std::endl;
LREnergyContainerOP new_dec( new OneToAllEnergyContainer( fixed_residue_, pose.total_residue(), PB_elec ) );
energies.set_long_range_container( lr_type, new_dec );
}
}
/////////////////////////////////////////////////////////////////////////////
// methods
/////////////////////////////////////////////////////////////////////////////
bool PoissonBoltzmannEnergy::defines_residue_pair_energy(
pose::Pose const &,
Size res1,
Size res2
) const {
return ( res1 == fixed_residue_ || res2 == fixed_residue_ );
}
void
PoissonBoltzmannEnergy::eval_intrares_energy(
conformation::Residue const &,
pose::Pose const &,
ScoreFunction const &,
EnergyMap &
) const {
return;
}
bool
PoissonBoltzmannEnergy::residue_in_chains(
conformation::Residue const & rsd,
utility::vector1 <Size> chains
) const {
for ( Size ichain=1; ichain<=chains.size(); ++ichain ) {
if ( rsd.chain() == chains[ichain] ) return true;
}
return false;
}
Real
PoissonBoltzmannEnergy::revamp_weight_by_burial(
conformation::Residue const & rsd,
pose::Pose const & pose
) const {
utility::vector1 <Size> chains = basic::options::option[basic::options::OptionKeys::pb_potential::revamp_near_chain]();
Real weight = 1.;
Real neighbor_count = 0.;
Real threshold = 4.;
for ( Size j_res = 1; j_res <= pose.total_residue(); ++j_res ) {
if ( pose.residue(j_res).is_virtual_residue() ) continue;
if ( !residue_in_chains(pose.residue(j_res), chains) ) continue;
bool found_neighbor = false;
for ( Size i_atom = rsd.last_backbone_atom() + 1; i_atom <= rsd.nheavyatoms(); ++i_atom ) {
for ( Size j_atom = 1; j_atom <= rsd.nheavyatoms(); ++j_atom ) {
if ( pose.residue(j_res).is_virtual(j_atom) ) continue;
Real distance = rsd.xyz(i_atom).distance(pose.residue(j_res).xyz(j_atom));
if ( distance < threshold ) {
neighbor_count += 1.;
found_neighbor = true;
break;
}
}
if ( found_neighbor ) break;
}
}
if ( neighbor_count > 0 ) weight = 1./neighbor_count;
//using namespace ObjexxFCL::format;
//TR << "PB_weight:" << I(4,rsd.seqpos()) << F(8, 3, weight) << std::endl;
return weight;
}
void
PoissonBoltzmannEnergy::residue_pair_energy(
conformation::Residue const & rsd1,
conformation::Residue const & rsd2,
pose::Pose const & pose,
ScoreFunction const &,
EnergyMap & emap
) const {
//check fixed_residue_
conformation::Residue const &rsd (rsd1.seqpos() == fixed_residue_? rsd2 : rsd1 );
// If it is part of charged chain, skip.
if ( const_cast<std::map<std::string, bool>&>(charged_residues_)[rsd.type().name()] ) {
return;
}
Real PB_score_residue, PB_score_backbone, PB_score_sidechain;
Real PB_burial_weight(1.0);
if ( basic::options::option[basic::options::OptionKeys::pb_potential::revamp_near_chain].user() ) {
PB_burial_weight = revamp_weight_by_burial(rsd, pose);
}
poisson_boltzmann_potential_->eval_PB_energy_residue(
rsd,
PB_score_residue,
PB_score_backbone,
PB_score_sidechain,
PB_burial_weight );
if ( basic::options::option[basic::options::OptionKeys::pb_potential::sidechain_only]() ) {
emap[ PB_elec ] += PB_score_sidechain;
} else {
emap[ PB_elec ] += PB_score_residue;
}
}
/// @brief Energy is context independent and thus indicates that no context graphs need to
/// be maintained by class Energies
void
PoissonBoltzmannEnergy::indicate_required_context_graphs(
utility::vector1< bool > & /*context_graphs_required*/
)
const
{}
/// Compare if two poses are close in fold within tolerance.
///
/// To be specific, it returns True if for all a in A and b in B,
/// sqrt( (a.x-b.x)^2 + (a.y-b.y)^2 + (a.z-b.z)^2 ) <= tol,
/// for A and B are sets of all atoms in protein 1 and protein 2, respectively.
///
/// @param pose1 A protein's pose
/// @param pose2 Another protein's pose
/// @param atom_num The atom number
/// @param tol Tolerable distance in Angstrom, >= 0.A
///
bool
PoissonBoltzmannEnergy::protein_position_equal_within(
pose::Pose const & pose1,
pose::Pose const & pose2,
Size atom_num,
Real tol) const {
// error: reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to always evaluate to false [-Werror,-Wtautological-undefined-compare]
//if( &pose1 == NULL || &pose2 == NULL ) {
// return false;
//}
//if( &pose1 == NULL && &pose2 == NULL ) {
// return true;
//}
if ( pose1.total_residue() != pose2.total_residue() ) {
return false;
}
for ( Size i=1; i<=pose1.total_residue(); ++i ) {
// Skip nonprotein pose 1.
if ( !pose1.residue(i).is_protein() ) continue;
// If a protein residue from pose 1 matches seqpos of a nonprotein
// residue from pose 2, must be false.
if ( !pose2.residue(i).is_protein() ) return false;
// Nonmatching by definition.
if ( pose1.residue_type(i).natoms() != pose2.residue(i).natoms()
|| pose1.residue_type(i).aa() != pose2.residue_type(i).aa() ) {
return false;
}
const core::conformation::Atom atom1 = pose1.residue(i).atom(atom_num);
const core::conformation::Atom atom2 = pose2.residue(i).atom(atom_num);
const numeric::xyzVector<Real> xyz1 = atom1.xyz();
const numeric::xyzVector<Real> xyz2 = atom2.xyz();
const Real delta = xyz1.distance(xyz2);
if ( delta > tol ) {
// exceed tolerance
return false;
}
}
return true;
}
core::Size
PoissonBoltzmannEnergy::version() const
{
return 1; // Initial versioning
}
} // methods
} // scoring
} // core
| [
"malaifa@yahoo.com"
] | malaifa@yahoo.com |
d8d0cb1d0a4ac59feed63366c58a1270f7874b19 | 99f10345da76d84c1d4400e3798bde8ca72d6875 | /src/methods.cpp | ade1ebcae7bab117d79246fc29f7bea6c8bd3694 | [] | no_license | Drvanon/tinyweb | caee17ab6f09cdd94e6e7e7ef6dc8dc98e86186e | ec522028f9843ca7f93eef2537f0191dbbe1e95b | refs/heads/master | 2020-08-04T16:18:19.874413 | 2020-06-15T14:38:20 | 2020-06-15T14:38:20 | 212,199,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,313 | cpp | #include "methods.h"
namespace tinyweb
{
METHODS string_to_method (std::string str) {
METHODS method;
if (str == "GET") {
method = METHODS::GET;
} else if (str == "HEAD") {
method = METHODS::HEAD;
} else if (str == "POST") {
method = METHODS::POST;
} else if (str == "PUT") {
method = METHODS::PUT;
} else if (str == "DELETE") {
method = METHODS::DELETE;
} else if (str == "TRACE") {
method = METHODS::TRACE;
} else if (str == "CONNECT") {
method = METHODS::CONNECT;
}
return method;
}
std::string method_to_string (METHODS method) {
std::string str;
if (method == METHODS::GET) {
str == "GET";
} else if (method == METHODS::HEAD) {
str == "HEAD";
} else if (method == METHODS::POST) {
str == "POST";
} else if (method == METHODS::PUT) {
str == "PUT";
} else if (method == METHODS::DELETE) {
str == "DELETE";
} else if (method == METHODS::TRACE) {
str == "TRACE";
} else if (method == METHODS::CONNECT) {
str == "CONNECT";
}
return str;
}
} // namespace tinyweb
| [
"robin@gridt.org"
] | robin@gridt.org |
38ab5016f5a605ea7d7245f14ae0eeebd65862c6 | b38ab36ce6710bda9c495301d1d7b8769cfd454b | /projects/GoldMiner/Classes/SelectRoleAndPropMenu.cpp | 835bc0496f2f8f5738f24c7e297b4ebd29abfeaf | [] | no_license | wjf1616/TheMiners | 604fa141dbbe614a87ea88a1d9d9a4bc60678070 | afdb2eab217ad90434736d9580e942d5622bf929 | refs/heads/master | 2021-01-10T02:21:26.861908 | 2016-01-06T10:18:58 | 2016-01-06T10:18:58 | 48,987,660 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 83,442 | cpp | #include "SelectRoleAndPropMenu.h"
#include "Global.h"
#include "GoldenMinerScene.h"
#include "RoleInformation.h"
#include "Player.h"
#include "CartoonLayer.h"
#include "GameControl.h"
#include "LoadingLayer.h"
#include "PromptLayer.h"
USING_NS_CC;
USING_NS_CC_EXT;
#define SELECTROLEANDPROPMENU_YUN_ASIDE 11
#define SELECTROLEANDPROPMENU_FRAME_ASIDE 111
#define SELECTROLEANDPROPMENU_BUTTON_ASIDE 11
#define SELECTROLEANDPROPMENU_YUN_MIDDLE 21
#define SELECTROLEANDPROPMENU_FRAME_MIDDLE 121
#define SELECTROLEANDPROPMENU_BUTTON_MIDDLE 21
#define SELECTROLEANDPROPMENU_BUTTON_SELECTED_UP 102
#define SELECTROLEANDPROPMENU_BUTTON_UNSELECTED_DOWN 101
#define SELECTROLEANDPROPMENU_POINT_Y 40
#define SELECTROLEANDPROPMENU_POINT_X 30
static const ccColor3B myGrey={60,60,60};
static const ccColor4B myGrey4 = {0,0,0,200};
SelectRoleAndPropMenu::SelectRoleAndPropMenu(void)
: mAnimationManager(NULL)
,greyLayer(NULL)
,isBackGround(false)
,loadingLayer(NULL)
{
}
SelectRoleAndPropMenu::~SelectRoleAndPropMenu(void)
{
CC_SAFE_RELEASE_NULL(mAnimationManager);
CC_SAFE_RELEASE_NULL(rolePageButton);// 人物选择按钮
CC_SAFE_RELEASE_NULL(propPageButton);// 道具选择按钮
CC_SAFE_RELEASE_NULL(ingotNum);// 道具选择按钮
CC_SAFE_RELEASE_NULL(coupletSelect);// 道具选择按钮
CC_SAFE_RELEASE_NULL(coupletAbout);// 道具选择按钮
CC_SAFE_DELETE(propControl);
CCObject * p;
CC_SAFE_RELEASE(pointIndexSprite);
CCARRAY_FOREACH(selectPropId, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectRoleSpritesName, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(pointRoleSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(pointPropSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectPropPrice, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectPropName, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectSpritesIntroduce, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectRoleSpeedBackground, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectRolePowerBackground, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectRoleSpeed, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectRolePower, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectRoleSpritesSpeed, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectRoleSpritesPower, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectRoleSpritesIntroduce, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectPropIntroduce, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectPropPrice, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectPropName, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectRoleSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectRoleSpritesIsHaving, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectRoleSpritesIsOpen, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(selectPropSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectRoleSpritesIsHaving, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectRoleSpritesIsOpen, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectYunSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectButtonSelectSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectPropFrameSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectGetSelectSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectAboutSelectSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectFrameSprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCARRAY_FOREACH(currSelectButtonBuySprites, p)
{
CC_SAFE_RELEASE_NULL(p);
}
CCLOG("SelectRoleAndPropMenu::~SelectRoleAndPropMenu");
}
void SelectRoleAndPropMenu::onEnter(void)
{
CCLayer::onEnter();
setVisible(false);
isBackGround = true;
Player::getInstance()->getMusicControl()->playOtherBackGround();
isFristRolePage = true;
isFristPropPage = true;
currRoleIndex = 0;
currPropIndex = 0;
isRolePage = false;
rolePageButton = CCSprite::create("xuanren/renwu.png");
CC_SAFE_RETAIN(rolePageButton);
addChild(rolePageButton);
propPageButton = CCSprite::create("xuanren/daoju.png");
CC_SAFE_RETAIN(propPageButton);
addChild(propPageButton);
char _s[32];
sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT));
ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0');
CC_SAFE_RETAIN(ingotNum);
addChild(ingotNum, 998);
coupletSelect = CCSprite::create("xuanren/yishangzhen.png");// 已上阵
coupletSelect->setPosition(ccp(280, 320));
CC_SAFE_RETAIN(coupletSelect);
addChild(coupletSelect);
coupletAbout = CCSprite::create("xuanren/weijiesuo.png");// 未解锁
coupletAbout->setPosition(ccp(280, 320));
CC_SAFE_RETAIN(coupletAbout);
addChild(coupletAbout);
currSelectSprites = new CCArray();
currSelectRoleSpritesIsHaving = new cocos2d::CCArray();
selectRoleSpritesIsOpen = new cocos2d::CCArray();
selectPropSprites = new CCArray();
selectRoleSprites = new CCArray();
selectRoleSpritesIsHaving = new cocos2d::CCArray();
currSelectRoleSpritesIsOpen = new cocos2d::CCArray();
// 人物界面
selectRoleSpritesName = new CCArray();
currSelectRoleSpeedBackground = new CCArray();
currSelectRolePowerBackground = new CCArray();
currSelectRoleSpeed = new CCArray();
currSelectRolePower = new CCArray();
currSelectYunSprites = new CCArray();
currSelectButtonSelectSprites = new CCArray();
currSelectAboutSelectSprites = new CCArray();
currSelectGetSelectSprites = new CCArray();
currSelectFrameSprites = new CCArray();
currSelectSpritesIntroduce = new cocos2d::CCArray();
selectRoleSpritesSpeed = new CCArray();
selectRoleSpritesPower = new CCArray();
selectRoleSpritesIntroduce = new CCArray();
currSelectPropPrice = new cocos2d::CCArray();
currSelectPropName = new cocos2d::CCArray();
pointRoleSprites = new cocos2d::CCArray();
// 道具界面
currSelectButtonBuySprites = new CCArray();
currSelectPropFrameSprites = new cocos2d::CCArray();
selectPropIntroduce = new CCArray();
selectPropPrice = new CCArray();
selectPropName = new CCArray();
pointPropSprites = new cocos2d::CCArray();
selectPropId = new cocos2d::CCArray();
initSprites();
setPageButton(isRolePage);
Global::getInstance()->setSelectRoleId(Player::getInstance()->getLastRoleSelect());
((CCSprite *)selectRoleSpritesName->objectAtIndex((currRoleIndex + 1)%selectRoleSpritesName->count()))->setVisible(false);
schedule(schedule_selector(SelectRoleAndPropMenu::doAction), 0);
setTouchEnabled(true);
setKeypadEnabled(true);
}
void SelectRoleAndPropMenu::onEnterTransitionDidFinish(void)
{
CCLayer::onEnterTransitionDidFinish();
if (loadingLayer != NULL)
{
((LoadingLayer *)loadingLayer)->appendFinishLayerNum(1);
}
else
{
startSelf();
}
}
void SelectRoleAndPropMenu::startSelf(void)
{
setVisible(true);
isBackGround = false;
mAnimationManager->runAnimationsForSequenceNamed("daojuchuxian");
}
void SelectRoleAndPropMenu::setLoadingLayer(cocos2d::CCLayer * _layer)
{
loadingLayer = _layer;
if (loadingLayer == NULL)
{
setVisible(true);
}
}
void SelectRoleAndPropMenu::keyBackClicked(void)
{
onMenuItemBackClicked(NULL);
}
void SelectRoleAndPropMenu::onExit(void)
{
mAnimationManager->setAnimationCompletedCallback(NULL, NULL);
CCLayer::onExit();
}
SEL_MenuHandler SelectRoleAndPropMenu::onResolveCCBCCMenuItemSelector(CCObject * pTarget, const char * pSelectorName) {
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBack", SelectRoleAndPropMenu::onMenuItemBackClicked);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnPlay", SelectRoleAndPropMenu::onMenuItemPlayClicked);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnPlus", SelectRoleAndPropMenu::onMenuItemPlusClicked);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnShop", SelectRoleAndPropMenu::onMenuItemShopClicked);
// 解锁信息
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnUnlock1", SelectRoleAndPropMenu::menuAbout1Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnUnlock2", SelectRoleAndPropMenu::menuAbout2Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnUnlock3", SelectRoleAndPropMenu::menuAbout3Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnUnlock4", SelectRoleAndPropMenu::menuAbout4Callback);
// 购买道具
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBuy1", SelectRoleAndPropMenu::menuBuy1Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBuy2", SelectRoleAndPropMenu::menuBuy2Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBuy3", SelectRoleAndPropMenu::menuBuy3Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBuy4", SelectRoleAndPropMenu::menuBuy4Callback);
// 招募
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnRecruit1", SelectRoleAndPropMenu::menuGet1Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnRecruit2", SelectRoleAndPropMenu::menuGet2Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnRecruit3", SelectRoleAndPropMenu::menuGet3Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnRecruit4", SelectRoleAndPropMenu::menuGet4Callback);
// 上阵
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBattle1", SelectRoleAndPropMenu::menuSelect1Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBattle2", SelectRoleAndPropMenu::menuSelect2Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBattle3", SelectRoleAndPropMenu::menuSelect3Callback);
CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBattle4", SelectRoleAndPropMenu::menuSelect4Callback);
return NULL;
}
SEL_CCControlHandler SelectRoleAndPropMenu::onResolveCCBCCControlSelector(CCObject * pTarget, const char * pSelectorName) {
return NULL;
}
bool SelectRoleAndPropMenu::onAssignCCBMemberVariable(CCObject * pTarget, const char * pMemberVariableName, CCNode * pNode) {
CCB_MEMBERVARIABLEASSIGNER_GLUE(this, "mAnimationManager", CCBAnimationManager *, this->mAnimationManager);
return false;
}
void SelectRoleAndPropMenu::setAnimationManager(cocos2d::extension::CCBAnimationManager *pAnimationManager)
{
CC_SAFE_RELEASE_NULL(mAnimationManager);
mAnimationManager = pAnimationManager;
//mAnimationManager->runAnimationsForSequenceNamed("daojuchuxian");
mAnimationManager->setAnimationCompletedCallback(this, callfunc_selector(SelectRoleAndPropMenu::doAnimationCompleted));
CC_SAFE_RETAIN(mAnimationManager);
}
void SelectRoleAndPropMenu::setBackGround(bool _b)
{
if (_b == true)
{
if (greyLayer == NULL)
{
greyLayer = CCLayerColor::create(myGrey4);
}
Global::getInstance()->s->addLayerToRunningScene(greyLayer);
}
else
{
if (greyLayer != NULL)
{
Global::getInstance()->s->removeLayerToRunningScene(greyLayer);
greyLayer = NULL;
}
}
isBackGround = _b;
}
void SelectRoleAndPropMenu::onMenuItemShopClicked(cocos2d::CCObject * pSender)
{
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
}
void SelectRoleAndPropMenu::onMenuItemBackClicked(cocos2d::CCObject * pSender)
{
//Global::getInstance()->s->replaceScene(Global::getInstance()->s->getShopLayer(NULL));
//if (Global::getInstance()->getChallengeLevel() != 0)
//{
// LoadingLayer * _tmp;
// CCLayer * _tmp1;
// _tmp = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer();
// _tmp1 = Global::getInstance()->s->getMainLayer(_tmp);
// _tmp->setNextLayer(LAYER_ID_MAIN, _tmp1);
// _tmp->addLoadingLayer(0,_tmp1);
// Global::getInstance()->s->replaceScene(_tmp);
// //Global::getInstance()->s->replaceScene(Global::getInstance()->s->getMainLayer());
//}
//else
//{
// // 有loading
// Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
// LoadingLayer * _tmp;
// CCLayer * _tmp1;
// _tmp = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer();
// _tmp1 = Global::getInstance()->s->getSimleGateMenu(_tmp);
// _tmp->setNextLayer(LAYER_ID_SMILE_GATE_SCENCE, _tmp1);
// _tmp->addLoadingLayer(0,_tmp1);
// Global::getInstance()->s->replaceScene(_tmp);
// //Global::getInstance()->s->replaceScene(Global::getInstance()->s->getSimleGateMenu());
//
// // 没有loading
// //Global::getInstance()->s->replaceScene(Global::getInstance()->s->getSimleGateMenu(NULL));
//}
}
void SelectRoleAndPropMenu::onMenuItemPlayClicked(cocos2d::CCObject * pSender)
{
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
Player::getInstance()->setLastRoleSelect(Global::getInstance()->getSelectRoleId());
if (Global::getInstance()->getChallengeLevel() != 0)
{
//// 开始游戏loading的页面
//LoadingLayer * p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer();
//CCLayer * p1 = Global::getInstance()->s->getChallengeLayer(Global::getInstance()->getNextChallengeGateId(), Global::getInstance()->getSelectRoleId(), p);
////((GameControl *)p1)->setLoadingLayer(p);
////p->appendLoadingLayerNum(1);
//p->addLoadingLayer(0,p1);
//p->setNextLayer(LAYER_ID_GAMING, p1);
//Global::getInstance()->s->replaceScene(p);
////Global::getInstance()->s->addLayerToRunningScene(p1);
//开始游戏没有loading的页面
Global::getInstance()->s->replaceScene(Global::getInstance()->s->getChallengeLayer(Global::getInstance()->getNextChallengeGateId(), Global::getInstance()->getSelectRoleId(), NULL));
//Global::getInstance()->s->replaceScene(Global::getInstance()->s->getChallengeLayer(Global::getInstance()->getNextChallengeGateId(), Global::getInstance()->getSelectRoleId()));
}
else
{
Player::getInstance()->setLastMapId(Global::getInstance()->getMapIdByGateId(Global::getInstance()->getSelectGateId()));
// 播放漫画
Global::getInstance()->setCartoonId(0);
Global::getInstance()->setCartoonId(Global::getInstance()->getSelectGateId());
//// 开始游戏loading的页面
//LoadingLayer * p = NULL;
//CCLayer * p1 = NULL;
//CCLayer * p2 = NULL;
//CCLayer * p3 = NULL;
//switch(Global::getInstance()->getCartoonId())
//{
//case 0:
// p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer();
// p1 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p);
// p->setNextLayer(LAYER_ID_GAMING, p1);
// //((GameControl *)p1)->setLoadingLayer(p);
// //p->appendLoadingLayerNum(1);
// p->addLoadingLayer(0,p1);
// Global::getInstance()->s->replaceScene(p);
// //Global::getInstance()->s->addLayerToRunningScene(p1);
// break;
//case CARTOON_BAOXIANGGUO:
// p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer();
// p1 = Global::getInstance()->s->getCartoonLayer(CARTOON_START, p);
// p2 = Global::getInstance()->s->getCartoonLayer(CARTOON_BAOXIANGGUO, p);
// p3 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p);
// p->setNextLayer(LAYER_ID_CARTOON, p1);
// ((CartoonLayer *)p1)->setNextLayer(LAYER_ID_CARTOON, p2);
// ((CartoonLayer *)p2)->setNextLayer(LAYER_ID_GAMING, p3);
// //((CartoonLayer *)p1)->setLoadingLayer(p);
// //((CartoonLayer *)p2)->setLoadingLayer(p);
// //((GameControl *)p3)->setLoadingLayer(p);
// //p->appendLoadingLayerNum(1);
// p->addLoadingLayer(0,p1);
// p->addLoadingLayer(0,p2);
// p->addLoadingLayer(0,p3);
// Global::getInstance()->s->replaceScene(p);
// //Global::getInstance()->s->addLayerToRunningScene(p1);
// //Global::getInstance()->s->addLayerToRunningScene(p2);
// //Global::getInstance()->s->addLayerToRunningScene(p3);
// break;
//case CARTOON_TONGYIANHE:
// p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer();
// p1 = Global::getInstance()->s->getCartoonLayer(CARTOON_TONGYIANHE,p);
// p2 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p);
// p->setNextLayer(LAYER_ID_CARTOON, p1);
// ((CartoonLayer *)p1)->setNextLayer(LAYER_ID_GAMING, p2);
// //((CartoonLayer *)p1)->setLoadingLayer(p);
// //((GameControl *)p2)->setLoadingLayer(p);
// //p->appendLoadingLayerNum(1);
// p->addLoadingLayer(0,p1);
// p->addLoadingLayer(0,p2);
// Global::getInstance()->s->replaceScene(p);
// //Global::getInstance()->s->addLayerToRunningScene(p1);
// //Global::getInstance()->s->addLayerToRunningScene(p2);
// break;
//case CARTOON_NVERGUO:
// p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer();
// p1 = Global::getInstance()->s->getCartoonLayer(CARTOON_NVERGUO,p);
// p2 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p);
// p->setNextLayer(LAYER_ID_CARTOON, p1);
// ((CartoonLayer *)p1)->setNextLayer(LAYER_ID_GAMING, p2);
// //((CartoonLayer *)p1)->setLoadingLayer(p);
// //((GameControl *)p2)->setLoadingLayer(p);
// //p->appendLoadingLayerNum(1);
// p->addLoadingLayer(0,p1);
// p->addLoadingLayer(0,p2);
// Global::getInstance()->s->replaceScene(p);
// //Global::getInstance()->s->addLayerToRunningScene(p1);
// //Global::getInstance()->s->addLayerToRunningScene(p2);
// break;
//case CARTOON_HUOYANSHAN:
// p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer();
// p1 = Global::getInstance()->s->getCartoonLayer(CARTOON_HUOYANSHAN,p);
// p2 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p);
// p->setNextLayer(LAYER_ID_CARTOON, p1);
// ((CartoonLayer *)p1)->setNextLayer(LAYER_ID_GAMING, p2);
// //((CartoonLayer *)p1)->setLoadingLayer(p);
// //((GameControl *)p2)->setLoadingLayer(p);
// //p->appendLoadingLayerNum(1);
// p->addLoadingLayer(0,p1);
// p->addLoadingLayer(0,p2);
// Global::getInstance()->s->replaceScene(p);
// //Global::getInstance()->s->addLayerToRunningScene(p1);
// //Global::getInstance()->s->addLayerToRunningScene(p2);
// break;
//case CARTOON_LINGSHAN:
// p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer();
// p1 = Global::getInstance()->s->getCartoonLayer(CARTOON_LINGSHAN,p);
// p2 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p);
// p->setNextLayer(LAYER_ID_CARTOON, p1);
// ((CartoonLayer *)p1)->setNextLayer(LAYER_ID_GAMING, p2);
// //((CartoonLayer *)p1)->setLoadingLayer(p);
// //((GameControl *)p2)->setLoadingLayer(p);
// //p->appendLoadingLayerNum(1);
// p->addLoadingLayer(0,p1);
// p->addLoadingLayer(0,p2);
// Global::getInstance()->s->replaceScene(p);
// //Global::getInstance()->s->addLayerToRunningScene(p1);
// //Global::getInstance()->s->addLayerToRunningScene(p2);
// break;
//default:
// break;
//}
// 开始游戏loading的页面
if (Global::getInstance()->getCartoonId() != 0)
{
if (Global::getInstance()->getCartoonId() == CARTOON_BAOXIANGGUO)
{
Global::getInstance()->s->replaceScene(Global::getInstance()->s->getCartoonLayer(CARTOON_START, NULL));
}
else
{
Global::getInstance()->s->replaceScene(Global::getInstance()->s->getCartoonLayer(Global::getInstance()->getCartoonId(), NULL));
}
}
else
{
Global::getInstance()->s->replaceScene(Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(), NULL));
}
//// 播放漫画
//Global::getInstance()->setCartoonId(Global::getInstance()->getSelectGateId());
//if (Global::getInstance()->getCartoonId() != 0)
//{
// Global::getInstance()->s->replaceScene(Global::getInstance()->s->getCartoonLayer(Global::getInstance()->getCartoonId()));
//}
//else
//{
// Player::getInstance()->setLastMapId(Global::getInstance()->getSelectGateId());
// Global::getInstance()->s->replaceScene(Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId()));
//}
}
}
void SelectRoleAndPropMenu::onMenuItemPlusClicked(cocos2d::CCObject * pSender)
{
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
}
void SelectRoleAndPropMenu::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
if (isBackGround)
{
return;
}
//此方法是cocos2d-x的标准操作,取touch集合第一个touch,将其位置转成opengl坐标,没办法,这些坐标太乱了,touch默认坐标是屏幕坐标,左上角为远点,cocos默认坐标是opengl坐标,左下角是原点。
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
m_touchBeginPos = touch->getLocation ();
m_touchBeginPos = CCDirector::sharedDirector()->convertToGL( m_touchBeginPos );
if (isRolePage)
{
isCheckButtonIsSelected = Global::getInstance()->isInRect(
new CCRect(rolePageButton->getPositionX() + rolePageButton->getContentSize().width/2,
propPageButton->getPositionY() - propPageButton->getContentSize().height*0.7/2,
propPageButton->getContentSize().width*0.7,
propPageButton->getContentSize().height*0.7
),
m_touchBeginPos.x,
480 - m_touchBeginPos.y);
}
else
{
isCheckButtonIsSelected = Global::getInstance()->isInRect(
new CCRect(rolePageButton->getPositionX() - rolePageButton->getContentSize().width*0.7/2,
rolePageButton->getPositionY() - rolePageButton->getContentSize().height*0.7/2,
propPageButton->getPositionX() - (rolePageButton->getPositionX() - rolePageButton->getContentSize().width*0.7/2),
rolePageButton->getContentSize().height*0.7
),
m_touchBeginPos.x,
480 - m_touchBeginPos.y);
}
m_touchMove = false;
}
void SelectRoleAndPropMenu::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
{
if (isBackGround)
{
return;
}
m_touchMove = true;
}
void SelectRoleAndPropMenu::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{
if (isBackGround)
{
return;
}
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
m_touchEndPos = touch->getLocation ();
m_touchEndPos = CCDirector::sharedDirector()->convertToGL( m_touchEndPos );
if(m_touchMove)
{
//如果move了,那么看手指是否上下滑动超过50像素,这个纠正值得有,否则太灵敏了
if ((m_touchBeginPos.x - m_touchEndPos.x) > 50)
{
if(isRolePage)
{
setCurrRole(true);
}
else
{
setCurrProp(true);
}
}
else if ((m_touchEndPos.x - m_touchBeginPos.x) > 50)
{
if(isRolePage)
{
setCurrRole(false);
}
else
{
setCurrProp(false);
}
}
else
{
checkButtonEvent();
}
}
else
{
checkButtonEvent();
}
m_touchMove = false;
}
void SelectRoleAndPropMenu::changeCurrPage(void)
{
for (int i = 0; i < selectRoleSpritesName->count(); i++)
{
((CCSprite *)selectRoleSpritesName->objectAtIndex(i))->setVisible(false);
}
if(isRolePage)
{
mAnimationManager->runAnimationsForSequenceNamed("rwxiaoshi");
// 换button的显示
}
else
{
mAnimationManager->runAnimationsForSequenceNamed("daojuxiaoshi");
// 换button的显示
}
}
void SelectRoleAndPropMenu::setCurrRole(bool _isXiangZuo)
{
if (_isXiangZuo)
{
setNodeBySelectIndex(_isXiangZuo);
currRoleIndex++;
currRoleIndex = currRoleIndex % selectRoleSprites->count();
mAnimationManager->runAnimationsForSequenceNamed("xiangzuo");
for (int i = 0; i < 4; i++)
{
if (i == 2)
{
currButtonIndex = 3;
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_MIDDLE);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE);
}
else
{
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_ASIDE);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE);
}
}
}
else
{
setNodeBySelectIndex(_isXiangZuo);
currRoleIndex--;
currRoleIndex = (currRoleIndex + selectRoleSprites->count()) % selectRoleSprites->count();
mAnimationManager->runAnimationsForSequenceNamed("xiangyou");
for (int i = 0; i < 4; i++)
{
if (i == 0)
{
currButtonIndex = 1;
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_MIDDLE);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE);
}
else
{
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_ASIDE);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE);
}
}
}
((CCSprite *)selectRoleSpritesName->objectAtIndex((currRoleIndex + 1)%selectRoleSpritesName->count()))->setVisible(true);
}
void SelectRoleAndPropMenu::setCurrProp(bool _isXiangZuo)
{
if (_isXiangZuo)
{
currButtonIndex = 3;
setNodeBySelectIndex(_isXiangZuo);
currPropIndex++;
currPropIndex = currPropIndex % selectPropSprites->count();
mAnimationManager->runAnimationsForSequenceNamed("djxiangzuo");
}
else
{
currButtonIndex = 1;
setNodeBySelectIndex(_isXiangZuo);
currPropIndex--;
currPropIndex = (currPropIndex + selectPropSprites->count()) % selectPropSprites->count();
mAnimationManager->runAnimationsForSequenceNamed("djxiangyou");
}
}
void SelectRoleAndPropMenu::checkButtonEvent(void)
{
if (isCheckButtonIsSelected)
{
if (isRolePage)
{
if (Global::getInstance()->isInRect(
new CCRect(rolePageButton->getPositionX() + rolePageButton->getContentSize().width/2,
propPageButton->getPositionY() - propPageButton->getContentSize().height*0.7/2,
propPageButton->getContentSize().width*0.7,
propPageButton->getContentSize().height*0.7
),
m_touchEndPos.x,
480 - m_touchEndPos.y))
{
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
changeCurrPage();
//setPageButton(false);
}
}
else
{
if (isCheckButtonIsSelected = Global::getInstance()->isInRect(
new CCRect(rolePageButton->getPositionX() - rolePageButton->getContentSize().width*0.7/2,
rolePageButton->getPositionY() - rolePageButton->getContentSize().height*0.7/2,
propPageButton->getPositionX() - (rolePageButton->getPositionX() - rolePageButton->getContentSize().width*0.7/2),
rolePageButton->getContentSize().height*0.7
),
m_touchEndPos.x,
480 - m_touchEndPos.y))
{
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
changeCurrPage();
//setPageButton(true);
}
}
}
}
void SelectRoleAndPropMenu::setPageButton(bool _isRolePage)
{
isRolePage = _isRolePage;
if (_isRolePage)
{
rolePageButton->setPosition(ccp(97,41));
rolePageButton->setScale(1);
rolePageButton->setZOrder(SELECTROLEANDPROPMENU_BUTTON_SELECTED_UP);
propPageButton->setPosition(ccp(204,28));
propPageButton->setScale(0.7);
propPageButton->setZOrder(SELECTROLEANDPROPMENU_BUTTON_UNSELECTED_DOWN);
for (int i = 0 ; i < 4; i++)
{
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setVisible(true);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setVisible(true);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setVisible(true);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setVisible(true);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setVisible(true);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setVisible(true);
((CCSprite *)currSelectPropName->objectAtIndex(i))->setVisible(false);
((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setVisible(false);
((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setVisible(false);
((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setVisible(false);
}
for (int i =0; i < pointRoleSprites->count(); i++)
{
((CCSprite *)pointRoleSprites->objectAtIndex(i))->setVisible(true);
}
for (int i =0; i < pointPropSprites->count(); i++)
{
((CCSprite *)pointPropSprites->objectAtIndex(i))->setVisible(false);
}
coupletAbout->setVisible(false);
coupletSelect->setVisible(false);
isFristRolePage = true;
setNodeBySelectIndex(true);
}
else
{
rolePageButton->setPosition(ccp(71,28));
rolePageButton->setScale(0.7);
rolePageButton->setZOrder(SELECTROLEANDPROPMENU_BUTTON_UNSELECTED_DOWN);
propPageButton->setPosition(ccp(182,41));
propPageButton->setScale(1);
propPageButton->setZOrder(SELECTROLEANDPROPMENU_BUTTON_SELECTED_UP);
for (int i = 0 ; i < 4; i++)
{
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setVisible(false);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setVisible(false);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setVisible(false);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setVisible(false);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setVisible(false);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setVisible(false);
((CCSprite *)currSelectPropName->objectAtIndex(i))->setVisible(true);
((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setVisible(true);
((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setVisible(true);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setVisible(false);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setVisible(false);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setVisible(false);
((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setVisible(true);
}
for (int i =0; i < pointRoleSprites->count(); i++)
{
((CCSprite *)pointRoleSprites->objectAtIndex(i))->setVisible(false);
}
for (int i =0; i < pointPropSprites->count(); i++)
{
((CCSprite *)pointPropSprites->objectAtIndex(i))->setVisible(true);
}
isFristPropPage = true;
coupletAbout->setVisible(false);
coupletSelect->setVisible(false);
setNodeBySelectIndex(true);
}
getChildByTag(999)->setZOrder(100);
}
void SelectRoleAndPropMenu::doAnimationCompleted(void)
{
if (strcmp(mAnimationManager->getLastCompletedSequenceName().c_str(),"rwxiaoshi") == 0)
{
setPageButton(false);
mAnimationManager->runAnimationsForSequenceNamed("daojuchuxian");
}
else if (strcmp(mAnimationManager->getLastCompletedSequenceName().c_str(),"daojuxiaoshi") == 0)
{
setPageButton(true);
mAnimationManager->runAnimationsForSequenceNamed("renwuchuxian2");
((CCSprite *)selectRoleSpritesName->objectAtIndex((currRoleIndex + 1)%selectRoleSpritesName->count()))->setVisible(true);
}
}
void SelectRoleAndPropMenu::reBack(int _type, bool _b)
{
setBackGround(false);
// type是值回来前调用界面的类型 这里没必要区分 只是购买才需要处理
if(_b)
{
int index = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex((currRoleIndex + 1) % selectRoleSprites->count()));
if(CC_INVALID_INDEX != index)
{
((CCSprite *)currSelectGetSelectSprites->objectAtIndex(index))->setVisible(false);
((CCSprite *)currSelectButtonSelectSprites->objectAtIndex(index))->setVisible(true);
}
index = (currRoleIndex + 1) % selectRoleSprites->count();
CCInteger * p = CCInteger::create(1);
selectRoleSpritesIsHaving->addObject(p);
selectRoleSpritesIsHaving->exchangeObjectAtIndex(selectRoleSpritesIsHaving->count()-1, index);
selectRoleSpritesIsHaving->removeLastObject();
char _s[32];
sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT));
removeChild(ingotNum);
ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0');
CC_SAFE_RETAIN(ingotNum);
addChild(ingotNum, 998);
}
}
void SelectRoleAndPropMenu::initSprites(void)
{
// 人物界面
// 龙女
if (Player::getInstance()->getRoleHavingStatusByRoleId(ROLE_TYPE_XIAOLONGNV))
{
selectRoleSpritesIsHaving->addObject(CCInteger::create(1));
selectRoleSpritesIsOpen->addObject(CCInteger::create(1));
selectRoleSprites->addObject(CCSprite::create("xuanren/longnv1.png"));
}
else
{
selectRoleSpritesIsHaving->addObject(CCInteger::create(0));
if (Player::getInstance()->getRoleOpenStatusByRoleId(ROLE_TYPE_XIAOLONGNV))
{
selectRoleSpritesIsOpen->addObject(CCInteger::create(1));
selectRoleSprites->addObject(CCSprite::create("xuanren/longnv1.png"));
}
else
{
selectRoleSpritesIsOpen->addObject(CCInteger::create(0));
selectRoleSprites->addObject(CCSprite::create("xuanren/longnv1.png"));
//selectRoleSprites->addObject(CCSprite::create("xuanren/longnvhui.png"));
}
}
selectRoleSpritesName->addObject(CCSprite::create("xuanren/longnv.png"));
((CCSprite *)selectRoleSpritesName->lastObject())->setPosition(ccp(405, 425));
((CCSprite *)selectRoleSpritesName->lastObject())->setVisible(false);
addChild((CCSprite *)selectRoleSpritesName->lastObject(), 998);
// 还要初始化是否拥有对象(假的现在)是否已经开启对象
selectRoleSpritesSpeed->addObject(CCInteger::create(1));
selectRoleSpritesPower->addObject(CCInteger::create(1));
selectRoleSpritesIntroduce->addObject(CCSprite::create("xuanren/hxsh.png"));
// 唐僧
selectRoleSpritesIsHaving->addObject(CCInteger::create(1));
selectRoleSpritesIsOpen->addObject(CCInteger::create(1));
selectRoleSprites->addObject(CCSprite::create("xuanren/tangseng1.png"));
selectRoleSpritesName->addObject(CCSprite::create("xuanren/tangseng.png"));
((CCSprite *)selectRoleSpritesName->lastObject())->setPosition(ccp(405, 425));
((CCSprite *)selectRoleSpritesName->lastObject())->setVisible(false);
addChild((CCSprite *)selectRoleSpritesName->lastObject(), 998);
// 还要初始化是否拥有对象(假的现在)是否已经开启对象
selectRoleSpritesSpeed->addObject(CCInteger::create(1));
selectRoleSpritesPower->addObject(CCInteger::create(1));
selectRoleSpritesIntroduce->addObject(CCSprite::create("xuanren/dscj.png"));
// 八戒
if (Player::getInstance()->getRoleHavingStatusByRoleId(ROLE_TYPE_ZHUBAJIE))
{
selectRoleSpritesIsHaving->addObject(CCInteger::create(1));
selectRoleSpritesIsOpen->addObject(CCInteger::create(1));
selectRoleSprites->addObject(CCSprite::create("xuanren/bajie1.png"));
}
else
{
selectRoleSpritesIsHaving->addObject(CCInteger::create(0));
if (Player::getInstance()->getRoleOpenStatusByRoleId(ROLE_TYPE_ZHUBAJIE))
{
selectRoleSpritesIsOpen->addObject(CCInteger::create(1));
selectRoleSprites->addObject(CCSprite::create("xuanren/bajie1.png"));
}
else
{
selectRoleSpritesIsOpen->addObject(CCInteger::create(0));
selectRoleSprites->addObject(CCSprite::create("xuanren/bajie1.png"));
//selectRoleSprites->addObject(CCSprite::create("xuanren/bajiehui.png"));
}
}
selectRoleSpritesName->addObject(CCSprite::create("xuanren/bajie.png"));
((CCSprite *)selectRoleSpritesName->lastObject())->setPosition(ccp(405, 425));
((CCSprite *)selectRoleSpritesName->lastObject())->setVisible(false);
addChild((CCSprite *)selectRoleSpritesName->lastObject(), 998);
// 还要初始化是否拥有对象(假的现在)是否已经开启对象
selectRoleSpritesSpeed->addObject(CCInteger::create(1));
selectRoleSpritesPower->addObject(CCInteger::create(1));
selectRoleSpritesIntroduce->addObject(CCSprite::create("xuanren/dahailaoz.png"));
// 沙僧
if (Player::getInstance()->getRoleHavingStatusByRoleId(ROLE_TYPE_SHAHESHANG))
{
selectRoleSpritesIsHaving->addObject(CCInteger::create(1));
selectRoleSpritesIsOpen->addObject(CCInteger::create(1));
selectRoleSprites->addObject(CCSprite::create("xuanren/shaseng1.png"));
}
else
{
selectRoleSpritesIsHaving->addObject(CCInteger::create(0));
if (Player::getInstance()->getRoleOpenStatusByRoleId(ROLE_TYPE_SHAHESHANG))
{
selectRoleSpritesIsOpen->addObject(CCInteger::create(1));
selectRoleSprites->addObject(CCSprite::create("xuanren/shaseng1.png"));
}
else
{
selectRoleSpritesIsOpen->addObject(CCInteger::create(0));
selectRoleSprites->addObject(CCSprite::create("xuanren/shaseng1.png"));
//selectRoleSprites->addObject(CCSprite::create("xuanren/shasenghui.png"));
}
}
selectRoleSpritesName->addObject(CCSprite::create("xuanren/shaseng.png"));
((CCSprite *)selectRoleSpritesName->lastObject())->setPosition(ccp(405, 425));
((CCSprite *)selectRoleSpritesName->lastObject())->setVisible(false);
addChild((CCSprite *)selectRoleSpritesName->lastObject(), 998);
// 还要初始化是否拥有对象(假的现在)是否已经开启对象
selectRoleSpritesSpeed->addObject(CCInteger::create(1));
selectRoleSpritesPower->addObject(CCInteger::create(1));
selectRoleSpritesIntroduce->addObject(CCSprite::create("xuanren/jjdj.png"));
// 悟空
if (Player::getInstance()->getRoleHavingStatusByRoleId(ROLE_TYPE_SUNWUKONG))
{
selectRoleSpritesIsHaving->addObject(CCInteger::create(1));
selectRoleSpritesIsOpen->addObject(CCInteger::create(1));
selectRoleSprites->addObject(CCSprite::create("xuanren/wukong1.png"));
}
else
{
selectRoleSpritesIsHaving->addObject(CCInteger::create(0));
if (Player::getInstance()->getRoleOpenStatusByRoleId(ROLE_TYPE_SUNWUKONG))
{
selectRoleSpritesIsOpen->addObject(CCInteger::create(1));
selectRoleSprites->addObject(CCSprite::create("xuanren/wukong1.png"));
}
else
{
selectRoleSpritesIsOpen->addObject(CCInteger::create(0));
selectRoleSprites->addObject(CCSprite::create("xuanren/wukong1.png"));
//selectRoleSprites->addObject(CCSprite::create("xuanren/wukonghui.png"));
}
}
selectRoleSpritesName->addObject(CCSprite::create("xuanren/wukong.png"));
((CCSprite *)selectRoleSpritesName->lastObject())->setPosition(ccp(405, 425));
((CCSprite *)selectRoleSpritesName->lastObject())->setVisible(false);
addChild((CCSprite *)selectRoleSpritesName->lastObject(), 998);
// 还要初始化是否拥有对象(假的现在)是否已经开启对象
selectRoleSpritesSpeed->addObject(CCInteger::create(1));
selectRoleSpritesPower->addObject(CCInteger::create(1));
selectRoleSpritesIntroduce->addObject(CCSprite::create("xuanren/sjjz.png"));
// 添加任务点点
for (int i = 0; i < 5; i++)
{
pointRoleSprites->addObject(CCSprite::create("xuandaguan/dian2.png"));
((CCSprite *)pointRoleSprites->lastObject())->setPosition(ccp(400 - 5*SELECTROLEANDPROPMENU_POINT_X/2 + i*SELECTROLEANDPROPMENU_POINT_X + SELECTROLEANDPROPMENU_POINT_X/2, SELECTROLEANDPROPMENU_POINT_Y));
addChild((CCSprite *)pointRoleSprites->lastObject());
}
// 道具界面 当界面选项不足所需的4个时候 要添加一个循环
char _s[32];
propControl = new Prop();
selectPropSprites->addObject(CCSprite::create("xuanren/sl.png"));
selectPropName->addObject(CCSprite::create("xuanren/sl1.png"));
sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_MOONLIGHT));
selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'));
selectPropId->addObject(CCInteger::create(PROP_TYPE_MOONLIGHT));
selectPropIntroduce->addObject(CCSprite::create("xuanren/sl2.png"));
selectPropSprites->addObject(CCSprite::create("xuanren/zd.png"));
selectPropName->addObject(CCSprite::create("xuanren/zhadan.png"));
sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_GRENADE));
selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'));
selectPropId->addObject(CCInteger::create(PROP_TYPE_GRENADE));
selectPropIntroduce->addObject(CCSprite::create("xuanren/zd1.png"));
selectPropSprites->addObject(CCSprite::create("xuanren/llys.png"));
selectPropName->addObject(CCSprite::create("xuanren/llys1.png"));
sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_VIGOROUSLY_PILL));
selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'));
selectPropId->addObject(CCInteger::create(PROP_TYPE_VIGOROUSLY_PILL));
selectPropIntroduce->addObject(CCSprite::create("xuanren/dlys2.png"));
selectPropSprites->addObject(CCSprite::create("xuanren/miaozhunjing.png"));
selectPropName->addObject(CCSprite::create("xuanren/miaozhunjing2.png"));
sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_ALIGNMENT));
selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'));
selectPropId->addObject(CCInteger::create(PROP_TYPE_ALIGNMENT));
selectPropIntroduce->addObject(CCSprite::create("xuanren/miaozhunjing1.png"));
//selectPropSprites->addObject(CCSprite::create("xuanren/sl.png"));
//selectPropName->addObject(CCSprite::create("xuanren/sl1.png"));
//sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_MOONLIGHT));
//selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'));
//selectPropId->addObject(CCInteger::create(PROP_TYPE_MOONLIGHT));
//selectPropIntroduce->addObject(CCSprite::create("xuanren/sl2.png"));
//selectPropSprites->addObject(CCSprite::create("xuanren/zd.png"));
//selectPropName->addObject(CCSprite::create("xuanren/zhadan.png"));
//sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_GRENADE));
//selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'));
//selectPropId->addObject(CCInteger::create(PROP_TYPE_GRENADE));
//selectPropIntroduce->addObject(CCSprite::create("xuanren/zd1.png"));
//selectPropSprites->addObject(CCSprite::create("xuanren/llys.png"));
//selectPropName->addObject(CCSprite::create("xuanren/llys1.png"));
//sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_VIGOROUSLY_PILL));
//selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'));
//selectPropId->addObject(CCInteger::create(PROP_TYPE_VIGOROUSLY_PILL));
//selectPropIntroduce->addObject(CCSprite::create("xuanren/sl2.png"));
// 添加道具点点
for (int i = 0; i < 4; i++)
{
pointPropSprites->addObject(CCSprite::create("xuandaguan/dian2.png"));
((CCSprite *)pointPropSprites->lastObject())->setPosition(ccp(400 - 3*SELECTROLEANDPROPMENU_POINT_X/2 + i*SELECTROLEANDPROPMENU_POINT_X + SELECTROLEANDPROPMENU_POINT_X/2, SELECTROLEANDPROPMENU_POINT_Y));
addChild((CCSprite *)pointPropSprites->lastObject());
}
// 亮点点
pointIndexSprite = CCSprite::create("xuandaguan/dian1.png");
pointIndexSprite->retain();
addChild(pointIndexSprite,998);
currSelectButtonSelectSprites->addObject(getChildByTag(999)->getChildByTag(41));
currSelectButtonSelectSprites->addObject(getChildByTag(999)->getChildByTag(42));
currSelectButtonSelectSprites->addObject(getChildByTag(999)->getChildByTag(43));
currSelectButtonSelectSprites->addObject(getChildByTag(999)->getChildByTag(44));
currSelectAboutSelectSprites->addObject(getChildByTag(999)->getChildByTag(11));
currSelectAboutSelectSprites->addObject(getChildByTag(999)->getChildByTag(12));
currSelectAboutSelectSprites->addObject(getChildByTag(999)->getChildByTag(13));
currSelectAboutSelectSprites->addObject(getChildByTag(999)->getChildByTag(14));
currSelectGetSelectSprites->addObject(getChildByTag(999)->getChildByTag(31));
currSelectGetSelectSprites->addObject(getChildByTag(999)->getChildByTag(32));
currSelectGetSelectSprites->addObject(getChildByTag(999)->getChildByTag(33));
currSelectGetSelectSprites->addObject(getChildByTag(999)->getChildByTag(34));
currSelectButtonBuySprites->addObject(getChildByTag(999)->getChildByTag(21));
currSelectButtonBuySprites->addObject(getChildByTag(999)->getChildByTag(22));
currSelectButtonBuySprites->addObject(getChildByTag(999)->getChildByTag(23));
currSelectButtonBuySprites->addObject(getChildByTag(999)->getChildByTag(24));
for (int i = 0; i< 4; i++)
{
currSelectYunSprites->addObject(CCSprite::create("xuanren/yun.png"));
addChild((CCSprite *)currSelectYunSprites->objectAtIndex(i));
currSelectFrameSprites->addObject(CCSprite::create("xuanren/jieshao.png"));
addChild((CCSprite *)currSelectFrameSprites->objectAtIndex(i));
currSelectRoleSpeedBackground->addObject(CCSprite::create("xuanren/hui.png"));
addChild((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i));
currSelectRolePowerBackground->addObject(CCSprite::create("xuanren/hui.png"));
addChild((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i));
currSelectRoleSpeed->addObject(CCSprite::create("xuanren/lan.png"));
addChild((CCSprite *)currSelectRoleSpeed->objectAtIndex(i));
currSelectRolePower->addObject(CCSprite::create("xuanren/hong.png"));
addChild((CCSprite *)currSelectRolePower->objectAtIndex(i));
//addChild((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i));
//addChild((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i));
//addChild((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i));
currSelectPropName->addObject((CCSprite *)selectPropName->objectAtIndex(i));
currSelectPropPrice->addObject((CCSprite *)selectPropPrice->objectAtIndex(i));
currSelectSprites->addObject(selectRoleSprites->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count()));
currSelectSpritesIntroduce->addObject(selectRoleSpritesIntroduce->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count()));
currSelectPropFrameSprites->addObject(CCSprite::create("xuanren/daojukuang.png"));
getChildByTag(i+1)->addChild((CCSprite *)currSelectSprites->objectAtIndex(i));
addChild((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i));
addChild((CCSprite *)currSelectPropPrice->objectAtIndex(i));
addChild((CCSprite *)currSelectPropName->objectAtIndex(i));
((CCSprite *)currSelectPropName->objectAtIndex(i))->setVisible(false);
getChildByTag(i+1)->addChild((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i));
//if (i % 2 == 0)
//{
// ((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(myGrey);
//}
}
}
void SelectRoleAndPropMenu::setNodeBySelectIndex(bool _isXiangZuo)
{
if (isRolePage)
{
for (int i = 4; i > 0; i--)
{// 移除node中的ccSprite
getChildByTag(i)->removeChild((CCSprite *)currSelectSprites->lastObject());
removeChild((CCSprite *)currSelectSpritesIntroduce->lastObject(),true);
currSelectSprites->removeLastObject();
currSelectSpritesIntroduce->removeLastObject();
}
for (int i = 0; i< 4; i++)
{
// 按钮显示相关
if (((CCInteger *)selectRoleSpritesIsHaving->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count()))->getValue() == 1)
{
// 拥有人物
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setVisible(true);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setVisible(false);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setVisible(false);
}
else
{ // 没有拥有人物
if (((CCInteger *)selectRoleSpritesIsOpen->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count()))->getValue() == 1)
{// 可以购买人物
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setVisible(false);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setVisible(true);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setVisible(false);
}
else
{// 不能购买人物 只能看介绍
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setVisible(false);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setVisible(false);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setVisible(true);
}
}
// 属性显示相关
if (_isXiangZuo)
{
currSelectSprites->addObject(selectRoleSprites->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count()));
currSelectSpritesIntroduce->addObject(selectRoleSpritesIntroduce->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count()));
}
else
{
if (i == 3)
{
currSelectSprites->addObject(selectRoleSprites->objectAtIndex((selectRoleSprites->count() - 1 + currRoleIndex) % selectRoleSprites->count()));
currSelectSpritesIntroduce->addObject(selectRoleSpritesIntroduce->objectAtIndex((selectRoleSprites->count() - 1 + currRoleIndex) % selectRoleSprites->count()));
}
else
{
currSelectSprites->addObject(selectRoleSprites->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count()));
currSelectSpritesIntroduce->addObject(selectRoleSpritesIntroduce->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count()));
}
}
getChildByTag(i+1)->addChild((CCSprite *)currSelectSprites->objectAtIndex(i));
addChild((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i));
if (isFristRolePage)
{
if (i % 2 == 0)
{
((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setColor(myGrey);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setColor(myGrey);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setColor(myGrey);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setColor(myGrey);
}
else
{
((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setColor(ccWHITE);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setColor(ccWHITE);
}
if (i == 1)
{
currButtonIndex = 2;
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_MIDDLE);
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_MIDDLE);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE);
}
else
{
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_ASIDE);
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_ASIDE);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE);
}
}
else
{
if (i % 2 == 1)
{
((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setColor(myGrey);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setColor(myGrey);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setColor(myGrey);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setColor(myGrey);
}
else
{
((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setColor(ccWHITE);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setColor(ccWHITE);
}
}
}
if (isFristRolePage)
{
isFristRolePage = false;
}
for (int i = 0; i < selectRoleSpritesName->count(); i++)
{
((CCSprite *)selectRoleSpritesName->objectAtIndex(i))->setVisible(false);
}
getChildByTag(999)->setZOrder(100);
}
else
{
for (int i = 4; i > 0; i--)
{// 移除node中的ccSprite
getChildByTag(i)->removeChild((CCSprite *)currSelectSprites->lastObject());
currSelectSprites->removeLastObject();
removeChild((CCSprite *)currSelectSpritesIntroduce->lastObject(),true);
currSelectSpritesIntroduce->removeLastObject();
removeChild((CCLabelAtlas *)currSelectPropPrice->lastObject(),true);
currSelectPropPrice->removeLastObject();
removeChild((CCSprite *)currSelectPropName->lastObject(),true);
currSelectPropName->removeLastObject();
}
for (int i = 0; i< 4; i++)
{
if (_isXiangZuo)
{
currSelectSprites->addObject(selectPropSprites->objectAtIndex((i + currPropIndex) % selectPropSprites->count()));
currSelectSpritesIntroduce->addObject(selectPropIntroduce->objectAtIndex((i + currPropIndex) % selectPropSprites->count()));
currSelectPropPrice->addObject(selectPropPrice->objectAtIndex((i + currPropIndex) % selectPropSprites->count()));
currSelectPropName->addObject(selectPropName->objectAtIndex((i + currPropIndex) % selectPropSprites->count()));
}
else
{
if (i == 3)
{
currSelectSprites->addObject(selectPropSprites->objectAtIndex((selectPropSprites->count() - 1 + currPropIndex) % selectPropSprites->count()));
currSelectSpritesIntroduce->addObject(selectPropIntroduce->objectAtIndex((selectPropSprites->count() - 1 + currPropIndex) % selectPropSprites->count()));
currSelectPropPrice->addObject(selectPropPrice->objectAtIndex((selectPropSprites->count() - 1 + currPropIndex) % selectPropSprites->count()));
currSelectPropName->addObject(selectPropName->objectAtIndex((selectPropSprites->count() - 1 + currPropIndex) % selectPropSprites->count()));
}
else
{
currSelectSprites->addObject(selectPropSprites->objectAtIndex((i + currPropIndex) % selectPropSprites->count()));
currSelectSpritesIntroduce->addObject(selectPropIntroduce->objectAtIndex((i + currPropIndex) % selectPropSprites->count()));
currSelectPropPrice->addObject(selectPropPrice->objectAtIndex((i + currPropIndex) % selectPropSprites->count()));
currSelectPropName->addObject(selectPropName->objectAtIndex((i + currPropIndex) % selectPropSprites->count()));
}
}
getChildByTag(i+1)->addChild((CCSprite *)currSelectSprites->objectAtIndex(i));
addChild((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i));
addChild((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i));
addChild((CCSprite *)currSelectPropName->objectAtIndex(i));
if (isFristPropPage)
{
currButtonIndex = 2;
if (i % 2 == 0)
{
((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey);
((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectPropName->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setColor(myGrey);
((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setColor(myGrey);
}
else
{
((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE);
((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectPropName->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setColor(ccWHITE);
}
}
else
{
if (i % 2 == 1)
{
((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey);
((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectPropName->objectAtIndex(i))->setColor(myGrey);
((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setColor(myGrey);
((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setColor(myGrey);
}
else
{
((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE);
((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectPropName->objectAtIndex(i))->setColor(ccWHITE);
((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setColor(ccWHITE);
((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setColor(ccWHITE);
}
}
}
if (isFristPropPage)
{
isFristPropPage = false;
}
getChildByTag(999)->setZOrder(100);
}
}
void SelectRoleAndPropMenu::menuSelect1Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 1)
{
int _tmpIndex = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex(Global::getInstance()->getSelectRoleId()));
if (_tmpIndex != CC_INVALID_INDEX)
{
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(_tmpIndex))->setVisible(true);
}
Global::getInstance()->setSelectRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuSelect2Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 2)
{
int _tmpIndex = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex(Global::getInstance()->getSelectRoleId()));
if (_tmpIndex != CC_INVALID_INDEX)
{
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(_tmpIndex))->setVisible(true);
}
Global::getInstance()->setSelectRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuSelect3Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 3)
{
int _tmpIndex = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex(Global::getInstance()->getSelectRoleId()));
if (_tmpIndex != CC_INVALID_INDEX)
{
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(_tmpIndex))->setVisible(true);
}
Global::getInstance()->setSelectRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuSelect4Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 4)
{
int _tmpIndex = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex(Global::getInstance()->getSelectRoleId()));
if (_tmpIndex != CC_INVALID_INDEX)
{
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(_tmpIndex))->setVisible(true);
}
Global::getInstance()->setSelectRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuGet1Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 1)
{
// 购买人物
RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this);
setBackGround(true);
Global::getInstance()->s->addLayerToRunningScene(information);
information->getRoleGetInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuGet2Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 2)
{
// 购买人物
RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this);
setBackGround(true);
Global::getInstance()->s->addLayerToRunningScene(information);
information->getRoleGetInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuGet3Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 3)
{
// 购买人物
RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this);
setBackGround(true);
Global::getInstance()->s->addLayerToRunningScene(information);
information->getRoleGetInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuGet4Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 4)
{
// 购买人物
RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this);
setBackGround(true);
Global::getInstance()->s->addLayerToRunningScene(information);
information->getRoleGetInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuAbout1Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 1)
{
// 介绍
RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this);
setBackGround(true);
Global::getInstance()->s->addLayerToRunningScene(information);
information->getRoleAboutInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuAbout2Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 2)
{
// 介绍
RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this);
setBackGround(true);
Global::getInstance()->s->addLayerToRunningScene(information);
information->getRoleAboutInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuAbout3Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 3)
{
// 介绍
RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this);
setBackGround(true);
Global::getInstance()->s->addLayerToRunningScene(information);
information->getRoleAboutInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuAbout4Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 4)
{
// 介绍
RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this);
setBackGround(true);
Global::getInstance()->s->addLayerToRunningScene(information);
information->getRoleAboutInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count());
}
}
void SelectRoleAndPropMenu::menuBuy1Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 1)
{
// 购买道具
int id = ((CCInteger *)selectPropId->objectAtIndex((currPropIndex + 1) % selectPropSprites->count()))->getValue();
if (id == PROP_TYPE_ALIGNMENT && (Player::getInstance()->getPropNum(PROP_TYPE_ALIGNMENT) > 0))
{
// 提示已经购买了瞄准线了 (瞄准线最多1个)
PromptLayer * promptLayer = (PromptLayer *)Global::getInstance()->s->getPromptLayer(this, LAYER_ID_PROP_ROLE);
setBackGround(true);
//promptLayer->setForwardLayer(this);
Global::getInstance()->s->addLayerToRunningScene(promptLayer);
promptLayer->miaoZhunXianInformation();
}
else
{
if (Player::getInstance()->getPropNum(PROP_TYPE_INGOT) >= propControl->getPrice(id))
{
Player::getInstance()->appendPropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id));
Player::getInstance()->savePropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id));
Player::getInstance()->appendPropNum(id ,1);
Player::getInstance()->savePropNum(id ,1);
char _s[32];
sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT));
removeChild(ingotNum);
ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0');
CC_SAFE_RETAIN(ingotNum);
addChild(ingotNum, 998);
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FINISH);
}
else
{
// 钱不够购买
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FAILED);
}
}
}
}
void SelectRoleAndPropMenu::menuBuy2Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 2)
{
// 购买道具
int id = ((CCInteger *)selectPropId->objectAtIndex((currPropIndex + 1) % selectPropSprites->count()))->getValue();
if (id == PROP_TYPE_ALIGNMENT && (Player::getInstance()->getPropNum(PROP_TYPE_ALIGNMENT) > 0))
{
// 提示已经购买了瞄准线了 (瞄准线最多1个)
}
else
{
if (Player::getInstance()->getPropNum(PROP_TYPE_INGOT) >= propControl->getPrice(id))
{
Player::getInstance()->appendPropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id));
Player::getInstance()->savePropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id));
Player::getInstance()->appendPropNum(id ,1);
Player::getInstance()->savePropNum(id ,1);
char _s[32];
sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT));
removeChild(ingotNum);
ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0');
CC_SAFE_RETAIN(ingotNum);
addChild(ingotNum, 998);
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FINISH);
}
else
{
// 钱不够购买
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FAILED);
}
}
}
}
void SelectRoleAndPropMenu::menuBuy3Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 3)
{
// 购买道具
int id = ((CCInteger *)selectPropId->objectAtIndex((currPropIndex + 1) % selectPropSprites->count()))->getValue();
if (id == PROP_TYPE_ALIGNMENT && (Player::getInstance()->getPropNum(PROP_TYPE_ALIGNMENT) > 0))
{
// 提示已经购买了瞄准线了 (瞄准线最多1个)
}
else
{
if (Player::getInstance()->getPropNum(PROP_TYPE_INGOT) >= propControl->getPrice(id))
{
Player::getInstance()->appendPropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id));
Player::getInstance()->savePropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id));
Player::getInstance()->appendPropNum(id ,1);
Player::getInstance()->savePropNum(id ,1);
char _s[32];
sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT));
removeChild(ingotNum);
ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0');
CC_SAFE_RETAIN(ingotNum);
addChild(ingotNum, 998);
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FINISH);
}
else
{
// 钱不够购买
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FAILED);
}
}
}
}
void SelectRoleAndPropMenu::menuBuy4Callback(CCObject* pSender)
{
if (isBackGround)
{
return;
}
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON);
if (currButtonIndex == 4)
{
// 购买道具
int id = ((CCInteger *)selectPropId->objectAtIndex((currPropIndex + 1) % selectPropSprites->count()))->getValue();
if (id == PROP_TYPE_ALIGNMENT && (Player::getInstance()->getPropNum(PROP_TYPE_ALIGNMENT) > 0))
{
// 提示已经购买了瞄准线了 (瞄准线最多1个)
}
else
{
if (Player::getInstance()->getPropNum(PROP_TYPE_INGOT) >= propControl->getPrice(id))
{
Player::getInstance()->appendPropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id));
Player::getInstance()->savePropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id));
Player::getInstance()->appendPropNum(id ,1);
Player::getInstance()->savePropNum(id ,1);
char _s[32];
sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT));
removeChild(ingotNum);
ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0');
CC_SAFE_RETAIN(ingotNum);
addChild(ingotNum, 998);
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FINISH);
}
else
{
// 钱不够购买
Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FAILED);
}
}
}
}
void SelectRoleAndPropMenu::doAction(float _f)
{
if (isRolePage)
{
for (int i = 0; i < 4; i++)
{
double _positionX = ((CCNode *)getChildByTag(i+1))->getPositionX();
double _positionY = ((CCNode *)getChildByTag(i+1))->getPositionY();
double _scale = ((CCNode *)getChildByTag(i+1))->getScale();
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setPosition(ccp(_positionX+7*_scale, _positionY-124*_scale));
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setPosition(ccp(_positionX+237*_scale, _positionY-111*_scale));
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setPosition(ccp(_positionX+1*_scale, _positionY-139*_scale));
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setPosition(ccp(_positionX+1*_scale, _positionY-139*_scale));
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setPosition(ccp(_positionX+1*_scale, _positionY-139*_scale));
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setPosition(ccp(_positionX+233.5*_scale, _positionY-137.5*_scale));
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setPosition(ccp(_positionX+226*_scale, _positionY-87.5*_scale));
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setPosition(ccp(_positionX+226*_scale, _positionY-87.5*_scale));
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setPosition(ccp(_positionX+233.5*_scale, _positionY-112.5*_scale));
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setPosition(ccp(_positionX+233.5*_scale, _positionY-112.5*_scale));
((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setScale(_scale);
((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setScale(_scale);
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setScale(_scale);
((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setScale(_scale);
((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setScale(_scale);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setScale(_scale);
((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setScale(_scale);
((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setScale(_scale);
((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setScale(_scale);
((CCSprite *)currSelectRolePower->objectAtIndex(i))->setScale(_scale);
}
int _tmpIndex = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex(Global::getInstance()->getSelectRoleId()));
if (_tmpIndex != CC_INVALID_INDEX)
{
((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(_tmpIndex))->setVisible(false);
}
if (0 == ((CCInteger *)selectRoleSpritesIsOpen->objectAtIndex((currRoleIndex + 1) % selectRoleSprites->count()))->getValue())
{
coupletAbout->setVisible(true);
coupletSelect->setVisible(false);
}
else
{
if ((currRoleIndex + 1) % selectRoleSprites->count() == Global::getInstance()->getSelectRoleId())
{
coupletAbout->setVisible(false);
coupletSelect->setVisible(true);
}
else
{
coupletAbout->setVisible(false);
coupletSelect->setVisible(false);
}
}
pointIndexSprite->setPosition(((CCSprite *)pointRoleSprites->objectAtIndex(currRoleIndex%pointRoleSprites->count()))->getPosition());
}
else
{
for (int i = 0; i < 4; i++)
{
double _positionX = ((CCNode *)getChildByTag(i+1))->getPositionX();
double _positionY = ((CCNode *)getChildByTag(i+1))->getPositionY();
double _scale = ((CCNode *)getChildByTag(i+1))->getScale();
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setPosition(ccp(_positionX-2.5*_scale, _positionY-96.5*_scale));
((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setPosition(ccp(_positionX-43.5*_scale, _positionY-38*_scale));
((CCSprite *)currSelectPropName->objectAtIndex(i))->setPosition(ccp(_positionX+2*_scale, _positionY+30.5*_scale));
((CCSprite *)currSelectSprites->objectAtIndex(i))->setPosition(ccp(0, 100+40*_scale));
((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setPosition(ccp(_positionX-2*_scale, _positionY+ 35+ 35*_scale));
((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setScale(_scale);
((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setScale(_scale);
((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setScale(_scale);
((CCSprite *)currSelectPropName->objectAtIndex(i))->setScale(_scale);
((CCSprite *)currSelectSprites->objectAtIndex(i))->setScale(_scale);
}
pointIndexSprite->setPosition(((CCSprite *)pointPropSprites->objectAtIndex(currPropIndex%pointPropSprites->count()))->getPosition());
}
double _positionX = ((CCNode *)getChildByTag(10))->getPositionX();
double _positionY = ((CCNode *)getChildByTag(10))->getPositionY();
int i = 0;
int length = Player::getInstance()->getPropNum(PROP_TYPE_INGOT);
while(1)
{
length = length / 10;
if (length > 0)
{
i++;
}
else
{
break;
}
}
ingotNum->setPosition(ccp(_positionX - i*8, _positionY - 13));
} | [
"wjf1616@163.com"
] | wjf1616@163.com |
6f6231bcef9d9a8625b6cfa08c6c93839612281b | 8101a9dcde73f28dc59ab58244c3722e5c30d593 | /v3/SingleRelay.cpp | 39c44d20bb7aecb741b6ce4b9c767ea278efd289 | [] | no_license | winkste/esp8266_template | 8c8583c2321781ddc55a9b0ea38356aeb5b4370b | d324ed60753a4b2fcfc2fca38b2f842eec791df8 | refs/heads/master | 2021-08-26T05:34:56.133840 | 2017-11-21T20:05:13 | 2017-11-21T20:05:13 | 109,651,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,871 | cpp | /*****************************************************************************************
* FILENAME : SingleRelay.cpp
*
* DESCRIPTION :
* Implementation of the single relay shield.
*
* PUBLIC FUNCTIONS :
*
*
* NOTES :
*
*
* Copyright (c) [2017] [Stephan Wink]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
vAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* AUTHOR : Stephan Wink START DATE : 01.10.2017
*
*****************************************************************************************/
/****************************************************************************************/
/* Include Interfaces */
#include "SingleRelay.h"
#include "MqttDevice.h"
#include "Trace.h"
#include "PubSubClient.h"
/****************************************************************************************/
/* Local constant defines */
#define RELAY_PIN 5
#define MQTT_SUB_TOGGLE "/relay/toggle" // command message for toggle command
#define MQTT_SUB_BUTTON "/relay/switch" // command message for button commands
#define MQTT_PUB_LIGHT_STATE "/relay/status" //state of relay
#define MQTT_PAYLOAD_CMD_ON "ON"
#define MQTT_PAYLOAD_CMD_OFF "OFF"
/****************************************************************************************/
/* Local function like makros */
/****************************************************************************************/
/* Local type definitions (enum, struct, union) */
/****************************************************************************************/
/* Public functions (unlimited visibility) */
/**---------------------------------------------------------------------------------------
* @brief Constructor for the single relay shield
* @author winkste
* @date 20 Okt. 2017
* @param p_trace trace object for info and error messages
* @return n/a
*//*-----------------------------------------------------------------------------------*/
SingleRelay::SingleRelay(Trace *p_trace) : MqttDevice(p_trace)
{
this->prevTime_u32 = 0;
this->publications_u16 = 0;
this->relayState_bol = false;
this->publishState_bol = true;
}
/**---------------------------------------------------------------------------------------
* @brief Default destructor
* @author winkste
* @date 20 Okt. 2017
* @return n/a
*//*-----------------------------------------------------------------------------------*/
SingleRelay::~SingleRelay()
{
// TODO Auto-generated destructor stub
}
/**---------------------------------------------------------------------------------------
* @brief Initialization of the single relay object
* @author winkste
* @date 20 Okt. 2017
* @return n/a
*//*-----------------------------------------------------------------------------------*/
void SingleRelay::Initialize()
{
p_trace->println(trace_INFO_MSG, "Single relay initialized");
pinMode(RELAY_PIN, OUTPUT);
this->setRelay();
this->isInitialized_bol = true;
}
/**---------------------------------------------------------------------------------------
* @brief Function call to initialize the MQTT interface for this module
* @author winkste
* @date 20 Okt. 2017
* @param client mqtt client object
* @param dev_p client device id for building the mqtt topics
* @return n/a
*//*-----------------------------------------------------------------------------------*/
void SingleRelay::Reconnect(PubSubClient *client_p, const char *dev_p)
{
if(NULL != client_p)
{
this->dev_p = dev_p;
this->isConnected_bol = true;
p_trace->println(trace_INFO_MSG, "Single relay reconnected");
// ... and resubscribe
// toggle relay
client_p->subscribe(build_topic(MQTT_SUB_TOGGLE));
client_p->loop();
p_trace->print(trace_INFO_MSG, "[mqtt] subscribed 1: ");
p_trace->println(trace_PURE_MSG, MQTT_SUB_TOGGLE);
// change relay state with payload
client_p->subscribe(build_topic(MQTT_SUB_BUTTON));
client_p->loop();
p_trace->print(trace_INFO_MSG, "[mqtt] subscribed 2: ");
p_trace->println(trace_PURE_MSG, MQTT_SUB_BUTTON);
client_p->loop();
}
else
{
// failure, not connected
p_trace->println(trace_ERROR_MSG,
"uninizialized MQTT client in single relay detected");
this->isConnected_bol = false;
}
}
/**---------------------------------------------------------------------------------------
* @brief Callback function to process subscribed MQTT publication
* @author winkste
* @date 20 Okt. 2017
* @param client mqtt client object
* @param p_topic received topic
* @param p_payload attached payload message
* @return n/a
*//*-----------------------------------------------------------------------------------*/
void SingleRelay::CallbackMqtt(PubSubClient *client, char* p_topic, String p_payload)
{
if(true == this->isConnected_bol)
{
// received toggle relay mqtt topic
if (String(build_topic(MQTT_SUB_TOGGLE)).equals(p_topic))
{
p_trace->println(trace_INFO_MSG, "Single relay mqtt callback");
p_trace->println(trace_INFO_MSG, p_topic);
p_trace->println(trace_INFO_MSG, p_payload);
this->ToggleRelay();
}
// execute command to switch on/off the relay
else if (String(build_topic(MQTT_SUB_BUTTON)).equals(p_topic))
{
p_trace->println(trace_INFO_MSG, "Single relay mqtt callback");
p_trace->println(trace_INFO_MSG, p_topic);
p_trace->println(trace_INFO_MSG, p_payload);
// test if the payload is equal to "ON" or "OFF"
if(0 == p_payload.indexOf(String(MQTT_PAYLOAD_CMD_ON)))
{
this->relayState_bol = true;
this->setRelay();
}
else if(0 == p_payload.indexOf(String(MQTT_PAYLOAD_CMD_OFF)))
{
this->relayState_bol = false;
this->setRelay();
}
else
{
p_trace->print(trace_ERROR_MSG, "[mqtt] unexpected payload: ");
p_trace->println(trace_PURE_MSG, p_payload);
}
}
}
else
{
p_trace->println(trace_ERROR_MSG, "connection failure in sonoff CallbackMqtt ");
}
}
/**---------------------------------------------------------------------------------------
* @brief Sending generated publications
* @author winkste
* @date 20 Okt. 2017
* @param client mqtt client object
* @return n/a
*//*-----------------------------------------------------------------------------------*/
bool SingleRelay::ProcessPublishRequests(PubSubClient *client)
{
String tPayload;
boolean ret = false;
if(true == this->isConnected_bol)
{
// check if state has changed, than publish this state
if(true == publishState_bol)
{
p_trace->print(trace_INFO_MSG, "[mqtt] publish requested state: ");
p_trace->print(trace_PURE_MSG, MQTT_PUB_LIGHT_STATE);
p_trace->print(trace_PURE_MSG, " : ");
if(true == this->relayState_bol)
{
ret = client->publish(build_topic(MQTT_PUB_LIGHT_STATE),
MQTT_PAYLOAD_CMD_ON, true);
p_trace->println(trace_PURE_MSG, MQTT_PAYLOAD_CMD_ON);
}
else
{
ret = client->publish(build_topic(MQTT_PUB_LIGHT_STATE),
MQTT_PAYLOAD_CMD_OFF, true);
p_trace->println(trace_PURE_MSG, MQTT_PAYLOAD_CMD_OFF);
}
if(ret)
{
publishState_bol = false;
}
}
}
else
{
p_trace->println(trace_ERROR_MSG,
"connection failure in sonoff ProcessPublishRequests ");
}
return ret;
};
/**---------------------------------------------------------------------------------------
* @brief This function toggles the relay
* @author winkste
* @date 20 Okt. 2017
* @return void
*//*-----------------------------------------------------------------------------------*/
void SingleRelay::ToggleRelay(void)
{
if(true == this->relayState_bol)
{
this->TurnRelayOff();
}
else
{
this->TurnRelayOn();
}
}
/****************************************************************************************/
/* Private functions: */
/**---------------------------------------------------------------------------------------
* @brief This function turns the relay off
* @author winkste
* @date 20 Okt. 2017
* @return void
*//*-----------------------------------------------------------------------------------*/
void SingleRelay::TurnRelayOff(void)
{
if(true == this->isInitialized_bol)
{
this->relayState_bol = false;
digitalWrite(RELAY_PIN, LOW);
p_trace->println(trace_INFO_MSG, "relay turned off");
this->publishState_bol = true;
}
}
/**---------------------------------------------------------------------------------------
* @brief This function turns the relay on
* @author winkste
* @date 20 Okt. 2017
* @return void
*//*-----------------------------------------------------------------------------------*/
void SingleRelay::TurnRelayOn(void)
{
if(true == this->isInitialized_bol)
{
this->relayState_bol = true;
digitalWrite(RELAY_PIN, HIGH);
p_trace->println(trace_INFO_MSG, "relay turned on");
this->publishState_bol = true;
}
}
/**---------------------------------------------------------------------------------------
* @brief This function sets the relay based on the state of the relayState_bol
* attribute
* @author winkste
* @date 20 Okt. 2017
* @return n/a
*//*-----------------------------------------------------------------------------------*/
void SingleRelay::setRelay(void)
{
if(true == this->relayState_bol)
{
TurnRelayOn();
}
else
{
TurnRelayOff();
}
}
/**---------------------------------------------------------------------------------------
* @brief This function helps to build the complete topic including the
* custom device.
* @author winkste
* @date 20 Okt. 2017
* @param topic pointer to topic string
* @return combined topic as char pointer, it uses buffer_stca to store the topic
*//*-----------------------------------------------------------------------------------*/
char* SingleRelay::build_topic(const char *topic)
{
sprintf(buffer_ca, "%s%s", this->dev_p, topic);
return buffer_ca;
}
| [
"stephan_wink@winkste-MBP.fritz.box"
] | stephan_wink@winkste-MBP.fritz.box |
d378b8c6adef327b5745512eb5ce60410c5df4c5 | 59fbad8202b6e67777305bf9eef5fd9635735d7d | /Engine/Code/Engine/Math/MathUtil.cpp | 90b8babdf2634f254058d8293ba533b881a2839a | [] | no_license | neesarg-yb/N-gene | da22a533112f8824ed3b3179adbd2acf08512f10 | 3f7f16683e0c543f566636e1576c9d663d6d5282 | refs/heads/master | 2020-03-19T08:58:57.927495 | 2019-05-07T07:33:04 | 2019-05-07T07:34:50 | 136,250,286 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,717 | cpp | #pragma once
#include "MathUtil.hpp"
#include "Engine/Math/Vector2.hpp"
using namespace std;
bool AreEqualFloats( float a, float b, uint ulp )
{
float absDiff = std::fabsf( a - b );
float absSum = std::fabsf( a + b );
// the machine epsilon has to be scaled to the magnitude of the values used
// and multiplied by the desired precision in ULPs (units in the last place)
float scaledEpsilon = std::numeric_limits<float>::epsilon() * absSum * ulp;
float epsilonForSubnormals = std::numeric_limits<float>::min(); // unless the result is subnormal
return (absDiff <= scaledEpsilon) || (absDiff < epsilonForSubnormals);
}
bool SolveQuadraticEquation( Vector2& out, float a, float b, float c )
{
// Quadratic Equation:
//
// root = ( -b +- (d)^(0.5) ) / ( 2a )
// d = ( b^2 ) - ( 4ac )
float bSquare = b * b;
float ac = a * c;
float d = bSquare - (4.f * ac);
// Solution is imaginary or infinite
if( d < 0 || a == 0 )
return false;
float squareRootD = sqrt( d );
float root1 = ( -b + squareRootD ) / ( 2.f * a );
float root2 = ( -b - squareRootD ) / ( 2.f * a );
// Smaller root first & larger second
if( root1 <= root2 )
{
out.x = root1;
out.y = root2;
}
else
{
out.x = root2;
out.y = root1;
}
return true;
}
float AreaOfTriangle2D( Vector2 p1, Vector2 p2, Vector2 p3 )
{
return abs( ((p1.x * (p2.y - p3.y)) + (p2.x * (p3.y - p1.y)) + (p3.x * (p1.y - p2.y))) * 0.5f );
}
bool IsPointIsInsideTriangle2D( Vector2 point, Vector2 triangleCornerA, Vector2 triangleCornerB, Vector2 triangleCornerC )
{
// Area of the triangle
float A = AreaOfTriangle2D( triangleCornerA, triangleCornerB, triangleCornerC );
// Area of three sub-triangles made with the point & two corners
float A1 = AreaOfTriangle2D( point, triangleCornerA, triangleCornerB );
float A2 = AreaOfTriangle2D( point, triangleCornerB, triangleCornerC );
float A3 = AreaOfTriangle2D( point, triangleCornerA, triangleCornerC );
// If sum of sub-area(s) == total area i.e. the point is inside
return ( A == (A1 + A2 + A3) );
}
void GetPointsOnCircle2D( Vector2 center, float radius, int numPoints, Vector2 *outArray )
{
float stepInDegrees = 360.f / numPoints;
for( int i = 0; i < numPoints; i++ )
{
outArray[i].x = radius * CosDegree( stepInDegrees * i );
outArray[i].y = radius * SinDegree( stepInDegrees * i );
}
}
float DegreeToRadian(float degree) {
return ( (degree * M_PI) / 180.f );
}
float RadianToDegree(float radian) {
return ( (radian * 180) / M_PI );
}
float CosDegree(float degree) {
return ( cosf(DegreeToRadian(degree)) );
}
float SinDegree(float degree) {
return ( sinf(DegreeToRadian(degree)) );
}
float atan2fDegree(float y, float x) {
return RadianToDegree(atan2f(y, x));
}
float GetRandomFloatZeroToOne() {
return ( (float) rand() / (float) RAND_MAX );
}
float GetRandomFloatInRange(float minInclusive, float maxInclusive) {
float range = (maxInclusive - minInclusive);
return minInclusive + (GetRandomFloatZeroToOne() * range) ;
}
float GetRandomFloatAsPlusOrMinusOne() {
return (rand() % 2 ? 1.f : -1.f);
}
int GetRandomNonNegativeIntLessThan(int maxNotInclusive) {
return ( (int) rand() % maxNotInclusive );
}
int GetRandomIntInRange(int minInclusive, int maxInclusive) {
int range = (maxInclusive - minInclusive) + 1;
return ( minInclusive + GetRandomNonNegativeIntLessThan(range) );
}
bool CheckRandomChance( float chanceForSuccess ) {
chanceForSuccess *= 100;
int testInt = GetRandomIntInRange( 1, 100 );
if( testInt <= chanceForSuccess) {
return true;
}
return false;
}
int ClampInt( int inValue, int min, int max ) {
if(inValue < min) {
inValue = min;
}
else if(inValue > max) {
inValue = max;
}
return inValue;
}
float ClampFloat01(float number) {
number = ClampFloat(number, 0.f, 1.f);
return number;
}
float ClampFloat(float inValue, float minInclusive, float maxInclusive) {
if(inValue < minInclusive) {
inValue = minInclusive;
}
else if(inValue > maxInclusive) {
inValue = maxInclusive;
}
return inValue;
}
float ClampFloatNegativeOneToOne( float inValue ) {
if(inValue < -1.f) {
inValue = -1.f;
}
else if(inValue > 1.f) {
inValue = 1.f;
}
return inValue;
}
int RoundToNearestInt( float inValue ) {
int sign = inValue >= 0 ? +1 : -1;
float absInValue = abs(inValue);
float fraction = absInValue - (int) absInValue;
// Positive Number, do normal round
if( sign == +1 ) {
return (int)(inValue+0.5);
}
// Negative Number, so special round
if(fraction > 0.5) {
return (int)inValue - 1; // -1.6 -> -2
}
else /* if(fraction <= 0.5) */
{
return (int)inValue; // -1.5 -> -1
}
}
float GetSign( float number )
{
if( number >= 0.f )
return +1.f;
else
return -1.f;
}
void NewSeedForRandom() {
srand( (unsigned int) time(NULL) );
}
float RangeMapFloat(float inValue, float inStart, float inEnd, float outStart, float outEnd) {
// If inRange is zero, call of this function is not-appropriate, handle this situation..
if(inStart == inEnd) {
return (outStart + outEnd) * 0.5f;
}
// Function call is appropriate, start calculation
float inRange = inEnd - inStart;
float outRange = outEnd - outStart;
float inRelativeToStart = inValue - inStart;
float fractionOfRange = inRelativeToStart / inRange; // inRange can't be ZERO
float outRelativeToStart = fractionOfRange * outRange;
return outRelativeToStart + outStart;
}
float GetFractionInRange( float inValue, float rangeStart, float rangeEnd ) {
float relativePosition = inValue - rangeStart;
float range = rangeEnd - rangeStart; // range can't be ZERO
// Short-circuit if unsensible range
if(range == 0) return 0.f;
float fraction = relativePosition / range;
return fraction;
}
float Interpolate( float start, float end, float fractionTowardEnd ) {
float range = end - start; // range can't be ZERO
// Short-circuit if unsensible range
if(range == 0) return start;
float relativePosition = fractionTowardEnd * range;
float numberAtGivenFraction = relativePosition + start;
return numberAtGivenFraction;
}
float GetAngularDisplacement( float startDegrees, float endDegrees ) {
float angularDisp = endDegrees - startDegrees;
while ( angularDisp > 180.f ) {
angularDisp -= 360;
}
while ( angularDisp < -180.f ) {
angularDisp += 360;
}
return angularDisp;
}
float TurnToward( float currentDegrees, float goalDegrees, float maxTurnDegrees ) {
float difference = goalDegrees - currentDegrees;
while (difference > 180.f) {
difference -= 360;
}
while (difference < -180.f) {
difference += 360;
}
if( difference != 0 ) {
if( abs(difference) >= abs(maxTurnDegrees) ) {
float diffSign = (difference < 0.f) ? -1.f : 1.f; // Since we compared abs(values), we need sign to determine:
return currentDegrees + (maxTurnDegrees*diffSign); // whether add/subtract the maxTurnDegrees
}
else /* abs(diffrence) < maxTurnDegrees */ {
return currentDegrees + difference;
}
}
else /* difference == 0 */ {
return currentDegrees;
}
}
bool AreBitsSet( unsigned char bitFlags8, unsigned char flagsToCheck ) {
if( (bitFlags8 & flagsToCheck) == flagsToCheck ) {
return true;
}
return false;
}
bool AreBitsSet( unsigned int bitFlags32, unsigned int flagsToCheck ) {
if( (bitFlags32 & flagsToCheck) == flagsToCheck ) {
return true;
}
return false;
}
void SetBits( unsigned char& bitFlags8, unsigned char flagsToSet ) {
bitFlags8 = bitFlags8 | flagsToSet;
}
void SetBits( unsigned int& bitFlags32, unsigned int flagsToSet ) {
bitFlags32 = bitFlags32 | flagsToSet;
}
void ClearBits( unsigned char& bitFlags8, unsigned char flagToClear ) {
unsigned char invertFlag = ~flagToClear;
bitFlags8 = bitFlags8 & invertFlag;
}
void ClearBits( unsigned int& bitFlags32, unsigned int flagToClear ) {
unsigned int invertFlag = ~flagToClear;
bitFlags32 = bitFlags32 & invertFlag;
}
float SmoothStart2( float t )
{
t = ClampFloat01(t);
return t * t;
}
float SmoothStart3( float t )
{
t = ClampFloat01(t);
return t * t * t;
}
float SmoothStart4( float t )
{
t = ClampFloat01(t);
return t * t * t * t;
}
float SmoothStop2 ( float t )
{
t = ClampFloat01(t);
float flip = 1.f - t;
float square = flip * flip;
float result = 1.f - square; // flip again
return result;
}
float SmoothStop3 ( float t )
{
t = ClampFloat01(t);
float flip = 1.f - t;
float cube = flip * flip * flip;
float result = 1.f - cube; // flip again
return result;
}
float SmoothStop4 ( float t )
{
t = ClampFloat01(t);
float flip = 1.f - t;
float pow4 = flip * flip * flip * flip;
float result = 1.f - pow4; // flip again
return result;
}
float SmoothStep3 ( float t )
{
t = ClampFloat01(t);
float smoothStart = SmoothStart3(t);
float smoothStop = SmoothStop3(t);
float smoothStep = ( ( 1.f - t ) * smoothStart ) + ( t * smoothStop ); // using t as a weight
return smoothStep;
}
int Interpolate( int start, int end, float fractionTowardEnd )
{
float range = (float)end - (float)start; // range can't be ZERO
// Short-circuit if unsensible range
if(range == 0) return start;
float relativePosition = fractionTowardEnd * range;
float floatAnswer = ( relativePosition ) + start;
float roundIt = floatAnswer < 0 ? -0.5f : 0.5f;
int numberAtGivenFraction = (int) (floatAnswer + roundIt);
// Why (relativePosition + 0.5f) ?
// Computer consider (int) 6.51 = 6, but we need (int) 6.51 = 7.
return numberAtGivenFraction;
}
unsigned char Interpolate( unsigned char start, unsigned char end, float fractionTowardEnd )
{
unsigned char resuleNumber = (unsigned char) Interpolate( (int)start , (int)end , fractionTowardEnd );
resuleNumber = (unsigned char) ClampInt( (int)resuleNumber , 0 , 255 );
return resuleNumber;
}
void SetFromText( int& setIt , const char* text )
{
setIt = atoi(text);
}
void SetFromText( float& setIt , const char* text )
{
setIt = (float) atof(text);
}
void SetFromText( bool& setIt , const char* text )
{
setIt = false; // In case of malfunction, default value will be FALSE
if( strcmp( text , "true" ) == 0 || strcmp( text , "1" ) == 0 )
setIt = true;
}
void SetFromText( std::vector<std::string>& setIt, const char* delimiter, const char* text )
{
std::string inputText = text;
size_t startPos = 0;
for( size_t nextDelPos = inputText.find( delimiter, startPos); nextDelPos != std::string::npos; nextDelPos = inputText.find( delimiter, nextDelPos+1 ) )
{
// delimiter found, push_back the string
std::string strToPush( inputText, startPos, nextDelPos-startPos );
setIt.push_back( strToPush );
startPos = nextDelPos+1;
}
// push_back last part
std::string strToPush( inputText, startPos );
setIt.push_back( strToPush );
}
int GetIndexFromColumnRowNumberForMatrixOfWidth( int columnNum , int rowNum , int width )
{
int index = ( width * rowNum ) + columnNum;
return index;
}
std::vector<std::string> SplitIntoStringsByDelimiter( std::string passedString, char delimeter )
{
std::string word = "";
passedString += delimeter;
int stringTotalLength = (int) passedString.length();
// Traverse the string from left-to-right
std::vector<std::string> subStringList;
for( int i=0; i<stringTotalLength; i++ )
{
if( passedString[i] != delimeter )
word += passedString[i];
else
{
if( (int) word.size() != 0 )
subStringList.push_back( word );
word = "";
}
}
return subStringList;
}
void ReplaceAllInString( std::string &stringToModify, std::string const &replaceFrom, std::string const &replaceTo )
{
if( replaceFrom.empty() )
return;
size_t startPos = 0;
while( (startPos = stringToModify.find( replaceFrom, startPos )) != std::string::npos )
{
stringToModify.replace( startPos, replaceFrom.length(), replaceTo );
startPos += replaceTo.length();
}
}
int ModuloNonNegative( int operatingOn, int moduloBy )
{
// ( b + (a % b) ) % b
int nnMod = ( moduloBy + ( operatingOn % moduloBy ) ) % moduloBy;
return nnMod;
}
bool CycleLess( uint16_t a, uint16_t b )
{
// Converting (Negative Number) -> (Unsigned Number)
// --------------------------------------------------
// [ Way 1 ]: Taking 2's compliment
//
// Negative is calculated as 2's compliment for unsigned numbers
// => 6 = 110'b
// => -6 = 010'b
// ---------- (addition results into ZERO)
// 0 = 000'b
//
// 2's compliment is NOT( number-as-positive ), and then add 0001'b to it
// => (-6) = NOT(110'b) + 001'b
// = 001'b + 001'b
// = 010'b = 2
//
// [ Way 2 ]: MAX_NUM + 1 + (negative number)
//
// => -6 = (111'b) + (001'b) + (negative number)
// = 7 + 1 - 6
// = 8 - 6
// = 2 = (010)
uint16_t diff = b - a;
return (diff != 0) && (diff < 0x8000);
}
| [
"neesarg.banglawala@gmail.com"
] | neesarg.banglawala@gmail.com |
037beb0fa5e70e5074fd6e92826630500efff0be | c766bece263e5149d0dbab04ea20308bf1191ab8 | /AdobeInDesignCCProductsSDK.2020/source/public/interfaces/architecture/IRecoveryList.h | 04aff3c384e8c02c0d6e757cd306adb8b8f673e5 | [] | no_license | stevenstong/adobe-tools | 37a36868619db90984d5303187305c9da1e024f7 | c74d61d882363a91da4938fd525b97f83084cb2e | refs/heads/master | 2022-04-08T17:31:35.516938 | 2020-03-18T20:57:40 | 2020-03-18T20:57:40 | 248,061,036 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,972 | h | //========================================================================================
//
// $File: //depot/devtech/15.0/plugin/source/public/interfaces/architecture/IRecoveryList.h $
//
// Owner: Roey Horns
//
// $Author: pmbuilder $
//
// $DateTime: 2019/10/11 10:48:01 $
//
// $Revision: #2 $
//
// $Change: 1061132 $
//
// Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
// with the terms of the Adobe license agreement accompanying it. If you have received
// this file from a source other than Adobe, then your use, modification, or
// distribution of it requires the prior written permission of Adobe.
//
//========================================================================================
#pragma once
#ifndef __IRecoveryList__
#define __IRecoveryList__
#include "IPMUnknown.h"
#include "PMString.h"
#include "DocumentID.h"
class IRecoveryList : public IPMUnknown
{
public:
// Methods for Default Pub Recovery (accessed by CSession)
virtual bool16 DefaultFileWasOpen() const = 0;
virtual const IDFile *GetDefaultMiniSaveFile() const = 0;
virtual void SetDefaultMiniSaveFile(const IDFile *file) = 0;
virtual void StartDefaultFileRecovery() = 0;
virtual void EndDefaultFileRecovery() = 0;
virtual bool16 InDefaultFileRecovery() = 0;
// Recovery Control
virtual void DoRecovery() = 0;
virtual bool16 InRecovery() const = 0;
// Recovery List Maintainance
// The doc interface could be a regular InDesign document or
// book file or some other special files we may support later.
//virtual void AddDocument(IPMUnknown *doc, ClassID commandID = kRecoverDocumentCmdBoss) = 0;
virtual void AddDocument(IPMUnknown *doc, ClassID commandID = kInvalidClass) = 0;
virtual void UpdateDocument(IPMUnknown *doc) = 0;
virtual void RemoveDocument(IPMUnknown *doc) = 0;
};
#endif // __IRecoveryList__ | [
"steven.tong@hcl.com"
] | steven.tong@hcl.com |
2ca00c247f1b73dd8f8cdb6ad83ca7a4814de196 | 60d718b01b6c1adbab2ec072836e5826c3985f3a | /QxOrm/src/QxDao/QxSqlRelationParams.cpp | d3628a4371ec1027945ee1edb0f7154c3c9227cb | [] | no_license | jpush/jchat-windows | 1084127d0ce39ad00a344661f265e5d65389c186 | e782268c8d04ffad5d6e9a69308fad30b583603e | refs/heads/master | 2022-01-14T06:35:47.571133 | 2019-05-14T05:32:42 | 2019-05-14T05:42:19 | 106,393,361 | 19 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,955 | cpp | /****************************************************************************
**
** http://www.qxorm.com/
** Copyright (C) 2013 Lionel Marty (contact@qxorm.com)
**
** This file is part of the QxOrm library
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any
** damages arising from the use of this software
**
** Commercial Usage
** Licensees holding valid commercial QxOrm licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Lionel Marty
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file 'license.gpl3.txt' included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met : http://www.gnu.org/copyleft/gpl.html
**
** If you are unsure which license is appropriate for your use, or
** if you have questions regarding the use of this file, please contact :
** contact@qxorm.com
**
****************************************************************************/
#include <QxPrecompiled.h>
#include <QxDao/QxSqlRelationParams.h>
#include <QxDao/QxSqlRelationLinked.h>
#include <QxDao/IxSqlQueryBuilder.h>
#include <QxDao/IxSqlRelation.h>
#include <QxMemLeak/mem_leak.h>
namespace qx {
QxSqlRelationParams::QxSqlRelationParams() : m_lIndex(0), m_lIndexOwner(0), m_lOffset(0), m_sql(NULL), m_builder(NULL), m_query(NULL), m_database(NULL), m_pOwner(NULL), m_eJoinType(qx::dao::sql_join::no_join), m_pRelationX(NULL), m_eSaveMode(qx::dao::save_mode::e_check_insert_or_update), m_bRecursiveMode(false), m_pColumns(NULL) { ; }
QxSqlRelationParams::QxSqlRelationParams(long lIndex, long lOffset, QString * sql, IxSqlQueryBuilder * builder, QSqlQuery * query, void * pOwner) : m_lIndex(lIndex), m_lIndexOwner(0), m_lOffset(lOffset), m_sql(sql), m_builder(builder), m_query(query), m_database(NULL), m_pOwner(pOwner), m_eJoinType(qx::dao::sql_join::no_join), m_pRelationX(NULL), m_eSaveMode(qx::dao::save_mode::e_check_insert_or_update), m_bRecursiveMode(false), m_pColumns(NULL) { ; }
QxSqlRelationParams::QxSqlRelationParams(long lIndex, long lOffset, QString * sql, IxSqlQueryBuilder * builder, QSqlQuery * query, void * pOwner, const QVariant & vId) : m_vId(vId), m_lIndex(lIndex), m_lIndexOwner(0), m_lOffset(lOffset), m_sql(sql), m_builder(builder), m_query(query), m_database(NULL), m_pOwner(pOwner), m_eJoinType(qx::dao::sql_join::no_join), m_pRelationX(NULL), m_eSaveMode(qx::dao::save_mode::e_check_insert_or_update), m_bRecursiveMode(false), m_pColumns(NULL) { ; }
QxSqlRelationParams::~QxSqlRelationParams() { ; }
} // namespace qx
| [
"wangshun@jiguang.cn"
] | wangshun@jiguang.cn |
a8efe39ed49af6aa38ecee392c58bb3865fc8421 | 44bf3ced806bcd72fc2476cd15c7143b6fc81dcc | /src/blend2d/bitarray.h | 28fe9f966ec98e58f63176514f14eb536fe8c6d2 | [
"Zlib"
] | permissive | blend2d/blend2d | 9bc48e614a0f1cda65cb0ceaafda709d4453ad85 | 99fc3aa9a1d113e913df67166d40d2a81bef1dcb | refs/heads/master | 2023-08-30T03:10:19.645400 | 2023-08-28T11:40:00 | 2023-08-28T11:40:00 | 16,447,163 | 1,305 | 112 | Zlib | 2023-05-01T08:16:41 | 2014-02-02T02:01:04 | C++ | UTF-8 | C++ | false | false | 18,771 | h | // This file is part of Blend2D project <https://blend2d.com>
//
// See blend2d.h or LICENSE.md for license and copyright information
// SPDX-License-Identifier: Zlib
#ifndef BLEND2D_BITARRAY_H
#define BLEND2D_BITARRAY_H
#include "object.h"
//! \addtogroup blend2d_api_globals
//! \{
//! \name BLBitArray - C API
//! \{
BL_BEGIN_C_DECLS
BL_API BLResult BL_CDECL blBitArrayInit(BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayInitMove(BLBitArrayCore* self, BLBitArrayCore* other) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayInitWeak(BLBitArrayCore* self, const BLBitArrayCore* other) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayDestroy(BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayReset(BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayAssignMove(BLBitArrayCore* self, BLBitArrayCore* other) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayAssignWeak(BLBitArrayCore* self, const BLBitArrayCore* other) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayAssignWords(BLBitArrayCore* self, const uint32_t* wordData, uint32_t wordCount) BL_NOEXCEPT_C;
BL_API bool BL_CDECL blBitArrayIsEmpty(const BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API uint32_t BL_CDECL blBitArrayGetSize(const BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API uint32_t BL_CDECL blBitArrayGetWordCount(const BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API uint32_t BL_CDECL blBitArrayGetCapacity(const BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API const uint32_t* BL_CDECL blBitArrayGetData(const BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API uint32_t BL_CDECL blBitArrayGetCardinality(const BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API uint32_t BL_CDECL blBitArrayGetCardinalityInRange(const BLBitArrayCore* self, uint32_t startBit, uint32_t endBit) BL_NOEXCEPT_C;
BL_API bool BL_CDECL blBitArrayHasBit(const BLBitArrayCore* self, uint32_t bitIndex) BL_NOEXCEPT_C;
BL_API bool BL_CDECL blBitArrayHasBitsInRange(const BLBitArrayCore* self, uint32_t startBit, uint32_t endBit) BL_NOEXCEPT_C;
BL_API bool BL_CDECL blBitArraySubsumes(const BLBitArrayCore* a, const BLBitArrayCore* b) BL_NOEXCEPT_C;
BL_API bool BL_CDECL blBitArrayIntersects(const BLBitArrayCore* a, const BLBitArrayCore* b) BL_NOEXCEPT_C;
BL_API bool BL_CDECL blBitArrayGetRange(const BLBitArrayCore* self, uint32_t* startOut, uint32_t* endOut) BL_NOEXCEPT_C;
BL_API bool BL_CDECL blBitArrayEquals(const BLBitArrayCore* a, const BLBitArrayCore* b) BL_NOEXCEPT_C;
BL_API int BL_CDECL blBitArrayCompare(const BLBitArrayCore* a, const BLBitArrayCore* b) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayClear(BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayResize(BLBitArrayCore* self, uint32_t nBits) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayReserve(BLBitArrayCore* self, uint32_t nBits) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayShrink(BLBitArrayCore* self) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArraySetBit(BLBitArrayCore* self, uint32_t bitIndex) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayFillRange(BLBitArrayCore* self, uint32_t startBit, uint32_t endBit) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayFillWords(BLBitArrayCore* self, uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayClearBit(BLBitArrayCore* self, uint32_t bitIndex) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayClearRange(BLBitArrayCore* self, uint32_t startBit, uint32_t endBit) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayClearWord(BLBitArrayCore* self, uint32_t bitIndex, uint32_t wordValue) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayClearWords(BLBitArrayCore* self, uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayReplaceOp(BLBitArrayCore* self, uint32_t nBits, uint32_t** dataOut) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayReplaceBit(BLBitArrayCore* self, uint32_t bitIndex, bool bitValue) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayReplaceWord(BLBitArrayCore* self, uint32_t bitIndex, uint32_t wordValue) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayReplaceWords(BLBitArrayCore* self, uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayAppendBit(BLBitArrayCore* self, bool bitValue) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayAppendWord(BLBitArrayCore* self, uint32_t wordValue) BL_NOEXCEPT_C;
BL_API BLResult BL_CDECL blBitArrayAppendWords(BLBitArrayCore* self, const uint32_t* wordData, uint32_t wordCount) BL_NOEXCEPT_C;
// TODO: Future API (BitArray).
/*
BL_API BLResult BL_CDECL blBitArrayCombine(BLBitArrayCore* dst, const BLBitArrayCore* a, const BLBitArrayCore* b, BLBooleanOp booleanOp) BL_NOEXCEPT_C;
*/
BL_END_C_DECLS
//! BitArray container [C API].
struct BLBitArrayCore BL_CLASS_INHERITS(BLObjectCore) {
BL_DEFINE_OBJECT_DETAIL
BL_DEFINE_OBJECT_DCAST(BLBitArray)
};
//! \}
//! \cond INTERNAL
//! \name BLBitArray - Internals
//! \{
//! BitArray container [Impl].
struct BLBitArrayImpl BL_CLASS_INHERITS(BLObjectImpl) {
//! Size in bit units.
uint32_t size;
//! Capacity in bit-word units.
uint32_t capacity;
#ifdef __cplusplus
//! Pointer to array data.
BL_INLINE_NODEBUG uint32_t* data() noexcept { return reinterpret_cast<uint32_t*>(this + 1); }
//! Pointer to array data (const).
BL_INLINE_NODEBUG const uint32_t* data() const noexcept { return reinterpret_cast<const uint32_t*>(this + 1); }
#endif
};
//! \}
//! \endcond
//! \name BLBitArray - C++ API
//! \{
#ifdef __cplusplus
//! BitArray container [C++ API].
class BLBitArray final : public BLBitArrayCore {
public:
//! \cond INTERNAL
//! \name Internals
//! \{
enum : uint32_t {
//! Number of words that can be used by SSO representation.
kSSOWordCount = 3,
//! Signature of SSO representation of an empty BitArray.
kSSOEmptySignature = BLObjectInfo::packTypeWithMarker(BL_OBJECT_TYPE_BIT_ARRAY)
};
BL_INLINE_NODEBUG BLBitArrayImpl* _impl() const noexcept { return static_cast<BLBitArrayImpl*>(_d.impl); }
//! \}
//! \endcond
//! \name Construction & Destruction
//! \{
BL_INLINE_NODEBUG BLBitArray() noexcept {
_d.initStatic(BLObjectInfo{kSSOEmptySignature});
}
BL_INLINE_NODEBUG BLBitArray(BLBitArray&& other) noexcept {
_d = other._d;
other._d.initStatic(BLObjectInfo{kSSOEmptySignature});
}
BL_INLINE_NODEBUG BLBitArray(const BLBitArray& other) noexcept { blBitArrayInitWeak(this, &other); }
//! Destroys the BitArray.
BL_INLINE_NODEBUG ~BLBitArray() noexcept {
if (BLInternal::objectNeedsCleanup(_d.info.bits))
blBitArrayDestroy(this);
}
//! \}
//! \name Overloaded Operators
//! \{
//! Tests whether the BitArray has a content.
//!
//! \note This is essentially the opposite of `empty()`.
BL_INLINE_NODEBUG explicit operator bool() const noexcept { return !empty(); }
//! Move assignment.
//!
//! \note The `other` BitArray is reset by move assignment, so its state after the move operation is the same as
//! a default constructed BitArray.
BL_INLINE_NODEBUG BLBitArray& operator=(BLBitArray&& other) noexcept { blBitArrayAssignMove(this, &other); return *this; }
//! Copy assignment, performs weak copy of the data held by the `other` BitArray.
BL_INLINE_NODEBUG BLBitArray& operator=(const BLBitArray& other) noexcept { blBitArrayAssignWeak(this, &other); return *this; }
BL_INLINE_NODEBUG bool operator==(const BLBitArray& other) const noexcept { return equals(other); }
BL_INLINE_NODEBUG bool operator!=(const BLBitArray& other) const noexcept { return !equals(other); }
BL_INLINE_NODEBUG bool operator<(const BLBitArray& other) const noexcept { return compare(other) < 0; }
BL_INLINE_NODEBUG bool operator<=(const BLBitArray& other) const noexcept { return compare(other) <= 0; }
BL_INLINE_NODEBUG bool operator>(const BLBitArray& other) const noexcept { return compare(other) > 0; }
BL_INLINE_NODEBUG bool operator>=(const BLBitArray& other) const noexcept { return compare(other) >= 0; }
//! \}
//! \name Common Functionality
//! \{
//! Clears the content of the BitArray and releases its data.
//!
//! After reset the BitArray content matches a default constructed instance.
BL_INLINE_NODEBUG BLResult reset() noexcept { return blBitArrayReset(this); }
//! Swaps the content of this string with the `other` string.
BL_INLINE_NODEBUG void swap(BLBitArrayCore& other) noexcept { _d.swap(other._d); }
//! \name Accessors
//! \{
//! Tests whether the BitArray is empty (has no content).
//!
//! Returns `true` if the BitArray's size is zero.
BL_INLINE_NODEBUG bool empty() const noexcept { return blBitArrayIsEmpty(this); }
//! Returns the size of the BitArray in bits.
BL_INLINE_NODEBUG uint32_t size() const noexcept { return _d.sso() ? uint32_t(_d.pField()) : _impl()->size; }
//! Returns number of BitWords this BitArray uses.
BL_INLINE_NODEBUG uint32_t wordCount() const noexcept {
return sizeof(void*) >= 8 ? (uint32_t((uint64_t(size()) + 31u) / 32u))
: (size() / 32u + uint32_t((size() & 31u) != 0u));
}
//! Returns the capacity of the BitArray in bits.
BL_INLINE_NODEBUG uint32_t capacity() const noexcept { return _d.sso() ? uint32_t(kSSOWordCount * 32u) : _impl()->capacity; }
//! Returns the number of bits set in the BitArray.
BL_INLINE_NODEBUG uint32_t cardinality() const noexcept { return blBitArrayGetCardinality(this); }
//! Returns the number of bits set in the given `[startBit, endBit)` range.
BL_INLINE_NODEBUG uint32_t cardinalityInRange(uint32_t startBit, uint32_t endBit) const noexcept { return blBitArrayGetCardinalityInRange(this, startBit, endBit); }
//! Returns bit data.
BL_INLINE_NODEBUG const uint32_t* data() const noexcept { return _d.sso() ? _d.u32_data : _impl()->data(); }
//! \}
//! \name Test Operations
//! \{
//! Returns a bit-value at the given `bitIndex`.
BL_INLINE_NODEBUG bool hasBit(uint32_t bitIndex) const noexcept { return blBitArrayHasBit(this, bitIndex); }
//! Returns whether the bit-set has at least on bit in the given `[startBit, endbit)` range.
BL_INLINE_NODEBUG bool hasBitsInRange(uint32_t startBit, uint32_t endBit) const noexcept { return blBitArrayHasBitsInRange(this, startBit, endBit); }
//! Returns whether this BitArray subsumes `other`.
BL_INLINE_NODEBUG bool subsumes(const BLBitArrayCore& other) const noexcept { return blBitArraySubsumes(this, &other); }
//! Returns whether this BitArray intersects with `other`.
BL_INLINE_NODEBUG bool intersects(const BLBitArrayCore& other) const noexcept { return blBitArrayIntersects(this, &other); }
//! \}
//! \name Equality & Comparison
//! \{
//! Returns whether this BitArray and `other` are bitwise equal.
BL_INLINE_NODEBUG bool equals(const BLBitArrayCore& other) const noexcept { return blBitArrayEquals(this, &other); }
//! Compares this BitArray with `other` and returns either `-1`, `0`, or `1`.
BL_INLINE_NODEBUG int compare(const BLBitArrayCore& other) const noexcept { return blBitArrayCompare(this, &other); }
//! \}
//! \name Content Manipulation
//! \{
//! Move assignment, the same as `operator=`, but returns a `BLResult` instead of `this`.
BL_INLINE_NODEBUG BLResult assign(BLBitArrayCore&& other) noexcept { return blBitArrayAssignMove(this, &other); }
//! Copy assignment, the same as `operator=`, but returns a `BLResult` instead of `this`.
BL_INLINE_NODEBUG BLResult assign(const BLBitArrayCore& other) noexcept { return blBitArrayAssignWeak(this, &other); }
//! Replaces the content of the BitArray by bits specified by `wordData` of size `wordCount` [the size is in uint32_t units].
BL_INLINE_NODEBUG BLResult assignWords(const uint32_t* wordData, uint32_t wordCount) noexcept { return blBitArrayAssignWords(this, wordData, wordCount); }
//! Clears the content of the BitArray without releasing its dynamically allocated data, if possible.
BL_INLINE_NODEBUG BLResult clear() noexcept { return blBitArrayClear(this); }
//! Resizes the BitArray so its size matches `nBits`.
BL_INLINE_NODEBUG BLResult resize(uint32_t nBits) noexcept { return blBitArrayResize(this, nBits); }
//! Reserves `nBits` in the BitArray (capacity would match `nBits`) without changing its size.
BL_INLINE_NODEBUG BLResult reserve(uint32_t nBits) noexcept { return blBitArrayResize(this, nBits); }
//! Shrinks the capacity of the BitArray to match the actual content with the intention to save memory.
BL_INLINE_NODEBUG BLResult shrink() noexcept { return blBitArrayShrink(this); }
//! Sets a bit to true at the given `bitIndex`.
BL_INLINE_NODEBUG BLResult setBit(uint32_t bitIndex) noexcept { return blBitArraySetBit(this, bitIndex); }
//! Fills bits in `[startBit, endBit)` range to true.
BL_INLINE_NODEBUG BLResult fillRange(uint32_t startBit, uint32_t endBit) noexcept { return blBitArrayFillRange(this, startBit, endBit); }
//! Fills bits starting from `bitIndex` specified by `wordData` and `wordCount` to true (zeros in wordData are ignored).
//!
//! \note This operation uses an `OR` operator - bits in `wordData` are combined with OR operator with existing bits in BitArray.
BL_INLINE_NODEBUG BLResult fillWords(uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) noexcept { return blBitArrayFillWords(this, bitIndex, wordData, wordCount); }
//! Sets a bit to false at the given `bitIndex`.
BL_INLINE_NODEBUG BLResult clearBit(uint32_t bitIndex) noexcept { return blBitArrayClearBit(this, bitIndex); }
//! Sets bits in `[startBit, endBit)` range to false.
BL_INLINE_NODEBUG BLResult clearRange(uint32_t startBit, uint32_t endBit) noexcept { return blBitArrayClearRange(this, startBit, endBit); }
//! Sets bits starting from `bitIndex` specified by `wordValue` to false (zeros in wordValue are ignored).
//!
//! \note This operation uses an `AND_NOT` operator - bits in `wordData` are negated and then combined with AND operator with existing bits in BitArray.
BL_INLINE_NODEBUG BLResult clearWord(uint32_t bitIndex, uint32_t wordValue) noexcept { return blBitArrayClearWord(this, bitIndex, wordValue); }
//! Sets bits starting from `bitIndex` specified by `wordData` and `wordCount` to false (zeros in wordData are ignored).
//!
//! \note This operation uses an `AND_NOT` operator - bits in `wordData` are negated and then combined with AND operator with existing bits in BitArray.
BL_INLINE_NODEBUG BLResult clearWords(uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) noexcept { return blBitArrayClearWords(this, bitIndex, wordData, wordCount); }
//! Makes the BitArray mutable with the intention to replace all bits of it.
//!
//! \note All bits in the BitArray will be set to zero.
BL_INLINE_NODEBUG BLResult replaceOp(uint32_t nBits, uint32_t** dataOut) noexcept { return blBitArrayReplaceOp(this, nBits, dataOut); }
//! Replaces a bit in the BitArray at the given `bitIndex` to match `bitValue`.
BL_INLINE_NODEBUG BLResult replaceBit(uint32_t bitIndex, bool bitValue) noexcept { return blBitArrayReplaceBit(this, bitIndex, bitValue); }
//! Replaces bits starting from `bitIndex` to match the bits specified by `wordValue`.
//!
//! \note Replaced bits from BitArray are not combined by using any operator, `wordValue` is copied as is, thus
//! replaces fully the existing bits.
BL_INLINE_NODEBUG BLResult replaceWord(uint32_t bitIndex, uint32_t wordValue) noexcept { return blBitArrayReplaceWord(this, bitIndex, wordValue); }
//! Replaces bits starting from `bitIndex` to match the bits specified by `wordData` and `wordCount`.
//!
//! \note Replaced bits from BitArray are not combined by using any operator, `wordData` is copied as is, thus
//! replaces fully the existing bits.
BL_INLINE_NODEBUG BLResult replaceWords(uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) noexcept { return blBitArrayReplaceWords(this, bitIndex, wordData, wordCount); }
//! Appends a bit `bitValue` to the BitArray.
BL_INLINE_NODEBUG BLResult appendBit(bool bitValue) noexcept { return blBitArrayAppendBit(this, bitValue); }
//! Appends a single word `wordValue` to the BitArray.
BL_INLINE_NODEBUG BLResult appendWord(uint32_t wordValue) noexcept { return blBitArrayAppendWord(this, wordValue); }
//! Appends whole words to the BitArray.
BL_INLINE_NODEBUG BLResult appendWords(const uint32_t* wordData, uint32_t wordCount) noexcept { return blBitArrayAppendWords(this, wordData, wordCount); }
/*
// TODO: Future API (BitArray).
BL_INLINE_NODEBUG BLResult and_(const BLBitArrayCore& other) noexcept { return blBitArrayCombine(this, this, &other, BL_BOOLEAN_OP_AND); }
BL_INLINE_NODEBUG BLResult or_(const BLBitArrayCore& other) noexcept { return blBitArrayCombine(this, this, &other, BL_BOOLEAN_OP_OR); }
BL_INLINE_NODEBUG BLResult xor_(const BLBitArrayCore& other) noexcept { return blBitArrayCombine(this, this, &other, BL_BOOLEAN_OP_XOR); }
BL_INLINE_NODEBUG BLResult andNot(const BLBitArrayCore& other) noexcept { return blBitArrayCombine(this, this, &other, BL_BOOLEAN_OP_AND_NOT); }
BL_INLINE_NODEBUG BLResult notAnd(const BLBitArrayCore& other) noexcept { return blBitArrayCombine(this, this, &other, BL_BOOLEAN_OP_NOT_AND); }
BL_INLINE_NODEBUG BLResult combine(const BLBitArrayCore& other, BLBooleanOp booleanOp) noexcept { return blBitArrayCombine(this, this, &other, booleanOp); }
static BL_INLINE_NODEBUG BLResult and_(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b) noexcept { return blBitArrayCombine(&dst, &a, &b, BL_BOOLEAN_OP_AND); }
static BL_INLINE_NODEBUG BLResult or_(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b) noexcept { return blBitArrayCombine(&dst, &a, &b, BL_BOOLEAN_OP_OR); }
static BL_INLINE_NODEBUG BLResult xor_(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b) noexcept { return blBitArrayCombine(&dst, &a, &b, BL_BOOLEAN_OP_XOR); }
static BL_INLINE_NODEBUG BLResult andNot(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b) noexcept { return blBitArrayCombine(&dst, &a, &b, BL_BOOLEAN_OP_AND_NOT); }
static BL_INLINE_NODEBUG BLResult notAnd(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b) noexcept { return blBitArrayCombine(&dst, &a, &b, BL_BOOLEAN_OP_NOT_AND); }
static BL_INLINE_NODEBUG BLResult combine(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b, BLBooleanOp booleanOp) noexcept { return blBitArrayCombine(&dst, &a, &b, booleanOp); }
*/
//! \}
};
#endif
//! \}
//! \}
#endif // BLEND2D_BITARRAY_H
| [
"kobalicek.petr@gmail.com"
] | kobalicek.petr@gmail.com |
55ecc547b8fc58ad1b17429874cda8c64de397e6 | 3052e22574a9a8f36d3aa9ef8d7fcfd67808df31 | /test/view/ints.cpp | cb4511ad75a14813ad7b7eec085218aa8f51241c | [
"NCSA",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-other-permissive"
] | permissive | krzysztof-jusiak/range-v3 | 35bc90f6ede2cd03cf1896e121237a46a71cdd4e | 565394cc0c067b8b0bdfe00e1bbe94edc8378314 | refs/heads/master | 2021-01-18T20:06:21.519869 | 2016-04-21T15:36:54 | 2016-04-21T15:36:54 | 56,779,437 | 0 | 0 | null | 2016-04-21T14:15:27 | 2016-04-21T14:15:27 | null | UTF-8 | C++ | false | false | 2,398 | cpp | // Range v3 library
//
// Copyright Eric Niebler 2014
//
// 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)
//
// Project home: https://github.com/ericniebler/range-v3
//
#include <range/v3/core.hpp>
#include <range/v3/view/ints.hpp>
#include <range/v3/view/take.hpp>
#include <range/v3/view/indirect.hpp>
#include "../simple_test.hpp"
#include "../test_utils.hpp"
#include "../test_iterators.hpp"
int main()
{
using namespace ranges;
::check_equal(view::ints | view::take(10), {0,1,2,3,4,5,6,7,8,9});
::check_equal(view::ints(0) | view::take(10), {0,1,2,3,4,5,6,7,8,9});
::check_equal(view::ints(0,9), {0,1,2,3,4,5,6,7,8});
::check_equal(view::closed_ints(0,9), {0,1,2,3,4,5,6,7,8,9});
::check_equal(view::ints(1,10), {1,2,3,4,5,6,7,8,9});
::check_equal(view::closed_ints(1,10), {1,2,3,4,5,6,7,8,9,10});
auto chars = view::ints(std::numeric_limits<char>::min(),
std::numeric_limits<char>::max());
static_assert(Same<int, range_difference_t<decltype(chars)>>(), "");
::models<concepts::RandomAccessView>(chars);
models<concepts::BoundedView>(chars);
auto shorts = view::ints(std::numeric_limits<unsigned short>::min(),
std::numeric_limits<unsigned short>::max());
models<concepts::BoundedView>(shorts);
static_assert(Same<int, range_difference_t<decltype(shorts)>>(), "");
auto uints = view::closed_ints(
std::numeric_limits<std::uint32_t>::min(),
std::numeric_limits<std::uint32_t>::max());
models<concepts::BoundedView>(uints);
static_assert(Same<std::int64_t, range_difference_t<decltype(uints)>>(), "");
static_assert(Same<std::uint64_t, range_size_t<decltype(uints)>>(), "");
CHECK(uints.size() == (static_cast<uint64_t>(std::numeric_limits<std::uint32_t>::max()) + 1));
auto ints = view::closed_ints(
std::numeric_limits<std::int32_t>::min(),
std::numeric_limits<std::int32_t>::max());
static_assert(Same<std::int64_t, range_difference_t<decltype(ints)>>(), "");
static_assert(Same<std::uint64_t, range_size_t<decltype(ints)>>(), "");
CHECK(ints.size() == (static_cast<uint64_t>(std::numeric_limits<std::uint32_t>::max()) + 1));
return ::test_result();
}
| [
"krzysztof@jusiak.net"
] | krzysztof@jusiak.net |
0f16cc5ea0c3a0319907371b6fe622320371203f | 529a4f10d008553636fb36a087684297cebee88e | /algorithm/cgal/DilateXY.h | 3f064033d0ff0393c2ac6d21387bbcdd705fbe3b | [
"MIT"
] | permissive | jsxcad/JSxCAD | fba3f55a5b442d078814fc727f01c5b18e03545e | 962689c323d29b4ef97ec9fcc95218e6ec011a51 | refs/heads/master | 2023-08-09T17:58:35.062711 | 2023-08-03T14:41:52 | 2023-08-03T14:41:52 | 173,755,199 | 36 | 13 | MIT | 2023-09-11T15:07:13 | 2019-03-04T13:59:33 | JavaScript | UTF-8 | C++ | false | false | 1,441 | h | #include <CGAL/Nef_polyhedron_3.h>
#include <CGAL/minkowski_sum_3.h>
int DilateXY(Geometry* geometry, double amount) {
typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron;
size_t size = geometry->getSize();
geometry->copyInputMeshesToOutputMeshes();
geometry->transformToAbsoluteFrame();
Nef_polyhedron tool;
// Build a rough circle in XY.
{
const double segments = 16;
Points points;
for (double a = 0; a < CGAL_PI * 2; a += CGAL_PI / segments) {
points.push_back(Point(compute_approximate_point_value(sin(-a) * amount),
compute_approximate_point_value(cos(-a) * amount),
0));
}
typedef Points::iterator point_iterator;
typedef std::pair<point_iterator, point_iterator> point_range;
typedef std::list<point_range> polyline;
polyline poly;
poly.push_back(point_range(points.begin(), points.end()));
tool = Nef_polyhedron(poly.begin(), poly.end(),
Nef_polyhedron::Polylines_tag());
}
for (size_t nth = 0; nth < size; nth++) {
if (geometry->type(nth) != GEOMETRY_MESH) {
continue;
}
Surface_mesh& mesh = geometry->mesh(nth);
Nef_polyhedron nef(mesh);
Nef_polyhedron result = CGAL::minkowski_sum_3(nef, tool);
mesh.clear();
CGAL::convert_nef_polyhedron_to_polygon_mesh(result, mesh, true);
}
geometry->transformToLocalFrame();
return STATUS_OK;
}
| [
"brian.spilsbury@gmail.com"
] | brian.spilsbury@gmail.com |
ff5aea193b1ace4cf434caa5988825afce526de3 | 3a3b2ff8f104bc68a47408fb1fe43a14371222a1 | /include/GLUtils.h | f440da9b44f793628b691c7860defd880f16f877 | [] | no_license | easterbunny273/BambooEngine | 33ef13ebd3be60ff3fffbf314a8a723ca448cee7 | f2cef8a95f56091a872a03faa41be4e79a1c8b0a | refs/heads/master | 2020-04-10T15:18:05.783569 | 2012-10-28T22:34:09 | 2012-10-28T22:34:09 | 2,694,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,555 | h | /*
* header file for Logger class
* written by: christian moellinger <ch.moellinger@gmail.com>
* written by: florian spechtenhauser <florian.spechtenhauser@gmail.com>
* 07/2011, Project Cube
*/
#ifndef __COMMON_OPENGL_HEADER
#define __COMMON_OPENGL_HEADER
//include extension wrapper - important: necessary to include BEFORE glfw to prevent compile errors
#include <GL/glew.h>
//include glfw
//#define GLFW_NO_GLU
//#include <GL/glfw.h>
namespace GLUtils
{
//helper function for translating glerrors to char*
inline const char *TranslateGLerror(GLenum error)
{
switch (error)
{
case GL_INVALID_ENUM:
return "GL_INVALID_ENUM";
break;
case GL_INVALID_VALUE:
return "GL_INVALID_VALUE";
break;
case GL_INVALID_OPERATION:
return "GL_INVALID_OPERATION";
break;
case GL_STACK_OVERFLOW:
return "GL_STACK_OVERFLOW";
break;
case GL_STACK_UNDERFLOW:
return "GL_STACK_UNDERFLOW";
break;
case GL_OUT_OF_MEMORY:
return "GL_OUT_OF_MEMORY";
break;
case GL_TABLE_TOO_LARGE:
return "GL_TABLE_TOO_LARGE";
break;
default:
return "unknown GL error";
break;
}
}
//helper function for translating glerrors to char*
inline const char *TranslateFBOStatus(GLenum status)
{
switch (status)
{
case GL_FRAMEBUFFER_UNDEFINED:
return "GL_FRAMEBUFFER_UNDEFINED";
break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
return "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER";
break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
return "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER";
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
return "GL_FRAMEBUFFER_UNSUPPORTED";
break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
return "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE";
break;
case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
return "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS";
break;
default:
return "unknown fbo status";
break;
}
}
}
#endif
| [
"ch.moellinger@gmail.com"
] | ch.moellinger@gmail.com |
d49fcc31438210d7d0b86476558b27615d7f01ff | 1a3f007c27b777c780c41618c7a9572bff4ad0f7 | /examples/SD BMP/SD BMP.ino | e2059d578def03399e6fb9f0141098f901fca83b | [] | no_license | bacilladoro/TFT9486 | 1bede32a7305ceb46cc2a3353d845c6608623a20 | 2e86b223b6e0fc4fb27796844006d241e5868aca | refs/heads/master | 2020-04-18T19:20:43.936827 | 2019-01-26T17:57:35 | 2019-01-26T17:57:35 | 167,709,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,590 | ino | #include <Arduino.h>
#define LCD_CS PB6 // Chip Select goes to Analog 3
#define LCD_CD PB5 // Command/Data goes to Analog 2
#define LCD_WR PB4 // LCD Write goes to Analog 1
#define LCD_RD PB3 // LCD Read goes to Analog 0
#define LCD_RESET PB7 // Can alternately just connect to Arduino's reset pin
#include <SPI.h> // f.k. for Arduino-1.5.2
#include "Fruit_GFX.h"
#include <mcutft.h>
int Ax = 0;
int Ay = 50;
int L_P = 0;
//#define USE_SDFAT
#include <SD.h> // Use the official SD library on hardware pins
mcutft tft;
#define SD_CS 10
#define NAMEMATCH "" // "" matches any name
//#define NAMEMATCH "tiger" // *tiger*.bmp
#define PALETTEDEPTH 0 // do not support Palette modes
//#define PALETTEDEPTH 8 // support 256-colour Palette
char namebuf[32] = "/"; //BMP files in root directory
//char namebuf[32] = "/bitmaps/"; //BMP directory e.g. files in /bitmaps/*.bmp
File root;
int pathlen;
// Assign human-readable names to some common 16-bit color values:
#define BLACK 0x0000
#define BLUE 0x001F
#define RED 0xF800
#define GREEN 0x07E0
#define CYAN 0x07FF
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define WHITE 0xFFFF
#ifndef min
#define min(a, b) (((a) < (b)) ? (a) : (b))
#endif
void setup(void);
void loop(void);
uint8_t showBMP(char *nm, int x, int y);
uint32_t read32(File& f);
uint16_t read16(File& f);
void setup(void) {
Serial.begin(9600);
uint32_t when = millis();
// while (!Serial) ; //hangs a Leonardo until you connect a Serial
if (!Serial) delay(5000); //allow some time for Leonardo
Serial.println("Serial took " + String((millis() - when)) + "ms to start");
// tft.reset(); //hardware reset
uint16_t ID = tft.readID(); //
Serial.print("ID = 0x");
Serial.println(ID, HEX);
if (ID == 0xD3D3) ID = 0x9481; // write-only shield
// ID = 0x9329; // force ID
Serial.print("Show BMP files on TFT with ID:0x");
Serial.println(ID, HEX);
tft.begin(ID);
tft.setRotation(L_P);
tft.setTextColor(0xFFFF, 0x0000);
bool good = SD.begin(SD_CS);
if (!good) {
Serial.print(F("cannot start SD"));
while (1);
}
root = SD.open(namebuf);
pathlen = strlen(namebuf);
}
void loop(void) {
char *nm = namebuf + pathlen;
File f = root.openNextFile();
uint8_t ret;
uint32_t start;
if (f != NULL) {
#ifdef USE_SDFAT
f.getName(nm, 32 - pathlen);
#else
strcpy(nm, (char *)f.name());
#endif
f.close();
strlwr(nm);
if (strstr(nm, ".bmp") != NULL && strstr(nm, NAMEMATCH) != NULL) {
Serial.print(namebuf);
Serial.print(F(" - "));
tft.fillScreen(0);
start = millis();
ret = showBMP(namebuf, Ax, Ay);
switch (ret) {
case 0:
Serial.print(millis() - start);
Serial.println(F("ms"));
delay(5000);
break;
case 1:
Serial.println(F("bad position"));
break;
case 2:
Serial.println(F("bad BMP ID"));
break;
case 3:
Serial.println(F("wrong number of planes"));
break;
case 4:
Serial.println(F("unsupported BMP format"));
break;
case 5:
Serial.println(F("unsupported palette"));
break;
default:
Serial.println(F("unknown"));
break;
}
}
}
else root.rewindDirectory();
}
#define BMPIMAGEOFFSET 54
#define BUFFPIXEL 20
uint16_t read16(File& f) {
uint16_t result; // read little-endian
f.read((uint8_t*)&result, sizeof(result));
return result;
}
uint32_t read32(File& f) {
uint32_t result;
f.read((uint8_t*)&result, sizeof(result));
return result;
}
uint8_t showBMP(char *nm, int x, int y)
{
File bmpFile;
int bmpWidth, bmpHeight; // W+H in pixels
uint8_t bmpDepth; // Bit depth (currently must be 24, 16, 8, 4, 1)
uint32_t bmpImageoffset; // Start of image data in file
uint32_t rowSize; // Not always = bmpWidth; may have padding
uint8_t sdbuffer[3 * BUFFPIXEL]; // pixel in buffer (R+G+B per pixel)
uint16_t lcdbuffer[(1 << PALETTEDEPTH) + BUFFPIXEL], *palette = NULL;
uint8_t bitmask, bitshift;
boolean flip = true; // BMP is stored bottom-to-top
int w, h, row, col, lcdbufsiz = (1 << PALETTEDEPTH) + BUFFPIXEL, buffidx;
uint32_t pos; // seek position
boolean is565 = false; //
uint16_t bmpID;
uint16_t n; // blocks read
uint8_t ret;
if ((x >= tft.width()) || (y >= tft.height()))
return 1; // off screen
bmpFile = SD.open(nm); // Parse BMP header
bmpID = read16(bmpFile); // BMP signature
(void) read32(bmpFile); // Read & ignore file size
(void) read32(bmpFile); // Read & ignore creator bytes
bmpImageoffset = read32(bmpFile); // Start of image data
(void) read32(bmpFile); // Read & ignore DIB header size
bmpWidth = read32(bmpFile);
bmpHeight = read32(bmpFile);
n = read16(bmpFile); // # planes -- must be '1'
bmpDepth = read16(bmpFile); // bits per pixel
pos = read32(bmpFile); // format
if (bmpID != 0x4D42) ret = 2; // bad ID
else if (n != 1) ret = 3; // too many planes
else if (pos != 0 && pos != 3) ret = 4; // format: 0 = uncompressed, 3 = 565
else if (bmpDepth < 16 && bmpDepth > PALETTEDEPTH) ret = 5; // palette
else {
bool first = true;
is565 = (pos == 3); // ?already in 16-bit format
// BMP rows are padded (if needed) to 4-byte boundary
rowSize = (bmpWidth * bmpDepth / 8 + 3) & ~3;
if (bmpHeight < 0) { // If negative, image is in top-down order.
bmpHeight = -bmpHeight;
flip = false;
}
w = bmpWidth;
h = bmpHeight;
if ((x + w) >= tft.width()) // Crop area to be loaded
w = tft.width() - x;
if ((y + h) >= tft.height()) //
h = tft.height() - y;
if (bmpDepth <= PALETTEDEPTH) { // these modes have separate palette
bmpFile.seek(BMPIMAGEOFFSET); //palette is always @ 54
bitmask = 0xFF;
if (bmpDepth < 8)
bitmask >>= bmpDepth;
bitshift = 8 - bmpDepth;
n = 1 << bmpDepth;
lcdbufsiz -= n;
palette = lcdbuffer + lcdbufsiz;
for (col = 0; col < n; col++) {
pos = read32(bmpFile); //map palette to 5-6-5
palette[col] = ((pos & 0x0000F8) >> 3) | ((pos & 0x00FC00) >> 5) | ((pos & 0xF80000) >> 8);
}
}
// Set TFT address window to clipped image bounds
tft.setAddrWindow(x, y, x + w - 1, y + h - 1);
for (row = 0; row < h; row++) { // For each scanline...
// Seek to start of scan line. It might seem labor-
// intensive to be doing this on every line, but this
// method covers a lot of gritty details like cropping
// and scanline padding. Also, the seek only takes
// place if the file position actually needs to change
// (avoids a lot of cluster math in SD library).
uint8_t r, g, b, *sdptr;
int lcdidx, lcdleft;
if (flip) // Bitmap is stored bottom-to-top order (normal BMP)
pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize;
else // Bitmap is stored top-to-bottom
pos = bmpImageoffset + row * rowSize;
if (bmpFile.position() != pos) { // Need seek?
bmpFile.seek(pos);
buffidx = sizeof(sdbuffer); // Force buffer reload
}
for (col = 0; col < w; ) { //pixels in row
lcdleft = w - col;
if (lcdleft > lcdbufsiz) lcdleft = lcdbufsiz;
for (lcdidx = 0; lcdidx < lcdleft; lcdidx++) { // buffer at a time
uint16_t color;
// Time to read more pixel data?
if (buffidx >= sizeof(sdbuffer)) { // Indeed
bmpFile.read(sdbuffer, sizeof(sdbuffer));
buffidx = 0; // Set index to beginning
r = 0;
}
switch (bmpDepth) { // Convert pixel from BMP to TFT format
case 24:
b = sdbuffer[buffidx++];
g = sdbuffer[buffidx++];
r = sdbuffer[buffidx++];
color = tft.color565(r, g, b);
break;
case 16:
b = sdbuffer[buffidx++];
r = sdbuffer[buffidx++];
if (is565)
color = (r << 8) | (b);
else
color = (r << 9) | ((b & 0xE0) << 1) | (b & 0x1F);
break;
case 1:
case 4:
case 8:
if (r == 0)
b = sdbuffer[buffidx++], r = 8;
color = palette[(b >> bitshift) & bitmask];
r -= bmpDepth;
b <<= bmpDepth;
break;
}
lcdbuffer[lcdidx] = color;
}
tft.pushColors(lcdbuffer, lcdidx, first);
first = false;
col += lcdidx;
} // end cols
} // end rows
tft.setAddrWindow(0, 0, tft.width() - 1, tft.height() - 1); //restore full screen
ret = 0; // good render
}
bmpFile.close();
return (ret);
}
| [
"noreply@github.com"
] | bacilladoro.noreply@github.com |
35940afb25ad9c8bbbc75fe1ca9ecf895a17506d | ec68c973b7cd3821dd70ed6787497a0f808e18e1 | /Cpp/SDK/Trait_ArmorPiercer_classes.h | fae08e15c3097cbc3204baef5d9c9c7ea025c330 | [] | no_license | Hengle/zRemnant-SDK | 05be5801567a8cf67e8b03c50010f590d4e2599d | be2d99fb54f44a09ca52abc5f898e665964a24cb | refs/heads/main | 2023-07-16T04:44:43.113226 | 2021-08-27T14:26:40 | 2021-08-27T14:26:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | h | #pragma once
// Name: Remnant, Version: 1.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Trait_ArmorPiercer.Trait_ArmorPiercer_C
// 0x0000
class UTrait_ArmorPiercer_C : public UBP_RemnantTrait_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Trait_ArmorPiercer.Trait_ArmorPiercer_C");
return ptr;
}
void ModifyInspectInfo();
void ModifyDamage();
void GetArmoredDamageMod();
void OnComputeStats();
void ExecuteUbergraph_Trait_ArmorPiercer();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
e550cc89d58fd577b9fef7ff1efb178850126569 | f0ae9b02d6b471e2631e66c84e880be583c9ef97 | /plugin/hook.h | caf59269d3e8961526b00b81d58fdcf1df9f5dd6 | [
"BSD-2-Clause"
] | permissive | Bloodhacker/samp-plugin-crashdetect | a995386735d38ce29d42cce8699d549543f175aa | 96a001f754ed90604e536af8b64cb36e20755667 | refs/heads/master | 2021-01-16T17:10:17.084452 | 2013-08-31T17:19:46 | 2013-08-31T17:19:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,801 | h | // Copyright (c) 2011-2013 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 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 HOOK_H
#define HOOK_H
#include <cstddef>
#if !defined _M_IX86 && !defined __i386__
#error Unsupported architecture
#endif
class Hook {
public:
static const std::size_t kJmpInstrSize = 5;
Hook();
Hook(void *src, void *dst);
~Hook();
bool Install();
bool Install(void *src, void *dst);
bool IsInstalled() const;
bool Remove();
static void *GetTargetAddress(void *jmp);
// Temporary Remove()
class ScopedRemove {
public:
ScopedRemove(Hook *jmp)
: jmp_(jmp),
removed_(jmp->Remove())
{
// nothing
}
~ScopedRemove() {
if (removed_) {
jmp_->Install();
}
}
private:
ScopedRemove(const ScopedRemove &);
void operator=(const ScopedRemove &);
private:
Hook *jmp_;
bool removed_;
};
// Temporary Install()
class ScopedInstall {
public:
ScopedInstall(Hook *jmp)
: jmp_(jmp),
installed_(jmp->Install())
{
// nothing
}
~ScopedInstall() {
if (installed_) {
jmp_->Remove();
}
}
private:
ScopedInstall(const ScopedInstall &);
void operator=(const ScopedInstall &);
private:
Hook *jmp_;
bool installed_;
};
private:
static void Unprotect(void *address, std::size_t size);
private:
Hook(const Hook &);
void operator=(const Hook &);
private:
void *src_;
void *dst_;
unsigned char code_[5];
bool installed_;
};
#endif
| [
"zeex@rocketmail.com"
] | zeex@rocketmail.com |
2336d798a900927071cf8fc5764e3132b2fa311f | 6afa2c437044c1f6015ccbb8bada7bb84d0bea53 | /Catch Mind/Client Catch Mind/Client Catch Mind/Object.h | f2cd32d5783dbb93c710aa62e56c1f061dc44322 | [] | no_license | nskogkatt/CatchMind | 3642fd443a02d565051cbc801d4f1d3e3bd5644c | 20cd6ea0c47b546fd51434b3a5cfd9d0179ba1dc | refs/heads/master | 2020-04-15T18:44:37.852790 | 2019-01-27T06:21:55 | 2019-01-27T06:21:55 | 164,908,459 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | h | #pragma once
#include "ResManager.h"
#include "../../Common/defineSize.h"
class Bitmap;
class Object
{
protected:
RECT m_rcRect;
bool m_bLive;
public:
virtual void Init(int iIndex, Bitmap** pBitmap, RECT rcRect);
virtual void Draw() = 0;
virtual bool InputMouseLButtonDown(POINT& ptMouse);
virtual void SetLiveObject(bool bLive);
Object();
virtual ~Object();
};
| [
"43883216+nskogkatt@users.noreply.github.com"
] | 43883216+nskogkatt@users.noreply.github.com |
7897d4f4f641cbf4f1b95b5b42715112a1727630 | fe91ffa11707887e4cdddde8f386a8c8e724aa58 | /net/reporting/reporting_delivery_agent_unittest.cc | 893cdd61eb28ee88d3b2d31eceb564afdc674162 | [
"BSD-3-Clause"
] | permissive | akshaymarch7/chromium | 78baac2b45526031846ccbaeca96c639d1d60ace | d273c844a313b1e527dec0d59ce70c95fd2bd458 | refs/heads/master | 2023-02-26T23:48:03.686055 | 2020-04-15T01:20:07 | 2020-04-15T01:20:07 | 255,778,651 | 2 | 1 | BSD-3-Clause | 2020-04-15T02:04:56 | 2020-04-15T02:04:55 | null | UTF-8 | C++ | false | false | 21,755 | cc | // Copyright 2017 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 "net/reporting/reporting_delivery_agent.h"
#include <vector>
#include "base/json/json_reader.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/test/values_test_util.h"
#include "base/time/time.h"
#include "base/timer/mock_timer.h"
#include "base/values.h"
#include "net/base/backoff_entry.h"
#include "net/base/network_isolation_key.h"
#include "net/reporting/reporting_cache.h"
#include "net/reporting/reporting_report.h"
#include "net/reporting/reporting_test_util.h"
#include "net/reporting/reporting_uploader.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace net {
namespace {
class ReportingDeliveryAgentTest : public ReportingTestBase {
protected:
ReportingDeliveryAgentTest() {
ReportingPolicy policy;
policy.endpoint_backoff_policy.num_errors_to_ignore = 0;
policy.endpoint_backoff_policy.initial_delay_ms = 60000;
policy.endpoint_backoff_policy.multiply_factor = 2.0;
policy.endpoint_backoff_policy.jitter_factor = 0.0;
policy.endpoint_backoff_policy.maximum_backoff_ms = -1;
policy.endpoint_backoff_policy.entry_lifetime_ms = 0;
policy.endpoint_backoff_policy.always_use_initial_delay = false;
UsePolicy(policy);
}
const NetworkIsolationKey kNik_ = NetworkIsolationKey::Todo();
const GURL kUrl_ = GURL("https://origin/path");
const GURL kSubdomainUrl_ = GURL("https://sub.origin/path");
const url::Origin kOrigin_ = url::Origin::Create(GURL("https://origin/"));
const GURL kEndpoint_ = GURL("https://endpoint/");
const std::string kUserAgent_ = "Mozilla/1.0";
const std::string kGroup_ = "group";
const std::string kType_ = "type";
const base::Time kExpires_ = base::Time::Now() + base::TimeDelta::FromDays(7);
const ReportingEndpointGroupKey kGroupKey_ =
ReportingEndpointGroupKey(kNik_, kOrigin_, kGroup_);
};
TEST_F(ReportingDeliveryAgentTest, SuccessfulImmediateUpload) {
base::DictionaryValue body;
body.SetString("key", "value");
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0);
// Upload is automatically started when cache is modified.
ASSERT_EQ(1u, pending_uploads().size());
EXPECT_EQ(kEndpoint_, pending_uploads()[0]->url());
{
auto value = pending_uploads()[0]->GetValue();
base::ListValue* list;
ASSERT_TRUE(value->GetAsList(&list));
EXPECT_EQ(1u, list->GetSize());
base::DictionaryValue* report;
ASSERT_TRUE(list->GetDictionary(0, &report));
EXPECT_EQ(5u, report->size());
ExpectDictIntegerValue(0, *report, "age");
ExpectDictStringValue(kType_, *report, "type");
ExpectDictStringValue(kUrl_.spec(), *report, "url");
ExpectDictStringValue(kUserAgent_, *report, "user_agent");
ExpectDictDictionaryValue(body, *report, "body");
}
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
// Successful upload should remove delivered reports.
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
{
const ReportingEndpoint::Statistics stats =
GetEndpointStatistics(kGroupKey_, kEndpoint_);
EXPECT_EQ(1, stats.attempted_uploads);
EXPECT_EQ(1, stats.successful_uploads);
EXPECT_EQ(1, stats.attempted_reports);
EXPECT_EQ(1, stats.successful_reports);
}
// TODO(dcreager): Check that BackoffEntry was informed of success.
}
TEST_F(ReportingDeliveryAgentTest, SuccessfulImmediateSubdomainUpload) {
base::DictionaryValue body;
body.SetString("key", "value");
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_,
OriginSubdomains::INCLUDE));
cache()->AddReport(kNik_, kSubdomainUrl_, kUserAgent_, kGroup_, kType_,
body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0);
// Upload is automatically started when cache is modified.
ASSERT_EQ(1u, pending_uploads().size());
EXPECT_EQ(kEndpoint_, pending_uploads()[0]->url());
{
auto value = pending_uploads()[0]->GetValue();
base::ListValue* list;
ASSERT_TRUE(value->GetAsList(&list));
EXPECT_EQ(1u, list->GetSize());
base::DictionaryValue* report;
ASSERT_TRUE(list->GetDictionary(0, &report));
EXPECT_EQ(5u, report->size());
ExpectDictIntegerValue(0, *report, "age");
ExpectDictStringValue(kType_, *report, "type");
ExpectDictStringValue(kSubdomainUrl_.spec(), *report, "url");
ExpectDictStringValue(kUserAgent_, *report, "user_agent");
ExpectDictDictionaryValue(body, *report, "body");
}
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
// Successful upload should remove delivered reports.
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
{
const ReportingEndpoint::Statistics stats =
GetEndpointStatistics(kGroupKey_, kEndpoint_);
EXPECT_EQ(1, stats.attempted_uploads);
EXPECT_EQ(1, stats.successful_uploads);
EXPECT_EQ(1, stats.attempted_reports);
EXPECT_EQ(1, stats.successful_reports);
}
// TODO(dcreager): Check that BackoffEntry was informed of success.
}
TEST_F(ReportingDeliveryAgentTest,
SuccessfulImmediateSubdomainUploadWithOverwrittenEndpoint) {
base::DictionaryValue body;
body.SetString("key", "value");
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_,
OriginSubdomains::INCLUDE));
cache()->AddReport(kNik_, kSubdomainUrl_, kUserAgent_, kGroup_, kType_,
body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0);
// Upload is automatically started when cache is modified.
ASSERT_EQ(1u, pending_uploads().size());
// Change the endpoint group to exclude subdomains.
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_,
OriginSubdomains::EXCLUDE));
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
{
const ReportingEndpoint::Statistics stats =
GetEndpointStatistics(kGroupKey_, kEndpoint_);
EXPECT_EQ(1, stats.attempted_uploads);
EXPECT_EQ(1, stats.successful_uploads);
EXPECT_EQ(1, stats.attempted_reports);
EXPECT_EQ(1, stats.successful_reports);
}
// Successful upload should remove delivered reports.
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
}
TEST_F(ReportingDeliveryAgentTest, SuccessfulDelayedUpload) {
base::DictionaryValue body;
body.SetString("key", "value");
// Trigger and complete an upload to start the delivery timer.
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0);
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
// Add another report to upload after a delay.
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0);
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
ASSERT_EQ(1u, pending_uploads().size());
EXPECT_EQ(kEndpoint_, pending_uploads()[0]->url());
{
auto value = pending_uploads()[0]->GetValue();
base::ListValue* list;
ASSERT_TRUE(value->GetAsList(&list));
EXPECT_EQ(1u, list->GetSize());
base::DictionaryValue* report;
ASSERT_TRUE(list->GetDictionary(0, &report));
EXPECT_EQ(5u, report->size());
ExpectDictIntegerValue(0, *report, "age");
ExpectDictStringValue(kType_, *report, "type");
ExpectDictStringValue(kUrl_.spec(), *report, "url");
ExpectDictStringValue(kUserAgent_, *report, "user_agent");
ExpectDictDictionaryValue(body, *report, "body");
}
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
{
const ReportingEndpoint::Statistics stats =
GetEndpointStatistics(kGroupKey_, kEndpoint_);
EXPECT_EQ(2, stats.attempted_uploads);
EXPECT_EQ(2, stats.successful_uploads);
EXPECT_EQ(2, stats.attempted_reports);
EXPECT_EQ(2, stats.successful_reports);
}
// Successful upload should remove delivered reports.
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
// TODO(juliatuttle): Check that BackoffEntry was informed of success.
}
TEST_F(ReportingDeliveryAgentTest, FailedUpload) {
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
ASSERT_EQ(1u, pending_uploads().size());
pending_uploads()[0]->Complete(ReportingUploader::Outcome::FAILURE);
{
const ReportingEndpoint::Statistics stats =
GetEndpointStatistics(kGroupKey_, kEndpoint_);
EXPECT_EQ(1, stats.attempted_uploads);
EXPECT_EQ(0, stats.successful_uploads);
EXPECT_EQ(1, stats.attempted_reports);
EXPECT_EQ(0, stats.successful_reports);
}
// Failed upload should increment reports' attempts.
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
ASSERT_EQ(1u, reports.size());
EXPECT_EQ(1, reports[0]->attempts);
// Since endpoint is now failing, an upload won't be started despite a pending
// report.
ASSERT_TRUE(pending_uploads().empty());
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
EXPECT_TRUE(pending_uploads().empty());
{
const ReportingEndpoint::Statistics stats =
GetEndpointStatistics(kGroupKey_, kEndpoint_);
EXPECT_EQ(1, stats.attempted_uploads);
EXPECT_EQ(0, stats.successful_uploads);
EXPECT_EQ(1, stats.attempted_reports);
EXPECT_EQ(0, stats.successful_reports);
}
}
TEST_F(ReportingDeliveryAgentTest, DisallowedUpload) {
// This mimics the check that is controlled by the BACKGROUND_SYNC permission
// in a real browser profile.
context()->test_delegate()->set_disallow_report_uploads(true);
static const int kAgeMillis = 12345;
base::DictionaryValue body;
body.SetString("key", "value");
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0);
tick_clock()->Advance(base::TimeDelta::FromMilliseconds(kAgeMillis));
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
// We should not try to upload the report, since we weren't given permission
// for this origin.
EXPECT_TRUE(pending_uploads().empty());
{
const ReportingEndpoint::Statistics stats =
GetEndpointStatistics(kGroupKey_, kEndpoint_);
EXPECT_EQ(0, stats.attempted_uploads);
EXPECT_EQ(0, stats.successful_uploads);
EXPECT_EQ(0, stats.attempted_reports);
EXPECT_EQ(0, stats.successful_reports);
}
// Disallowed reports should NOT have been removed from the cache.
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
EXPECT_EQ(1u, reports.size());
}
TEST_F(ReportingDeliveryAgentTest, RemoveEndpointUpload) {
static const url::Origin kDifferentOrigin =
url::Origin::Create(GURL("https://origin2/"));
static const ReportingEndpointGroupKey kOtherGroupKey(
NetworkIsolationKey(), kDifferentOrigin, kGroup_);
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
ASSERT_TRUE(SetEndpointInCache(kOtherGroupKey, kEndpoint_, kExpires_));
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
ASSERT_EQ(1u, pending_uploads().size());
pending_uploads()[0]->Complete(ReportingUploader::Outcome::REMOVE_ENDPOINT);
// "Remove endpoint" upload should remove endpoint from *all* origins and
// increment reports' attempts.
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
ASSERT_EQ(1u, reports.size());
EXPECT_EQ(1, reports[0]->attempts);
EXPECT_FALSE(FindEndpointInCache(kGroupKey_, kEndpoint_));
EXPECT_FALSE(FindEndpointInCache(kOtherGroupKey, kEndpoint_));
// Since endpoint is now failing, an upload won't be started despite a pending
// report.
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
EXPECT_TRUE(pending_uploads().empty());
}
TEST_F(ReportingDeliveryAgentTest, ConcurrentRemove) {
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
ASSERT_EQ(1u, pending_uploads().size());
// Remove the report while the upload is running.
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
EXPECT_EQ(1u, reports.size());
const ReportingReport* report = reports[0];
EXPECT_FALSE(cache()->IsReportDoomedForTesting(report));
// Report should appear removed, even though the cache has doomed it.
cache()->RemoveReports(reports, ReportingReport::Outcome::UNKNOWN);
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
EXPECT_TRUE(cache()->IsReportDoomedForTesting(report));
// Completing upload shouldn't crash, and report should still be gone.
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
}
TEST_F(ReportingDeliveryAgentTest, ConcurrentRemoveDuringPermissionsCheck) {
// Pause the permissions check, so that we can try to remove some reports
// while we're in the middle of verifying that we can upload them. (This is
// similar to the previous test, but removes the reports during a different
// part of the upload process.)
context()->test_delegate()->set_pause_permissions_check(true);
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
ASSERT_TRUE(context()->test_delegate()->PermissionsCheckPaused());
// Remove the report while the upload is running.
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
EXPECT_EQ(1u, reports.size());
const ReportingReport* report = reports[0];
EXPECT_FALSE(cache()->IsReportDoomedForTesting(report));
// Report should appear removed, even though the cache has doomed it.
cache()->RemoveReports(reports, ReportingReport::Outcome::UNKNOWN);
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
EXPECT_TRUE(cache()->IsReportDoomedForTesting(report));
// Completing upload shouldn't crash, and report should still be gone.
context()->test_delegate()->ResumePermissionsCheck();
ASSERT_EQ(1u, pending_uploads().size());
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
}
// Test that the agent will combine reports destined for the same endpoint, even
// if the reports are from different origins.
TEST_F(ReportingDeliveryAgentTest,
BatchReportsFromDifferentOriginsToSameEndpoint) {
static const GURL kDifferentUrl("https://origin2/path");
static const url::Origin kDifferentOrigin =
url::Origin::Create(kDifferentUrl);
const ReportingEndpointGroupKey kDifferentGroupKey(NetworkIsolationKey(),
kDifferentOrigin, kGroup_);
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
ASSERT_TRUE(SetEndpointInCache(kDifferentGroupKey, kEndpoint_, kExpires_));
// Trigger and complete an upload to start the delivery timer.
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
// Now that the delivery timer is running, these reports won't be immediately
// uploaded.
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
cache()->AddReport(kNik_, kDifferentUrl, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
EXPECT_EQ(0u, pending_uploads().size());
// When we fire the delivery timer, we should NOT batch these two reports into
// a single upload, since each upload must only contain reports about a single
// origin.
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
ASSERT_EQ(2u, pending_uploads().size());
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
EXPECT_EQ(0u, pending_uploads().size());
}
// Test that the agent won't start a second upload to the same endpoint for a
// particular origin while one is pending, but will once it is no longer
// pending.
TEST_F(ReportingDeliveryAgentTest, SerializeUploadsToEndpoint) {
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
EXPECT_EQ(1u, pending_uploads().size());
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
ASSERT_EQ(1u, pending_uploads().size());
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
EXPECT_EQ(0u, pending_uploads().size());
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
ASSERT_EQ(1u, pending_uploads().size());
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
EXPECT_EQ(0u, pending_uploads().size());
}
// Test that the agent won't start a second upload for an (origin, group) while
// one is pending, even if a different endpoint is available, but will once the
// original delivery is complete and the (origin, group) is no longer pending.
TEST_F(ReportingDeliveryAgentTest, SerializeUploadsToGroup) {
static const GURL kDifferentEndpoint("https://endpoint2/");
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kDifferentEndpoint, kExpires_));
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
EXPECT_EQ(1u, pending_uploads().size());
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
ASSERT_EQ(1u, pending_uploads().size());
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
EXPECT_EQ(0u, pending_uploads().size());
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
ASSERT_EQ(1u, pending_uploads().size());
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
EXPECT_EQ(0u, pending_uploads().size());
}
// Tests that the agent will start parallel uploads to different groups within
// the same origin.
TEST_F(ReportingDeliveryAgentTest, ParallelizeUploadsAcrossGroups) {
static const GURL kDifferentEndpoint("https://endpoint2/");
static const std::string kDifferentGroup("group2");
const ReportingEndpointGroupKey kDifferentGroupKey(NetworkIsolationKey(),
kOrigin_, kDifferentGroup);
ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_));
ASSERT_TRUE(
SetEndpointInCache(kDifferentGroupKey, kDifferentEndpoint, kExpires_));
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
cache()->AddReport(kNik_, kUrl_, kUserAgent_, kDifferentGroup, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
EXPECT_TRUE(delivery_timer()->IsRunning());
delivery_timer()->Fire();
ASSERT_EQ(2u, pending_uploads().size());
pending_uploads()[1]->Complete(ReportingUploader::Outcome::SUCCESS);
pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS);
EXPECT_EQ(0u, pending_uploads().size());
}
} // namespace
} // namespace net
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
46f5fa8b6b7a6ca4293269043aca818aa3fa2ba0 | 9bf063f6c46777d15e82a1ab45d5a03449412fe4 | /rewards/RewardRuleResolver.cpp | 3aaa91fb9fd62c2f04783ef47cdf9bcc3fce120b | [] | no_license | arctgarg/rewards_calculator | 7b68e4a9497ab3e4846f80eb7da64bb1c322cdd8 | ebbb5e3292652f6385a7afacad54c6ca84e175cf | refs/heads/master | 2021-01-07T21:59:48.187876 | 2020-02-24T18:00:29 | 2020-02-24T18:00:29 | 241,831,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,828 | cpp | //
// Created by agarg145 on 2/16/20.
//
#include "RewardRuleResolver.h"
#include "CSVReader.h"
#include <math.h>
#include <iostream>
using std::vector;
RewardRule RewardRuleResolver::findApplicableRule(const Transaction &transaction) {
int matchingParamterCount = 0;
RewardRule matchingRule;
for(auto rule : this->rules)
{
int count = this->getMatchingParametersCount(rule, transaction);
if(count > matchingParamterCount)
{
matchingRule = rule;
matchingParamterCount = count;
}
}
return matchingRule;
}
RewardRuleResolver::RewardRuleResolver(vector<RewardRule> rules) {
this->rules = rules;
}
int RewardRuleResolver::getMatchingParametersCount(const RewardRule &rule, const Transaction transaction) {
int matchingParameterCount = 0;
if(rule.getTransactionType() != "NULL" ){
if(rule.getTransactionType() != transaction.getTransactionType())
return 0;
else matchingParameterCount++;
}
if(rule.getMerchantType() != "NULL"){
if(rule.getMerchantType() != transaction.getMerchantType())
return 0;
else matchingParameterCount++;
}
auto absoluteTransactionAmount = abs(transaction.getTransactionAmount());
if(rule.getUpperTransactionAmountLimit() >= absoluteTransactionAmount) matchingParameterCount++;
if(rule.getLowerTransactionAmountLimit() <= absoluteTransactionAmount) matchingParameterCount++;
return matchingParameterCount;
}
std::vector<RewardRule> RewardRuleCSVReader::readRules() {
auto rows = getNextRecords(1000);
vector<RewardRule> rules;
for(auto& row : rows)
{
rules.push_back(RewardRule(row));
}
return rules;
}
RewardRuleCSVReader::RewardRuleCSVReader(std::string filepath) : CSVReader(filepath) {
}
| [
"agarg145@bloomberg.net"
] | agarg145@bloomberg.net |
f40b485776ab82587c3247d710f906465efc0e79 | 7c34490a04ec37a171398e098c68911ec93e57ae | /winvnc/winvnc/vncbuffer.h | aa6ad0c74e6863e0eca860fc77441763b77ad3e3 | [] | no_license | larytet/UltraVNC-SC | 20344b1e9ae0a7eb19138ec96a1bbc63aee62d8a | 882b3c2be385ad536d24550f69cb129f094e3fbf | refs/heads/master | 2020-07-04T06:32:33.131632 | 2016-09-12T09:51:59 | 2016-09-12T09:51:59 | 67,602,481 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,237 | h | // Copyright (C) 2002 Ultr@VNC Team Members. All Rights Reserved.
// Copyright (C) 2002 RealVNC Ltd. All Rights Reserved.
// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
//
// This file is part of the VNC system.
//
// The VNC system is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
// If the source code for the VNC system is not available from the place
// whence you received this file, check http://www.uk.research.att.com/vnc or contact
// the authors on vnc@uk.research.att.com for information on obtaining it.
// vncBuffer object
// The vncBuffer object provides a client-local copy of the screen
// It can tell the client which bits have changed in a given region
// It uses the specified vncDesktop to read screen data from
class vncDesktop;
class vncBuffer;
#if !defined(_WINVNC_VNCBUFFER)
#define _WINVNC_VNCBUFFER
#pragma once
// Includes
#include "stdhdrs.h"
#include "vncEncoder.h"
#include "rfbRegion.h"
#include "rfbRect.h"
#include "rfb.h"
#include "vncmemcpy.h"
// Class definition
class vncBuffer
{
// Methods
public:
// Create/Destroy methods
vncBuffer();
~vncBuffer();
void SetDesktop(vncDesktop *desktop);
// BUFFER INFO
rfb::Rect GetSize();
rfbPixelFormat GetLocalFormat();
// BUFFER MANIPULATION
BOOL CheckBuffer();
// SCREEN SCANNING
// void Clear(const rfb::Rect &rect);
void CheckRegion(rfb::Region2D &dest,rfb::Region2D &cache, const rfb::Region2D &src);
void CheckRect(rfb::Region2D &dest,rfb::Region2D &cache, const rfb::Rect &src);
// SCREEN CAPTURE
void CopyRect(const rfb::Rect &dest, const rfb::Point &delta);
void GrabMouse();
void GrabRegion(rfb::Region2D &src,BOOL driver,bool capture);
void GetMousePos(rfb::Rect &rect);
// CACHE RDV
void ClearCache();
void ClearCacheRect(const rfb::Rect &dest);
void ClearBack();
void BlackBack();
void EnableCache(BOOL enable);
BOOL IsCacheEnabled();
BOOL IsShapeCleared();
void Display(int number);
int GetDisplay();
// sf@2005 - Grey Palette
void EnableGreyPalette(BOOL enable);
// Modif sf@2002 - Scaling
void ScaleRect(rfb::Rect &rect);
void GreyScaleRect(rfb::Rect &rect);
rfb::Rect GetViewerSize();
UINT GetScale();
BOOL SetScale(int scale);
// Modif sf@2002 - Optim
BOOL SetAccuracy(int accuracy);
// CURSOR HANDLING
BOOL IsCursorUpdatePending(){return m_cursorpending;};
void SetCursorPending(BOOL enable){m_cursorpending=enable;};
bool ClipRect(int *x, int *y, int *w, int *h, int cx, int cy, int cw, int ch);
// Implementation
protected:
// Routine to verify the mainbuff handle hasn't changed
BOOL FastCheckMainbuffer();
// Fetch pixel data to the main buffer from the screen
void GrabRect(const rfb::Rect &rect,BOOL driver,bool capture);
BOOL m_freemainbuff;
UINT m_bytesPerRow;
// CACHE RDV
BOOL m_use_cache;
BOOL m_display_prim;
BOOL m_display_sec;
// Modif sf@2002 - Scaling
UINT m_ScaledSize;
UINT m_nScale;
BYTE *m_ScaledBuff;
int m_nAccuracyDiv; // Accuracy divider for changes detection in Rects
int nRowIndex;
// CURSOR HANDLING
BOOL m_cursorpending;
public:
rfbServerInitMsg m_scrinfo;
// vncEncodeMgr reads data from back buffer directly when encoding
BYTE *m_backbuff;
UINT m_backbuffsize;
// CACHE RDV
BYTE *m_cachebuff;
BYTE *m_mainbuff;
vncDesktop *m_desktop;
BOOL m_cursor_shape_cleared;
// sf@2005 - Grey palette
BOOL m_fGreyPalette;
};
#endif // _WINVNC_VNCBUFFER | [
"larytet@yahoo.com"
] | larytet@yahoo.com |
bc5facd964781422812694115e3a0b0b10b737e2 | 93edd9b5a7ae05fa6a16ffc86418b5de465490f6 | /programmers/깊이너비우선탐색/단어변환/word_jiwon.cpp | 5ee3bd4f9db8ac714e75f8152cc88e6eac3536b5 | [] | no_license | Yellin36/LOGO-algorithm | dbc0590d5fdc22d74652aa009d988272ad98e281 | 2da7f99aeca36ec982c324e132e030e0dfe8e724 | refs/heads/master | 2023-05-07T01:34:21.883476 | 2021-05-25T17:04:57 | 2021-05-25T17:04:57 | 329,848,372 | 3 | 0 | null | 2021-05-25T17:04:57 | 2021-01-15T08:08:28 | C++ | UTF-8 | C++ | false | false | 930 | cpp | #include <string>
#include <vector>
using namespace std;
bool visit[51];
int answer = 51;
void DFS(string begin, string target, int cnt, vector<string> words){
if(begin == target){
if(answer>cnt)
answer = cnt;
return;
}
for(int i=0;i<words.size();i++){
if(!visit[i] && begin != words[i]){
int num = 0;
for(int j=0;j<begin.length();j++){
if(begin[j] != words[i][j])
num++;
if(num > 1)
break;
}
if(num == 1){
visit[i] = true;
DFS(words[i],target,cnt+1,words);
visit[i] = false;
}
}
}
}
int solution(string begin, string target, vector<string> words) {
DFS(begin,target,0, words);
//반환할 수 없는 경우
if(answer==51)
answer = 0;
return answer;
}
| [
"tjfdnjs0829@naver.com"
] | tjfdnjs0829@naver.com |
3add123ba8aec226ee8ea688157cb92ba4755ff9 | 66684ef8257e424ae24af6a25379bbb64eec7436 | /union/models/VertexBuffer.cpp | 06a34b99b4af166abc7009f07d4e043c689fb6ea | [] | no_license | sergey-shambir/toAlexeyMalov | d39aa416649583f1a2c056fdb268ff0278908b83 | f0bc5c9119e3954e97df9adeb4b05614d874773c | refs/heads/master | 2020-05-29T12:03:33.817310 | 2015-10-15T22:59:34 | 2015-10-15T22:59:34 | 8,674,751 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,730 | cpp | #include "VertexBuffer.h"
#include "../helpers/ResourceHeap.h"
#include <GL/glew.h>
#include <stdexcept>
namespace GL {
static unsigned bufferConstructor()
{
if (!GLEW_VERSION_1_5)
{
throw std::runtime_error("ERROR: hardware requirement missed - OpenGL >= 1.5,"
" update drivers or try run on another graphics card");
}
unsigned bufferId(0);
glGenBuffers(1, &bufferId);
return bufferId;
}
static void bufferDestructor(unsigned bufferId)
{
glDeleteBuffers(1, &bufferId);
}
VertexBuffer::VertexBuffer()
: m_id(0)
, m_type(Type_Attributes)
, m_usageHint(GL_STATIC_DRAW)
, m_bytesCount(0)
{
}
VertexBuffer::VertexBuffer(const VertexBuffer &other)
: m_id(other.m_id)
, m_type(other.m_type)
, m_usageHint(other.m_usageHint)
, m_bytesCount(0)
{
ResourceHeap::instance().retain(m_id, ResourceHeap::VertexBuffer);
}
VertexBuffer &VertexBuffer::operator =(const VertexBuffer &other)
{
ResourceHeap::instance().retain(m_id, ResourceHeap::VertexBuffer);
m_id = other.m_id;
m_type = other.m_type;
m_usageHint = other.m_usageHint;
m_bytesCount = other.m_bytesCount;
return *this;
}
VertexBuffer::~VertexBuffer()
{
ResourceHeap::instance().release(m_id, ResourceHeap::VertexBuffer);
}
void VertexBuffer::ensureInitializated()
{
if (m_id == 0) {
m_id = ResourceHeap::instance().create(bufferConstructor,
bufferDestructor,
ResourceHeap::VertexBuffer);
}
}
void VertexBuffer::setType(VertexBuffer::Type type)
{
m_type = type;
}
void VertexBuffer::setUsageHint(int usageHint)
{
m_usageHint = usageHint;
}
void VertexBuffer::init(const void *data, unsigned bytesCount)
{
ensureInitializated();
m_bytesCount = bytesCount;
GLenum target = (m_type == Type_Attributes)
? GL_ARRAY_BUFFER
: GL_ELEMENT_ARRAY_BUFFER;
glBindBuffer(target, m_id);
glBufferData(target, bytesCount, data, m_usageHint);
}
void VertexBuffer::bind() const
{
GLenum target = (m_type == Type_Attributes)
? GL_ARRAY_BUFFER
: GL_ELEMENT_ARRAY_BUFFER;
glBindBuffer(target, m_id);
}
void VertexBuffer::unbind() const
{
GLenum target = (m_type == Type_Attributes)
? GL_ARRAY_BUFFER
: GL_ELEMENT_ARRAY_BUFFER;
glBindBuffer(target, 0);
}
void VertexBuffer::unbind(Type type)
{
GLenum target = (type == Type_Attributes)
? GL_ARRAY_BUFFER
: GL_ELEMENT_ARRAY_BUFFER;
glBindBuffer(target, 0);
}
unsigned VertexBuffer::bytesCount() const
{
return m_bytesCount;
}
} // namespace GL
| [
"sergey.shambir.auto@gmail.com"
] | sergey.shambir.auto@gmail.com |
2ccf0594afd4a3ea05ab188343450a75a6aebecf | 3e5ae9b260b16fcc86bb0669c1bd4e56912b5433 | /VCB600ENU1/MSDN_VCB/SAMPLES/VC98/MFC/GENERAL/CTRLTEST/PAREDIT.H | de5d922bbc77169d7ddba37f0e5be63a44adabd2 | [] | no_license | briancpark/deitel-cpp | e8612c7011c9d9d748290419ae2708d2f3f11543 | 90cdae5661718e65ab945bcf45fe6adff30c1e10 | refs/heads/main | 2023-06-14T14:07:05.497253 | 2021-07-05T01:46:04 | 2021-07-05T01:46:04 | 382,984,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,094 | h | // paredit.h: C++ derived edit control for numbers/letters etc
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) 1992-1998 Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
/////////////////////////////////////////////////////////////////////////////
// CParsedEdit is a specialized CEdit control that only allows characters
// of a given type.
// This class is used in 3 different ways in the samples
class CParsedEdit : public CEdit
{
protected:
WORD m_wParseStyle; // C++ member data
public:
// Construction
CParsedEdit();
// explicit construction (see DERTEST.CPP)
BOOL Create(DWORD dwStyle /* includes PES_ style*/, const RECT& rect,
CWnd* pParentWnd, UINT nID);
// subclassed construction (see SUBTEST.CPP)
BOOL SubclassEdit(UINT nID, CWnd* pParent, WORD wParseStyle);
// for WNDCLASS Registered window
static BOOL RegisterControlClass();
// Overridables
virtual void OnBadInput();
// Implementation
protected:
//{{AFX_MSG(CParsedEdit)
afx_msg void OnChar(UINT, UINT, UINT); // for character validation
afx_msg void OnVScroll(UINT, UINT, CScrollBar*); // for spin buttons
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////
// Parsed edit control sub-styles
#define PES_NUMBERS 0x0001
#define PES_LETTERS 0x0002
#define PES_OTHERCHARS 0x0004
#define PES_ALL 0xFFFF
/////////////////////////////////////////////////////////////////////////////
// Extra control notifications
// above the range for normal EN_ messages
#define PEN_ILLEGALCHAR 0x8000
// sent to parent when illegal character hit
// return 0 if you want parsed edit to beep
/////////////////////////////////////////////////////////////////////////////
| [
"briancpark@berkeley.edu"
] | briancpark@berkeley.edu |
71e35f1a22ee8a004b8d5fb436e57ffa7b3c5373 | e199dc22cf988d78b9290ce2757cdd5ad849f9c6 | /PeisikInterpreter/Program.cpp | 1a08e0a6c894db391dbfdf19430267f46ee01ef5 | [
"MIT"
] | permissive | polsys/Peisik | 9c42545339dc2e5d3d48045b06f72c2733e21f3a | 5c55a41c4f4154b0ee2f23f9cbde576401c20832 | refs/heads/master | 2021-01-20T14:23:40.681288 | 2018-05-01T13:34:36 | 2018-05-01T13:34:36 | 90,603,083 | 0 | 0 | null | 2018-02-03T13:24:57 | 2017-05-08T08:15:27 | C# | UTF-8 | C++ | false | false | 5,416 | cpp | #include "pch.h"
#include "Bytecode.h"
#include "PeisikException.h"
#include "Program.h"
using namespace Peisik;
/*
* Function
*/
const std::vector<BytecodeOp>& Function::GetBytecode() const
{
return m_bytecode;
}
short Peisik::Function::GetFunctionIndex() const
{
return m_functionIndex;
}
const std::vector<PrimitiveType>& Peisik::Function::GetLocalTypes() const
{
return m_localTypes;
}
short Peisik::Function::GetParameterCount() const
{
return m_parameterCount;
}
PrimitiveType Function::GetReturnType() const
{
return m_returnType;
}
/*
* Program
*/
PObject Program::GetConstant(short index) const
{
if (index < 0 || index >= GetConstantCount())
{
throw std::range_error("Constant index out of range.");
}
return m_constants[index];
}
short Program::GetConstantCount() const
{
return static_cast<short>(m_constants.size());
}
const Function& Program::GetFunction(short index) const
{
if (index < 0 || index >= GetFunctionCount())
{
throw std::range_error("Function index out of range.");
}
return m_functions[index];
}
short Program::GetFunctionCount() const
{
return static_cast<short>(m_functions.size());
}
short Program::GetMainFunctionIndex() const
{
return m_mainFunctionIndex;
}
/*
* Global namespace
*/
static void AssertValidType(short type)
{
if (type <= (short)PrimitiveType::NoType || type > (short)PrimitiveType::Bool)
throw std::invalid_argument("Invalid constant type.");
}
template <typename T>
static void Read(T* to, std::istream& stream)
{
stream.read(reinterpret_cast<char*>(to), sizeof(T));
}
Program Peisik::DeserializeProgram(std::istream& stream)
{
// Make all errors throw
stream.exceptions(std::istream::badbit | std::istream::eofbit | std::istream::failbit);
Program result;
// The header contains a magic number, bytecode version and the main function index
uint32_t magic = 0;
Read(&magic, stream);
if (magic != 0x53494550 /* PEIS (notice the endianness) */)
throw InterpreterException("Not a compiled Peisik file.");
uint32_t bytecodeVersion = 0;
Read(&bytecodeVersion, stream);
if (bytecodeVersion != Program::BytecodeVersion)
throw InterpreterException("Wrong bytecode version.");
uint32_t mainIndex = 0;
Read(&mainIndex, stream);
result.m_mainFunctionIndex = static_cast<short>(mainIndex);
// Then, the constants.
// First, a 32-bit integer for their count and then each constant
int32_t constCount = -1;
Read(&constCount, stream);
if (constCount < 0)
throw InterpreterException("Constant count less than 0.");
for (int i = 0; i < constCount; i++)
{
// Type code
short type = 0;
Read(&type, stream);
AssertValidType(type);
// 6 bytes of UTF-8 encoded name as padding - ignore
char name[6];
stream.read(name, 6 * sizeof(char));
// Value
int64_t value = -1;
Read(&value, stream);
// Add the constant
result.m_constants.push_back(PObject(static_cast<PrimitiveType>(type), value));
}
// Then the functions.
// First, a 32-bit integer for their count.
// Then for each function:
// 1. The return type (2 bytes)
// 2. Parameter count (2 bytes)
// 3. Parameter types, 2 bytes each
// (4. 2 bytes of padding if odd number of parameters)
// 5. Bytecode size (4 bytes)
// 6. Bytecode
int32_t functionCount = -1;
Read(&functionCount, stream);
if (functionCount < 0)
throw InterpreterException("Function count less than 0.");
if (functionCount > 32768)
throw std::range_error("Too many functions.");
for (int i = 0; i < functionCount; i++)
{
Function func;
func.m_functionIndex = static_cast<short>(i);
// Return type
short returnType;
Read(&returnType, stream);
AssertValidType(returnType);
func.m_returnType = static_cast<PrimitiveType>(returnType);
// Parameter count
Read(&func.m_parameterCount, stream);
if (func.m_parameterCount < 0)
throw InterpreterException("Parameter count less than 0.");
// Locals
short localCount = -1;
Read(&localCount, stream);
if (localCount < 0)
throw InterpreterException("Local count less than 0.");
func.m_localTypes.reserve(localCount);
for (int localIdx = 0; localIdx < localCount; localIdx++)
{
short type = 0;
Read(&type, stream);
AssertValidType(type);
func.m_localTypes.push_back(static_cast<PrimitiveType>(type));
}
if (localCount % 2 == 1)
{
short unused = 0;
Read(&unused, stream);
}
// Bytecode
int32_t codeSize = -1;
Read(&codeSize, stream);
if (codeSize < 0)
throw InterpreterException("Code size less than 0.");
func.m_bytecode.reserve(codeSize);
for (int j = 0; j < codeSize; j++)
{
short op = -1;
Read(&op, stream);
short param = -1;
Read(¶m, stream);
func.m_bytecode.push_back(BytecodeOp(static_cast<Opcode>(op), param));
}
result.m_functions.push_back(func);
}
return result;
}
| [
"polsys@users.noreply.github.com"
] | polsys@users.noreply.github.com |
a86dba580cfd434305edc5db4fce93f479c4d022 | dfb7297f114bbff7a89fea86cb9b8e0e16243d01 | /CCF-CSP/CCF-CSP/17-09-2.cpp | 9a0a399969e39b888cfa22d8a46c7868b0e77282 | [] | no_license | rainingapple/algorithm-competition-code | c06bd549d44e14c64e808d7026a0204d285f1fb3 | 809bff5cdf092568de47def7d24d36edef8d0c1e | refs/heads/main | 2023-03-30T13:11:23.359366 | 2021-04-09T01:29:18 | 2021-04-09T01:29:18 | 343,407,072 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,357 | cpp | //#include<iostream>
//#include<vector>
//#include<queue>
//#include<map>
//#include<algorithm>
//using namespace std;
//struct node {
// int no;
// int flag;
// int time;
// node(int a, int b, int c) :no(a), flag(b), time(c) {}
//};
//int n, k;
//int key[1005];
//vector<node> action;
//priority_queue<int,vector<int>,greater<int>> q;
//map<int, int> pos;
//bool cmp(node n1, node n2) {
// if (n1.time != n2.time)
// return n1.time < n2.time;
// else if (n1.flag != n2.flag) {
// return n1.flag > n2.flag;
// }
// else {
// return n1.no < n2.no;
// }
//}
//void fuc(node x) {
// int no = x.no;
// int flag = x.flag;
// int time = x.time;
// if (flag == 1) {
// int top = q.top();
// q.pop();
// key[top] = no;
// pos[no] = top;
// }
// else {
// key[pos[no]] = 0;
// q.push(pos[no]);
// }
//}
//int main() {
// cin >> n >> k;
// for (int i = 1;i <= n;i++) {
// key[i] = i;
// pos[i] = i;
// }
// for (int i = 0;i < k;i++) {
// int no, b_time, e_time;
// cin >> no >> b_time >> e_time;
// action.push_back(node(no, 0, b_time));
// action.push_back(node(no, 1, b_time+e_time));
// }
// sort(action.begin(), action.end(), cmp);
// for (auto i = action.begin();i < action.end();i++) {
// fuc(*i);
// }
// for (int i = 1;i <= n;i++) {
// cout << key[i] << " ";
// }
// return 0;
//} | [
"825140645@qq.com"
] | 825140645@qq.com |
09138c47f29e7679be97843d2c9a8a779e856be5 | 1d3496037ed70eab651a69ad607ce0a331b34f60 | /algo/endterm/d.cpp | 9e7b5b3d11bc01ffaf2c6cab12fd792a8dda92c6 | [] | no_license | olzhas-b/algorithm-data-structure | 90f00961585aef6796df9859d5554445bc8212c0 | 72803bbe9fbd772fd9233307051df21bfac16e95 | refs/heads/master | 2023-05-05T08:30:29.978262 | 2021-06-03T18:10:30 | 2021-06-03T18:10:30 | 373,599,853 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,015 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
int n; cin >> n;
vector<int> v(n);
vector<long long> mx(3);
for(int i = 0; i < n; i++) {
cin >> v[i];
}
for(int i = 0; i < min(3, n); i++) {
mx[i] = v[i];
}
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
if (mx[k] > mx[k+1])
swap(mx[k], mx[k+1]);
for(int i = 0; i < n; i++) {
if(i < 2) {
cout << -1 << endl;
} else {
if(i == 2) {
cout << mx[0] * mx[1] * mx[2] << endl;
} else {
if(v[i] >= mx[0]) {
mx[0] = v[i];
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
if (mx[k] > mx[k+1])
swap(mx[k], mx[k+1]);
}
cout << mx[0] * mx[1] * mx[2] << endl;
}
}
}
return 0;
} | [
"oljas.bazarbekov15@gmail.com"
] | oljas.bazarbekov15@gmail.com |
c0807937637f6ce78b5a479535463eb58426c51a | 27c28ce3e77b620b97f0683069ff596491a694d0 | /Day 8/Prefix Calculator.cpp | 8aa33c37a9e54c3a0bb43c51104ebca4e85bdd78 | [
"MIT"
] | permissive | shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress | fd1b0b80e8c4476b01d6de01508bd15b38e3a07d | 0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166 | refs/heads/master | 2020-10-02T02:47:51.461794 | 2020-03-20T11:01:36 | 2020-03-20T11:01:36 | 227,684,132 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | cpp | // Prefix Calculator
// Day #8
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_set>
using namespace std;
class Solution {
public:
int prefixCalc(string str) {
unordered_set<string> ops = { "+", "-", "/", "*" };
stack<string> rev;
stack<int> s;
cout << str << endl << endl;
istringstream iss(str);
string word;
while (iss >> word) rev.push(word);
while (!rev.empty()) {
string word = rev.top(); rev.pop();
if (!ops.count(word)) s.push(stoi(word));
else {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
if (word == "+") s.push(a + b);
if (word == "-") s.push(a - b);
if (word == "*") s.push(a * b);
if (word == "/") s.push(a / b);
}
}
return s.top();
}
};
int main(void) {
//"+ 4 * 3 12" -> 40
string input = "+ 4 * 3 12";
Solution obj;
cout << "Result: " << obj.prefixCalc(input);
return 0;
} | [
"noreply@github.com"
] | shtanriverdi.noreply@github.com |
feb0663c6a363b147cb749411c51b29f741190ca | be31580024b7fb89884cfc9f7e8b8c4f5af67cfa | /CTDL1/New folder/VC/VCWizards/CodeWiz/MFC/Simple/Templates/3082/dhtmldlg.cpp | a056084dd68e91ef4a54dc8fddd6e6eb9c099acd | [] | no_license | Dat0309/CTDL-GT1 | eebb73a24bd4fecf0ddb8428805017e88e4ad9da | 8b5a7ed4f98e5d553bf3c284cd165ae2bd7c5dcc | refs/heads/main | 2023-06-09T23:04:49.994095 | 2021-06-23T03:34:47 | 2021-06-23T03:34:47 | 379,462,390 | 1 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 3,016 | cpp | // [!output IMPL_FILE]: archivo de implementación
//
#include "stdafx.h"
[!if PROJECT_NAME_HEADER]
#include "[!output PROJECT_NAME].h"
[!endif]
#include "[!output HEADER_FILE]"
[!if !MERGE_FILE]
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
[!endif]
// Cuadro de diálogo de [!output CLASS_NAME]
IMPLEMENT_DYNCREATE([!output CLASS_NAME], CDHtmlDialog)
[!output CLASS_NAME]::[!output CLASS_NAME](CWnd* pParent /*=NULL*/)
: CDHtmlDialog([!output CLASS_NAME]::IDD, [!output CLASS_NAME]::IDH, pParent)
{
[!if ACCESSIBILITY]
#ifndef _WIN32_WCE
EnableActiveAccessibility();
#endif
[!endif]
[!if AUTOMATION || CREATABLE]
EnableAutomation();
[!endif]
[!if CREATABLE]
// El constructor llama a AfxOleLockApp para mantener la aplicación en ejecución
// mientras el objeto de automatización OLE está activo.
AfxOleLockApp();
[!endif]
}
[!output CLASS_NAME]::~[!output CLASS_NAME]()
{
[!if CREATABLE]
// El destructor llama a AfxOleUnlockApp para terminar la aplicación
// una vez creados todos los objetos con automatización OLE.
AfxOleUnlockApp();
[!endif]
}
[!if AUTOMATION || CREATABLE]
void [!output CLASS_NAME]::OnFinalRelease()
{
// Cuando se libera la última referencia para un objeto de automatización,
// se llama a OnFinalRelease. La clase base eliminará automáticamente
// el objeto. Se requiere limpieza adicional para el
// objeto antes de llamar a la clase base.
CDHtmlDialog::OnFinalRelease();
}
[!endif]
void [!output CLASS_NAME]::DoDataExchange(CDataExchange* pDX)
{
CDHtmlDialog::DoDataExchange(pDX);
}
BOOL [!output CLASS_NAME]::OnInitDialog()
{
CDHtmlDialog::OnInitDialog();
return TRUE; // devolver TRUE a menos que se establezca el foco en un control
}
BEGIN_MESSAGE_MAP([!output CLASS_NAME], CDHtmlDialog)
END_MESSAGE_MAP()
BEGIN_DHTML_EVENT_MAP([!output CLASS_NAME])
DHTML_EVENT_ONCLICK(_T("ButtonOK"), OnButtonOK)
DHTML_EVENT_ONCLICK(_T("ButtonCancel"), OnButtonCancel)
END_DHTML_EVENT_MAP()
[!if AUTOMATION || CREATABLE]
BEGIN_DISPATCH_MAP([!output CLASS_NAME], CDHtmlDialog)
END_DISPATCH_MAP()
// Nota: suministramos compatibilidad con IID_I[!output CLASS_NAME_ROOT] para admitir enlaces de seguridad de tipos
// desde VBA. Este IID debe coincidir con el GUID asociado a la interfaz Dispinterface
// del archivo .IDL.
// {[!output DISPIID_REGISTRY_FORMAT]}
static const IID IID_I[!output CLASS_NAME_ROOT] =
[!output DISPIID_STATIC_CONST_GUID_FORMAT];
BEGIN_INTERFACE_MAP([!output CLASS_NAME], CDHtmlDialog)
INTERFACE_PART([!output CLASS_NAME], IID_I[!output CLASS_NAME_ROOT], Dispatch)
END_INTERFACE_MAP()
[!endif]
[!if CREATABLE]
// {[!output CLSID_REGISTRY_FORMAT]}
IMPLEMENT_OLECREATE([!output CLASS_NAME], "[!output TYPEID]", [!output CLSID_IMPLEMENT_OLECREATE_FORMAT])
[!endif]
// Controladores de mensajes de [!output CLASS_NAME]
HRESULT [!output CLASS_NAME]::OnButtonOK(IHTMLElement* /*pElement*/)
{
OnOK();
return S_OK;
}
HRESULT [!output CLASS_NAME]::OnButtonCancel(IHTMLElement* /*pElement*/)
{
OnCancel();
return S_OK;
}
| [
"71766267+Dat0309@users.noreply.github.com"
] | 71766267+Dat0309@users.noreply.github.com |
adb2df9bf51608c419518c7331626e579a7b2fc4 | 16804ada1f93742f075f9a3c79201f514d1cd950 | /Graph/1557. Minimum Number of Vertices to Reach All Nodes /MinimumNumberOfVerticesToReachAllNodes.cpp | 68e4a29cca2b126c7327071ca707988bfb2e8ca1 | [] | no_license | Jack--Ma/LeetCode | feff40b3aa880c62ff98e5812fb1a961f44caee9 | 86a10dc3adc6dc95e0bbd92be1ad7ac23e76f3b5 | refs/heads/master | 2023-06-13T01:14:37.706610 | 2023-06-05T15:09:43 | 2023-06-05T15:09:43 | 63,851,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,996 | cpp | //
// MinimumNumberOfVerticesToReachAllNodes.cpp
// LeetCode-main
//
// Created by jackma on 2022/3/28.
// Copyright © 2022 JackMa. All rights reserved.
//
#include "MinimumNumberOfVerticesToReachAllNodes.hpp"
/**
Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.
Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
Output: [0,3]
Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].
Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
Output: [0,2,3]
Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
*/
void testFindSmallestSetOfVertices() {
vector<vector<int>> edges = {{0,1},{2,1},{3,1},{1,4},{2,4}};
printVector(Solution().findSmallestSetOfVertices(5, edges));
}
vector<int> Solution::findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
// index mean number, value mean whether have node point to this number
vector<int> reachNodes(n, 0);
// set 1 mean there is a node point to second number
for (vector<int> edge : edges) {
int second = edge[1];
reachNodes[second] = 1;
}
/**
Eg. default is 0, if has relationship set 1
0 1 2 3 4
0 1
1 1
2 1 1
3 1
4
reachNodes contain number 1/4, and the number 0/2/3 are not pointed by other nodes
so we just need to filter this number
*/
vector<int> result = {};
for (int i = 0; i < n; i++) {
if (reachNodes[i] == 0) {
result.push_back(i);
}
}
return result;
}
| [
"100858433@qq.com"
] | 100858433@qq.com |
68d1a3aa3b6dda18a976ea83b9f827a1c55f3bf9 | 5d021944aea1c741592c00d274af013af51eda6d | /Code/libraries/utilities/include/datxio/utilities/key_conversion.hpp | f1dfdea20f829a55f764515cc1932de491b72526 | [
"MIT"
] | permissive | railliu/DATx | 4596865f0c9e5c0e56f787218b973f884c4ee7f0 | f5f782c0101f8c4af65bcb892668e524bd37f836 | refs/heads/master | 2020-04-01T23:01:59.059667 | 2018-10-18T03:25:40 | 2018-10-18T03:25:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | hpp | /**
* @file
* @copyright defined in datx/LICENSE.txt
*/
#pragma once
#include <string>
#include <fc/crypto/elliptic.hpp>
#include <fc/optional.hpp>
namespace datxio { namespace utilities {
std::string key_to_wif(const fc::sha256& private_secret );
std::string key_to_wif(const fc::ecc::private_key& key);
fc::optional<fc::ecc::private_key> wif_to_key( const std::string& wif_key );
} } // end namespace datxio::utilities
| [
"tsfdsong@163.com"
] | tsfdsong@163.com |
7302ba3093297dcbc882a8a0177dee1b164535a1 | f2f43c78369b0cf0ab522f0b0078098810b83504 | /Project/Encrypted Storage/WebServerESP8266/TimeNtp.h | 7ebaccad843cdc91fd2c0b0f203e9387de0ef70e | [
"MIT"
] | permissive | sebsalva/OpenThermostat-1 | 41bf8c0fac2a6e0b82e402461e22ef2ab2dd4318 | 8b3a85f92342c05687564ccd85e9777c446fa97c | refs/heads/master | 2021-11-29T08:42:30.050250 | 2018-03-23T00:24:49 | 2018-03-23T00:24:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 911 | h | #ifndef TimeNtp_h
#define TimeNtp_h
#include <TimeLib.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include "Application.h"
class TimeNtp
{
private:
static TimeNtp* getTimeObject;
WiFiUDP Udp;
// default NTP Servers:
String ntpServerName = "fr.pool.ntp.org";
uint8_t timeZone = 2; // paris france
unsigned int localPort = 8888; // local port to listen for UDP packets
static const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
time_t getNtpTime();
void sendNTPpacket(IPAddress &address);
static time_t globalGetNTPTime();
bool summertime(int year, byte month, byte day, byte hour, byte tzHours);
unsigned int tempo = 20;
public:
bool gotTime = false;
TimeNtp();
TimeNtp(String server, int zone);
time_t getTime(void);
void init(String server, int zone);
};
#endif
| [
"gryfenflash@gmail.com"
] | gryfenflash@gmail.com |
e53c5f1a4904f24a8f06daea0416e609defece45 | e22ef92b15d4849c1dfc6f2d4ec5f97c7e85efe8 | /Repo.cpp | 97f2d4652478524e3a3e6ed0c5b0e7244e0a49dd | [] | no_license | LauraDiosan-CS/lab8-11-polimorfism-TersigniGiulia | 79e12c19201afa8b1c361340a366358e6f787cb7 | 3ec33f27f19f964b6b0e2c22d27578821a3dfc84 | refs/heads/master | 2022-07-11T21:44:56.291351 | 2020-05-18T15:34:24 | 2020-05-18T15:34:24 | 255,322,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,498 | cpp | #include "Repo.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "ResursaFinanciara.h"
#include "ResursaMateriala.h"
#include "BadTypeException.h"
const int MAX = 100;
using namespace std;
Repo::Repo()
{
this->fileName = "";
}
Repo::Repo(string fileName)
{
this->fileName = fileName;
this->readFromFile();
}
Repo::Repo(Repo& r)
{
this->resurse = r.resurse;
this->fileName = r.fileName;
this->readFromFile();
}
Repo::~Repo()
{
this->fileName.~basic_string();
}
void Repo::adaugaResursa(IE* res)
{
this->resurse->addElem(res);
}
void Repo::modificaResursa(IE* oldRes, IE* newRes)
{
IIterator* it = this->resurse->getIterator();
while (it->isValid()) {
if (it->getCrtElem()->equals(oldRes)) {
this->resurse->removeElem(oldRes);
this->resurse->addElem(newRes);
}
it->moveNext();
}
ofstream f;
f.open("Input.txt");
if (!f.is_open()) {
cout << "File not opened!";
return;
}
it->moveFirst();
while (it->isValid()) {
f << it->getCrtElem()->writeToFile();
it->moveNext();
}
}
IContainer* Repo::GetAll()
{
return this->resurse;
}
void Repo::setFileName(string fileName)
{
this->fileName = fileName;
this->readFromFile();
}
string Repo::getFileName()
{
return this->fileName;
}
void Repo::printAll()
{
IIterator* it = this->resurse->getIterator();
int index = 1;
while (it->isValid()) {
cout << to_string(index) + ". " + it->getCrtElem()->toString() << endl;
index++;
it->moveNext();
}
}
IE* Repo::findResursaByIndex(int index)
{
int localIndex = 1;
IIterator* it = this->resurse->getIterator();
while (it->isValid()) {
if (localIndex == index) {
return it->getCrtElem()->clone();
}
else {
localIndex++;
it->moveNext();
}
}
throw BadTypeException("Index out of bounds");
}
void Repo::readFromFile()
{
fstream f;
string line;
f.open("Input.txt");
if (!f.is_open()) {
cout << "File not opened!";
return;
}
while (getline(f, line))
{
string delimiter = ",";
vector<string> words;
size_t pos = 0;
string token;
while ((pos = line.find(delimiter)) != string::npos) {
token = line.substr(0, pos);
words.push_back(token);
line.erase(0, pos + delimiter.length());
}
words.push_back(line);
std::string::size_type sz;
if (words.size() == 4) // resursa financiara
{
ResursaFinanciara* rf = new ResursaFinanciara();
string nume;
Date data;
double valoare;
string moneda;
for (unsigned int i = 0; i < words.size(); i++)
{
stringstream ss(words[i]);
switch (i)
{
case 0: {
getline(ss, nume);
break;
}
case 1: {
try {
ss >> data;
if (data.getDay() > 31 || data.getDay() < 1 || data.getMonth() > 12 || data.getMonth() < 1 || data.getYear() < 2018)
{
throw BadTypeException("Invalid date!");
}
}
catch (BadTypeException& ex) {
cout << "Exception: " << ex.getMessage() << endl;
}
break;
}
case 2: {
try {
string val;
ss >> val;
if (val.find_first_not_of("0123456789-+.") != string::npos) {
throw BadTypeException("Not an int");
}
valoare = stod(val, &sz);
if (valoare < 0) {
throw BadTypeException("Value cannot be <0");
}
}
catch (BadTypeException& ex) {
cout << "Exception: " << ex.getMessage() << endl;
}
break;
}
case 3: {
try {
ss >> moneda;
if (moneda.find_first_of("0123456789-+.") != string::npos) {
throw BadTypeException("Invalid currency");
}
}
catch (BadTypeException& ex) {
cout << "Exception: " << ex.getMessage() << endl;
}
break;
}
}
ss.clear();
}
rf->setNume(nume);
rf->setDate(data);
rf->setValoare(valoare);
rf->setMoneda(moneda);
nume.~basic_string();
moneda.~basic_string();
this->resurse->addElem(rf);
}
else if (words.size() == 5) {
ResursaMateriala* rm = new ResursaMateriala();
string nume = "";
Date data;
double valoare = 0;
int durataDeViata = 0;
int numarDeExemplare = 0;
for (unsigned int i = 0; i < words.size(); i++)
{
stringstream ss(words[i]);
switch (i) {
case 0: {
getline(ss, nume);
break;
}
case 1: {
try {
ss >> data;
if (data.getDay() > 31 || data.getDay() < 1 || data.getMonth() > 12 || data.getMonth() < 1 || data.getYear() < 2018)
{
throw BadTypeException("Invalid date!");
}
}
catch (BadTypeException& ex) {
cout << "Exception: " << ex.getMessage() << endl;
}
break;
}
case 2: {
try {
string val;
ss >> val;
if (val.find_first_not_of("0123456789-+.") != string::npos) {
throw BadTypeException("Not an int");
}
valoare = stod(val, &sz);
if (valoare < 0) {
throw BadTypeException("Value cannot be < 0");
}
}
catch (BadTypeException& ex) {
cout << "Exception: " << ex.getMessage() << endl;
}
break;
}
case 3: {
try {
string val;
ss >> val;
if (val.find_first_not_of("0123456789-+.") != string::npos) {
throw BadTypeException("Not an int");
}
durataDeViata = stoi(val, &sz, 10);
if (durataDeViata < 0) {
throw BadTypeException("Durata de viata nu poate fi < 0");
}
}
catch (BadTypeException& ex) {
cout << "Exception: " << ex.getMessage() << endl;
}
break;
}
case 4: {
try {
string val;
ss >> val;
if (val.find_first_not_of("0123456789-+.") != string::npos) {
throw BadTypeException("Not an int");
}
numarDeExemplare = stoi(val, &sz, 10);
if (numarDeExemplare < 0) {
throw BadTypeException("NumarDeExemplare nu poate fi < 0");
}
}
catch (BadTypeException& ex) {
cout << "Exception: " << ex.getMessage() << endl;
}
break;
}
}
ss.clear();
}
rm->setNume(nume);
rm->setDate(data);
rm->setValoare(valoare);
rm->setDurataDeViata(durataDeViata);
rm->setNumarDeExemplare(numarDeExemplare);
this->resurse->addElem(rm);
nume.~basic_string();
}
words.~vector();
}
} | [
"noreply@github.com"
] | LauraDiosan-CS.noreply@github.com |
15f494bd7f799352f6018d9f93f3a4861bec5e4b | 43119a707e0ab4790a4bda74bb40f1715f906b56 | /Regular_Batch/1b_HelloWorld_EXPLAINED.cpp | f2f22b1517f79b68e51afb376235961d0c544317 | [] | no_license | gouthamkrishnakv/csea-secondyr-workshop | 6098a56f9d7bc1a8c2a1007fa2bcc0fe6179d2b9 | 296005a5f1c30e702d3bdce032964bc95d92654c | refs/heads/master | 2023-01-29T03:52:18.993832 | 2019-01-08T18:32:37 | 2019-01-08T18:32:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp | // YOUR FIRST PROGRAM
// ANYTHING STARTING WITH A '#'IS CALLED A PREPROCESSOR DIRECTIVE.
// THIS TELLS THE COMPILER WHAT TO DO BEFORE COMPILATION,
// LIKE ADDING OTHER LIBRARIES, DEFINING MACROS (WE'LL GO THROUGH THAT LATER).
// 'include' DIRECTIVE TELLS THE COMPILER WHICH ALL LIBRARIES TO INCLUDE BEFORE EXECUTION
// WE INCLUDED THE LIBRARY 'iostream' TO ENABLE INPUT/OUTPUT FOR THE PROGRAM.
// 'IOSTREAM' MANAGES INPUT OUTPUT STREAMS.
#include <iostream>
// 'std' MANAGES STANDARD I/O METHODS HERE. MAKES cout & cin WORK.
using namespace std;
// main FUNCTION --> START OF EVERY PROGRAM, PROGRAM STARTS BY EXECUTING CODE FROM main FUNCTION
int main()
{
// cout --> Used to output the file onto the terminal
cout << "Hello World!\n";
// EVERY PROGRAM ENDS WHEN THE MAIN FUNCTION RETURNS A VALUE, IN THIS CASE 0.
// 0 IS TRADITIONALLY EXPECTED TO BE RETURNED BY THE PROGRAM IF THE PROGRAM
// WORKED PROPERLY. YOU CAN RETURN ANY INTEGER VALUE HERE THOUGH.
return 0;
} | [
"gauthamkrishna9991@live.com"
] | gauthamkrishna9991@live.com |
237972b191730d218b4f91b296c6cfb027f81bcc | 1482f91b80a80fac5a890d946f2256603adeba05 | /FitTemplateWf.hxx | 04fa07901207e4d649065679ea407acee9cf8fba | [] | no_license | kirbybri/FitTemplate | b4765c3c7c6142434cb0cf4c2da4aa2eae83a215 | 91d425261c9354641a63ab0bcf18aae80c2e2452 | refs/heads/master | 2020-09-01T17:51:18.207480 | 2019-11-24T01:30:34 | 2019-11-24T01:30:34 | 219,020,103 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,539 | hxx | #include <iostream>
#include <stdlib.h>
#include <math.h>
#include "TMinuit.h"
///////////TEMPLATE DATA CLASS/////////////////
class TemplateData {
private:
public:
TemplateData();
~TemplateData();
void addTemplate(const std::vector<double>& val, double period);
void getSignalValue(double time, double offset, double pulseStartTime, double amp,double& simVal);
std::vector<double> samp;
double sampPeriod;
};
TemplateData::TemplateData(){
sampPeriod = 0.01; //fractions of sample
samp.clear();
}
TemplateData::~TemplateData(){
}
void TemplateData::addTemplate(const std::vector<double>& val, double period){
samp.clear();
samp = val;
sampPeriod = period;
return;
}
//get response function value quickly from vector interpolation
void TemplateData::getSignalValue(double time, double offset, double templateStartTime, double amp,double& simVal){
simVal = offset; //simVal defaults to baseline if interpolation fails
double sampTime = 0;
if( time > templateStartTime )
sampTime = time - templateStartTime;
//determine position of time value in signal vector
double templateSampTime = sampTime/sampPeriod; //convert req time into sample # within template array
unsigned int templateSampNum = floor(templateSampTime); //get actual template array element #
if( templateSampNum >= samp.size() - 1 ) //if req time exceeds template array, simVal is just the baseline
return;
//do linear interpolation
double sigVal = samp[templateSampNum] + ( samp[templateSampNum+1] - samp[templateSampNum] )*(templateSampTime - templateSampNum);
//scale by amplitude factor, this assumes template is pedestal subtracted
sigVal = amp*sigVal;
simVal += sigVal;
return;
}
//Stupid TMinuit global variables/functions
static void ffer_fitFuncML(int& npar, double* gout, double& result, double par[], int flg);
void ffer_calcLnL(double par[], double& result);
double ffer_sampleErr;
std::vector<double> *ffer_fitData_vals;
std::vector<bool> *ffer_fitData_quality;
TemplateData *ffer_tempData;
class FitTemplateWf {
private:
public:
FitTemplateWf();
~FitTemplateWf();
void clearData();
void addTemplate(const std::vector<double>& val, double period);
void addData(const std::vector<double>& val, const std::vector<bool>& valQuality);
void doFit();
void setSampleError(double err);
bool showOutput;
double sampleErr;
int status;
TemplateData *tempData;
std::vector<double> fitData_vals;
std::vector<bool> fitData_quality;
std::vector<double> initVals;
std::vector<double> initErrs;
std::vector<double> fitVals;
std::vector<double> fitValErrs;
std::vector<unsigned int> fixFitVars;
};
using namespace std;
FitTemplateWf::FitTemplateWf(){
//initial values
showOutput = 0;
sampleErr = 1.;
status = -1;
tempData = new TemplateData();
}
FitTemplateWf::~FitTemplateWf(){
delete tempData;
}
void FitTemplateWf::clearData(){
fitData_vals.clear();
fitData_quality.clear();
tempData->samp.clear();
initVals.clear();
initErrs.clear();
fitVals.clear();
fitValErrs.clear();
fixFitVars.clear();
}
void FitTemplateWf::setSampleError(double err){
sampleErr = 1.;
if(err <= 0. )
return;
sampleErr = err;
return;
}
void FitTemplateWf::addTemplate(const std::vector<double>& val, double period){
tempData->addTemplate(val,period);
return;
}
void FitTemplateWf::addData(const std::vector<double>& val, const std::vector<bool>& valQuality){
fitData_vals.clear();
fitData_quality.clear();
fitData_vals = val;
fitData_quality = valQuality;
return;
}
//wrapper function for TMinuit
void FitTemplateWf::doFit(){
//sanity checks
if( fitData_vals.size() == 0 || tempData->samp.size() == 0 || initVals.size() == 0 || initErrs.size() == 0 ){
std::cout << "Invalid # of data or template vectors" << std::endl;
return;
}
//give the global variables to the class objects (very lame)
ffer_sampleErr = sampleErr;
ffer_fitData_vals = &fitData_vals;
ffer_fitData_quality = &fitData_quality;
ffer_tempData = tempData;
//initialize variables
status = -1;
unsigned int numParameters = 3;
TMinuit *minimizer = new TMinuit(numParameters);
//Set print level , -1 = suppress, 0 = info
minimizer->SetPrintLevel(-1);
if( showOutput == 1 )
minimizer->SetPrintLevel(3);
//define fit parameters
minimizer->SetFCN(ffer_fitFuncML);
minimizer->DefineParameter(0, "Offset", initVals[0], initErrs[0],0,0);
minimizer->DefineParameter(1, "Time", initVals[1], initErrs[1],0,0);
minimizer->DefineParameter(2, "Amp", initVals[2], initErrs[2],0,0);
//optionally fix parameters
for( unsigned int i = 0 ; i < fixFitVars.size() ; i++ ){
if( fixFitVars.at(i) < numParameters )
minimizer->FixParameter( fixFitVars.at(i) );
}
//Set Minuit flags
Double_t arglist[10];
arglist[0] = 0.5; //what is this
Int_t ierflg = 0;
minimizer->mnexcm("SET ERR", arglist ,1,ierflg); //command, arguments, # arguments, error flag
//Do MIGRAD minimization
Double_t tmp[1];
tmp[0] = 100000;
Int_t err;
minimizer->mnexcm("MIG", tmp ,1,err);
//minimizer->mnexcm("HES", tmp ,1,err);
status = err;
fitVals.clear();
fitValErrs.clear();
for(unsigned int i = 0 ; i < numParameters ; i++ ){
double fitVal, fitValErr;
minimizer->GetParameter(i, fitVal, fitValErr);
fitVals.push_back( fitVal );
fitValErrs.push_back( fitValErr );
}
delete minimizer; //memory leak?
return;
}
//likelihood calc - note not included in class
void calcLnL(double par[], double& result){
double diffSq = 0;
double norm = 1./(ffer_sampleErr)/(ffer_sampleErr);
//loop over data vector elements
for(unsigned int num = 0 ; num < ffer_fitData_vals->size() ; num++ ){
//skip over invalid data elements
if( ffer_fitData_quality->operator[](num) == 0 )
continue;
//create fit hypothesis
double simVal = 0;
ffer_tempData->getSignalValue(num, par[0], par[1], par[2],simVal);
//do lnL calc
double dataVal = ffer_fitData_vals->operator[](num);
diffSq = diffSq + (dataVal - simVal)*(dataVal - simVal)*norm; //gauss err assumed, noise is correlated but assume small
}//end of element loop
//calculate value to minimize
result = -0.5*diffSq;
return;
}
//Fit wrapper function - used by Minuit - has to be static void, annoying
static void ffer_fitFuncML(int& npar, double* gout, double& result, double par[], int flg){
calcLnL(par, result);
result = -1.*result;//Minuit is minimizing result ie maximizing LnL
return;
}
| [
"kirbybri@gmail.com"
] | kirbybri@gmail.com |
d4c5984a537ef245ce7531679fa84ef42021bef5 | 96ee331287ddffd513ed3a0a1ba9f6ffb64119a7 | /算法与数据结构/合并K个有序链表.cpp | 1fe404f117dc387bae15894ca5de53d5a60a6613 | [] | no_license | noahyzhang/IT- | be2c1f19cd27266563d273407ede1b1c7055b9d5 | 6e5657e52a56f9387318b4aa5357ea3b72d24c1d | refs/heads/master | 2022-01-19T20:17:46.594942 | 2019-06-24T03:53:17 | 2019-06-24T03:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,339 | cpp | #include<iostream>
#include<vector>
#include<string>
#include<queue>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
ListNode* List(vector<int>& vec)
{
ListNode* head = new ListNode(vec[0]);
ListNode* tmp = head;
for (int i = 1; i < vec.size(); ++i)
{
tmp->next = new ListNode(vec[i]);
tmp = tmp->next;
}
return head;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<int,vector<int>,greater<int>> pri_qu;
for (int i = 0; i < lists.size(); ++i)
{
ListNode* tmp = lists[i];
while (tmp != nullptr)
{
pri_qu.push(tmp->val);
tmp = tmp->next;
}
}
ListNode* head = new ListNode(0);
ListNode* tmp_head = head;
while (!pri_qu.empty())
{
tmp_head->next = new ListNode(pri_qu.top());
tmp_head = tmp_head->next;
pri_qu.pop();
}
return head->next;
}
};
#if 0
int main()
{
ListNode ln(0);
vector<ListNode*> vec;
vector<int> tmp{ 1,4,5 };
ListNode* str = ln.List(tmp);
vec.push_back(str);
tmp={ 1,3,4 };
str = ln.List(tmp);
vec.push_back(str);
tmp = { 2,6 };
str = ln.List(tmp);
vec.push_back(str);
Solution sn;
ListNode* res = sn.mergeKLists(vec);
while (res != nullptr)
{
std::cout << res->val << std::endl;
res = res->next;
}
return 0;
}
#endif | [
"13572252156@163.com"
] | 13572252156@163.com |
73bdbfd715f3ccc7607bcd04c76a594ad1c15ad5 | 6df0e4923493e9b8576df58c4615fe7d9041895a | /DWT.cpp | 3c7d87f3ad4e734745a7ed36e1b2532b72f31199 | [] | no_license | liyuglikz/CoSaMP | 3dc80e2a301d762fd58df1c48578e6d4a2425b4c | 1a4d3c55017a96af21edcf31784d324567dd5f81 | refs/heads/master | 2020-03-28T22:10:32.040859 | 2015-07-28T16:41:38 | 2015-07-28T16:41:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,197 | cpp |
#include <math.h>
#include <iostream>
#include "head.h"
//using namespace std;
int shift=4;
double *h, *h1;
double p_alfa, p_beta, p_gama, p_delta, p_kesa,p_t=0.730174 ;
void filterset(double t)
{
h = new double [9];
h1 = new double [7];
*h = (8*t*t*t-6*t*t+3*t)/(1+2*t)*(1/32.)*sqrt(2.0);
*(h+1) = (-16*t*t*t+20*t*t-12*t+3)/(1+2*t)*(1/32.)*sqrt(2.0);
*(h+2) = (2*t-3)/(1+2*t)*(1/8.)*sqrt(2.0);
*(h+3) = (16*t*t*t-20*t*t+28*t+5)/(1+2*t)*(1/32.)*sqrt(2.0);
*(h+4) = (-8*t*t*t+6*t*t+5*t+20)/(1+2*t)*(1/16.)*sqrt(2.0);
*(h+5) = *(h+3);
*(h+6) = *(h+2);
*(h+7) = *(h+1);
*(h+8) = *(h+0);
double r0, r1, s0, t0;
r0 = (*(h+4))-2*(*h)*(*(h+3))/(*(h+1));
r1 = (*(h+2))-(*h)-(*h)*(*(h+3))/(*(h+1));
s0 = (*(h+3))-(*(h+1))-(*(h+1))*r0/r1;
t0 = r0-2*r1;
p_alfa = (*h)/(*(h+1));
p_beta = (*(h+1))/r1;
p_gama = r1/s0;
p_delta = s0/t0;
p_kesa = t0;
}
void Dwt1D(double *buffer, int buflen)
{
int i;
int itemp;
double *d, *s, *p;
p = new double [buflen+2*shift];
d = new double [(buflen>>1)+shift];
s = new double [(buflen>>1)+shift];
for (i=0; i<(buflen>>1)+shift; i++){
itemp = i-(shift>>1);
*(d+i) = *(p+shift+2*itemp+1) + p_alfa*( *(p+shift+2*itemp)+*(p+shift+2*itemp+2) );
}
for (i=0; i<(buflen>>1)+shift-1; i++){
itemp = i+1-(shift>>1);
*(s+i+1) = *(p+shift+2*itemp) + p_beta*( *(d+i+1)+*(d+i+1-1) );
}
for (i=0; i<(buflen>>1)+shift-1; i++){
//itemp = i-(shift>>1);
*(p+shift+(buflen>>1)+i) = *(d+i) + p_gama*( *(s+i)+*(s+i+1));
}
/* s2 */
for (i=0; i<(buflen>>1)+shift-1; i++){
// itemp = i-(shift>>1);
*(p+i+1) = *(s+i+1) + p_delta*(*(p+(buflen>>1)+shift+i+1) + *(p+(buflen>>1)+shift+i+1-1) );
}
/* d3 */
for (i=0; i<(buflen>>1); i++)
*(d+i) = *(p+i+(buflen>>1)+shift+(shift>>1)) +p_kesa*(1-p_kesa)*(*(p+i+(shift>>1)));
/* s3 */
for (i=0; i<(buflen>>1); i++)
*(s+i) = *(p+i+(shift>>1)) -1/p_kesa*(*(d+i));
/* d4 */
for (i=0; i<(buflen>>1); i++)
*(buffer+i+(buflen>>1)) = *(d+i) +(p_kesa-1)*(*(s+i));
/* s4 */
for (i=0; i<(buflen>>1); i++)
*(buffer+i) = *(s+i) + *(buffer+i+(buflen>>1));
/* for (i=0; i<(buflen>>1); i++){
*(buffer+i) = p_kesa*(*(p+i+(shift>>1)));
*(buffer+i+(buflen>>1)) = 1/p_kesa*(*(p+i+(buflen>>1)+shift+(shift>>1)));
}
*/
delete []p;
delete []d;
delete []s;
}
void IDwt1D(double *buffer, int buflen)
{
int i;
double *p1, *p2, *s, *d;
p1 = new double [(buflen>>1)+shift];
p2 = new double [(buflen>>1)+shift];
s = new double [(buflen>>1)+shift];
d = new double [(buflen>>1)+shift];
/* s3 */
for (i=0; i<(buflen>>1); i++)
*(s+i) = *(buffer+i) - *(buffer+i+(buflen>>1));
/* d3 */
for (i=0; i<(buflen>>1); i++)
*(d+i) =*(buffer+i+(buflen>>1))- (p_kesa-1)*(*(s+i));
/* s2 */
for (i=0; i<(buflen>>1); i++)
*(buffer+i) = *(s+i) + (1/p_kesa)*(*(d+i));
/* d2 */
for (i=0; i<(buflen>>1); i++)
*(buffer+i+(buflen>>1)) = *(d+i) - p_kesa*(1-p_kesa)*(*(buffer+i));
for (i=0; i<(shift>>1); i++){
p1[i] = buffer[i+(buflen>>1)-(shift>>1)];
p1[i+(shift>>1)+(buflen>>1)] = buffer[i];
p2[i] = buffer[i+buflen-(shift>>1)];
p2[i+(shift>>1)+(buflen>>1)] = buffer[i+(buflen>>1)];
}
for (i=0; i<(buflen>>1); i++){
p1[i+(shift>>1)] = buffer[i];
p2[i+(shift>>1)] = buffer[i+(buflen>>1)];
}
for (i=0; i<(shift>>1); i++){
p1[i] = buffer[(shift>>1)-i];
p1[i+(shift>>1)+(buflen>>1)] = buffer[(buflen>>1)-i-1];
p2[i] = buffer[(buflen>>1)+(shift>>1)-i-1];
p2[i+(shift>>1)+(buflen>>1)] = buffer[buflen-i-2];
}
for (i=0; i<(buflen>>1); i++){
p1[i+(shift>>1)] = buffer[i];
p2[i+(shift>>1)] = buffer[i+(buflen>>1)];
}
/* s1 */
for (i=0; i<(buflen>>1)+shift-1; i++)
*(s+i+1) = *(p1+i+1) - p_delta*( *(p2+i+1) + *(p2+i+1-1));
/* d1 */
for (i=0; i<(buflen>>1)+shift-1; i++)
*(d+i) = *(p2+i) - p_gama*(*(s+i) + *(s+i+1));
/* p1 = s0 */
for (i=0; i<(buflen>>1)+shift-1; i++)
*(p1+i+1) = *(s+i+1) - p_beta*( *(d+i+1)+*(d+i+1-1));
/* p2 = d0 */
for (i=0; i<(buflen>>1)+shift-1; i++)
*(p2+i) = *(d+i) - p_alfa*(*(p1+i) + *(p1+i+1));
for (i=0; i<(buflen>>1); i++){
*(buffer+2*i) = *(p1+i+(shift>>1)) ;
*(buffer+2*i+1) = *(p2+i+(shift>>1));
}
delete []p1;
delete []p2;
delete []s;
delete []d;
}
void DwtND(double buffer[], int height, int width, int lv)
{
int i,j,k;
int nheight,nwidth;
for ( k=0; k<lv; k++){
nheight=height>>k;
nwidth=width>>k;
double *pdata;
pdata = new double [nwidth];
for (i=0; i<nheight; i++){
for(j=0; j<nwidth; j++)
*(pdata+j) = *(buffer+i*width+j);
Dwt1D(pdata,nwidth);
for(j=0; j<nwidth; j++)
*(buffer+i*width+j) = *(pdata+j);
}
delete []pdata;
double *p1data;
p1data = new double [nheight];
for(j=0; j<nwidth; j++){
for (i=0; i<nheight; i++)
*(p1data+i)=*(buffer+i*width+j);
Dwt1D(p1data,nheight);
for(i=0; i<nwidth; i++)
*(buffer+i*width+j) = *(p1data+i);
}
delete []p1data;
}
}
void IDwtND(double buffer[], int height, int width, int lv)
{
int i,j,k;
int nheight,nwidth;
for (k=0; k<lv; k++){
nheight=height>>(lv-k-1);
nwidth=width>>(lv-k-1);
double *pdata;
pdata = new double [nheight];
for(j=0; j<nwidth; j++){
for (i=0; i<nheight; i++)
*(pdata+i) = *(buffer+i*width+j);
IDwt1D(pdata,nheight);
for(i=0; i<nwidth; i++)
*(buffer+i*width+j) = *(pdata+i);
}
delete []pdata;
double *p1data;
p1data = new double [nwidth];
for (i=0; i<nheight; i++){
for(j=0; j<nwidth; j++)
*(p1data+j)=*(buffer+i*width+j);
IDwt1D(p1data,nwidth);
for(j=0; j<nwidth; j++)
*(buffer+i*width+j) = *(p1data+j);
}
delete []p1data;
}
}
void Adjust(double *ImageData,int bmpHeight,int bmpWidth, double *SparseMat,short *OutData)
{
double fTempBufforDisp, MaxPixVal,MinPixVal,Diff;
int x,y;
MaxPixVal=ImageData[0];
MinPixVal=ImageData[0];
for( y=0; y<bmpHeight; y++)
{
for( x=0; x<bmpWidth; x++)
{
if(MaxPixVal< ImageData[y*bmpWidth+x])
MaxPixVal=ImageData[y*bmpWidth+x];
if(MinPixVal>ImageData[y*bmpWidth+x])
MinPixVal=ImageData[y*bmpWidth+x];
SparseMat[y*bmpWidth+x]=ImageData[y*bmpWidth+x];
}
}
Diff=MaxPixVal-MinPixVal;
for( y=0;y<bmpHeight/2;y++)
for( x=0;x<bmpWidth;x++)
{
fTempBufforDisp=ImageData[y*bmpWidth+x];
fTempBufforDisp-=MinPixVal;
fTempBufforDisp*=255;
fTempBufforDisp/=Diff;
OutData[y*bmpWidth+x]=(short) fTempBufforDisp;
}
for( y=bmpHeight/2;y<bmpHeight;y++)
for( x=0;x<bmpWidth;x++)
{
fTempBufforDisp=ImageData[y*bmpWidth+x];
fTempBufforDisp-=MinPixVal;
fTempBufforDisp*=255;
fTempBufforDisp/=Diff;
OutData[y*bmpWidth+x]=(short) fTempBufforDisp;
}
for( y=bmpHeight*3/4;y<bmpHeight;y++)
for( x=0;x<bmpWidth/2;x++)
{
fTempBufforDisp=ImageData[y*bmpWidth+x];
fTempBufforDisp-=MinPixVal;
fTempBufforDisp*=255;
fTempBufforDisp/=Diff;
OutData[y*bmpWidth+x]=(short) fTempBufforDisp;
}
for( y=bmpHeight/2;y<bmpHeight*3/4;y++)
for( x=0;x<bmpWidth/2;x++)
{
fTempBufforDisp=ImageData[y*bmpWidth+x];
fTempBufforDisp-=MinPixVal;
fTempBufforDisp*=255;
fTempBufforDisp/=Diff;
OutData[y*bmpWidth+x]=(short) fTempBufforDisp;
}
}
| [
"jtao@cct.lsu.edu"
] | jtao@cct.lsu.edu |
abdfc8de00cc3aa13d2c44d5d40b28cd2b107e60 | cad35287bc893aaef3761af2079a4ad08db2299c | /client/cpp/src/tarscli/util/include/util/tc_enable_shared_from_this.h | 187f0f1ba37526f89cfc5aaae4decd9908564330 | [
"Apache-2.0"
] | permissive | foolishantcat/CxxDBC | 3eafb94b6c1532a2ac236392be8544182206a9e9 | f0f9e95baad72318e7fe53231aeca2ffa4a8b574 | refs/heads/master | 2021-09-25T21:23:11.977712 | 2018-10-25T17:19:46 | 2018-10-25T17:19:46 | 272,710,881 | 1 | 0 | Apache-2.0 | 2020-06-16T13:08:34 | 2020-06-16T13:08:33 | null | UTF-8 | C++ | false | false | 2,167 | h | /**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 __TC_ENABLE_SHARED_FROM_THIS_H__
#define __TC_ENABLE_SHARED_FROM_THIS_H__
#include "tc_shared_ptr.h"
namespace tars
{
template <class T>
class TC_EnableSharedFromThis
{
public:
TC_SharedPtr<T> sharedFromThis()
{
TC_SharedPtr<T> p(m_this, m_owner_use_count);
return p;
}
TC_SharedPtr<const T> sharedFromThis() const
{
TC_SharedPtr<const T> p(m_this, m_owner_use_count);
return p;
}
protected:
TC_EnableSharedFromThis()
: m_this(NULL)
, m_owner_use_count(NULL)
{ }
TC_EnableSharedFromThis(const TC_EnableSharedFromThis&)
{ }
TC_EnableSharedFromThis& operator=(const TC_EnableSharedFromThis&)
{
return *this;
}
~TC_EnableSharedFromThis()
{ }
private:
template <typename U>
void acceptOwner(const TC_SharedPtr<U>& p) const
{
if (m_owner_use_count == NULL)
{
m_owner_use_count = p.m_pn;
m_this = p.get();
}
}
mutable T *m_this;
mutable detail::tc_shared_count_base *m_owner_use_count;
template <class X, class U>
friend void detail::tc_sp_enable_shared_from_this(const TC_SharedPtr<X> *pp, const TC_EnableSharedFromThis<U> *px);
};
}
#endif
| [
"cxxjava@163.com"
] | cxxjava@163.com |
e6d4d7c71b2db0956ec6785eabe82e2372f7fbda | b451767f16cd2b9501285ba3dc57cbd163944828 | /ocminutes.h | 44485fb6890f50adef619c89d300e761d02bd8e2 | [] | no_license | othelarian/othy_clock3 | 42b06d77775e0afc61053f46382e6823a21a501c | f006393c4a77b50c8294c44f3023e128cb141711 | refs/heads/master | 2021-01-22T23:00:45.997609 | 2017-04-21T15:28:14 | 2017-04-21T15:28:14 | 85,596,919 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | h | #ifndef OCMINUTES_H
#define OCMINUTES_H
#include <QQuickItem>
#include <QQuickPaintedItem>
#include "ocsettings.h"
// OCminutesTicks class #################
class OCminutesTicks : public QQuickPaintedItem
{
Q_OBJECT
public:
OCminutesTicks(QQuickItem *parent = 0);
void paint(QPainter *painter);
//
};
// OCminutesCog class ###################
class OCminutesCog : public QQuickPaintedItem
{
Q_OBJECT
public:
OCminutesCog(QQuickItem *parent = 0);
void paint(QPainter *painter);
//
};
#endif // OCMINUTES_H
| [
"le.maitre.killian@gmail.com"
] | le.maitre.killian@gmail.com |
28fd3ad1b270540d5b40f132774f9490893279be | 694df92026911544a83df9a1f3c2c6b321e86916 | /c++/Inherit/VirtualFunctionWithException.cpp | f3529fca71cc3d3b3bcffa7c620b56ce584c4fd2 | [
"MIT"
] | permissive | taku-xhift/labo | f485ae87f01c2f45e4ef1a2a919cda7e571e3f13 | 89dc28fdb602c7992c6f31920714225f83a11218 | refs/heads/main | 2021-12-10T21:19:29.152175 | 2021-08-14T21:08:51 | 2021-08-14T21:08:51 | 81,219,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | cpp |
#include <iostream>
#include <typeinfo>
class Base {
virtual void print() = 0;
};
class Derived
: public Base
{
public:
void print() throw() {
std::cout << typeid(this).name() << std::endl;
}
};
int main() {
Derived derived;
derived.print();
}
| [
"shishido_takuya@xhift.com"
] | shishido_takuya@xhift.com |
fe44916d20c011139bee3e70175a6244a1318938 | 7ce390d147542a2cfaf198c66fb40494bb75e5ed | /project-files/dms/neurolib/KohonenNet.cpp | 1da7b484a09f5a29f7a65a3ef18eac91e11995f5 | [] | no_license | Nikita94/Data-Mining-Tool-System | 2b51f6f7ff452264a9adc438a4560341477bb242 | faf4f9d3d9abd5b2630267c6cb0d29e6ed8f0086 | refs/heads/master | 2020-01-23T21:40:35.842420 | 2018-03-11T11:58:11 | 2018-03-11T11:58:11 | 74,689,923 | 0 | 0 | null | 2016-11-24T16:36:29 | 2016-11-24T16:36:29 | null | UTF-8 | C++ | false | false | 10,856 | cpp | #include "KohonenNet.h"
#include "KohonenPretrain.h"
#include <algorithm>
#include "mkl_cblas.h"
using namespace nnets_kohonen;
int nnets_kohonen::getDistance(int neuron1, int neuron2, void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
NeuronIndex n1 = kn->neuron_index_map[neuron1];
NeuronIndex n2 = kn->neuron_index_map[neuron2];
return n1.distanceTo(n2);
}
size_t nnets_kohonen::getWeightsMatrixSize(void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
return kn->getWeightsMatrixSize();
}
void nnets_kohonen::setWeights(const float* w, void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
kn->setWeights(w);
}
void nnets_kohonen::setUseNormalization(bool norm, void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
kn->setUseNormalization(norm);
}
size_t nnets_kohonen::getAllWeights(float * w, void * obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
return kn->getWeights(w);
}
void nnets_kohonen::disableNeurons(std::vector<int> neurons, void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
std::vector<NeuronIndex> new_neuron_map;
std::vector<int> old_new_map;
for (int j = 0; j < neurons.size(); j++)
if ((neurons[j] < 0) || (neurons[j] > kn->neuron_index_map.size()))
throw "Neuron index out of range";
for (int i = 0; i < kn->neuron_index_map.size(); i++)
{
bool is_disable = false;
for (int j = 0; j < neurons.size(); j++)
{
if (i == neurons[j])
{
is_disable = true;
break;
}
}
if (is_disable == false)
{
new_neuron_map.push_back(kn->neuron_index_map[i]);
old_new_map.push_back(i);
}
}
delete[] kn->kohonen_layer;
kn->kohonen_layer = new float[new_neuron_map.size()];
float* new_weights = new float[new_neuron_map.size() * kn->x_size];
float** new_classes = new float*[new_neuron_map.size()];
for (int i = 0; i < new_neuron_map.size(); i++)
{
int old_index = old_new_map[i];
for (int j = 0; j < kn->x_size; j++)
new_weights[i * kn->x_size + j] = kn->weights[old_index * kn->x_size + j];
new_classes[i] = new float[kn->y_size];
for (int j = 0; j < kn->y_size; j++)
new_classes[i][j] = kn->classes[old_index][j];
delete[] kn->classes[old_index];
}
delete[] kn->classes;
delete[] kn->weights;
kn->classes = new_classes;
kn->weights = new_weights;
kn->neuron_index_map = new_neuron_map;
}
void * nnets_kohonen::copyKohonen(void * obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
return new KohonenNet(*kn);
}
void nnets_kohonen::freeKohonen(void *& obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
delete kn;
obj = nullptr;
}
const float* nnets_kohonen::getWeights(int neuron, void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
if (neuron == -1) throw "Invalid neuron index";
return kn->weights + neuron * kn->x_size;
}
int nnets_kohonen::getWinner(void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
return kn->getInternalIndex(kn->winner);
}
size_t nnets_kohonen::solve(const float* x, float* y, void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
return kn->solve(x, y);
}
int nnets_kohonen::getMaxNeuronIndex(void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
return kn->neuron_index_map.size();
}
void nnets_kohonen::addmultWeights(int neuron, float alpha, float beta, const float* x, void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
if (neuron != -1)
{
float* w = kn->weights + neuron * kn->x_size;
for (int i = 0; i < kn->x_size; i++)
w[i] = alpha * w[i] + beta * x[i];
}
else throw "Invalid neuron index";
}
void nnets_kohonen::setY(int neuron, const float* y, void* obj)
{
KohonenNet* kn = static_cast<KohonenNet*>(obj);
if (neuron != -1)
kn->setClass(kn->neuron_index_map[neuron], y);
else throw "Invalid neuron index";
}
void KohonenNet::initByNeuronMap(std::vector<NeuronIndex> map)
{
kohonen_layer = new float[map.size()];
weights = new float[map.size() * x_size];
classes = new float*[map.size()];
for (int i = 0; i < map.size(); i++)
{
for (int j = 0; j < x_size; j++)
weights[i * x_size + j] = 0.0f;
classes[i] = new float[y_size];
for (int j = 0; j < y_size; j++)
classes[i][j] = 0.0f;
}
neuron_index_map = map;
}
KohonenNet::KohonenNet(int inputs_count, int outputs_count,
int koh_width, int koh_height, float classEps,
ClassInitializer initializer, Metric metric) :
winner({0,0}),
neurons_width(koh_width), neurons_height(koh_height),
x_size(inputs_count), y_size(outputs_count),
initializer(initializer), metric(metric), class_eps(classEps)
{
use_norm_x = false;
x_internal = new float[x_size];
std::vector<NeuronIndex> map;
for (int y = 0; y < neurons_height; y++)
for (int x = 0; x < neurons_width; x++)
map.push_back(int2d{ x, y });
initByNeuronMap(map);
}
KohonenNet::KohonenNet(KohonenNet& kn) : winner({0,0})
{
use_norm_x = kn.use_norm_x;
neurons_width = kn.neurons_width; neurons_height = kn.neurons_height;
x_size = kn.x_size; y_size = kn.y_size;
metric = kn.metric; initializer = kn.initializer;
class_eps = kn.class_eps;
x_internal = new float[x_size];
initByNeuronMap(kn.neuron_index_map);
for (int i = 0; i < neuron_index_map.size() * x_size; i++)
weights[i] = kn.weights[i];
for (int i = 0; i < neuron_index_map.size(); i++)
for (int j = 0; j < y_size; j++)
classes[i][j] = kn.classes[i][j];
}
size_t KohonenNet::getInputsCount() { return x_size; }
size_t KohonenNet::getOutputsCount() { return y_size; }
void KohonenNet::setWeights(const float* weights)
{
for (int i = 0; i < neuron_index_map.size() * x_size; i++)
this->weights[i] = weights[i];
}
void KohonenNet::setClasses(float ** classes)
{
for (int i = 0; i < neuron_index_map.size(); i++)
for (int j = 0; j < y_size; j++)
this->classes[i][j] = classes[i][j];
}
void nnets_kohonen::KohonenNet::setClasses(float ** y, int rowsCount)
{
ClassExtracter extr { class_eps };
extr.fit(y, rowsCount, getOutputsCount());
auto distr = extr.getClassesDistributions();
int all_sizes = getMaxNeuronIndex(this);
if ((initializer == Statistical) || (initializer == Revert))
{
if (initializer == Revert)
{
std::sort(distr.begin(), distr.end(),
[](std::pair<int, int> p1, std::pair<int, int> p2) { return p1.second < p2.second; });
auto first = distr.begin();
auto last = distr.end() - 1;
while (first < last)
{
int temp = first->first;
first->first = last->first;
last->first = temp;
first++;
last--;
}
}
int sum = 0;
for (int i = 0; i < distr.size(); i++)
{
int temp = distr[i].second * all_sizes;
distr[i].second = temp / rowsCount;
sum += distr[i].second;
}
distr[distr.size() - 1].second += (all_sizes - sum);
}
else if (initializer == Evenly)
{
int sum = 0;
for (int i = 0; i < distr.size(); i++)
{
distr[i].second = all_sizes / distr.size();
sum += distr[i].second;
}
distr[distr.size() - 1].second += (all_sizes - sum);
}
else throw "Unsupported class initializer";
int currentClassIndex = 0;
for (int j = 0; j < all_sizes; j++)
{
if (distr[currentClassIndex].second <= 0)
currentClassIndex++;
setY(j, y[distr[currentClassIndex].first], this);
distr[currentClassIndex].second--;
}
}
void KohonenNet::setNeurons(std::vector<NeuronIndex>& neurons)
{
delete[] kohonen_layer;
for (int i = 0; i < neurons_width * neurons_height; i++)
delete[] classes[i];
delete[] classes;
delete[] weights;
initByNeuronMap(neurons);
}
int KohonenNet::getInternalIndex(NeuronIndex n)
{
int found_index = -1;
for (int i = 0; i < neuron_index_map.size(); i++)
if (neuron_index_map[i] == n)
return i;
return -1;
}
void KohonenNet::setClass(NeuronIndex n, const float* y)
{
int found_index = getInternalIndex(n);
if (found_index != -1)
{
float* cur_class = classes[found_index];
for (int i = 0; i < y_size; i++)
cur_class[i] = y[i];
}
else
throw "Invalid neuron index";
}
void nnets_kohonen::KohonenNet::setClassEps(float eps)
{
class_eps = eps;
}
void KohonenNet::setUseNormalization(bool norm)
{
use_norm_x = norm;
}
size_t nnets_kohonen::KohonenNet::getClasses(float ** classes)
{
for (int i = 0; i < neuron_index_map.size(); i++)
for (int j = 0; j < y_size; j++)
classes[i][j] = this->classes[i][j];
return neuron_index_map.size() * y_size;
}
float nnets_kohonen::KohonenNet::getClassEps()
{
return class_eps;
}
size_t KohonenNet::getWeights(float* weights)
{
for (int i = 0; i < neuron_index_map.size() * x_size; i++)
weights[i] = this->weights[i];
return neuron_index_map.size() * x_size;
}
std::vector<NeuronIndex> nnets_kohonen::KohonenNet::getNeurons()
{
return neuron_index_map;
}
size_t KohonenNet::getClass(NeuronIndex n, float* y)
{
int found_index = getInternalIndex(n);
if (found_index != -1)
{
float* cur_class = classes[found_index];
for (int i = 0; i < y_size; i++)
y[i] = cur_class[i];
return y_size;
}
return 0;
}
size_t KohonenNet::getWeightsMatrixSize()
{
return neuron_index_map.size() * x_size;
}
bool nnets_kohonen::KohonenNet::getUseNormalization()
{
return use_norm_x;
}
int nnets_kohonen::KohonenNet::getWinnerIndex()
{
return getInternalIndex(winner);
}
KohonenNet::~KohonenNet()
{
delete[] kohonen_layer;
for (int i = 0; i < neurons_width * neurons_height; i++)
delete[] classes[i];
delete[] classes;
delete[] weights;
delete[] x_internal;
}
NeuronIndex KohonenNet::calcWinner(const float* x)
{
const float* input = x;
if (use_norm_x)
{
float norm = 0.0f;
for (int i = 0; i < x_size; i++)
norm += x[i] * x[i];
norm = std::sqrt(norm);
for (int i = 0; i < x_size; i++)
x_internal[i] = x[i] / norm;
input = x_internal;
}
int winner_index = 0;
if (metric == Metric::Default)
{
cblas_sgemv(CblasRowMajor, CblasNoTrans,
neuron_index_map.size(), x_size,
1.0f, weights, x_size,
input, 1, 0.0f, kohonen_layer, 1);
float max_value = kohonen_layer[0];
for (int i = 1; i < neuron_index_map.size(); i++)
{
if (max_value < kohonen_layer[i])
{
max_value = kohonen_layer[i];
winner_index = i;
}
}
}
else if (metric == Metric::Euclidean)
{
for (int i = 0; i < neuron_index_map.size(); i++)
{
kohonen_layer[i] = 0.0f;
for (int j = 0; j < x_size; j++)
{
float temp = input[i] - weights[i * x_size + j];
kohonen_layer[i] += temp * temp;
}
}
float min_value = kohonen_layer[0];
for (int i = 1; i < neuron_index_map.size(); i++)
{
if (min_value > kohonen_layer[i])
{
min_value = kohonen_layer[i];
winner_index = i;
}
}
}
else throw "Undefined metric";
return neuron_index_map[winner_index];
}
size_t KohonenNet::solve(const float* x, float* y)
{
winner = calcWinner(x);
int found_index = getInternalIndex(winner);
float* cur_class = classes[found_index];
for (int i = 0; i < y_size; i++)
y[i] = cur_class[i];
return y_size;
} | [
"michael_smirnov@me.com"
] | michael_smirnov@me.com |
778aef1fa47dba76184954eff0a2a748af79690f | 2d568794c70ab5b8f5bae284c757be4fbf230bcd | /0018-4sum.cpp | d450b3b3c1b78adaa4ee7f6255b77f4a5d54ed6d | [
"MIT"
] | permissive | lwcM/leetcode_solution | 5fc3d3a943db97a415a1f987954caf4aa9de7566 | a5e714a9785fd94e530396d93c81f71fd8b9c1b6 | refs/heads/master | 2020-03-28T12:54:01.669006 | 2018-09-20T06:39:10 | 2018-09-20T06:39:10 | 148,344,855 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | cpp | static const auto __=[]{
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>> v;
for(int i=0; i<nums.size(); i++) {
if(i && nums[i-1]==nums[i]) continue;
for(int j=i+1; j<nums.size(); j++) {
if(j>i+1 && nums[j-1]==nums[j]) continue;
int l=j+1, r=nums.size()-1;
while(l<r) {
int s = nums[i]+nums[j]+nums[l]+nums[r];
if(s < target) l++;
else if(s > target) r--;
else {
v.push_back({nums[i], nums[j], nums[l], nums[r]});
while(l < r && nums[l] == nums[l+1]) l++;
while(l < r && nums[r] == nums[r-1]) r--;
l++;
r--;
}
}
}
}
return v;
}
};
| [
"lwc@lwcs-MacBook-Pro.local"
] | lwc@lwcs-MacBook-Pro.local |
a0297eb043e3e7166b311fe4ffb9e638e304d3b0 | 51ea7d94c07acce8afd538a2b1b011a8c2082362 | /programs/dataSource/cdatatransfer.cpp | bd59d1295272b307d223296e1ae19207025736b9 | [] | no_license | noachain/dapp | 29ecb9c5606c804289bdfbe3a3bdea9c46f8a62f | 27dfcb63b988d771e792dd7282feb22a27809028 | refs/heads/master | 2020-03-21T22:27:42.632232 | 2018-06-29T09:19:33 | 2018-06-29T09:19:33 | 139,127,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | cpp | #include "cdatatransfer.h"
using namespace std;
CDataTransfer::CDataTransfer()
{
}
void CDataTransfer::initIpfs()
{
}
void CDataTransfer::uploadMetadata(const std::string &strUrl, int eLoadType)
{
}
void CDataTransfer::downloadMetadata(const std::string &strIpfsHash, int eDownloadSaveType)
{
}
void CDataTransfer::uploadCiphertext(const string &strUrl, int eLoadType)
{
}
void CDataTransfer::downloadCiphertext(const string &strIpfsHase, int eDownloadSaveType)
{
}
void CDataTransfer::uploadFhlibContent(const FHEcontext *context, const FHEPubKey *pkey)
{
}
void CDataTransfer::downloadFhlibContent(FHEcontext *context, FHEPubKey *pkey, const string &strIpfsHash)
{
}
| [
"paizzj@126.com"
] | paizzj@126.com |
ff77aa8f6b1e8b328486db160b5d90fc4c76cbee | aa887833c7c5fc6557dae37eef325e14743bbbd3 | /3.cpp | a4a0d6f8a24fdb56c568ba5a35a5d247faeac153 | [] | no_license | qpwo2468/github-upload | f28dba6949e2d7d4f5d674282ed4f389fa45b0e3 | e7e1e921aa10ee8b5e37d3afa2c75c52154c814d | refs/heads/master | 2022-10-23T04:43:53.000605 | 2020-06-05T02:18:59 | 2020-06-05T02:18:59 | 269,505,187 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,987 | cpp | /*
题目:
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路:
1. 使用栈保存链表,然后存入vector
2. 使用递归操作(写法简单,但不推荐,容易爆)
3. 直接存入vector, 然后反转
4. 反转链表存入vector
*/
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
struct ListNode
{
int val;
struct ListNode* next;
ListNode(int x) :
val(x), next(nullptr) {}
};
//1
vector<int> printListFromTailToHead(ListNode* head)
{
stack<int> data;
vector<int> result;
while (head != NULL)
{
data.push(head->val);
head = head->next;
}
int size = data.size();
for (int i = 0; i < size; i++)
{
result.push_back(data.top());
data.pop();
}
return result;
}
//2
vector<int >result;
vector<int> printListFromTailToHead(ListNode* head)
{
if (head != NULL)
{
if(head->next != NULL)
printListFromTailToHead(head->next);
result.push_back(head->val);
}
return result;
}
//3
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> result;
while (head != NULL)
{
result.push_back(head->val);
head = head->next;
}
for (int i = 0; i < result.size() / 2; i++)
{
int temp = result[i];
result[i] = result[result.size() - i - 1];
result[result.size() - i - 1] = temp;
}
return result;
}
//4
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> result;
struct ListNode* newHead;
struct ListNode* temp;
struct ListNode* node = NULL;
while (head != NULL)
{
temp = head->next;
newHead = head;
newHead->next = node;
node = newHead;
head = temp;
}
while (newHead != NULL)
{
result.push_back(newHead->val);
newHead = newHead->next;
}
return result;
}
| [
"songyj@7invensun.com"
] | songyj@7invensun.com |
8fc0ec893dff64d8bfd3e2eb740e5433193f81b2 | e5474f6051792fd2aaeb970bb9ce0fe6d4ea656c | /include/sigma/graphics/opengl/static_mesh_manager.hpp | 20834adcc969313907a27b7387fff43dc30ca6d2 | [] | no_license | sigma-engine/sigma-opengl | 2906c65e8b1591ce204b6725c494df916f523d95 | f38c8fb891f4324690b95ad73906cba077363b79 | refs/heads/master | 2020-03-28T09:38:47.614165 | 2019-03-31T16:32:25 | 2019-03-31T16:32:25 | 148,048,703 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,934 | hpp | #ifndef SIGMA_ENGINE_STATIC_MESH_MANAGER_HPP
#define SIGMA_ENGINE_STATIC_MESH_MANAGER_HPP
#include <sigma/graphics/static_mesh.hpp>
#include <sigma/buddy_array_allocator.hpp>
#include <sigma/config.hpp>
#include <sigma/resource/cache.hpp>
#include <glad/glad.h>
#include <cstddef>
#define VERTEX_BLOCK_SIZE 64
#define MAX_VERTEX_BLOCKS 512
#define INDEX_BLOCK_SIZE 63
#define MAX_INDEX_BLOCKS 1040
namespace sigma {
namespace opengl {
class static_mesh_manager {
public:
struct mesh_buffer {
std::size_t batch_index = -1;
std::size_t base_vertex = 0;
std::size_t base_index = 0;
};
static_mesh_manager(resource::cache<graphics::static_mesh>& static_mesh_cache);
static_mesh_manager(static_mesh_manager&&) = default;
static_mesh_manager& operator=(static_mesh_manager&&) = default;
~static_mesh_manager();
std::size_t batch_size() const;
void bind_batch(std::size_t batch);
std::pair<graphics::static_mesh*, mesh_buffer> acquire(const resource::handle<graphics::static_mesh>& hndl);
private:
static_mesh_manager(const static_mesh_manager&) = delete;
static_mesh_manager& operator=(const static_mesh_manager&) = delete;
resource::cache<graphics::static_mesh>& static_mesh_cache_;
std::vector<mesh_buffer> static_meshes_;
struct buffer_batch {
GLuint vertex_array = 0;
// MAX_VERTEX_BLOCKS blocks of VERTEX_BLOCK_SIZE vertices.
buddy_array_allocator vertex_allocator { MAX_VERTEX_BLOCKS };
GLuint vertex_buffer = 0;
// MAX_INDEX_BLOCKS blocks of INDEX_BLOCK_SIZE indicies.
buddy_array_allocator index_allocator { MAX_INDEX_BLOCKS };
GLuint index_buffer = 0;
};
std::vector<buffer_batch> batches_;
};
}
}
#endif // SIGMA_ENGINE_STATIC_MESH_MANAGER_HPP
| [
"siegelaaron94@gmail.com"
] | siegelaaron94@gmail.com |
56aa4a9b3c5b73f7db659a71b55d7b97b06292fc | 48e7dfc263778cc53d56e055f5c4c48fa1d29efc | /Source/Aren/Pawns/CampPawn.cpp | da0b6e989db45ea7ced068f818c488845624b4d9 | [] | no_license | JBeluche/aren | 11955c84e6c26148c67bfbd2de21716fb4012061 | 32f76a073b4193f080c840d640e6541673242dfb | refs/heads/master | 2023-06-06T18:00:25.485477 | 2021-07-08T13:50:47 | 2021-07-08T13:50:47 | 339,785,757 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 946 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Aren/Pawns/CampPawn.h"
#include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h"
// Sets default values
ACampPawn::ACampPawn()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = false;
SpringArmComponent = CreateDefaultSubobject<USpringArmComponent>(TEXT("Spring Arm"));
RootComponent = SpringArmComponent;
CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
CameraComponent->SetupAttachment(RootComponent);
}
// Called when the game starts or when spawned
void ACampPawn::BeginPlay()
{
Super::BeginPlay();
}
// Called to bind functionality to input
void ACampPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
}
| [
"j.beluche@outlook.com"
] | j.beluche@outlook.com |
1e8ddc2f2fca3bf8b4f5b56b50f707a29d7c36d3 | 28f0faf491453700d8a0e0dfa1fbcb7e0d088544 | /OpenGL/PointLight.cpp | d0c743cb6ab545d2160dea9dfe60d2547934644e | [] | no_license | Zoreno/OpenGLTest | 492755d9e91b03baf2d640a20e9af1e1cd27df66 | 8cab00671e9ece224f5554489527d15aba70997c | refs/heads/master | 2021-01-11T15:42:37.196670 | 2017-03-03T00:31:25 | 2017-03-03T00:31:25 | 79,905,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 791 | cpp | #include "PointLight.h"
PointLight::PointLight(
const glm::vec3& position,
const glm::vec3& ambient,
const glm::vec3& diffuse,
const glm::vec3& specular,
float constant,
float linear,
float quadratic)
: position(position),
ambient(ambient),
diffuse(diffuse),
specular(specular),
constant(constant),
linear(linear),
quadratic(quadratic)
{}
glm::vec3 PointLight::getPosition() const
{
return position;
}
float PointLight::getConstant() const
{
return constant;
}
float PointLight::getLinear() const
{
return linear;
}
float PointLight::getQuadratic() const
{
return quadratic;
}
glm::vec3 PointLight::getAmbient() const
{
return ambient;
}
glm::vec3 PointLight::getDiffuse() const
{
return diffuse;
}
glm::vec3 PointLight::getSpecular() const
{
return specular;
}
| [
"metallica317@spray.se"
] | metallica317@spray.se |
2bc968f11026d8035bf2914bd44da2bfd5d37a7b | 04248e705f7ccd9b7900a880b445261b98286cc6 | /project/src/skinning/skeleton_joint.hpp | 9b079fe04683bcd241f78d72f132419d53988651 | [] | no_license | jeanyves-yang/skinning | 68360bb5727c59fc9725ea2b6460504a7b284d61 | 3a37b79e24bf19c48461e7039c1fb62126f2d1fb | refs/heads/master | 2021-01-10T08:59:11.976023 | 2015-11-18T16:48:06 | 2015-11-18T16:48:06 | 46,427,539 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,244 | hpp | /*
** TP CPE Lyon
** Copyright (C) 2015 Damien Rohmer
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef SKELETON_JOINT_HPP
#define SKELETON_JOINT_HPP
#include "../lib/3d/vec3.hpp"
#include "../lib/3d/quaternion.hpp"
namespace cpe
{
/** A geometrical joint storing a 3D position and an orientation as a quaternion. */
struct skeleton_joint
{
skeleton_joint();
skeleton_joint(vec3 const& position_param,quaternion const& orientation_param);
/** 3D position of the joint */
vec3 position;
/** Orientation of the joint */
quaternion orientation;
};
}
#endif
| [
"jean-yves.yang@mastertp"
] | jean-yves.yang@mastertp |
06f44310aedad1cb8e3ce34061e376fea99bd70d | 6446c6e0649895e8b8fc6442e334f92641df4d15 | /branches/0.5.2.Stoepsel/EScript/Statements/SetAttribute.cpp | 46d9f2062d3605043c9f2125eb0ed48d1a67c366 | [] | no_license | BackupTheBerlios/escript-svn | e33b5dc2192de09b62078cfcec38ad8eec61747a | 36b2e5f69adb768214cd05204a47cf03c09eba9e | refs/heads/master | 2016-08-04T17:36:45.234689 | 2014-01-06T20:08:03 | 2014-01-06T20:08:03 | 40,668,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,431 | cpp | // SetAttribute.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#include "SetAttribute.h"
#include "../Runtime/Runtime.h"
#include "../Objects/Void.h"
#include <iostream>
using namespace EScript;
//! (ctor)
SetAttribute::SetAttribute(Object * obj,identifierId _attrId,Object * valueExp,assignType_t _assignType,int _line):
objRef(obj),valueExpRef(valueExp),attrId(_attrId),assignType(_assignType),line(_line) {
//ctor
}
//! (dtor)
SetAttribute::~SetAttribute() {
//dtor
}
//! ---|> [Object]
std::string SetAttribute::toString()const {
std::string s="";
if (!objRef.isNull()) {
s+=objRef.toString();
} else s+="_";
s+="."+identifierIdToString(attrId);
switch(assignType){
case ASSIGN:
s+="=";
break;
case SET_OBJ_ATTRIBUTE:
s+=":=";
break;
case SET_TYPE_ATTRIBUTE:
s+="::=";
break;
}
s+="("+valueExpRef.toString()+") ";
return s;
}
//! ---|> [Object]
Object * SetAttribute::execute(Runtime & rt) {
if(line>0)
rt.setCurrentLine(line);
ObjRef valueRef=NULL;
if (!valueExpRef.isNull()) {
valueRef=rt.executeObj(valueExpRef.get());
if(!rt.assertNormalState(this))
return NULL;
/// Bug[20070703] fixed:
if(!valueRef.isNull()){
valueRef=valueRef->getRefOrCopy();
}else{
valueRef=Void::get();
}
}
/// Local variable
if (objRef.isNull()) {
rt.assignToVariable(attrId,valueRef.get());
return valueRef.detachAndDecrease();
} /// obj.ident
ObjRef obj2=rt.executeObj(objRef.get());
if(!rt.assertNormalState(this))
return NULL;
if(obj2.isNull())
obj2=Void::get();
if(assignType == ASSIGN){
if(!obj2->assignAttribute(attrId,valueRef.get())){
rt.warn(std::string("Unkown attribute \"")+identifierIdToString(attrId)+"\" ("+
(objRef.isNull()?"":objRef->toDbgString())+"."+identifierIdToString(attrId)+"="+(valueRef.isNull()?"":valueRef->toDbgString())+")");
if(!obj2->setObjAttribute(attrId,valueRef.get())){
rt.warn(std::string("Can't set object attribute \"")+identifierIdToString(attrId)+"\" ("+
(objRef.isNull()?"":objRef->toDbgString())+"."+identifierIdToString(attrId)+"="+(valueRef.isNull()?"":valueRef->toDbgString())+")");
}
}
}else if(assignType == SET_OBJ_ATTRIBUTE){
if(!obj2->setObjAttribute(attrId,valueRef.get()))
rt.warn(std::string("Can't set object attribute \"")+identifierIdToString(attrId)+"\" ("+
(objRef.isNull()?"":objRef->toDbgString())+"."+identifierIdToString(attrId)+"="+(valueRef.isNull()?"":valueRef->toDbgString())+")");
}else if(assignType == SET_TYPE_ATTRIBUTE){
Type * t=obj2.toType<Type>();
if(t){
t->setTypeAttribute(attrId,valueRef.get());
}else{
rt.warn(std::string("Can not set typeAttr to non-Type-Object: \"")+identifierIdToString(attrId)+"\" ("+
(objRef.isNull()?"":objRef->toDbgString())+"."+identifierIdToString(attrId)+"="+(valueRef.isNull()?"":valueRef->toDbgString())+")"
+"Setting objAttr instead.");
if(!obj2->setObjAttribute(attrId,valueRef.get())){
rt.warn(std::string("Can't set object attribute \"")+identifierIdToString(attrId)+"\" ("+
(objRef.isNull()?"":objRef->toDbgString())+"."+identifierIdToString(attrId)+"="+(valueRef.isNull()?"":valueRef->toDbgString())+")");
}
}
}
return valueRef.detachAndDecrease();
}
| [
"claudiusj@5693b1fc-3b75-4070-9b6b-3ce3692a40d5"
] | claudiusj@5693b1fc-3b75-4070-9b6b-3ce3692a40d5 |
4e33ca5c39bf307186c60a7d5203e063d72f154a | 864431c315f13c034b11c1475bb5baf2a81cbd9f | /Kernel/ThreadBlockers.cpp | d1e8b2cbb567bf6eefcf28911debf029c95a68e9 | [
"BSD-2-Clause"
] | permissive | zbennett10/serenity | de653b4db637b9e62f817813192105c515359bc4 | 47a4a5ac1d3631a3df0a2b9f8c242b2decec826a | refs/heads/master | 2023-02-19T03:35:48.662438 | 2021-01-21T10:34:46 | 2021-01-21T10:35:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,936 | cpp | /*
* Copyright (c) 2020, The SerenityOS developers.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#include <Kernel/FileSystem/FileDescription.h>
#include <Kernel/Net/Socket.h>
#include <Kernel/Process.h>
#include <Kernel/Scheduler.h>
#include <Kernel/Thread.h>
//#define WAITBLOCK_DEBUG
namespace Kernel {
bool Thread::Blocker::set_block_condition(Thread::BlockCondition& block_condition, void* data)
{
ASSERT(!m_block_condition);
if (block_condition.add_blocker(*this, data)) {
m_block_condition = &block_condition;
m_block_data = data;
return true;
}
return false;
}
Thread::Blocker::~Blocker()
{
ScopedSpinLock lock(m_lock);
if (m_block_condition)
m_block_condition->remove_blocker(*this, m_block_data);
}
void Thread::Blocker::begin_blocking(Badge<Thread>)
{
ScopedSpinLock lock(m_lock);
ASSERT(!m_is_blocking);
ASSERT(!m_blocked_thread);
m_blocked_thread = Thread::current();
m_is_blocking = true;
}
auto Thread::Blocker::end_blocking(Badge<Thread>, bool did_timeout) -> BlockResult
{
ScopedSpinLock lock(m_lock);
// if m_is_blocking is false here, some thread forced to
// unblock us when we get here. This is only called from the
// thread that was blocked.
ASSERT(Thread::current() == m_blocked_thread);
m_is_blocking = false;
m_blocked_thread = nullptr;
was_unblocked(did_timeout);
return block_result();
}
Thread::JoinBlocker::JoinBlocker(Thread& joinee, KResult& try_join_result, void*& joinee_exit_value)
: m_joinee(joinee)
, m_joinee_exit_value(joinee_exit_value)
{
{
// We need to hold our lock to avoid a race where try_join succeeds
// but the joinee is joining immediately
ScopedSpinLock lock(m_lock);
try_join_result = joinee.try_join([&]() {
if (!set_block_condition(joinee.m_join_condition))
m_should_block = false;
});
m_join_error = try_join_result.is_error();
if (m_join_error)
m_should_block = false;
}
}
void Thread::JoinBlocker::not_blocking(bool timeout_in_past)
{
if (!m_should_block) {
// set_block_condition returned false, so unblock was already called
ASSERT(!timeout_in_past);
return;
}
// If we should have blocked but got here it must have been that the
// timeout was already in the past. So we need to ask the BlockCondition
// to supply us the information. We cannot hold the lock as unblock
// could be called by the BlockCondition at any time!
ASSERT(timeout_in_past);
m_joinee->m_join_condition.try_unblock(*this);
}
bool Thread::JoinBlocker::unblock(void* value, bool from_add_blocker)
{
{
ScopedSpinLock lock(m_lock);
if (m_did_unblock)
return false;
m_did_unblock = true;
m_joinee_exit_value = value;
do_set_interrupted_by_death();
}
if (!from_add_blocker)
unblock_from_blocker();
return true;
}
Thread::QueueBlocker::QueueBlocker(WaitQueue& wait_queue, const char* block_reason)
: m_block_reason(block_reason)
{
if (!set_block_condition(wait_queue, Thread::current()))
m_should_block = false;
}
Thread::QueueBlocker::~QueueBlocker()
{
}
bool Thread::QueueBlocker::unblock()
{
{
ScopedSpinLock lock(m_lock);
if (m_did_unblock)
return false;
m_did_unblock = true;
}
unblock_from_blocker();
return true;
}
Thread::FutexBlocker::FutexBlocker(FutexQueue& futex_queue, u32 bitset)
: m_bitset(bitset)
{
if (!set_block_condition(futex_queue, Thread::current()))
m_should_block = false;
}
Thread::FutexBlocker::~FutexBlocker()
{
}
void Thread::FutexBlocker::finish_requeue(FutexQueue& futex_queue)
{
ASSERT(m_lock.own_lock());
set_block_condition_raw_locked(&futex_queue);
// We can now releas the lock
m_lock.unlock(m_relock_flags);
}
bool Thread::FutexBlocker::unblock_bitset(u32 bitset)
{
{
ScopedSpinLock lock(m_lock);
if (m_did_unblock || (bitset != FUTEX_BITSET_MATCH_ANY && (m_bitset & bitset) == 0))
return false;
m_did_unblock = true;
}
unblock_from_blocker();
return true;
}
bool Thread::FutexBlocker::unblock(bool force)
{
{
ScopedSpinLock lock(m_lock);
if (m_did_unblock)
return force;
m_did_unblock = true;
}
unblock_from_blocker();
return true;
}
Thread::FileDescriptionBlocker::FileDescriptionBlocker(FileDescription& description, BlockFlags flags, BlockFlags& unblocked_flags)
: m_blocked_description(description)
, m_flags(flags)
, m_unblocked_flags(unblocked_flags)
{
m_unblocked_flags = BlockFlags::None;
if (!set_block_condition(description.block_condition()))
m_should_block = false;
}
bool Thread::FileDescriptionBlocker::unblock(bool from_add_blocker, void*)
{
auto unblock_flags = m_blocked_description->should_unblock(m_flags);
if (unblock_flags == BlockFlags::None)
return false;
{
ScopedSpinLock lock(m_lock);
if (m_did_unblock)
return false;
m_did_unblock = true;
m_unblocked_flags = unblock_flags;
}
if (!from_add_blocker)
unblock_from_blocker();
return true;
}
void Thread::FileDescriptionBlocker::not_blocking(bool timeout_in_past)
{
if (!m_should_block) {
// set_block_condition returned false, so unblock was already called
ASSERT(!timeout_in_past);
return;
}
// If we should have blocked but got here it must have been that the
// timeout was already in the past. So we need to ask the BlockCondition
// to supply us the information. We cannot hold the lock as unblock
// could be called by the BlockCondition at any time!
ASSERT(timeout_in_past);
// Just call unblock here because we will query the file description
// for the data and don't need any input from the FileBlockCondition.
// However, it's possible that if timeout_in_past is true then FileBlockCondition
// may call us at any given time, so our call to unblock here may fail.
// Either way, unblock will be called at least once, which provides
// all the data we need.
unblock(false, nullptr);
}
const FileDescription& Thread::FileDescriptionBlocker::blocked_description() const
{
return m_blocked_description;
}
Thread::AcceptBlocker::AcceptBlocker(FileDescription& description, BlockFlags& unblocked_flags)
: FileDescriptionBlocker(description, (BlockFlags)((u32)BlockFlags::Accept | (u32)BlockFlags::Exception), unblocked_flags)
{
}
Thread::ConnectBlocker::ConnectBlocker(FileDescription& description, BlockFlags& unblocked_flags)
: FileDescriptionBlocker(description, (BlockFlags)((u32)BlockFlags::Connect | (u32)BlockFlags::Exception), unblocked_flags)
{
}
Thread::WriteBlocker::WriteBlocker(FileDescription& description, BlockFlags& unblocked_flags)
: FileDescriptionBlocker(description, (BlockFlags)((u32)BlockFlags::Write | (u32)BlockFlags::Exception), unblocked_flags)
{
}
auto Thread::WriteBlocker::override_timeout(const BlockTimeout& timeout) -> const BlockTimeout&
{
auto& description = blocked_description();
if (description.is_socket()) {
auto& socket = *description.socket();
if (socket.has_send_timeout()) {
m_timeout = BlockTimeout(false, &socket.send_timeout(), timeout.start_time(), timeout.clock_id());
if (timeout.is_infinite() || (!m_timeout.is_infinite() && m_timeout.absolute_time() < timeout.absolute_time()))
return m_timeout;
}
}
return timeout;
}
Thread::ReadBlocker::ReadBlocker(FileDescription& description, BlockFlags& unblocked_flags)
: FileDescriptionBlocker(description, (BlockFlags)((u32)BlockFlags::Read | (u32)BlockFlags::Exception), unblocked_flags)
{
}
auto Thread::ReadBlocker::override_timeout(const BlockTimeout& timeout) -> const BlockTimeout&
{
auto& description = blocked_description();
if (description.is_socket()) {
auto& socket = *description.socket();
if (socket.has_receive_timeout()) {
m_timeout = BlockTimeout(false, &socket.receive_timeout(), timeout.start_time(), timeout.clock_id());
if (timeout.is_infinite() || (!m_timeout.is_infinite() && m_timeout.absolute_time() < timeout.absolute_time()))
return m_timeout;
}
}
return timeout;
}
Thread::SleepBlocker::SleepBlocker(const BlockTimeout& deadline, timespec* remaining)
: m_deadline(deadline)
, m_remaining(remaining)
{
}
auto Thread::SleepBlocker::override_timeout(const BlockTimeout& timeout) -> const BlockTimeout&
{
ASSERT(timeout.is_infinite()); // A timeout should not be provided
// To simplify things only use the sleep deadline.
return m_deadline;
}
void Thread::SleepBlocker::not_blocking(bool timeout_in_past)
{
// SleepBlocker::should_block should always return true, so timeout
// in the past is the only valid case when this function is called
ASSERT(timeout_in_past);
calculate_remaining();
}
void Thread::SleepBlocker::was_unblocked(bool did_timeout)
{
Blocker::was_unblocked(did_timeout);
calculate_remaining();
}
void Thread::SleepBlocker::calculate_remaining()
{
if (!m_remaining)
return;
auto time_now = TimeManagement::the().current_time(m_deadline.clock_id()).value();
if (time_now < m_deadline.absolute_time())
timespec_sub(m_deadline.absolute_time(), time_now, *m_remaining);
else
*m_remaining = {};
}
Thread::BlockResult Thread::SleepBlocker::block_result()
{
auto result = Blocker::block_result();
if (result == Thread::BlockResult::InterruptedByTimeout)
return Thread::BlockResult::WokeNormally;
return result;
}
Thread::SelectBlocker::SelectBlocker(FDVector& fds)
: m_fds(fds)
{
for (auto& fd_entry : m_fds) {
fd_entry.unblocked_flags = FileBlocker::BlockFlags::None;
if (!m_should_block)
continue;
if (!fd_entry.description->block_condition().add_blocker(*this, &fd_entry))
m_should_block = false;
}
}
Thread::SelectBlocker::~SelectBlocker()
{
for (auto& fd_entry : m_fds)
fd_entry.description->block_condition().remove_blocker(*this, &fd_entry);
}
void Thread::SelectBlocker::not_blocking(bool timeout_in_past)
{
// Either the timeout was in the past or we didn't add all blockers
ASSERT(timeout_in_past || !m_should_block);
ScopedSpinLock lock(m_lock);
if (!m_did_unblock) {
m_did_unblock = true;
if (!timeout_in_past) {
auto count = collect_unblocked_flags();
ASSERT(count > 0);
}
}
}
bool Thread::SelectBlocker::unblock(bool from_add_blocker, void* data)
{
ASSERT(data); // data is a pointer to an entry in the m_fds vector
auto& fd_info = *static_cast<FDInfo*>(data);
{
ScopedSpinLock lock(m_lock);
if (m_did_unblock)
return false;
auto unblock_flags = fd_info.description->should_unblock(fd_info.block_flags);
if (unblock_flags == BlockFlags::None)
return false;
m_did_unblock = true;
// We need to store unblock_flags here, otherwise someone else
// affecting this file descriptor could change the information
// between now and when was_unblocked is called!
fd_info.unblocked_flags = unblock_flags;
}
// Only do this once for the first one
if (!from_add_blocker)
unblock_from_blocker();
return true;
}
size_t Thread::SelectBlocker::collect_unblocked_flags()
{
size_t count = 0;
for (auto& fd_entry : m_fds) {
ASSERT(fd_entry.block_flags != FileBlocker::BlockFlags::None);
// unblock will have set at least the first descriptor's unblock
// flags that triggered the unblock. Make sure we don't discard that
// information as it may have changed by now!
if (fd_entry.unblocked_flags == FileBlocker::BlockFlags::None)
fd_entry.unblocked_flags = fd_entry.description->should_unblock(fd_entry.block_flags);
if (fd_entry.unblocked_flags != FileBlocker::BlockFlags::None)
count++;
}
return count;
}
void Thread::SelectBlocker::was_unblocked(bool did_timeout)
{
Blocker::was_unblocked(did_timeout);
if (!did_timeout && !was_interrupted()) {
{
ScopedSpinLock lock(m_lock);
ASSERT(m_did_unblock);
}
size_t count = collect_unblocked_flags();
// If we were blocked and didn't time out, we should have at least one unblocked fd!
ASSERT(count > 0);
}
}
Thread::WaitBlockCondition::ProcessBlockInfo::ProcessBlockInfo(NonnullRefPtr<Process>&& process, WaitBlocker::UnblockFlags flags, u8 signal)
: process(move(process))
, flags(flags)
, signal(signal)
{
}
Thread::WaitBlockCondition::ProcessBlockInfo::~ProcessBlockInfo()
{
}
void Thread::WaitBlockCondition::try_unblock(Thread::WaitBlocker& blocker)
{
ScopedSpinLock lock(m_lock);
// We if we have any processes pending
for (size_t i = 0; i < m_processes.size(); i++) {
auto& info = m_processes[i];
// We need to call unblock as if we were called from add_blocker
// so that we don't trigger a context switch by yielding!
if (info.was_waited && blocker.is_wait())
continue; // This state was already waited on, do not unblock
if (blocker.unblock(info.process, info.flags, info.signal, true)) {
if (blocker.is_wait()) {
if (info.flags == Thread::WaitBlocker::UnblockFlags::Terminated) {
m_processes.remove(i);
#ifdef WAITBLOCK_DEBUG
dbg() << "WaitBlockCondition[" << m_process << "] terminated, remove " << *info.process;
#endif
} else {
#ifdef WAITBLOCK_DEBUG
dbg() << "WaitBlockCondition[" << m_process << "] terminated, mark as waited " << *info.process;
#endif
info.was_waited = true;
}
}
break;
}
}
}
void Thread::WaitBlockCondition::disowned_by_waiter(Process& process)
{
ScopedSpinLock lock(m_lock);
if (m_finalized)
return;
for (size_t i = 0; i < m_processes.size();) {
auto& info = m_processes[i];
if (info.process == &process) {
do_unblock([&](Blocker& b, void*, bool&) {
ASSERT(b.blocker_type() == Blocker::Type::Wait);
auto& blocker = static_cast<WaitBlocker&>(b);
bool did_unblock = blocker.unblock(info.process, WaitBlocker::UnblockFlags::Disowned, 0, false);
ASSERT(did_unblock); // disowning must unblock everyone
return true;
});
#ifdef WAITBLOCK_DEBUG
dbg() << "WaitBlockCondition[" << m_process << "] disowned " << *info.process;
#endif
m_processes.remove(i);
continue;
}
i++;
}
}
bool Thread::WaitBlockCondition::unblock(Process& process, WaitBlocker::UnblockFlags flags, u8 signal)
{
ASSERT(flags != WaitBlocker::UnblockFlags::Disowned);
bool did_unblock_any = false;
bool did_wait = false;
bool was_waited_already = false;
ScopedSpinLock lock(m_lock);
if (m_finalized)
return false;
if (flags != WaitBlocker::UnblockFlags::Terminated) {
// First check if this state was already waited on
for (auto& info : m_processes) {
if (info.process == &process) {
was_waited_already = info.was_waited;
break;
}
}
}
do_unblock([&](Blocker& b, void*, bool&) {
ASSERT(b.blocker_type() == Blocker::Type::Wait);
auto& blocker = static_cast<WaitBlocker&>(b);
if (was_waited_already && blocker.is_wait())
return false; // This state was already waited on, do not unblock
if (blocker.unblock(process, flags, signal, false)) {
did_wait |= blocker.is_wait(); // anyone requesting a wait
did_unblock_any = true;
return true;
}
return false;
});
// If no one has waited (yet), or this wasn't a wait, or if it's anything other than
// UnblockFlags::Terminated then add it to your list
if (!did_unblock_any || !did_wait || flags != WaitBlocker::UnblockFlags::Terminated) {
bool updated_existing = false;
for (auto& info : m_processes) {
if (info.process == &process) {
ASSERT(info.flags != WaitBlocker::UnblockFlags::Terminated);
info.flags = flags;
info.signal = signal;
info.was_waited = did_wait;
#ifdef WAITBLOCK_DEBUG
dbg() << "WaitBlockCondition[" << m_process << "] update " << process << " flags: " << (int)flags << " mark as waited: " << info.was_waited;
#endif
updated_existing = true;
break;
}
}
if (!updated_existing) {
#ifdef WAITBLOCK_DEBUG
dbg() << "WaitBlockCondition[" << m_process << "] add " << process << " flags: " << (int)flags;
#endif
m_processes.append(ProcessBlockInfo(process, flags, signal));
}
}
return did_unblock_any;
}
bool Thread::WaitBlockCondition::should_add_blocker(Blocker& b, void*)
{
// NOTE: m_lock is held already!
if (m_finalized)
return false;
ASSERT(b.blocker_type() == Blocker::Type::Wait);
auto& blocker = static_cast<WaitBlocker&>(b);
// See if we can match any process immediately
for (size_t i = 0; i < m_processes.size(); i++) {
auto& info = m_processes[i];
if (blocker.unblock(info.process, info.flags, info.signal, true)) {
// Only remove the entry if UnblockFlags::Terminated
if (info.flags == Thread::WaitBlocker::UnblockFlags::Terminated && blocker.is_wait())
m_processes.remove(i);
return false;
}
}
return true;
}
void Thread::WaitBlockCondition::finalize()
{
ScopedSpinLock lock(m_lock);
ASSERT(!m_finalized);
m_finalized = true;
// Clear the list of threads here so we can drop the references to them
m_processes.clear();
// No more waiters, drop the last reference immediately. This may
// cause us to be destructed ourselves!
ASSERT(m_process.ref_count() > 0);
m_process.unref();
}
Thread::WaitBlocker::WaitBlocker(int wait_options, idtype_t id_type, pid_t id, KResultOr<siginfo_t>& result)
: m_wait_options(wait_options)
, m_id_type(id_type)
, m_waitee_id(id)
, m_result(result)
, m_should_block(!(m_wait_options & WNOHANG))
{
switch (id_type) {
case P_PID: {
m_waitee = Process::from_pid(m_waitee_id);
if (!m_waitee || m_waitee->ppid() != Process::current()->pid()) {
m_result = ECHILD;
m_error = true;
return;
}
break;
}
case P_PGID: {
m_waitee_group = ProcessGroup::from_pgid(m_waitee_id);
if (!m_waitee_group) {
m_result = ECHILD;
m_error = true;
return;
}
break;
}
case P_ALL:
break;
default:
ASSERT_NOT_REACHED();
}
// NOTE: unblock may be called within set_block_condition, in which
// case it means that we already have a match without having to block.
// In that case set_block_condition will return false.
if (m_error || !set_block_condition(Process::current()->wait_block_condition()))
m_should_block = false;
}
void Thread::WaitBlocker::not_blocking(bool timeout_in_past)
{
ASSERT(timeout_in_past || !m_should_block);
if (!m_error)
Process::current()->wait_block_condition().try_unblock(*this);
}
void Thread::WaitBlocker::was_unblocked(bool)
{
bool got_sigchld, try_unblock;
{
ScopedSpinLock lock(m_lock);
try_unblock = !m_did_unblock;
got_sigchld = m_got_sigchild;
}
if (try_unblock)
Process::current()->wait_block_condition().try_unblock(*this);
// If we were interrupted by SIGCHLD (which gets special handling
// here) we're not going to return with EINTR. But we're going to
// deliver SIGCHLD (only) here.
auto* current_thread = Thread::current();
if (got_sigchld && current_thread->state() != State::Stopped)
current_thread->try_dispatch_one_pending_signal(SIGCHLD);
}
void Thread::WaitBlocker::do_was_disowned()
{
ASSERT(!m_did_unblock);
m_did_unblock = true;
m_result = ECHILD;
}
void Thread::WaitBlocker::do_set_result(const siginfo_t& result)
{
ASSERT(!m_did_unblock);
m_did_unblock = true;
m_result = result;
if (do_get_interrupted_by_signal() == SIGCHLD) {
// This makes it so that wait() will return normally despite the
// fact that SIGCHLD was delivered. Calling do_clear_interrupted_by_signal
// will disable dispatching signals in Thread::block and prevent
// it from returning with EINTR. We will then manually dispatch
// SIGCHLD (and only SIGCHLD) in was_unblocked.
m_got_sigchild = true;
do_clear_interrupted_by_signal();
}
}
bool Thread::WaitBlocker::unblock(Process& process, UnblockFlags flags, u8 signal, bool from_add_blocker)
{
ASSERT(flags != UnblockFlags::Terminated || signal == 0); // signal argument should be ignored for Terminated
switch (m_id_type) {
case P_PID:
ASSERT(m_waitee);
if (process.pid() != m_waitee_id)
return false;
break;
case P_PGID:
ASSERT(m_waitee_group);
if (process.pgid() != m_waitee_group->pgid())
return false;
break;
case P_ALL:
if (flags == UnblockFlags::Disowned) {
// Generic waiter won't be unblocked by disown
return false;
}
break;
default:
ASSERT_NOT_REACHED();
}
switch (flags) {
case UnblockFlags::Terminated:
if (!(m_wait_options & WEXITED))
return false;
break;
case UnblockFlags::Stopped:
if (!(m_wait_options & WSTOPPED))
return false;
if (!(m_wait_options & WUNTRACED) && !process.is_traced())
return false;
break;
case UnblockFlags::Continued:
if (!(m_wait_options & WCONTINUED))
return false;
if (!(m_wait_options & WUNTRACED) && !process.is_traced())
return false;
break;
case UnblockFlags::Disowned:
ScopedSpinLock lock(m_lock);
// Disowning must unblock anyone waiting for this process explicitly
if (!m_did_unblock)
do_was_disowned();
return true;
}
if (flags == UnblockFlags::Terminated) {
ASSERT(process.is_dead());
ScopedSpinLock lock(m_lock);
if (m_did_unblock)
return false;
// Up until this point, this function may have been called
// more than once!
do_set_result(process.wait_info());
} else {
siginfo_t siginfo;
memset(&siginfo, 0, sizeof(siginfo));
{
ScopedSpinLock lock(g_scheduler_lock);
// We need to gather the information before we release the sheduler lock!
siginfo.si_signo = SIGCHLD;
siginfo.si_pid = process.pid().value();
siginfo.si_uid = process.uid();
siginfo.si_status = signal;
switch (flags) {
case UnblockFlags::Terminated:
case UnblockFlags::Disowned:
ASSERT_NOT_REACHED();
case UnblockFlags::Stopped:
siginfo.si_code = CLD_STOPPED;
break;
case UnblockFlags::Continued:
siginfo.si_code = CLD_CONTINUED;
break;
}
}
ScopedSpinLock lock(m_lock);
if (m_did_unblock)
return false;
// Up until this point, this function may have been called
// more than once!
do_set_result(siginfo);
}
if (!from_add_blocker) {
// Only call unblock if we weren't called from within set_block_condition!
ASSERT(flags != UnblockFlags::Disowned);
unblock_from_blocker();
}
// Because this may be called from add_blocker, in which case we should
// not be actually trying to unblock the thread (because it hasn't actually
// been blocked yet), we need to return true anyway
return true;
}
}
| [
"kling@serenityos.org"
] | kling@serenityos.org |
8c872a2c984629f3c7a84c4d2b438c5fdd743f0c | 354fa96a6a33fb5f590b61b946490393fae832e9 | /test/thread_pool_test.cpp | c1f1d22c40776eb4fd0fb0d9f26eedeb04b0e7ba | [] | no_license | hpplinux/Mushroom | d0b23937496b01f09749638ee4e0a8e261b2c0d7 | 10f373f2266894a4d9dc6f505a05a3510bfde733 | refs/heads/master | 2021-01-13T03:18:33.789001 | 2016-11-30T08:20:23 | 2016-11-30T08:20:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,261 | cpp | /**
* > Author: UncP
* > Mail: 770778010@qq.com
* > Github: https://www.github.com/UncP/Mushroom
* > Description:
*
* > Created Time: 2016-10-17 13:50:46
**/
#include <iostream>
#include <fstream>
#include "../src/db.hpp"
#include "../src/iterator.hpp"
#include "../src/thread_pool.hpp"
int main(int argc, char **argv)
{
using namespace Mushroom;
const char *file = "../data/Str.txt";
const int key_len = 10;
const int total = (argc == 2) ? atoi(argv[1]) : 10;
MushroomDB db("mushroom", key_len);
KeySlice::SetStringFormat([](const KeySlice *key) {
return std::string(key->Data()) + " ";
});
std::ifstream in;
in.open(file);
assert(in.is_open());
std::string val;
ThreadPool pool(new FiniteQueue<Task>());
char *buf[total];
KeySlice *key = nullptr;
for (int i = 0; !in.eof() && i < total; ++i) {
buf[i] = new char[BTreePage::PageByte + key_len];
in >> val;
key = (KeySlice *)buf[i];
memcpy(key->Data(), val.c_str(), key_len);
pool.AddTask(Task(&BTree::Put, (BTree *)db.Btree(), key));
}
pool.Clear();
Iterator it(db.Btree());
assert(it.CheckBtree());
assert(db.Btree()->KeyCheck(in, total));
in.close();
for (int i = 0; i != total; ++i)
delete [] buf[i];
db.Close();
return 0;
}
| [
"770778010@qq.com"
] | 770778010@qq.com |
43f455b59616b809d377b57037d6f12e48ae83e1 | d69d609c0c80aade62c98f583c671dc0b27d0b27 | /Public_const_and_structs.h | b59f2a22882951cf9eab0f4547b1fb63f101be95 | [] | no_license | shakedguy/Tetris_Project | a525d6332153df3d75e4ce59dd452fbe106024a7 | 235827d5308e6bb35d41ba4e69557dabcea04cea | refs/heads/master | 2023-05-08T15:56:13.000791 | 2021-05-31T20:10:08 | 2021-05-31T20:10:08 | 350,011,730 | 0 | 0 | null | 2021-04-28T16:14:13 | 2021-03-21T13:47:41 | C++ | UTF-8 | C++ | false | false | 1,191 | h | /***************************************
Header file for the consts and structs of all the project.
***************************************/
#ifndef _CONSTS_STRUCTS_H_
#define _CONSTS_STRUCTS_H_
/* In this file all the const parameters of the project will be written,
* so if we will want to change sizes, locations or characters of objects,
* we can do it from here and will not have to change each file of the relevant class */
#include <iostream>
#include "io_utils.h"
#include <random>
#include <stdio.h>
#include <vector>
#include <map>
#include <array>
#include <list>
#include <fstream>
#include <string>
#include "Colors.h"
#include <time.h>
using std::cin;
using std::cout;
using std::endl;
using std::array;
using std::vector;
using std::string;
using std::map;
using std::list;
using std::pair;
#define EMPTY_CELL ' '// Define the character of the empty cell in the board
using ushort = unsigned short int;
using uint = unsigned int;
using sint = short int;
using uchar = unsigned char;
// Define the numbers that represent steps as consts
enum Keys { COUNTER_CLOCKWISE, CLOCKWISE, DROP, MOVE_LEFT, MOVE_RIGHT, DEFAULT, STOP, SPEED_MODE = 42, ESC = 27 };
#endif
| [
"shakedguy94@gmail.com"
] | shakedguy94@gmail.com |
e068ef174f7e2324f4cd6bed5f74587bea5693cc | f7eab131cd86ba217db9d8246024150931a68011 | /034.Search.for.a.Range.cpp | a7929db79ae0c3d2cd3df16cefb42b854f8d056c | [
"Unlicense"
] | permissive | limingjie/LeetCode | 068cee66139a176c798db3caa84541221211fe2d | 0a303ed71276fb1f94988a4b360f49a6a94a325a | refs/heads/master | 2016-08-03T15:18:02.697782 | 2015-09-16T10:44:13 | 2015-09-16T10:44:13 | 42,525,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | cpp | class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l = 0;
int h = nums.size() - 1;
int m;
vector<int> result;
// find first
while (l <= h)
{
m = l + (h - l) / 2;
if (nums[m] >= target)
{
h = m - 1;
}
else
{
l = m + 1;
}
}
if (l >= nums.size() || nums[l] != target)
{
result.push_back(-1);
result.push_back(-1);
return result;
}
result.push_back(l);
h = nums.size() - 1;
// find last
while (l <= h)
{
m = l + (h - l) / 2;
if (nums[m] <= target)
{
l = m + 1;
}
else
{
h = m - 1;
}
}
result.push_back(l - 1);
return result;
}
};
| [
"limingjie@outlook.com"
] | limingjie@outlook.com |
6ea9b7e7db52f6f90ef820f1dda19e797104e93a | 8e389f896a61cb2abab75616f0f2223aef6eeae7 | /count-occurences-of-anagrams.cpp | 7eae3f802d3908fadf4e8e29dc22af72edf4f035 | [] | no_license | PrateekRanjanSingh/Algorithms | 92304ebef9eb9835e7af1906adf9fb7cc3d5332b | 0cf2a326da21207e0083fd73e407f412b3910c09 | refs/heads/master | 2020-04-09T03:02:23.247855 | 2019-07-31T07:05:26 | 2019-07-31T07:05:26 | 159,966,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | cpp | #include <bits/stdc++.h>
#define MAX 256
using namespace std;
bool compare(int ar1[],int ar2[])
{
for(int i = 0;i<256;i++)
{
if(ar1[i]!=ar2[i]) return false;
}
return true;
}
int main() {
//code
int t;
cin >> t;
while(t--)
{
string s,c;
cin >> s >> c;
int ar1[256] = {0};
int ar2[256] = {0};
for(auto x: c)
{
ar2[x]++;
}
int count = 0;
for(int i = 0;i<c.length();i++)
{
ar1[s[i]]++;
}
if(compare(ar1,ar2)) count++;
for(int i = c.length();i<s.length();i++)
{
ar1[s[i]]++;
ar1[s[i-c.length()]]--;
if(compare(ar1,ar2)) count++;
}
cout << count << endl;
}
return 0;
} | [
"prateekranjansingh@gmail.com"
] | prateekranjansingh@gmail.com |
09484d18a46e402660bdad767decead2a5a7551b | dba51dd933ab25e691adba397c064b48804196a9 | /tdef-list/main.cpp | 6964ac560ef6a1a393abffde226d1a969745465a | [
"MIT"
] | permissive | Alirezaies/DataStructures | 342fd04688beecee2f2dcea5cc77d1f0fd583f84 | 2a4558edede6e412e06d918ec8c8c89d1cb28c64 | refs/heads/master | 2021-01-23T16:50:23.870217 | 2017-07-01T07:17:42 | 2017-07-01T07:17:42 | 93,306,127 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | cpp | #include "include/TArray.h"
#include <iostream>
using namespace std;
int main(){
TArray s(10);
s.append('C');
s.append('F');
s.append('H');
s.Traverse();
cout<<"==========="<<endl;
cout<<"Item 0: "<<s.getItem(0)<<endl;
cout<<"==========="<<endl;
s.add('K', 0);
s.add('K', 2);
s.Traverse();
return 0;
}
| [
"sadegh@webgo.ir"
] | sadegh@webgo.ir |
0b6c87acc4c06776cf09ff9f17e424c76b60008e | e97481996e8d4b58e1c390fb41ffa5166acff0ff | /nall/mosaic/parser.hpp | 5d68cd83f0503db28a83fb1d0759137a7665716c | [
"ISC"
] | permissive | kode54/resampler_iir | 9dafd38fbe5f3a903933a826b73f37fd0228dc0a | 95671c6735e964c8dd93dd0fc96cdbdc137aa4db | refs/heads/master | 2021-01-20T18:20:34.052590 | 2016-06-04T01:04:07 | 2016-06-04T01:04:07 | 60,292,227 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,613 | hpp | #pragma once
namespace nall { namespace mosaic {
struct parser {
//export from bitstream to canvas
auto load(bitstream& stream, uint64_t offset, context& ctx, uint width, uint height) -> void {
canvas.allocate(width, height);
canvas.fill(ctx.paddingColor);
parse(1, stream, offset, ctx, width, height);
}
//import from canvas to bitstream
auto save(bitstream& stream, uint64_t offset, context& ctx) -> bool {
if(stream.readonly) return false;
parse(0, stream, offset, ctx, canvas.width(), canvas.height());
return true;
}
private:
auto read(uint x, uint y) const -> uint32_t {
uint addr = y * canvas.width() + x;
if(addr >= canvas.width() * canvas.height()) return 0u;
auto buffer = (uint32_t*)canvas.data();
return buffer[addr];
}
auto write(uint x, uint y, uint32_t data) -> void {
uint addr = y * canvas.width() + x;
if(addr >= canvas.width() * canvas.height()) return;
auto buffer = (uint32_t*)canvas.data();
buffer[addr] = data;
}
auto parse(bool load, bitstream& stream, uint64_t offset, context& ctx, uint width, uint height) -> void {
stream.endian = ctx.endian;
uint canvasWidth = width / (ctx.mosaicWidth * ctx.tileWidth * ctx.blockWidth + ctx.paddingWidth);
uint canvasHeight = height / (ctx.mosaicHeight * ctx.tileHeight * ctx.blockHeight + ctx.paddingHeight);
uint bitsPerBlock = ctx.depth * ctx.blockWidth * ctx.blockHeight;
uint objectOffset = 0;
for(uint objectY = 0; objectY < canvasHeight; objectY++) {
for(uint objectX = 0; objectX < canvasWidth; objectX++) {
if(objectOffset >= ctx.count && ctx.count > 0) break;
uint objectIX = objectX * ctx.objectWidth();
uint objectIY = objectY * ctx.objectHeight();
objectOffset++;
uint mosaicOffset = 0;
for(uint mosaicY = 0; mosaicY < ctx.mosaicHeight; mosaicY++) {
for(uint mosaicX = 0; mosaicX < ctx.mosaicWidth; mosaicX++) {
uint mosaicData = ctx.mosaic(mosaicOffset, mosaicOffset);
uint mosaicIX = (mosaicData % ctx.mosaicWidth) * (ctx.tileWidth * ctx.blockWidth);
uint mosaicIY = (mosaicData / ctx.mosaicWidth) * (ctx.tileHeight * ctx.blockHeight);
mosaicOffset++;
uint tileOffset = 0;
for(uint tileY = 0; tileY < ctx.tileHeight; tileY++) {
for(uint tileX = 0; tileX < ctx.tileWidth; tileX++) {
uint tileData = ctx.tile(tileOffset, tileOffset);
uint tileIX = (tileData % ctx.tileWidth) * ctx.blockWidth;
uint tileIY = (tileData / ctx.tileWidth) * ctx.blockHeight;
tileOffset++;
uint blockOffset = 0;
for(uint blockY = 0; blockY < ctx.blockHeight; blockY++) {
for(uint blockX = 0; blockX < ctx.blockWidth; blockX++) {
if(load) {
uint palette = 0;
for(uint n = 0; n < ctx.depth; n++) {
uint index = blockOffset++;
if(ctx.order == 1) index = (index % ctx.depth) * ctx.blockWidth * ctx.blockHeight + (index / ctx.depth);
palette |= stream.read(offset + ctx.block(index, index)) << n;
}
write(
objectIX + mosaicIX + tileIX + blockX,
objectIY + mosaicIY + tileIY + blockY,
ctx.palette(palette, palette)
);
} else /* save */ {
uint32_t palette = read(
objectIX + mosaicIX + tileIX + blockX,
objectIY + mosaicIY + tileIY + blockY
);
for(uint n = 0; n < ctx.depth; n++) {
uint index = blockOffset++;
if(ctx.order == 1) index = (index % ctx.depth) * ctx.blockWidth * ctx.blockHeight + (index / ctx.depth);
stream.write(offset + ctx.block(index, index), palette & 1);
palette >>= 1;
}
}
} //blockX
} //blockY
offset += ctx.blockStride;
} //tileX
offset += ctx.blockOffset;
} //tileY
offset += ctx.tileStride;
} //mosaicX
offset += ctx.tileOffset;
} //mosaicY
offset += ctx.mosaicStride;
} //objectX
offset += ctx.mosaicOffset;
} //objectY
}
image canvas;
};
}}
| [
"kode54@gmail.com"
] | kode54@gmail.com |
4b0321d406120bee0ba9ff0f82c28212b0d64088 | 4f371e57ae035bd57c3de5c6190274d271c26d33 | /cpp/binary.cpp | ecd95a483e945e646c5fde247f184f3d96d2a9e0 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jailuthra/misc | 3df82fde3d28156099153a8f658da349d1cf4a85 | 782d6a8e6154f1a52a3b818bde26ac07e00912c2 | refs/heads/master | 2021-05-16T02:34:19.860380 | 2019-10-07T08:22:21 | 2020-04-22T01:37:04 | 6,692,678 | 0 | 1 | MIT | 2020-04-22T01:37:06 | 2012-11-14T18:34:08 | C | UTF-8 | C++ | false | false | 881 | cpp | #include<iostream>
using namespace std;
int main() {
int i, n, num, beg, end, mid, a[100], pos, flag=0;
cout << "Enter the size of the array: ";
cin >> n;
cout << "Enter the elements in ascending order of magnitude, one by one:\n";
for (i=0; i<n; i++)
cin >> a[i];
beg = 0;
end = n-1;
mid = (beg + end)/2;
cout << "Enter the number to search for: ";
cin >> num;
do {
if (num == a[mid]) {
pos = mid+1;
flag = 1;
break;
}
else if (num < a[mid])
end = mid-1;
else if (num > a[mid])
beg = mid+1;
mid = (beg + end)/2;
} while (beg != end);
if (flag == 1)
cout << "\nThe number was found at position: " << pos << endl;
else
cout << "\nThe number was not found in the given array" << endl;
return 0;
}
| [
"me@jailuthra.in"
] | me@jailuthra.in |
9fb62648e7f50d9df404100717c76480710acc92 | 0b63fa8325233e25478b76d0b4a9a6ee3070056d | /src/appleseed/foundation/utility/xmlelement.h | 9f827ae98500567f674b88dbbd2763b9b0655cc4 | [
"MIT"
] | permissive | hipopotamo-hipotalamo/appleseed | e8c61ccec64baf01b6aeb3cde4dd3031d37ece17 | eaf07e3e602218a35711e7495ac633ce210c6078 | refs/heads/master | 2020-12-07T02:39:27.454003 | 2013-10-29T13:10:59 | 2013-10-29T13:10:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,307 | h |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#ifndef APPLESEED_FOUNDATION_UTILITY_XMLELEMENT_H
#define APPLESEED_FOUNDATION_UTILITY_XMLELEMENT_H
// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/foreach.h"
#include "foundation/utility/indenter.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <cassert>
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
namespace foundation
{
//
// A class representing a XML element.
//
class XMLElement
{
public:
// Constructor, opens the element.
XMLElement(
const std::string& name,
std::FILE* file,
Indenter& indenter);
// Destructor, closes the element.
~XMLElement();
// Append an attribute to the element.
template <typename T>
void add_attribute(
const std::string& name,
const T& value);
// Write the element.
void write(const bool has_content);
// Close the element.
void close();
private:
typedef std::pair<std::string, std::string> Attribute;
typedef std::vector<Attribute> AttributeVector;
const std::string m_name;
std::FILE* m_file;
Indenter& m_indenter;
AttributeVector m_attributes;
bool m_opened;
};
//
// An utility function to write a dictionary to an XML file.
//
// Example: a dictionary containing two scalar values "x" and "y"
// and a child dictionary "nested" containing a scalar value "z"
// will be written as follow:
//
// <parameter name="x" value="17" />
// <parameter name="y" value="42" />
// <parameters name="nested">
// <parameter name="z" value="66" />
// </parameters>
//
void write_dictionary(
const Dictionary& dictionary,
std::FILE* file,
Indenter& indenter);
//
// Implementation.
//
inline XMLElement::XMLElement(
const std::string& name,
std::FILE* file,
Indenter& indenter)
: m_name(name)
, m_file(file)
, m_indenter(indenter)
, m_opened(false)
{
}
inline XMLElement::~XMLElement()
{
close();
}
template <typename T>
void XMLElement::add_attribute(
const std::string& name,
const T& value)
{
assert(!m_opened);
m_attributes.push_back(std::make_pair(name, to_string(value)));
}
inline void XMLElement::write(const bool has_content)
{
assert(!m_opened);
std::fprintf(m_file, "%s<%s", m_indenter.c_str(), m_name.c_str());
for (const_each<AttributeVector> i = m_attributes; i; ++i)
{
const std::string attribute_value = replace_special_xml_characters(i->second);
std::fprintf(m_file, " %s=\"%s\"", i->first.c_str(), attribute_value.c_str());
}
if (has_content)
{
std::fprintf(m_file, ">\n");
++m_indenter;
m_opened = true;
}
else
{
std::fprintf(m_file, " />\n");
}
}
inline void XMLElement::close()
{
if (m_opened)
{
--m_indenter;
std::fprintf(m_file, "%s</%s>\n", m_indenter.c_str(), m_name.c_str());
m_opened = false;
}
}
inline void write_dictionary(
const Dictionary& dictionary,
std::FILE* file,
Indenter& indenter)
{
for (const_each<StringDictionary> i = dictionary.strings(); i; ++i)
{
XMLElement element("parameter", file, indenter);
element.add_attribute("name", i->name());
element.add_attribute("value", i->value<std::string>());
element.write(false);
}
for (const_each<DictionaryDictionary> i = dictionary.dictionaries(); i; ++i)
{
XMLElement element("parameters", file, indenter);
element.add_attribute("name", i->name());
element.write(true);
write_dictionary(i->value(), file, indenter);
}
}
} // namespace foundation
#endif // !APPLESEED_FOUNDATION_UTILITY_XMLELEMENT_H
| [
"beaune@aist.enst.fr"
] | beaune@aist.enst.fr |
24a8ec802831ae3a87b95a5f69c8013751f4b74e | d9fa902ccf801f9ab78b316e35573e21328754e8 | /src/Werk/Utility/Action.cpp | a315f24b5bbafdd634a1bd7fd8cb947485fabd88 | [
"MIT"
] | permissive | kelvinxue/Werk | 9f3d3925067c7303a2a73cc02aed98a17e7229b5 | d972df393d0e2945ea3d2a388c11e4421b9db5d9 | refs/heads/master | 2020-03-27T14:54:05.134853 | 2018-01-05T02:04:55 | 2018-01-05T02:04:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,234 | cpp |
/*
* Copyright (c) 2015-2018 Agalmic Ventures LLC (www.agalmicventures.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "Action.hpp"
namespace werk
{
NullAction NULL_ACTION("Null");
}
| [
"ihutchinson@agalmicventures.com"
] | ihutchinson@agalmicventures.com |
bc0679f28b5ee780523ba98919ca70e73b655901 | 8726add10e5cfcb399b68456e1068c0e09fd8111 | /HelloWorld.cxx | 3a7e0a3bfa2ddc3c807504a2b55d499622f3f726 | [] | no_license | El-Sadeh/DDS-Hello-world | f537b6737af0e13d03c85eab2f918a8cee288731 | 64e1a4aeae59200c9f1b1a6aec34d4c24f795f59 | refs/heads/master | 2020-08-21T21:10:27.894170 | 2019-10-24T05:11:44 | 2019-10-24T05:11:44 | 216,246,407 | 0 | 0 | null | 2019-10-22T11:27:50 | 2019-10-19T17:41:30 | C++ | UTF-8 | C++ | false | false | 6,819 | cxx |
/*
WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY.
This file was generated from HelloWorld.idl using "rtiddsgen".
The rtiddsgen tool is part of the RTI Connext distribution.
For more information, type 'rtiddsgen -help' at a command shell
or consult the RTI Connext manual.
*/
#include <iosfwd>
#include <iomanip>
#include "rti/topic/cdr/Serialization.hpp"
#include "HelloWorld.hpp"
#include "HelloWorldPlugin.hpp"
#include <rti/util/ostream_operators.hpp>
// ---- TemperatureStruct:
TemperatureStruct::TemperatureStruct() :
m_temp_ (0) {
}
TemperatureStruct::TemperatureStruct (
int16_t temp)
:
m_temp_( temp ) {
}
#ifdef RTI_CXX11_RVALUE_REFERENCES
#ifdef RTI_CXX11_NO_IMPLICIT_MOVE_OPERATIONS
TemperatureStruct::TemperatureStruct(TemperatureStruct&& other_) OMG_NOEXCEPT :m_temp_ (std::move(other_.m_temp_))
{
}
TemperatureStruct& TemperatureStruct::operator=(TemperatureStruct&& other_) OMG_NOEXCEPT {
TemperatureStruct tmp(std::move(other_));
swap(tmp);
return *this;
}
#endif
#endif
void TemperatureStruct::swap(TemperatureStruct& other_) OMG_NOEXCEPT
{
using std::swap;
swap(m_temp_, other_.m_temp_);
}
bool TemperatureStruct::operator == (const TemperatureStruct& other_) const {
if (m_temp_ != other_.m_temp_) {
return false;
}
return true;
}
bool TemperatureStruct::operator != (const TemperatureStruct& other_) const {
return !this->operator ==(other_);
}
// --- Getters and Setters: -------------------------------------------------
int16_t& TemperatureStruct::temp() OMG_NOEXCEPT {
return m_temp_;
}
const int16_t& TemperatureStruct::temp() const OMG_NOEXCEPT {
return m_temp_;
}
void TemperatureStruct::temp(int16_t value) {
m_temp_ = value;
}
std::ostream& operator << (std::ostream& o,const TemperatureStruct& sample)
{
rti::util::StreamFlagSaver flag_saver (o);
o <<"[";
o << "temp: " << sample.temp() ;
o <<"]";
return o;
}
// --- Type traits: -------------------------------------------------
namespace rti {
namespace topic {
template<>
struct native_type_code<TemperatureStruct> {
static DDS_TypeCode * get()
{
static RTIBool is_initialized = RTI_FALSE;
static DDS_TypeCode_Member TemperatureStruct_g_tc_members[1]=
{
{
(char *)"temp",/* Member name */
{
0,/* Representation ID */
DDS_BOOLEAN_FALSE,/* Is a pointer? */
-1, /* Bitfield bits */
NULL/* Member type code is assigned later */
},
0, /* Ignored */
0, /* Ignored */
0, /* Ignored */
NULL, /* Ignored */
RTI_CDR_REQUIRED_MEMBER, /* Is a key? */
DDS_PUBLIC_MEMBER,/* Member visibility */
1,
NULL/* Ignored */
}
};
static DDS_TypeCode TemperatureStruct_g_tc =
{{
DDS_TK_STRUCT,/* Kind */
DDS_BOOLEAN_FALSE, /* Ignored */
-1, /*Ignored*/
(char *)"TemperatureStruct", /* Name */
NULL, /* Ignored */
0, /* Ignored */
0, /* Ignored */
NULL, /* Ignored */
1, /* Number of members */
TemperatureStruct_g_tc_members, /* Members */
DDS_VM_NONE /* Ignored */
}}; /* Type code for TemperatureStruct*/
if (is_initialized) {
return &TemperatureStruct_g_tc;
}
TemperatureStruct_g_tc_members[0]._representation._typeCode = (RTICdrTypeCode *)&DDS_g_tc_short;
is_initialized = RTI_TRUE;
return &TemperatureStruct_g_tc;
}
}; // native_type_code
const dds::core::xtypes::StructType& dynamic_type<TemperatureStruct>::get()
{
return static_cast<const dds::core::xtypes::StructType&>(
rti::core::native_conversions::cast_from_native<dds::core::xtypes::DynamicType>(
*(native_type_code<TemperatureStruct>::get())));
}
}
}
namespace dds {
namespace topic {
void topic_type_support<TemperatureStruct>:: register_type(
dds::domain::DomainParticipant& participant,
const std::string& type_name)
{
rti::domain::register_type_plugin(
participant,
type_name,
TemperatureStructPlugin_new,
TemperatureStructPlugin_delete);
}
std::vector<char>& topic_type_support<TemperatureStruct>::to_cdr_buffer(
std::vector<char>& buffer, const TemperatureStruct& sample)
{
// First get the length of the buffer
unsigned int length = 0;
RTIBool ok = TemperatureStructPlugin_serialize_to_cdr_buffer(
NULL,
&length,
&sample);
rti::core::check_return_code(
ok ? DDS_RETCODE_OK : DDS_RETCODE_ERROR,
"Failed to calculate cdr buffer size");
// Create a vector with that size and copy the cdr buffer into it
buffer.resize(length);
ok = TemperatureStructPlugin_serialize_to_cdr_buffer(
&buffer[0],
&length,
&sample);
rti::core::check_return_code(
ok ? DDS_RETCODE_OK : DDS_RETCODE_ERROR,
"Failed to copy cdr buffer");
return buffer;
}
void topic_type_support<TemperatureStruct>::from_cdr_buffer(TemperatureStruct& sample,
const std::vector<char>& buffer)
{
RTIBool ok = TemperatureStructPlugin_deserialize_from_cdr_buffer(
&sample,
&buffer[0],
static_cast<unsigned int>(buffer.size()));
rti::core::check_return_code(ok ? DDS_RETCODE_OK : DDS_RETCODE_ERROR,
"Failed to create TemperatureStruct from cdr buffer");
}
void topic_type_support<TemperatureStruct>::reset_sample(TemperatureStruct& sample)
{
rti::topic::reset_sample(sample.temp());
}
void topic_type_support<TemperatureStruct>::allocate_sample(TemperatureStruct& sample, int, int)
{
}
}
}
| [
"elelbaz10@hotmail.com"
] | elelbaz10@hotmail.com |
d415f2987b6e9639fec55ee23c1a7ab5dd2f6a9b | 2fa764b33e15edd3b53175456f7df61a594f0bb5 | /appseed/aura/primitive/collection/collection_key_sort_array.cpp | f721b925a3dd0ee6d24ede3e4e4f74bb2740a6c7 | [] | no_license | PeterAlfonsLoch/app | 5f6ac8f92d7f468bc99e0811537380fcbd828f65 | 268d0c7083d9be366529e4049adedc71d90e516e | refs/heads/master | 2021-01-01T17:44:15.914503 | 2017-07-23T16:58:08 | 2017-07-23T16:58:08 | 98,142,329 | 1 | 0 | null | 2017-07-24T02:44:10 | 2017-07-24T02:44:10 | null | UTF-8 | C++ | false | false | 25 | cpp | //#include "framework.h"
| [
"camilox_porting_to_android@ca2.cc"
] | camilox_porting_to_android@ca2.cc |
add2850a9928772499918a9ae1ff604212d0ea80 | cf1e0056e6ae530ff8ef1d25df3d973dea16bb0c | /Source/GA/GAAudioManager.cpp | 6267f4b0a03001f5427c2da40507a5dee980826c | [
"Apache-2.0"
] | permissive | JackHarb89/ga2014 | aa8c2a6ed4cb7031e8688dcfab6b66d013746c53 | 2d63e0f423ede52071605039a64eed4db792cb43 | refs/heads/master | 2016-09-06T08:49:36.178535 | 2014-08-08T05:28:59 | 2014-08-08T05:28:59 | 32,894,085 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 180 | cpp | #include "GA.h"
#include "GAEnemy.h"
#include "GAAudioManager.h"
AGAAudioManager::AGAAudioManager(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{
} | [
"Jack_Harb@gmx.de@435454b9-d0bb-46eb-8854-52d2cd3ebfb7"
] | Jack_Harb@gmx.de@435454b9-d0bb-46eb-8854-52d2cd3ebfb7 |
a764755d2c576c94078e700ec70790a0ed24c099 | 33c4e40cb9a97b289229140d258dc934e70582a8 | /mcg/src/external/BSR/include/concurrent/threads/synchronization/synchronizables/synchronizable.hh | c9499d83db9e2f25649d3f67e8c93e2ea4864695 | [
"AGPL-3.0-or-later",
"AGPL-3.0-only",
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | permissive | jinlinyi/rcnn-depth | f6930ceee71593b1fd6cc9ab21cc6b9143f61962 | c00da4a8b3df43a5df5e44d1820feb30bd6b2d7d | refs/heads/master | 2020-03-27T02:06:14.194595 | 2018-09-01T05:16:09 | 2018-09-01T05:16:09 | 145,766,652 | 0 | 0 | BSD-2-Clause | 2018-08-22T21:49:47 | 2018-08-22T21:49:47 | null | UTF-8 | C++ | false | false | 2,906 | hh | /*
* Synchronizable interface.
*
* This abstract base class provides an interface for controlling read and
* write access to objects by different threads. A thread requesting a
* particular type of access is suspended until that request is granted.
*/
#ifndef CONCURRENT__THREADS__SYNCHRONIZATION__SYNCHRONIZABLES__SYNCHRONIZABLE_HH
#define CONCURRENT__THREADS__SYNCHRONIZATION__SYNCHRONIZABLES__SYNCHRONIZABLE_HH
namespace concurrent {
namespace threads {
namespace synchronization {
namespace synchronizables {
/*
* Abstract base class for synchronization capabilities.
*/
class synchronizable {
public:
/*
* Constructor.
*/
synchronizable();
/*
* Destructor.
*/
virtual ~synchronizable();
/*
* Claim/release exclusive access (abstract interface).
*/
virtual void abstract_lock() const = 0;
virtual void abstract_unlock() const = 0;
/*
* Claim/release read access (abstract interface).
*/
virtual void abstract_read_lock() const = 0;
virtual void abstract_read_unlock() const = 0;
/*
* Claim/release write access (abstract interface).
*/
virtual void abstract_write_lock() const = 0;
virtual void abstract_write_unlock() const = 0;
/*
* Claim/release exclusive access to two synchronizable objects.
*/
static void lock(const synchronizable&, const synchronizable&);
static void unlock(const synchronizable&, const synchronizable&);
/*
* Claim/release read access to two synchronizable objects.
*/
static void read_lock(const synchronizable&, const synchronizable&);
static void read_unlock(const synchronizable&, const synchronizable&);
/*
* Claim/release write access to two synchronizable objects.
*/
static void write_lock(const synchronizable&, const synchronizable&);
static void write_unlock(const synchronizable&, const synchronizable&);
/*
* Claim/release read access to the first object and write access to the
* second.
*/
static void read_write_lock(const synchronizable&, const synchronizable&);
static void read_write_unlock(const synchronizable&, const synchronizable&);
protected:
/*
* Constructor.
* Initialize the synchronizable object to have the given id.
*/
explicit synchronizable(unsigned long);
/*
* Get identity of synchronizable object.
*/
inline unsigned long syn_id() const;
private:
/*
* Identity of synchronizable object.
*/
unsigned long _id;
/*
* Issue the next available identity.
* The zero id is reserved for unsynchronized objects.
*/
static unsigned long id_next();
};
/*
* Get identity of synchronizable object.
*/
inline unsigned long synchronizable::syn_id() const {
return _id;
}
} /* namespace synchronizables */
} /* namespace synchronization */
} /* namespace threads */
} /* namespace concurrent */
#endif
| [
"saurabhgupta.iitd@gmail.com"
] | saurabhgupta.iitd@gmail.com |
d083605808c6abdb36dc6b1e45c6ed168b9da357 | 0308ca5b152a082c1a206a1a136fd45e79b48143 | /usvao/prototype/ipac/stk/include/ipac/stk/json/JSONOutput.inl | f4ab03c33a14c768e89e0a8e989a038a856410c4 | [] | no_license | Schwarzam/usvirtualobservatory | b609bf21a09c187b70e311a4c857516284049c31 | 53fe6c14cc9312d048326acfa25377e3eac59858 | refs/heads/master | 2022-03-28T23:38:58.847018 | 2019-11-27T16:05:47 | 2019-11-27T16:05:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,685 | inl | /*************************************************************************
Copyright (c) 2014, California Institute of Technology, Pasadena,
California, under cooperative agreement 0834235 between the California
Institute of Technology and the National Science Foundation/National
Aeronautics and Space Administration.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
of this BSD 3-clause license are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This software was developed by the Infrared Processing and Analysis
Center (IPAC) for the Virtual Astronomical Observatory (VAO), jointly
funded by NSF and NASA, and managed by the VAO, LLC, a non-profit
501(c)(3) organization registered in the District of Columbia and a
collaborative effort of the Association of Universities for Research
in Astronomy (AURA) and the Associated Universities, Inc. (AUI).
*************************************************************************/
/** \file
\brief Inline and templated member function definitions for JSONOutput.h
\author Serge Monkewitz
*/
#ifndef IPAC_STK_JSON_JSONOUTPUT_H_
# error This file must be included from ipac/stk/json/JSONOutput.h
#else
# ifndef IPAC_STK_JSON_JSONOUTPUT_INL_
# define IPAC_STK_JSON_JSONOUTPUT_INL_
#include <sstream>
namespace ipac { namespace stk { namespace json {
/** Returns the formatting options for this JSONOutput.
*/
inline FormattingOptions const & JSONOutput::getFormattingOptions() const {
return _opts;
}
/** Returns the underlying output stream or null.
*/
inline std::ostream * JSONOutput::getOutputStream() {
return _out;
}
/** Returns the underlying Value or a null Value.
*/
inline Value const JSONOutput::getValue() const {
return _value;
}
/** Outputs the given object. A free function
\code outputJSON(T const &, JSONOutput &) \endcode
must have been defined in order for compilation to succeed.
*/
template <typename T>
inline JSONOutput & JSONOutput::value(T const & val) {
Transaction tx(*this);
outputJSON(val, *this);
tx.commit();
return *this;
}
//@{
/** Outputs the value pointed to or null.
*/
template <typename T> inline JSONOutput & JSONOutput::value(T const * val) {
if (!val) {
return value();
}
return value(*val);
}
template <typename T>
inline JSONOutput & JSONOutput::value(boost::shared_ptr<T> const & val) {
return value(val.get());
}
template <typename T>
inline JSONOutput & JSONOutput::value(boost::shared_ptr<T const> const & val) {
return value(val.get());
}
template <typename T>
inline JSONOutput & JSONOutput::value(boost::scoped_ptr<T> val) {
return value(val.get());
}
template <typename T>
inline JSONOutput & JSONOutput::value(boost::scoped_ptr<T const> val) {
return value(val.get());
}
//@}
/** Outputs the values in the given range as a JSON array.
*/
template <typename ForwardsIterator>
JSONOutput & JSONOutput::array(ForwardsIterator begin,
ForwardsIterator end)
{
Transaction tx(*this);
array();
for (; begin != end; ++begin) {
value(*begin);
}
close();
tx.commit();
return *this;
}
/** Outputs \c k/v as a key/value pair in a JSON object.
*/
template <typename T>
JSONOutput & JSONOutput::pair(std::string const & k, T const & v) {
Transaction tx(*this);
key(k);
value(v);
tx.commit();
return *this;
}
/** Outputs \c kv as a key/value pair in a JSON object.
*/
template <typename T>
inline JSONOutput & JSONOutput::pair(std::pair<std::string const, T> const & kv) {
return pair(kv.first, kv.second);
}
/** Outputs a map<std::string, T> as a JSON object.
*/
template <typename T>
JSONOutput & JSONOutput::object(std::map<std::string, T> const & map) {
typedef typename std::map<std::string, T>::const_iterator MapIter;
Transaction tx(*this);
object();
for (MapIter i(map.begin()), e(map.end()); i != e; ++i) {
pair(*i);
}
close();
tx.commit();
return *this;
}
/** Returns a JSON string representation of \c obj. A free function
\code outputJSON(T const &, JSONOutput &) \endcode must have been
defined in order for compilation to succeed.
*/
template <typename T>
std::string const JSONOutput::toString(T const & obj,
FormattingOptions const & opts)
{
std::ostringstream oss;
JSONOutput out(oss, opts);
outputJSON(obj, out);
return oss.str();
}
/** Returns a representation of \c obj as a heirarchical value. A free
function \code outputJSON(T const &, JSONOutput &) \endcode must have
been defined in order for compilation to succeed.
*/
template <typename T>
Value const JSONOutput::toValue(T const & obj) {
JSONOutput out(true);
outputJSON(obj, out);
return out.getValue();
}
/** Closes all currently open JSON objects and arrays.
*/
inline JSONOutput & JSONOutput::closeAll() {
return close(_stack.size());
}
inline std::string const JSONOutput::encode(char const * s) {
return encode(std::string(s));
}
inline std::string const JSONOutput::encode(char const * s, size_t n) {
return encode(std::string(s, n));
}
inline void JSONOutput::indent() {
indent(_stack.size());
}
}}} // namespace ipac::stk::json
# endif // IPAC_STK_JSON_JSONOUTPUT_INL_
#endif // IPAC_STK_JSON_JSONOUTPUT_H_
| [
"usvirtualobservatory@5a1e9bf7-f4d4-f7d4-5b89-e7d39643c4b5"
] | usvirtualobservatory@5a1e9bf7-f4d4-f7d4-5b89-e7d39643c4b5 |
399e8343414249682be50d7d0d63ba261f42847e | ca3449d1291ae8e93f88a56c5c9032103f730106 | /LilEngie/Core/src/Entity/Components/Text.h | df0fd9d91cfcaffcb24d3f3e27d1aab6483c6f3a | [
"MIT"
] | permissive | Nordaj/LilEngie | f1d38304ffabb55f2d21272179db0d3b2697e6c4 | 453cee13c45ae33abe2665e1446fc90e67b1117a | refs/heads/master | 2020-03-18T17:28:15.097151 | 2018-09-02T04:10:48 | 2018-09-02T04:10:48 | 135,031,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | h | #pragma once
#include <string>
#include <glm/glm.hpp>
#include <Entity/Component.h>
#include <Graphics/Text/TextRenderer.h>
class Text : public Component
{
public:
TextRenderer renderer;
Text(GameObject *obj);
COMPONENT_ID("Text")
};
| [
"Nordajnapmach@gmail.com"
] | Nordajnapmach@gmail.com |
9ce16692f7e6562d181eb15eee5e75d15b3ffec8 | 09c8013df6d4ca010706b5de1ec48b259f395e76 | /MiniJVM/include/buffer.h | e8b2b7682316b4eb60a964a3cc4cf94e780fa5b8 | [
"MIT"
] | permissive | lanrobin/minijvm | e048270c571327d4972678e1f0215b90684c477e | d6056012494656669a6665c981e6b23d8d121df8 | refs/heads/master | 2022-09-09T08:13:00.287176 | 2020-05-31T14:25:33 | 2020-05-31T14:25:33 | 258,674,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,016 | h | #ifndef __JVM_BUFFER_READER__
#define __JVM_BUFFER_READER__
#include "base_type.h"
#include "platform.h"
#include <iostream>
using std::istream;
struct Buffer {
private:
u1* buffer;
size_t read_pos;
size_t buffer_size;
// 这个有可能没有。
wstring mappingFromFile;
public:
Buffer(istream& is, const wstring & fromFile = std::wstring());
Buffer(const char* buf, size_t offset, size_t count, const wstring& fromFile = std::wstring());
u1 readu1();
u2 readu2();
u4 readu4();
u1 peaku1();
u2 peaku2();
u4 peaku4();
size_t rewind(size_t count);
size_t size() const;
size_t pos() const;
void resetReadPos();
void dumpToFile(const string& path);
void dumpToFile(const wstring& path);
wstring getMappingFile() const { return mappingFromFile; }
~Buffer();
private:
void init(const char* buf, size_t offset, size_t count);
public:
static shared_ptr<Buffer> fromFile(const string& filePath);
static shared_ptr<Buffer> fromFile(const wstring& filePath);
};
#endif //__JVM_BUFFER_READER__ | [
"rorbbin@gmail.com"
] | rorbbin@gmail.com |
6180943f293eae98e8e8b668b157f908c98a6829 | 240c51a603afb9d587c0bb24fc05fb15c9c5138f | /sketchbook/libraries/Motor/Motor.h | 3e5107e34610e01238b3af5bbe4f1b32d2d262a4 | [] | no_license | RingOfFireOrg/FT2014 | b8a294ccb4cb860dfb7fb8204bf28a383dfc27d8 | dec11c8572db0cf48a8fa7652e6cf78c6749c4dc | refs/heads/master | 2021-01-19T14:07:35.183855 | 2014-12-18T02:58:15 | 2014-12-18T02:58:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 903 | h | /*
* This is the implementation file that goes with Motor.h
* It gives control of a motor attached to DFRobotics Motor Shield for the
* Arduino. The constructor needs the pin numbers for the enable pin
* that controls direction (HIGH/LOW) and for the pwm pin that controls
* speed. It should work for pretty much any pwm controlled motor even with
* other controllers.
* author - Rob Mackie
* date - 10/20/2013
*/
#ifndef __MOTOR__
#define __MOTOR__
#include "Arduino.h"
class Motor {
public:
enum motor_id_t {MOTOR_1, MOTOR_2};
Motor(motor_id_t motor_id);
void setup(void);
void forward(unsigned char speed);
void reverse(unsigned char speed);
void stop(void);
protected:
static int const FORWARD = HIGH;
static int const REVERSE = LOW;
Motor(int e, int m);
private:
int direction_pin;
int speed_pin;
};
#endif //__MOTOR__
| [
"slaveofschool@gmail.com"
] | slaveofschool@gmail.com |
5c667617f632dc0621f71f0a15586a79046136cf | 2da0ea7ada36da3d32bd086b58877467e1b725ae | /1383(STL字符串查找).cpp | a0d03053ce563722d81052c038b602a62d6e13f1 | [] | no_license | czgggggggg/CUGBOJ | 7debccb831995a03e67bfffc9b1fd72380d24a31 | 270e4d8dbc19140e61b6041a598332cba885d852 | refs/heads/master | 2020-04-26T12:33:37.509721 | 2019-03-03T17:22:22 | 2019-03-03T17:22:22 | 173,553,715 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 501 | cpp | #include<iostream>
#include<set>
#include<string>
using namespace std;
int main(){
int n,m;
string str;
cin>>n>>m;
set<string> s;
for(int i=0;i<n;i++){
cin>>str;
s.insert(str);
}
set<string>::iterator iter;
int a[m];
for(int i=0;i<m;i++){
cin>>str;
if((iter=s.find(str))!=s.end())
a[i]=1;
else
a[i]=0;
}
for(int i=0;i<m;i++)
cout<<a[i]<<endl;
return 0;
}
| [
"noreply@github.com"
] | czgggggggg.noreply@github.com |
c3a5f92df2a2d2bc7a423324c71eea4f6ea27e9f | b1fa90f76f916d29b5d68b7048268f4d8b71c111 | /src/lightspeed/base/serialize/pointers.h | c6d9b38d7a217b03af7f28c9f18396efd49cabaf | [
"MIT"
] | permissive | ondra-novak/lightspeed | 742092dbf5925027a7c4281f61b008fcd18a40e5 | 21028adb7e47bebd264e02978da5edd7463ef621 | refs/heads/master | 2021-01-24T06:35:55.151750 | 2019-12-13T12:56:21 | 2019-12-13T12:56:21 | 27,496,470 | 2 | 2 | null | 2015-08-19T14:50:36 | 2014-12-03T16:32:35 | C++ | UTF-8 | C++ | false | false | 3,393 | h | #pragma once
#include "basicTypes.h"
#include "serializer.h"
#include "../containers/optional.h"
namespace LightSpeed {
///Interface to serialize pointer
/**
Interface need define type of used serializer and type of base,
which is common to all objects that will be serialized by this interface.
Interface itself can be bind to the another base, but there must be
possibility to make dynamic_cast between the bases.
* @tparam Serializer type of serializer used to serialize pointer
* @rparam BaseT common base type
*/
template<typename Serializer, typename BaseT>
class IPointerSerializer: public IService {
public:
///Destructor
virtual ~IPointerSerializer () {}
///Loads instance from the archive
/**
* @param arch archive to read, must be in loading state
* @return pointer to created instance or NULL (it is valid value)
*/
virtual BaseT *load(Serializer &arch) const = 0;
///Stores instance to the archive
/**
* @param arch archive to write into. Must be in storing state
* @param instance instance to store
*/
virtual void store(Serializer &arch, const BaseT *instance) const = 0;
///Destroyes the instance
/** Because caller don't have information about creation and allocation
of the instance, it cannot call delete to destroy instance. This
function must handle destroying.
* @param instance instance to destroy
*/
virtual void destroy(BaseT *instance) const = 0;
virtual TypeInfo getInterfaceType() const {
return typeid(IPointerSerializer);
}
};
///Specialization to serialize pointer
/**
* When pointer is serialized, it need to solve situation, when
* pointer points to derived class. Then it is not possible to simply
* call serialize method, because it will serialize only base part
* of the object, and mostly it can be impossible to serialize pointer,
* when it is abstract interface.
*
* This specialization expects section that defines implementation of
* the IPointerSerializer interface. Implementation must implement
* methods load(), store() and destroy() to handle pointer serialization
* It also can choose best way, how to create object, especially, ho
* to allocate object, because serializer itself doesn't define allocator
* to allocate these objects.
*
* @param Type of pointer that is expected in the serialization script.
*
* @section requires Requires
*
* It requires IPointerSerializer::AsSection instance, that contains
* pointer to an object implementing IPointerSerializer for given pointer type.
* Note that you have to declare separate section for every type of the
* pointer that can appear in the serialization script. To allow
* sharing one instance of IPointerSerializer between many base-pointer
* types, you can use class SrlzPtrConvert
*
* SrlzPtrConvert<Serializer,From,To>
*
*
*
*/
template<typename T>
class Serializable<T *> {
public:
template<typename Serializer>
static void serialize(T *& object, Serializer &arch) {
SrAttr<IPointerSerializer<Serializer,T> > pser(arch);
if (arch.storing()) {
pser->store(arch,object);
} else if (arch.loading()) {
T *tmp = pser->load(arch);
std::swap(tmp,object);
pser->destroy(tmp);
}
}
};
}
| [
"ondra-novak@email.cz"
] | ondra-novak@email.cz |
3703b6060c6d655d7e1c7042266c4650f760b1b6 | 0c2b97c6ded5fdec68cb1496d8e26d19d74c856a | /12_13/12_13main.cpp | a328ed06220010e0fd9ad05cacee9832db29e62c | [] | no_license | 17mappingchengguo/cheng_guo | bcce55d9fe0fb89712d6345bdd705d92b8c4b6e4 | 470ec8357ab81df941eb1c461373ebf280044799 | refs/heads/master | 2020-04-02T06:25:36.368439 | 2019-04-21T11:57:20 | 2019-04-21T11:57:20 | 154,147,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,091 | cpp | #include <iostream>
#include <vector>
#include "Shape.h"
#include "TwoDimensionalShape.h"
#include "ThreeDimensionalShape.h"
#include "Circle.h"
#include "Square.h"
#include "Sphere.h"
#include "Cube.h"
using namespace std;
int main()
{
vector < Shape * > shapes( 4 );
shapes[ 0 ] = new Circle( 3.5, 6, 9 );
shapes[ 1 ] = new Square( 12, 2, 2 );
shapes[ 2 ] = new Sphere( 5, 1.5, 4.5 );
shapes[ 3 ] = new Cube( 2.2 );
for ( int i = 0; i < 4; i++ )
{
cout << *shapes[ i ] << endl;
TwoDimensionalShape *twoDimensionalShapePtr =
dynamic_cast < TwoDimensionalShape * > ( shapes[ i ] );
if ( twoDimensionalShapePtr != 0 )
cout << "Area: " << twoDimensionalShapePtr->getArea() << endl;
ThreeDimensionalShape *threeDimensionalShapePtr =
dynamic_cast < ThreeDimensionalShape * > ( shapes[ i ] );
if ( threeDimensionalShapePtr != 0 )
cout << "Area: " << threeDimensionalShapePtr->getArea()
<< "\nVolume: " << threeDimensionalShapePtr->getVolume()
<< endl;
cout << endl;
}
}
| [
"2186479577@qq.com"
] | 2186479577@qq.com |
247af74cbb0d64d50a0ca0aee0c463afa9762cef | bc1c43d7ebb8fbb23d022f1554e1639285f276b2 | /osl/core/osl/progress.cc | 7a6d672794eaa5141fb5f78503c67e51a15fbe9e | [] | no_license | ai5/gpsfish | d1eafdece0c7c203c32603892ff9263a8fbcba59 | b6ed91f77478fdb51b8747e2fcd78042d79271d5 | refs/heads/master | 2020-12-24T06:54:11.062234 | 2016-07-02T20:42:10 | 2016-07-02T20:42:10 | 62,468,733 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,869 | cc | #include "osl/progress.h"
#include "osl/eval/weights.h"
#include "osl/eval/midgame.h"
#include "osl/eval/minorPiece.h"
#include "osl/additionalEffect.h"
#include "osl/bits/centering5x3.h"
#include "osl/oslConfig.h"
#include <iostream>
#include <fstream>
bool osl::progress::ml::
operator==(const NewProgressData& l, const NewProgressData& r)
{
return l.progresses == r.progresses
&& l.attack5x5_progresses == r.attack5x5_progresses
&& l.stand_progresses == r.stand_progresses
&& l.effect_progresses == r.effect_progresses
&& l.defenses == r.defenses
&& l.rook == r.rook && l.bishop == r.bishop && l.gold == r.gold
&& l.silver == r.silver && l.promoted == r.promoted
&& l.king_relative_attack == r.king_relative_attack
&& l.king_relative_defense == r.king_relative_defense
&& l.non_pawn_ptype_attacked_pair == r.non_pawn_ptype_attacked_pair
&& l.non_pawn_ptype_attacked_pair_eval == r.non_pawn_ptype_attacked_pair_eval;
}
osl::CArray<int, 81*15*10>
osl::progress::ml::NewProgress::attack_relative;
osl::CArray<int, 81*15*10>
osl::progress::ml::NewProgress::defense_relative;
osl::CArray<int, osl::Piece::SIZE>
osl::progress::ml::NewProgress::stand_weight;
osl::CArray<int, 1125>
osl::progress::ml::NewProgress::attack5x5_weight;
osl::CArray<int, 5625>
osl::progress::ml::NewProgress::attack5x5_x_weight;
osl::CArray<int, 10125>
osl::progress::ml::NewProgress::attack5x5_y_weight;
osl::CArray<int, 75>
osl::progress::ml::NewProgress::effectstate_weight;
osl::CArray<int, 4284>
osl::progress::ml::NewProgress::king_relative_weight;
osl::CArray<int, 262144>
osl::progress::ml::NewProgress::attacked_ptype_pair_weight;
osl::CArray<int, 10>
osl::progress::ml::NewProgress::pawn_facing_weight;
osl::CArray<int, 16>
osl::progress::ml::NewProgress::promotion37_weight;
osl::CArray<int, 56>
osl::progress::ml::NewProgress::piecestand7_weight;
int osl::progress::ml::NewProgress::max_progress;
bool osl::progress::ml::NewProgress::initialized_flag;
bool osl::progress::ml::NewProgress::setUp(const char *filename)
{
if (initialized_flag)
return true;
static CArray<int, 25> effect_weight;
static CArray<int, 225> effect_x_weight, effect_y_weight;
static CArray<int, 25> effect_defense_weight;
static CArray<int, 225> effect_per_effect;
static CArray<int, 225> effect_per_effect_defense;
static CArray<int, 2025> effect_per_effect_y, effect_per_effect_x;
std::ifstream is(filename);
int read_count = 0;
osl::eval::ml::Weights weights(25);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
effect_weight[i] = val;
++read_count;
}
for (size_t i = 0; i < 225; ++i)
{
int val;
is >> val;
effect_x_weight[i] = val;
++read_count;
}
for (size_t i = 0; i < 225; ++i)
{
int val;
is >> val;
effect_y_weight[i] = val;
++read_count;
}
weights.resetDimension(25);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
effect_defense_weight[i] = val;
++read_count;
}
weights.resetDimension(225);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
effect_per_effect[i] = val;
++read_count;
}
weights.resetDimension(225);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
effect_per_effect_defense[i] = val;
++read_count;
}
weights.resetDimension(2025);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
effect_per_effect_y[i] = val;
++read_count;
}
weights.resetDimension(2025);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
effect_per_effect_x[i] = val;
++read_count;
}
weights.resetDimension(Piece::SIZE);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
stand_weight[i] = val;
++read_count;
}
weights.resetDimension(1125);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
attack5x5_weight[i] = val;
++read_count;
}
weights.resetDimension(75);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
effectstate_weight[i] = val;
++read_count;
}
weights.resetDimension(5625);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
attack5x5_x_weight[i] = val;
++read_count;
}
weights.resetDimension(10125);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
attack5x5_y_weight[i] = val;
++read_count;
}
weights.resetDimension(4284);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
king_relative_weight[i] = val;
++read_count;
}
weights.resetDimension(262144);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
attacked_ptype_pair_weight[i] = val;
++read_count;
}
weights.resetDimension(10);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
pawn_facing_weight[i] = val;
++read_count;
}
weights.resetDimension(16);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
promotion37_weight[i] = val;
++read_count;
}
weights.resetDimension(56);
for (size_t i = 0; i < weights.dimension(); ++i)
{
int val;
is >> val;
piecestand7_weight[i] = val;
++read_count;
}
{
int val;
is >> val;
max_progress = val;
++read_count;
#ifdef EVAL_QUAD
while (((max_progress/ProgressScale) % 3) && max_progress > 0)
--max_progress;
#endif
}
for(int king_x=1;king_x<=9;king_x++){
for(int king_y=1;king_y<=9;king_y++){
Square king(king_x,king_y);
int king_index=(king_x-1)*9+king_y-1;
const Square center = Centering5x3::adjustCenter(king);
const int min_x = center.x() - 2;
const int min_y = center.y() - 1;
int i=0;
for (int dx=0; dx<5; ++dx)
{
for (int dy=0; dy<3; ++dy,++i)
{
const Square target(min_x+dx,min_y+dy);
int index0=king_index*15+i;
int index_a=index0*10;
int index_d=index0*10;
attack_relative[index_a]=
effect_weight[index<BLACK>(king, target)] +
effect_x_weight[indexX<BLACK>(king, target)] +
effect_y_weight[indexY<BLACK>(king, target)];
defense_relative[index_d]=
effect_defense_weight[index<BLACK>(king, target)];
for(int count=0;count<=8;count++){
attack_relative[index_a+count+1]=
effect_per_effect[indexPerEffect<BLACK>(king, target, count)] +
effect_per_effect_y[indexPerEffectY<BLACK>(king, target, count)] +
effect_per_effect_x[indexPerEffectX<BLACK>(king, target, count)];
defense_relative[index_d+count+1]=
effect_per_effect_defense[indexPerEffect<BLACK>(king, target, count)];
}
}
}
}
}
for(int king_x=1;king_x<=5;king_x++)
for(int promoted=0;promoted<=4;promoted++)
for(int silver=0;silver<=4;silver++)
for(int gold=0;gold<=4;gold++)
for(int bishop=0;bishop<=2;bishop++)
for(int rook=0;rook<=2;rook++){
int index0=promoted + 5 * (silver + 5 * (gold + 5 * (bishop + 3 * rook)));
int index1=king_x - 1 + 5 * (promoted + 5 * (silver + 5 * (gold + 5 * (bishop + 3 * rook))));
attack5x5_x_weight[index1]+=attack5x5_weight[index0];
}
for (int i=0; i<PTYPE_SIZE*2*PTYPE_SIZE; ++i)
for (int j=i+1; j<PTYPE_SIZE*2*PTYPE_SIZE; ++j) {
attacked_ptype_pair_weight[eval::ml::NonPawnAttackedPtypePair::index2(j,i)]
= attacked_ptype_pair_weight[eval::ml::NonPawnAttackedPtypePair::index2(i,j)];
}
// set sum of [1..i] into [i], keep [0] as is.
for (int i=2; i<10; ++i)
pawn_facing_weight[i] += pawn_facing_weight[i-1];
initialized_flag = static_cast<bool>(is);
if (!initialized_flag)
{
std::cerr << "Failed to load NewProgress data " << read_count
<< " from file " << filename << std::endl;
}
return initialized_flag;
}
bool osl::progress::ml::NewProgress::setUp()
{
return setUp(defaultFilename().c_str());
}
std::string osl::progress::ml::NewProgress::defaultFilename()
{
std::string filename = OslConfig::home();
filename += "/data/progress.txt";
return filename;
}
template <osl::Player P>
void osl::progress::ml::NewProgress::progressOne(
const NumEffectState &state, int &attack, int &defense)
{
const Square king = state.kingSquare<P>();
const Square center = Centering5x3::adjustCenter(king);
const int min_x = center.x() - 2;
const int min_y = center.y() - 1;
attack = defense = 0;
Square kingRel=king;
if(P==WHITE){
kingRel=kingRel.rotate180();
}
int index0=((kingRel.x()-1)*9+kingRel.y()-1)*15;
int index_a=index0*10 + (P==WHITE ? 10*14 : 0);
for (int dx=0; dx<5; ++dx)
{
for (int dy=0; dy<3; ++dy)
{
const Square target(min_x+dx,min_y+dy);
const int attack_count =
state.countEffect(alt(P), target);
const int defense_count =
state.countEffect(P, target);
attack += attack_count *attack_relative[index_a]+
attack_relative[index_a+std::min(attack_count,8)+1];
defense +=
defense_count * defense_relative[index_a]+
defense_relative[index_a+std::min(defense_count,8)+1];
if(P==BLACK){
index_a+=10;
}
else{
index_a-=10;
}
}
}
}
template <osl::Player P>
void osl::progress::ml::NewProgress::updateAttack5x5PiecesAndState(
const NumEffectState &state)
{
const Square king = state.kingSquare<P>();
const int min_x = std::max(1, king.x() - 2);
const int max_x = std::min(9, king.x() + 2);
const int min_y = std::max(1, king.y() - 2);
const int max_y = std::min(9, king.y() + 2);
effect_progresses[P] = 0;
PieceMask mask;
for (int y = min_y; y <= max_y; ++y)
{
for (int x = min_x; x <= max_x; ++x)
{
const Square target(x, y);
const NumBitmapEffect effect = state.effectSetAt(target);
const int effect_diff =
effect.countEffect(alt(P)) - effect.countEffect(P);
const int x_diff = std::abs(x - king.x());
const int y_diff = (P == WHITE ? king.y() - y : y - king.y());
int index = std::max(std::min(effect_diff, 2), -2) + 2 + 5 * x_diff +
5 * 3 * (y_diff + 2);
effect_progresses[P] += effectstate_weight[index];
mask |= effect;
}
}
updateAttack5x5Pieces<P>(mask, state);
}
template <osl::Player P>
void osl::progress::ml::NewProgress::updateAttack5x5Pieces(
PieceMask mask, const NumEffectState& state)
{
const Player attack = alt(P);
mask &= state.piecesOnBoard(attack);
rook[attack] = mask.selectBit<ROOK>().countBit();
bishop[attack] = mask.selectBit<BISHOP>().countBit();
gold[attack] = mask.selectBit<GOLD>().countBit();
silver[attack] =
(mask & ~state.promotedPieces()).selectBit<SILVER>().countBit();
PieceMask promoted_pieces = mask & state.promotedPieces();
promoted_pieces.clearBit<ROOK>();
promoted_pieces.clearBit<BISHOP>();
promoted[attack] =
std::min(promoted_pieces.countBit(), 4);
}
template <osl::Player P>
int osl::progress::ml::NewProgress::attack5x5Value(
const NumEffectState &state) const
{
const Player attack = alt(P);
int king_x = state.kingSquare<P>().x();
if (king_x > 5)
king_x = 10 - king_x;
const int king_y = (P == BLACK ? state.kingSquare<P>().y() :
10 - state.kingSquare<P>().y());
return (attack5x5_x_weight[index5x5x(
rook[attack] + state.countPiecesOnStand<ROOK>(attack),
bishop[attack] + state.countPiecesOnStand<BISHOP>(attack),
gold[attack] + state.countPiecesOnStand<GOLD>(attack),
silver[attack] + state.countPiecesOnStand<SILVER>(attack),
promoted[attack], king_x)] +
attack5x5_y_weight[index5x5y(
rook[attack] + state.countPiecesOnStand<ROOK>(attack),
bishop[attack] + state.countPiecesOnStand<BISHOP>(attack),
gold[attack] + state.countPiecesOnStand<GOLD>(attack),
silver[attack] + state.countPiecesOnStand<SILVER>(attack),
promoted[attack], king_y)]);
}
void
osl::progress::ml::NewProgress::updatePieceKingRelativeBonus(
const NumEffectState &state)
{
const CArray<Square,2> kings = {{
state.kingSquare(BLACK),
state.kingSquare(WHITE),
}};
king_relative_attack.fill(0);
king_relative_defense.fill(0);
for (int i = 0; i < Piece::SIZE; ++i)
{
const Piece piece = state.pieceOf(i);
if (piece.ptype() == osl::KING || !piece.isOnBoard())
continue;
Player pl = piece.owner();
const int index_attack = indexRelative(piece.owner(), kings[alt(pl)],
piece);
const int index_defense = indexRelative(piece.owner(), kings[pl],
piece) + 2142;
king_relative_attack[pl] += king_relative_weight[index_attack];
king_relative_defense[pl] += king_relative_weight[index_defense];
}
}
template <osl::Player Owner>
void osl::progress::ml::NewProgress::
updateNonPawnAttackedPtypePairOne(const NumEffectState& state)
{
PieceMask attacked = state.effectedMask(alt(Owner)) & state.piecesOnBoard(Owner);
attacked.reset(state.kingPiece<Owner>().number());
mask_t ppawn = state.promotedPieces().getMask<PAWN>() & attacked.selectBit<PAWN>();
attacked.clearBit<PAWN>();
attacked.orMask(PtypeFuns<PAWN>::indexNum, ppawn);
PieceVector pieces;
while (attacked.any())
{
const Piece piece = state.pieceOf(attacked.takeOneBit());
pieces.push_back(piece);
}
typedef eval::ml::NonPawnAttackedPtypePair feature_t;
int result = 0;
MultiInt result_eval;
for (size_t i=0; i<pieces.size(); ++i) {
const int i0 = feature_t::index1(state, pieces[i]);
result += attacked_ptype_pair_weight[feature_t::index2(0,i0)];
for (size_t j=i+1; j<pieces.size(); ++j) {
const int i1 = feature_t::index1(state, pieces[j]);
result += attacked_ptype_pair_weight[feature_t::index2(i0,i1)];
if (Owner == BLACK)
result_eval += feature_t::table[feature_t::index2(i0, i1)];
else
result_eval -= feature_t::table[feature_t::index2(i0, i1)];
}
}
non_pawn_ptype_attacked_pair[Owner] = result;
non_pawn_ptype_attacked_pair_eval[Owner] = result_eval;
}
void osl::progress::ml::NewProgress::
updateNonPawnAttackedPtypePair(const NumEffectState& state)
{
updateNonPawnAttackedPtypePairOne<BLACK>(state);
updateNonPawnAttackedPtypePairOne<WHITE>(state);
}
void osl::progress::ml::NewProgress::
updatePawnFacing(const NumEffectState& state)
{
PieceMask attacked = state.effectedMask(WHITE) & state.piecesOnBoard(BLACK);
mask_t pawn = attacked.selectBit<PAWN>()
& ~(state.promotedPieces().getMask<PAWN>());
int count = 0;
while (pawn.any()) {
const Piece p(state.pieceOf(pawn.takeOneBit()+PtypeFuns<PAWN>::indexNum*32));
if (state.hasEffectByPtypeStrict<PAWN>(WHITE, p.square()))
++count;
}
pawn_facing = pawn_facing_weight[count];
}
template <osl::Player P>
void osl::progress::ml::
NewProgress::promotion37One(const NumEffectState& state, int rank)
{
typedef eval::ml::Promotion37 feature_t;
CArray<int,PTYPE_SIZE> count = {{ 0 }};
for (int x=1; x<=9; ++x) {
const Square target(x, rank);
if (! state[target].isEmpty())
continue;
int a = state.countEffect(P, target);
const int d = state.countEffect(alt(P), target);
if (a > 0 && a == d)
a += AdditionalEffect::hasEffect(state, target, P);
if (a <= d)
continue;
const Ptype ptype = state.findCheapAttack(P, target).ptype();
if (isPiece(ptype) && ! isPromoted(ptype))
count[ptype]++;
}
for (int p=PTYPE_BASIC_MIN; p<=PTYPE_MAX; ++p) {
if (count[p] > 0) {
promotion37 += promotion37_weight[p];
promotion37_eval += feature_t::table[p]*sign(P);
}
if (count[p] > 1) {
promotion37 += promotion37_weight[p-8]*(count[p]-1);
promotion37_eval += feature_t::table[p-8]*(sign(P)*(count[p]-1));
}
}
}
void osl::progress::ml::NewProgress::
updatePromotion37(const NumEffectState& state)
{
promotion37 = 0;
promotion37_eval = MultiInt();
promotion37One<BLACK>(state, 3);
promotion37One<WHITE>(state, 7);
}
void osl::progress::ml::NewProgress::
updatePieceStand7(const NumEffectState& state)
{
piecestand7 = 0;
for (int z=0; z<2; ++z) {
CArray<int,7> stand = {{ 0 }};
int filled = 0;
for (Ptype ptype: PieceStand::order)
if (state.hasPieceOnStand(indexToPlayer(z), ptype))
stand[filled++] = ptype-PTYPE_BASIC_MIN;
for (int i=0; i<std::min(7,filled+1); ++i)
piecestand7 += piecestand7_weight[stand[i] + 8*i];
}
}
osl::progress::ml::NewProgress::NewProgress(
const NumEffectState &state)
{
assert(initialized_flag);
progressOne<BLACK>(state,
progresses[BLACK],
defenses[WHITE]);
progressOne<WHITE>(state,
progresses[WHITE],
defenses[BLACK]);
updateAttack5x5PiecesAndState<BLACK>(state);
updateAttack5x5PiecesAndState<WHITE>(state);
attack5x5_progresses[BLACK] =
attack5x5Value<BLACK>(state);
attack5x5_progresses[WHITE] =
attack5x5Value<WHITE>(state);
stand_progresses.fill(0);
for (Ptype ptype: PieceStand::order)
{
const int black_count =
state.countPiecesOnStand(BLACK, ptype);
const int white_count =
state.countPiecesOnStand(WHITE, ptype);
for (int j = 0; j < black_count; ++j)
{
stand_progresses[WHITE] +=
stand_weight[Ptype_Table.getIndexMin(ptype) + j];
}
for (int j = 0; j < white_count; ++j)
{
stand_progresses[BLACK] +=
stand_weight[Ptype_Table.getIndexMin(ptype) + j];
}
}
updatePieceKingRelativeBonus(state);
updateNonPawnAttackedPtypePair(state);
updatePawnFacing(state);
updatePromotion37(state);
updatePieceStand7(state);
}
template<osl::Player P>
inline
void osl::progress::ml::NewProgress::updateMain(
const NumEffectState &new_state,
Move last_move)
{
const Player altP=alt(P);
assert(new_state.turn()==altP);
assert(last_move.player()==P);
const Square kb = new_state.kingSquare<BLACK>(), kw = new_state.kingSquare<WHITE>();
const BoardMask mb = new_state.changedEffects(BLACK), mw = new_state.changedEffects(WHITE);
const bool king_move = last_move.ptype() == KING;
if ((king_move && altP == BLACK) || mb.anyInRange(Board_Mask_Table5x3_Center.mask(kw)) || mw.anyInRange(Board_Mask_Table5x3_Center.mask(kw)))
{
progressOne<WHITE>(new_state,progresses[WHITE],defenses[BLACK]);
}
if ((king_move && altP == WHITE) || mw.anyInRange(Board_Mask_Table5x3_Center.mask(kb)) || mb.anyInRange(Board_Mask_Table5x3_Center.mask(kb)))
{
progressOne<BLACK>(new_state,progresses[BLACK],defenses[WHITE]);
}
const Ptype captured = last_move.capturePtype();
if (last_move.isDrop())
{
const int count =
new_state.countPiecesOnStand(P, last_move.ptype()) + 1;
const int value =
stand_weight[Ptype_Table.getIndexMin(last_move.ptype()) + count - 1];
stand_progresses[altP] -= value;
}
else if (captured != PTYPE_EMPTY)
{
Ptype ptype = unpromote(captured);
const int count = new_state.countPiecesOnStand(P, ptype);
const int value =
stand_weight[(Ptype_Table.getIndexMin(ptype) + count - 1)];
stand_progresses[altP] += value;
}
if (king_move)
{
updatePieceKingRelativeBonus(new_state);
}
else
{
const CArray<Square,2> kings = {{
new_state.kingSquare(BLACK),
new_state.kingSquare(WHITE),
}};
if (!last_move.isDrop())
{
const int index_attack =
indexRelative<P>(kings[altP],
last_move.oldPtype(), last_move.from());
const int index_defense =
indexRelative<P>(kings[P],
last_move.oldPtype(), last_move.from()) + 2142;
king_relative_attack[P] -=
king_relative_weight[index_attack];
king_relative_defense[P] -=
king_relative_weight[index_defense];
}
{
const int index_attack =
indexRelative<P>(kings[altP],
last_move.ptype(), last_move.to());
const int index_defense =
indexRelative<P>(kings[P],
last_move.ptype(), last_move.to()) + 2142;
king_relative_attack[P] +=
king_relative_weight[index_attack];
king_relative_defense[P] +=
king_relative_weight[index_defense];
}
if (captured != PTYPE_EMPTY)
{
const int index_attack =
indexRelative<altP>(kings[P],
captured, last_move.to());
const int index_defense =
indexRelative<altP>(kings[altP],
captured, last_move.to()) + 2142;
king_relative_attack[altP] -=
king_relative_weight[index_attack];
king_relative_defense[altP] -=
king_relative_weight[index_defense];
}
}
updateNonPawnAttackedPtypePair(new_state);
updatePawnFacing(new_state);
updatePromotion37(new_state);
updatePieceStand7(new_state);
}
template<osl::Player P>
void osl::progress::ml::NewProgress::updateSub(
const NumEffectState &new_state,
Move last_move)
{
const Player altP=alt(P);
assert(new_state.turn()==altP);
if (last_move.isPass())
return;
const Square kb = new_state.kingSquare<BLACK>(), kw = new_state.kingSquare<WHITE>();
const BoardMask mb = new_state.changedEffects(BLACK), mw = new_state.changedEffects(WHITE);
const bool king_move = last_move.ptype() == KING;
const Ptype captured = last_move.capturePtype();
if ((king_move && altP == BLACK) ||
mb.anyInRange(Board_Mask_Table5x5.mask(kw)) ||
mw.anyInRange(Board_Mask_Table5x5.mask(kw)))
{
updateAttack5x5PiecesAndState<WHITE>(new_state);
attack5x5_progresses[WHITE] =
attack5x5Value<WHITE>(new_state);
}
else if (altP == WHITE &&(last_move.isDrop() || captured != PTYPE_EMPTY))
{
attack5x5_progresses[WHITE] =
attack5x5Value<WHITE>(new_state);
}
if ((king_move && altP == WHITE) ||
mw.anyInRange(Board_Mask_Table5x5.mask(kb)) ||
mb.anyInRange(Board_Mask_Table5x5.mask(kb)))
{
updateAttack5x5PiecesAndState<BLACK>(new_state);
attack5x5_progresses[BLACK] =
attack5x5Value<BLACK>(new_state);
}
else if (altP == BLACK && (last_move.isDrop() || captured != PTYPE_EMPTY))
{
attack5x5_progresses[BLACK] =
attack5x5Value<BLACK>(new_state);
}
updateMain<P>(new_state, last_move);
}
osl::progress::ml::NewProgressDebugInfo osl::progress::ml::NewProgress::debugInfo() const
{
NewProgressDebugInfo info;
info.black_values[NewProgressDebugInfo::ATTACK_5X3] = progresses[0];
info.black_values[NewProgressDebugInfo::DEFENSE_5X3] = defenses[0];
info.black_values[NewProgressDebugInfo::ATTACK5X5] = attack5x5_progresses[0];
info.black_values[NewProgressDebugInfo::STAND] = stand_progresses[0];
info.black_values[NewProgressDebugInfo::EFFECT5X5] = effect_progresses[0];
info.black_values[NewProgressDebugInfo::KING_RELATIVE_ATTACK] = king_relative_attack[0];
info.black_values[NewProgressDebugInfo::KING_RELATIVE_DEFENSE] = king_relative_defense[0];
info.black_values[NewProgressDebugInfo::NON_PAWN_ATTACKED_PAIR] = non_pawn_ptype_attacked_pair[0];
info.white_values[NewProgressDebugInfo::ATTACK_5X3] = progresses[1];
info.white_values[NewProgressDebugInfo::DEFENSE_5X3] = defenses[1];
info.white_values[NewProgressDebugInfo::ATTACK5X5] = attack5x5_progresses[1];
info.white_values[NewProgressDebugInfo::STAND] = stand_progresses[1];
info.white_values[NewProgressDebugInfo::EFFECT5X5] = effect_progresses[1];
info.white_values[NewProgressDebugInfo::KING_RELATIVE_ATTACK] = king_relative_attack[1];
info.white_values[NewProgressDebugInfo::KING_RELATIVE_DEFENSE] = king_relative_defense[1];
info.white_values[NewProgressDebugInfo::NON_PAWN_ATTACKED_PAIR] = non_pawn_ptype_attacked_pair[1];
return info;
}
namespace osl
{
namespace progress
{
namespace ml
{
template void osl::progress::ml::NewProgress::updateSub<osl::BLACK>(const NumEffectState &new_state,Move last_move);
template void osl::progress::ml::NewProgress::updateSub<osl::WHITE>(const NumEffectState &new_state,Move last_move);
}
}
}
// ;;; Local Variables:
// ;;; mode:c++
// ;;; c-basic-offset:2
// ;;; End:
| [
"taibarax@gmail.com"
] | taibarax@gmail.com |
2e970856caac6a2998f677547a6f6b4688adfa2d | 64f0586e989f1b02b4543d696b4d2b308aa8046f | /DemoGame2D/DemoGame2D/Common_Fuc.h | a93871ad4f56d1921d3e0961b4d2efa32cc820d5 | [] | no_license | hado-569/GameFirePlane | 7b1ec457bd16bcb92bb67cb3e4724e9a1e3bce93 | bf4f225568696dac89f639a911056ffd22488dcd | refs/heads/main | 2023-01-22T11:43:55.513239 | 2020-11-22T12:18:19 | 2020-11-22T12:18:19 | 315,029,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,094 | h | #ifndef _COMMON_FUNC_H_
#define _COMMON_FUNC_H_
#include <iostream>
#include <Windows.h>
#include <SDL.h>
#include <string>
#include <SDL_image.h>
#include <SDL_ttf.h>
const int BKG_WIDTH(4000);
const int BKG_HEIGHT(702);
const int SCREEN_WIDTH(1000);
const int SCREEN_HEIGHT(702);
const int SCREEN_BPP(32);
const int NUM_THREATS =2;
static SDL_Surface* g_screen = NULL;
static SDL_Surface* g_bkground = NULL;
static SDL_Surface* g_bkground2 = NULL;
static SDL_Surface* g_bkground3 = NULL;
static SDL_Surface* g_img_menu = NULL;
/*SDL_Surface* g_playerImage = NULL;*/
static SDL_Event g_event;
namespace CommonFunctionSDL {
SDL_Surface* LoadImage(std::string file_path);
SDL_Rect ApplySurface(SDL_Surface* src, SDL_Surface* des, int x, int y);
void ApplySurface2(SDL_Surface* src, SDL_Surface* des, SDL_Rect* clip, int x ,int y);
void Cleanup();
bool CheckColision(const SDL_Rect& object1, const SDL_Rect& object2);
int ShowMenu(SDL_Surface* des, TTF_Font* font);
bool CheckForcusWithRect(const int& x, const int& y, const SDL_Rect& rect);
}
#endif // !_COMMON_FUNC_H_
| [
"tonglao686@gmail.com"
] | tonglao686@gmail.com |
0152fabf06fffcd99982919d88c4184a4955b8f8 | e6559df51c2a14256962c3757073a491ea66de7c | /URI/1884 - Lutando Contra os Rajasi.cpp | 4831a3903716bcb8ba5aa31b7ddf0cbe49bf9c87 | [] | no_license | Maycon708/Maratona | c30eaedc3ee39d69582b0ed1a60f31ad8d666d43 | b6d07582544c230e67c23a20e1a1be99d4b47576 | refs/heads/master | 2020-04-25T23:37:53.992330 | 2019-02-28T17:10:25 | 2019-02-28T17:10:25 | 143,191,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,530 | cpp | #include <bits/stdc++.h>
#define INF 0x3F3F3F3F
#define rep(i, a, b) for(int i = int(a); i < int(b); i++)
#define it(i, a) for( typeof( a.begin() ) i = a.begin(); i != a.end(); i++ )
#define pb push_back
#define pi 3.1415926535897932384626433832795028841971
#define debug(x) cout << #x << " = " << x << endl;
#define debug2(x,y) cout << #x << " = " << x << " --- " << #y << " = " << y << "\n";
#define debugM( x, l, c ) { rep( i, 0, l ){ rep( j, 0, c ) cout << x[i][j] << " "; printf("\n");}}
#define all(S) (S).begin(), (S).end()
#define MAXV 1010000
#define MAXN 110
#define F first
#define S second
#define EPS 1e-9
#define mk make_pair
using namespace std;
typedef long long int ll;
typedef pair <ll, ll> ii;
inline bool cmp( ii a, ii b ){
int dif = a.F - b.F - a.S + b.S;
if( dif ) return ( a.F - a.S ) < ( b.F - b.S );
return a.F > b.F;
}
inline bool cmp2( ii a, ii b ){
if( a.F != b.F ) return a.F < b.F;
return a.S < b.S;
}
int main(){
ll t, n, h, k, g, r;
scanf("%lld", &t );
while( t-- ){
vector < ii > l, p;
scanf("%lld%lld%lld", &n, &h, &k );
rep( i, 0, n ){
scanf("%lld%lld", &g, &r );
if( g <= r )
l.pb( ii( g, r ) );
else
p.pb( ii( g, r ) );
}
sort( all( l ), cmp2 );
ll cnt = 0;
rep( i, 0, l.size() ){
if( h >= l[i].F ){
h = ( h - l[i].F + l[i].S );
cnt++;
}
}
sort( all( p ), cmp );
rep( i, 0, p.size() ){
if( h >= p[i].F ){
h = ( h - p[i].F + p[i].S );
cnt++;
}
}
if( cnt + k >= n ) printf("Y\n");
else printf("N\n");
}
}
| [
"mayconalves@gea.inatel.br"
] | mayconalves@gea.inatel.br |
ccc94a2b3da68d09a83b0aeed6a8c9d01c9ec120 | 092dd56a1bf9357466c05d0f5aedf240cec1a27b | /tests/mmstests/linearelasticity/nofaults-3d/GravityRefState3D.hh | 8ffafb49979afe54de969d5806487c507b2e0d3c | [
"MIT"
] | permissive | rwalkerlewis/pylith | cef02d5543e99a3e778a1c530967e6b5f1d5dcba | c5f872c6afff004a06311d36ac078133a30abd99 | refs/heads/main | 2023-08-24T18:27:30.877550 | 2023-06-21T22:03:01 | 2023-06-21T22:03:01 | 154,047,591 | 0 | 0 | MIT | 2018-10-21T20:05:59 | 2018-10-21T20:05:59 | null | UTF-8 | C++ | false | false | 1,153 | hh | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University at Buffalo
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2022 University of California, Davis
//
// See LICENSE.md for license information.
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "TestLinearElasticity.hh" // USES TestLinearElasticity_Data
namespace pylith {
class GravityRefState3D;
}
class pylith::GravityRefState3D {
public:
// Data factory methods
static TestLinearElasticity_Data* TetP1(void);
static TestLinearElasticity_Data* TetP2(void);
static TestLinearElasticity_Data* TetP3(void);
static TestLinearElasticity_Data* HexQ1(void);
static TestLinearElasticity_Data* HexQ2(void);
static TestLinearElasticity_Data* HexQ3(void);
private:
GravityRefState3D(void); ///< Not implemented
}; // GravityRefState3D
// End of file
| [
"baagaard@usgs.gov"
] | baagaard@usgs.gov |
022392c4c105dc5e097c76117bc9271712296625 | 081153422168d9feb8795a8ebeeb6b4414b74ae2 | /Source/PluginEditor.cpp | 1f6e2793c2cb2b4ce9c04837cf8be5e29aa2d623 | [] | no_license | sam-trolland/AudioMidiRecorderPlugin | c17cc5ec6d6178ce1d6ec7215143f903d9f85718 | 64ee869a936dd7c08007eb0f89efd7e363b91a52 | refs/heads/master | 2023-06-29T04:15:41.819901 | 2021-02-24T07:23:35 | 2021-02-24T07:23:35 | 341,801,566 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,908 | cpp | /*
==============================================================================
This file contains the basic framework code for a JUCE plugin editor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
//==============================================================================
AudioMidiRecorderPluginProcessorEditor::AudioMidiRecorderPluginProcessorEditor (AudioMidiRecorderPluginProcessor& p)
: AudioProcessorEditor (&p), audioProcessor (p)
{
// Make sure that before the constructor has finished, you've set the
// editor's size to whatever you need it to be.
setSize (200, 200);
// GUI Elements
/*
midiVolume.setSliderStyle(juce::Slider::LinearBarVertical);
midiVolume.setRange(0.0, 127.0, 1.0);
midiVolume.setTextBoxStyle(juce::Slider::NoTextBox, false, 90, 0);
midiVolume.setPopupDisplayEnabled(true, false, this);
midiVolume.setTextValueSuffix(" Volume");
midiVolume.setValue(1.0);
addAndMakeVisible(&midiVolume); // Add control to GUI
midiVolume.addListener(this);
*/
// Setup Record Button
addAndMakeVisible(recordButton);
recordButton.addListener(this);
recordButton.setButtonText("Record");
recordButton.setColour(TextButton::buttonColourId,Colours::green);
}
AudioMidiRecorderPluginProcessorEditor::~AudioMidiRecorderPluginProcessorEditor()
{
}
//==============================================================================
void AudioMidiRecorderPluginProcessorEditor::paint (juce::Graphics& g)
{
// (Our component is opaque, so we must completely fill the background with a solid colour)
g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId));
g.setColour (juce::Colours::white);
g.setFont (15.0f);
g.drawFittedText ("Midi Volume", 0, 0, getWidth(), 30, juce::Justification::centred, 1);
}
void AudioMidiRecorderPluginProcessorEditor::resized()
{
// This is generally where you'll want to lay out the positions of any
// subcomponents in your editor..
// GUI Components
//midiVolume.setBounds(40, 30, 20, getHeight() - 60);
recordButton.setBounds(0,0,getWidth(),getHeight());
}
void AudioMidiRecorderPluginProcessorEditor::buttonClicked (Button* button)
{
if (!recording){
// Start Recording
// Setup Recording Driectory
auto docsDir = File::getSpecialLocation (File::userDocumentsDirectory);
auto parentDir = File(docsDir.getFullPathName()+"/AudioMidiRecordings" );
parentDir.createDirectory();
// Audio Recording File (Swap between .wav and .ogg formats here)
audioRecordingFile = parentDir.getNonexistentChildFile("recording", ".wav"); //Wav Audio File Format
//audioRecordingFile = parentDir.getNonexistentChildFile("dinverno_system_recording", ".ogg"); //OGG Audio File Format
// Midi Recording File (same name as audio file - will overwrite if file exists)
midiRecordingFile = parentDir.getChildFile(audioRecordingFile.getFileNameWithoutExtension()+".mid");
// Tell Audio Processor to start recording
audioProcessor.startRecordingAudio(audioRecordingFile);
audioProcessor.startRecordingMidi(midiRecordingFile);
// Update GUI
recordButton.setButtonText("Stop Recording");
recordButton.setColour(TextButton::buttonColourId,Colours::red);
recording = true;
}else{
// Stop Recording
// Tell Audio Processor to Stop Recording
audioProcessor.stopRecordingAudio();
audioProcessor.stopRecordingMidi();
// Update GUI
recordButton.setButtonText("Record");
recordButton.setColour(TextButton::buttonColourId,Colours::green);
recording = false;
}
}
| [
"sam.trolland@gmail.com"
] | sam.trolland@gmail.com |
91526f35a9918d7209d8eb5a69358c0903b8d40d | abfd845716646e7c3074c890c211b805e65e5671 | /test/extensions/filters/http/alternate_protocols_cache/filter_integration_test.cc | b8910b290f3a0435e7bdc14fca3869d9ab0204a0 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | danzh2010/envoy | f094f0c7e8d2f8ebc5694c58f6956fe11e4f514d | 4239e739187f082aa974550cdc1229693f5e78df | refs/heads/master | 2023-08-05T06:10:02.361651 | 2022-06-24T18:07:05 | 2022-06-24T18:07:05 | 144,779,624 | 1 | 3 | Apache-2.0 | 2023-02-25T00:10:40 | 2018-08-14T22:48:20 | C++ | UTF-8 | C++ | false | false | 18,152 | cc | #include "envoy/config/bootstrap/v3/bootstrap.pb.h"
#include "envoy/config/cluster/v3/cluster.pb.h"
#include "envoy/config/common/key_value/v3/config.pb.validate.h"
#include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h"
#include "envoy/extensions/key_value/file_based/v3/config.pb.h"
#include "envoy/extensions/transport_sockets/tls/v3/cert.pb.h"
#include "source/common/http/http_server_properties_cache_impl.h"
#include "source/extensions/transport_sockets/tls/context_config_impl.h"
#include "source/extensions/transport_sockets/tls/ssl_socket.h"
#include "test/integration/http_integration.h"
#include "test/integration/http_protocol_integration.h"
#include "test/integration/ssl_utility.h"
namespace Envoy {
namespace {
#ifdef ENVOY_ENABLE_QUIC
// This tests the alternative service filter getting updated, by creating both
// HTTP/2 and HTTP/3 upstreams, and having the HTTP/2 upstream direct Envoy to
// the HTTP/3 upstream using alt-svc response headers.
class FilterIntegrationTest : public HttpProtocolIntegrationTest {
protected:
void initialize() override {
const std::string filename = TestEnvironment::temporaryPath("alt_svc_cache.txt");
envoy::config::core::v3::AlternateProtocolsCacheOptions alt_cache;
alt_cache.set_name("default_alternate_protocols_cache");
envoy::extensions::key_value::file_based::v3::FileBasedKeyValueStoreConfig config;
config.set_filename(filename);
config.mutable_flush_interval()->set_nanos(0);
envoy::config::common::key_value::v3::KeyValueStoreConfig kv_config;
kv_config.mutable_config()->set_name("envoy.key_value.file_based");
kv_config.mutable_config()->mutable_typed_config()->PackFrom(config);
alt_cache.mutable_key_value_store_config()->set_name("envoy.common.key_value");
alt_cache.mutable_key_value_store_config()->mutable_typed_config()->PackFrom(kv_config);
const std::string filter = fmt::format(R"EOF(
name: alternate_protocols_cache
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.alternate_protocols_cache.v3.FilterConfig
alternate_protocols_cache_options:
name: default_alternate_protocols_cache
key_value_store_config:
name: "envoy.common.key_value"
typed_config:
"@type": type.googleapis.com/envoy.config.common.key_value.v3.KeyValueStoreConfig
config:
name: envoy.key_value.file_based
typed_config:
"@type": type.googleapis.com/envoy.extensions.key_value.file_based.v3.FileBasedKeyValueStoreConfig
filename: {}
flush_interval:
nanos: 0
)EOF",
filename);
config_helper_.prependFilter(filter);
upstream_tls_ = true;
// This configures the upstream to use the connection grid (automatically
// selecting protocol and allowing HTTP/3)
config_helper_.configureUpstreamTls(/*use_alpn=*/true, /*http3=*/true, alt_cache);
HttpProtocolIntegrationTest::initialize();
}
// This function will create 2 upstreams, but Envoy will only point at the
// first, the HTTP/2 upstream.
void createUpstreams() override {
// The test is configured for one upstream (Envoy will only point to the HTTP/2 upstream) but
// we create two. Tell the test framework this is intentional.
skipPortUsageValidation();
ASSERT_FALSE(autonomous_upstream_);
// Until alt-svc supports different ports, try to get a TCP and UDP fake upstream on the same
// port.
for (int i = 0; i < 10; ++i) {
TRY_ASSERT_MAIN_THREAD {
// Make the first upstream HTTP/2
auto http2_config = configWithType(Http::CodecType::HTTP2);
Network::DownstreamTransportSocketFactoryPtr http2_factory =
createUpstreamTlsContext(http2_config);
addFakeUpstream(std::move(http2_factory), Http::CodecType::HTTP2);
// Make the next upstream is HTTP/3
auto http3_config = configWithType(Http::CodecType::HTTP3);
Network::DownstreamTransportSocketFactoryPtr http3_factory =
createUpstreamTlsContext(http3_config);
// If the UDP port is in use, this will throw an exception and get caught below.
fake_upstreams_.emplace_back(std::make_unique<FakeUpstream>(
std::move(http3_factory), fake_upstreams_[0]->localAddress()->ip()->port(), version_,
http3_config));
return;
}
END_TRY
catch (const EnvoyException& e) {
fake_upstreams_.clear();
ENVOY_LOG_MISC(warn, "Failed to use port {}",
fake_upstreams_[0]->localAddress()->ip()->port());
}
}
throw EnvoyException("Failed to find a port after 10 tries");
}
};
TEST_P(FilterIntegrationTest, AltSvc) {
const uint64_t request_size = 0;
const uint64_t response_size = 0;
const std::chrono::milliseconds timeout = TestUtility::DefaultTimeout;
initialize();
codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http"))));
Http::TestRequestHeaderMapImpl request_headers{
{":method", "POST"}, {":path", "/test/long/url"},
{":scheme", "http"}, {":authority", "sni.lyft.com"},
{"x-lyft-user-id", "123"}, {"x-forwarded-for", "10.0.0.1"}};
int port = fake_upstreams_[1]->localAddress()->ip()->port();
std::string alt_svc = absl::StrCat("h3=\":", port, "\"; ma=86400");
Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}, {"alt-svc", alt_svc}};
// First request should go out over HTTP/2 (upstream index 0). The response includes an
// Alt-Svc header.
auto response = sendRequestAndWaitForResponse(request_headers, request_size, response_headers,
response_size, 0, timeout);
checkSimpleRequestSuccess(request_size, response_size, response.get());
// Close the connection so the HTTP/2 connection will not be used.
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_http2_total", 1);
ASSERT_TRUE(fake_upstream_connection_->close());
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_destroy", 1);
fake_upstream_connection_.reset();
// Second request should go out over HTTP/3 (upstream index 1) because of the Alt-Svc information.
// This could arguably flake due to the race, at which point request #2 should go to {0, 1}
// but for now it seems to pass.
auto response2 = sendRequestAndWaitForResponse(request_headers, request_size, response_headers,
response_size, 1, timeout);
checkSimpleRequestSuccess(request_size, response_size, response2.get());
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_http3_total", 1);
}
TEST_P(FilterIntegrationTest, RetryAfterHttp3ZeroRttHandshakeFailed) {
const uint64_t response_size = 0;
const std::chrono::milliseconds timeout = TestUtility::DefaultTimeout;
initialize();
codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http"))));
int port = fake_upstreams_[0]->localAddress()->ip()->port();
std::string alt_svc = absl::StrCat("h3=\":", port, "\"; ma=86400");
Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}, {"alt-svc", alt_svc}};
// First request should go out over HTTP/2. The response includes an Alt-Svc header.
auto response = sendRequestAndWaitForResponse(default_request_headers_, 0, response_headers, 0,
/*upstream_index=*/0, timeout);
checkSimpleRequestSuccess(0, response_size, response.get());
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_http2_total", 1);
// Close the connection so the HTTP/2 connection will not be used.
ASSERT_TRUE(fake_upstream_connection_->close());
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_destroy", 1);
fake_upstream_connection_.reset();
// The 2nd request should go out over HTTP/3 because of the Alt-Svc information.
auto response2 = sendRequestAndWaitForResponse(default_request_headers_, 0,
default_response_headers_, response_size,
/*upstream_index=*/1, timeout);
checkSimpleRequestSuccess(0, response_size, response2.get());
EXPECT_EQ(1u, test_server_->counter("cluster.cluster_0.upstream_cx_http3_total")->value());
// Close the h3 upstream connection so that the next request will create another connection.
ASSERT_TRUE(fake_upstream_connection_->close());
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_destroy", 2);
fake_upstream_connection_.reset();
// Stop the HTTP/3 fake upstream.
fake_upstreams_[1]->cleanUp();
// The 3rd request should be sent over HTTP/3 as early data because of the cached 0-RTT
// credentials.
auto response3 = codec_client_->makeHeaderOnlyRequest(default_request_headers_);
// Wait for the upstream to connect timeout and the failed early data request to be retried.
test_server_->waitForCounterEq("cluster.cluster_0.upstream_rq_retry", 1);
EXPECT_EQ(1u, test_server_->counter("cluster.cluster_0.upstream_rq_0rtt")->value());
EXPECT_EQ(3u, test_server_->counter("cluster.cluster_0.upstream_cx_destroy")->value());
// The retry should attempt both HTTP/3 and HTTP/2. And the TCP connection will win the race.
waitForNextUpstreamRequest(0);
upstream_request_->encodeHeaders(response_headers, true);
ASSERT_TRUE(response3->waitForEndStream());
checkSimpleRequestSuccess(0, response_size, response3.get());
EXPECT_EQ(2u, test_server_->counter("cluster.cluster_0.upstream_cx_http2_total")->value());
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_connect_fail", 2);
EXPECT_EQ(3u, test_server_->counter("cluster.cluster_0.upstream_cx_http3_total")->value());
EXPECT_EQ(1u, test_server_->counter("cluster.cluster_0.upstream_http3_broken")->value());
upstream_request_.reset();
// As HTTP/3 is marked broken, the following request shouldn't cause the grid to attempt HTTP/3 to
// upstream at all.
auto response4 = sendRequestAndWaitForResponse(default_request_headers_, 0,
default_response_headers_, response_size,
/*upstream_index=*/0, timeout);
checkSimpleRequestSuccess(0, response_size, response4.get());
EXPECT_EQ(3u, test_server_->counter("cluster.cluster_0.upstream_cx_http3_total")->value());
}
TEST_P(FilterIntegrationTest, H3PostHandshakeFailoverToTcp) {
const uint64_t response_size = 0;
const std::chrono::milliseconds timeout = TestUtility::DefaultTimeout;
initialize();
codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http"))));
Http::TestRequestHeaderMapImpl request_headers{
{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "sni.lyft.com"},
{"x-lyft-user-id", "123"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-retry-on", "http3-post-connect-failure"}};
int port = fake_upstreams_[0]->localAddress()->ip()->port();
std::string alt_svc = absl::StrCat("h3=\":", port, "\"; ma=86400");
Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}, {"alt-svc", alt_svc}};
// First request should go out over HTTP/2. The response includes an Alt-Svc header.
auto response = sendRequestAndWaitForResponse(request_headers, 0, response_headers, 0,
/*upstream_index=*/0, timeout);
checkSimpleRequestSuccess(0, response_size, response.get());
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_http2_total", 1);
// Close the connection so the HTTP/2 connection will not be used.
ASSERT_TRUE(fake_upstream_connection_->close());
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_destroy", 1);
fake_upstream_connection_.reset();
// Second request should go out over HTTP/3 because of the Alt-Svc information.
auto response2 = codec_client_->makeHeaderOnlyRequest(request_headers);
waitForNextUpstreamRequest(1);
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_http3_total", 1);
// Close the HTTP/3 connection before sending back response. This would cause an upstream reset.
ASSERT_TRUE(fake_upstream_connection_->close());
fake_upstream_connection_.reset();
upstream_request_.reset();
// The reset request should be retried over TCP.
waitForNextUpstreamRequest(0);
upstream_request_->encodeHeaders(response_headers, true);
ASSERT_TRUE(response2->waitForEndStream());
if (Runtime::runtimeFeatureEnabled(Runtime::conn_pool_new_stream_with_early_data_and_http3)) {
EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.upstream_rq_retry")->value());
}
checkSimpleRequestSuccess(0, response_size, response2.get());
test_server_->waitForCounterEq("cluster.cluster_0.upstream_cx_http2_total", 2);
}
INSTANTIATE_TEST_SUITE_P(Protocols, FilterIntegrationTest,
testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams(
{Http::CodecType::HTTP2}, {Http::CodecType::HTTP3})),
HttpProtocolIntegrationTest::protocolTestParamsToString);
// This tests the connection grid with pre-populated alt-svc entries, and either
// an HTTP/2 or an HTTP/3 upstream (but not both).
class MixedUpstreamIntegrationTest : public FilterIntegrationTest {
protected:
MixedUpstreamIntegrationTest() {
TestEnvironment::writeStringToFileForTest("alt_svc_cache.txt", "");
default_request_headers_.setHost("sni.lyft.com");
}
void writeFile() {
uint32_t port = fake_upstreams_[0]->localAddress()->ip()->port();
std::string key = absl::StrCat("https://sni.lyft.com:", port);
size_t seconds = std::chrono::duration_cast<std::chrono::seconds>(
timeSystem().monotonicTime().time_since_epoch())
.count();
std::string value = absl::StrCat("h3=\":", port, "\"; ma=", 86400 + seconds, "|0|0");
TestEnvironment::writeStringToFileForTest(
"alt_svc_cache.txt", absl::StrCat(key.length(), "\n", key, value.length(), "\n", value));
}
void createUpstreams() override {
ASSERT_EQ(upstreamProtocol(), Http::CodecType::HTTP3);
ASSERT_EQ(fake_upstreams_count_, 1);
ASSERT_FALSE(autonomous_upstream_);
if (use_http2_) {
auto config = configWithType(Http::CodecType::HTTP2);
Network::DownstreamTransportSocketFactoryPtr factory = createUpstreamTlsContext(config);
addFakeUpstream(std::move(factory), Http::CodecType::HTTP2);
} else {
auto config = configWithType(Http::CodecType::HTTP3);
Network::DownstreamTransportSocketFactoryPtr factory = createUpstreamTlsContext(config);
addFakeUpstream(std::move(factory), Http::CodecType::HTTP3);
writeFile();
}
}
bool use_http2_{false};
};
int getSrtt(std::string alt_svc, TimeSource& time_source) {
auto data = Http::HttpServerPropertiesCacheImpl::originDataFromString(alt_svc, time_source,
/*from_cache=*/false);
return data.has_value() ? data.value().srtt.count() : 0;
}
// Test auto-config with a pre-populated HTTP/3 alt-svc entry. The upstream request will
// occur over HTTP/3.
TEST_P(MixedUpstreamIntegrationTest, BasicRequestAutoWithHttp3) {
initialize();
codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http"))));
sendRequestAndWaitForResponse(default_request_headers_, 0, default_response_headers_, 0, 0);
cleanupUpstreamAndDownstream();
std::string alt_svc;
// Make sure the srtt gets updated to a non-zero value.
for (int i = 0; i < 5; ++i) {
// Make sure that srtt is updated.
const std::string filename = TestEnvironment::temporaryPath("alt_svc_cache.txt");
alt_svc = TestEnvironment::readFileToStringForTest(filename);
if (getSrtt(alt_svc, timeSystem()) != 0) {
break;
}
timeSystem().advanceTimeWait(std::chrono::milliseconds(10));
}
EXPECT_NE(getSrtt(alt_svc, timeSystem()), 0) << alt_svc;
}
// Test simultaneous requests using auto-config and a pre-populated HTTP/3 alt-svc entry. The
// upstream request will occur over HTTP/3.
TEST_P(MixedUpstreamIntegrationTest, SimultaneousRequestsAutoWithHttp3) {
simultaneousRequest(1024, 512, 1023, 513);
}
// Test large simultaneous requests using auto-config and a pre-populated HTTP/3 alt-svc entry. The
// upstream request will occur over HTTP/3.
TEST_P(MixedUpstreamIntegrationTest, SimultaneousLargeRequestsAutoWithHttp3) {
config_helper_.setBufferLimits(1024, 1024); // Set buffer limits upstream and downstream.
simultaneousRequest(1024 * 20, 1024 * 14 + 2, 1024 * 10 + 5, 1024 * 16);
}
// Test auto-config with a pre-populated HTTP/3 alt-svc entry. With the HTTP/3 upstream "disabled"
// the upstream request will occur over HTTP/3.
TEST_P(MixedUpstreamIntegrationTest, BasicRequestAutoWithHttp2) {
// Only create an HTTP/2 upstream.
use_http2_ = true;
initialize();
codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http"))));
sendRequestAndWaitForResponse(default_request_headers_, 0, default_response_headers_, 0, 0);
}
// Same as above, only multiple requests.
TEST_P(MixedUpstreamIntegrationTest, SimultaneousRequestsAutoWithHttp2) {
use_http2_ = true;
simultaneousRequest(1024, 512, 1023, 513);
}
// Same as above, only large multiple requests.
TEST_P(MixedUpstreamIntegrationTest, SimultaneousLargeRequestsAutoWithHttp2) {
use_http2_ = true;
config_helper_.setBufferLimits(1024, 1024); // Set buffer limits upstream and downstream.
simultaneousRequest(1024 * 20, 1024 * 14 + 2, 1024 * 10 + 5, 1024 * 16);
}
INSTANTIATE_TEST_SUITE_P(Protocols, MixedUpstreamIntegrationTest,
testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams(
{Http::CodecType::HTTP2}, {Http::CodecType::HTTP3})),
HttpProtocolIntegrationTest::protocolTestParamsToString);
#endif
} // namespace
} // namespace Envoy
| [
"noreply@github.com"
] | danzh2010.noreply@github.com |
d592e22315f98f65f52093a3e5a53f0743e535e5 | 209790acca0bbcf14609ce6a5d629e2f6008bf8f | /Spring_Training/CCCC-GPLT/STL/F.cpp | 07e7628bf4aec8fb49771a415fad2868660ecdf1 | [] | no_license | JackieZhai/ICPC_Training | bf598188b7b78d5b529eb40d1e5cfa86c8fb9434 | 582400e33b68a753f8b4e92f50001141811f2127 | refs/heads/master | 2021-08-27T16:30:45.183200 | 2021-08-19T04:27:53 | 2021-08-19T04:27:53 | 128,522,278 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,471 | cpp | #include <bits/stdc++.h>
using namespace std;
struct Node{
string fr, lo;
int nu;
friend bool operator < (const Node &a, const Node &b)
{
if(a.lo==b.lo)
{
if(a.fr==b.fr)
return a.nu>b.nu;
return a.fr>b.fr;
}
return a.lo>b.lo;
}
Node(string f, string l, int n):fr(f), lo(l), nu(n){}
};
int N, M;
int main()
{
ios::sync_with_stdio(false);
cin>>N;
while(N--)
{
cin>>M;
priority_queue<Node> que, que2;
for(int i=0; i<M; i++)
{
string buf1, buf2;
cin>>buf1>>buf2;
int buf;
cin>>buf;
que.push(Node(buf1, buf2, buf));
}
while(que.size())
{
Node n=que.top();
que.pop();
if(que.size())
{
Node n2=que.top();
while(n2.fr==n.fr && n2.lo==n.lo)
{
que.pop();
n.nu+=n2.nu;
if(que.size())
n2=que.top();
else
break;
}
}
que2.push(n);
}
string nowlo="";
Node n=que2.top();
while(que2.size())
{
nowlo=n.lo;
cout<<nowlo<<endl;
while(nowlo==n.lo)
{
que2.pop();
cout<<" |----"<<n.fr<<"("<<n.nu<<")"<<endl;
if(que2.size())
n=que2.top();
else
break;
}
}
if(N)
cout<<endl;
}
return 0;
}
///原来map在用iterator遍历的时候也是有字典序的
string s1,s2;
int main()
{
typedef map<string,map<string,int> > mmp;
typedef map<string,int> mp;
mmp p;
int t,n,num,flag = 0;
cin>>t;
while(t--){
p.clear();
cin>>n;
while(n--){
cin>>s2>>s1>>num;
p[s1][s2]+=num;
}
mmp::iterator iter1;
mp::iterator iter2;
for(iter1 = p.begin(); iter1!= p.end();iter1++){
cout<<iter1->first<<endl;
for(iter2 = iter1->second.begin();iter2 != iter1->second.end();iter2++){
cout<<" |----"<<iter2->first<<"("<<iter2->second<<")"<<endl;
}
}
if(t){
cout<<endl;
}
}
return 0;
}
| [
"jackieturing@gmail.com"
] | jackieturing@gmail.com |
243b62579df517e66e0eb656e0072fb2c37f62a0 | 832fdaee7ab49f6bc18f005173695fd926e38f24 | /FindDriver.cpp | e136304889060dc6b9bd59367f75fec42207d669 | [
"Apache-2.0",
"MIT"
] | permissive | ChristophHaag/OSVR-Vive | 8012e7483d2ef82bda640ebb06b5e92498d9012b | 9a0dea88968f6d02b0ec65c8064fe4d615aad266 | refs/heads/master | 2021-01-11T14:18:48.363196 | 2016-12-02T17:29:43 | 2016-12-02T17:29:43 | 81,337,676 | 1 | 0 | null | 2017-02-08T14:22:59 | 2017-02-08T14:22:59 | null | UTF-8 | C++ | false | false | 9,998 | cpp | /** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Razer Inc.
//
// 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.
// Internal Includes
#include "FindDriver.h"
// Library/third-party includes
#include <boost/iostreams/stream.hpp>
#include <json/reader.h>
#include <json/value.h>
#include <osvr/Util/Finally.h>
#include <osvr/Util/PlatformConfig.h>
// Standard includes
#include <fstream> // std::ifstream
#include <iostream>
#include <limits.h>
#include <vector>
#if defined(OSVR_USING_FILESYSTEM_HEADER)
#include <filesystem>
#elif defined(OSVR_USING_BOOST_FILESYSTEM)
#include <boost/filesystem.hpp>
#endif
#if defined(OSVR_WINDOWS)
#include <shlobj.h>
#else
#include <cstdlib> // for getenv
#endif
#undef VIVELOADER_VERBOSE
using osvr::util::finally;
namespace osvr {
namespace vive {
#if defined(OSVR_WINDOWS)
static const auto PLATFORM_DIRNAME_BASE = "win";
static const auto DRIVER_EXTENSION = ".dll";
static const auto TOOL_EXTENSION = ".exe";
static const auto PATH_SEP = "\\";
#elif defined(OSVR_MACOSX)
/// @todo Note that there are no 64-bit steamvr runtimes or drivers on OS X
static const auto PLATFORM_DIRNAME_BASE = "osx";
static const auto DRIVER_EXTENSION = ".dylib";
static const auto TOOL_EXTENSION = "";
static const auto PATH_SEP = "/";
#elif defined(OSVR_LINUX)
static const auto PLATFORM_DIRNAME_BASE = "linux";
static const auto DRIVER_EXTENSION = ".so";
static const auto TOOL_EXTENSION = "";
static const auto PATH_SEP = "/";
#else
#error "Sorry, Valve does not produce a SteamVR runtime for your platform."
#endif
#if defined(OSVR_USING_FILESYSTEM_TR2)
using std::tr2::sys::path;
using std::tr2::sys::wpath;
using std::tr2::sys::exists;
#elif defined(OSVR_USING_FILESYSTEM_EXPERIMENTAL)
using std::experimental::filesystem::path;
#ifdef _WIN32
/// Some Windows functions deal in wide strings, easier to just let it cope
/// with it.
using wpath = path;
#endif
using std::experimental::filesystem::exists;
#elif defined(OSVR_USING_BOOST_FILESYSTEM)
using boost::filesystem::path;
using boost::filesystem::exists;
#endif
#ifdef OSVR_MACOSX
inline std::string getPlatformBitSuffix() {
// they use universal binaries but stick them in "32"
return "32";
}
#else
inline std::string getPlatformBitSuffix() {
return std::to_string(sizeof(void *) * CHAR_BIT);
}
#endif
inline std::string getPlatformDirname() {
return PLATFORM_DIRNAME_BASE + getPlatformBitSuffix();
}
inline void parsePathConfigFile(std::istream &is, Json::Value &ret) {
Json::Reader reader;
if (!reader.parse(is, ret)) {
std::cerr << "Error parsing file containing path configuration - "
"have you run SteamVR yet?"
<< std::endl;
std::cerr << reader.getFormattedErrorMessages() << std::endl;
}
}
#if defined(OSVR_WINDOWS)
inline Json::Value getPathConfig() {
PWSTR outString = nullptr;
Json::Value ret;
// It's OK to use Vista+ stuff here, since openvr_api.dll uses Vista+
// stuff too.
auto hr =
SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &outString);
if (!SUCCEEDED(hr)) {
std::cerr << "Could not get local app data directory!" << std::endl;
return ret;
}
// Free the string returned when we're all done.
auto freeString = [&] { CoTaskMemFree(outString); };
// Build the path to the file.
auto vrPaths =
wpath(outString) / wpath(L"openvr") / wpath(L"openvrpaths.vrpath");
std::ifstream is(vrPaths.string());
if (!is) {
std::wcerr << L"Could not open file containing path configuration "
L"- have you run SteamVR yet? "
<< vrPaths << L"\n";
return ret;
}
parsePathConfigFile(is, ret);
return ret;
}
#elif defined(OSVR_MACOSX) || defined(OSVR_LINUX)
inline Json::Value getPathConfig() {
auto home = std::getenv("HOME");
path homePath =
(nullptr == home
? path{"~"}
/*that's weird, should have been in environment...*/
: path{home});
auto vrPaths = homePath / path{".openvr"} / path{"openvrpaths.vrpath"};
std::ifstream is(vrPaths.string());
Json::Value ret;
if (!is) {
std::cerr << "Could not open file containing path configuration "
"- have you run SteamVR yet? "
<< vrPaths << "\n";
return ret;
}
parsePathConfigFile(is, ret);
return ret;
}
#endif
inline std::vector<std::string> getSteamVRRoots(Json::Value const &json) {
std::vector<std::string> ret;
auto &runtimes = json["runtime"];
if (!runtimes.isArray()) {
return ret;
}
for (auto &runtime : runtimes) {
ret.emplace_back(runtime.asString());
}
return ret;
}
inline std::vector<std::string> getSteamVRRoots() {
return getSteamVRRoots(getPathConfig());
}
inline void computeDriverRootAndFilePath(DriverLocationInfo &info,
std::string const &driver) {
auto p = path{info.steamVrRoot};
p /= "drivers";
p /= driver;
p /= "bin";
p /= getPlatformDirname();
info.driverRoot = p.string();
p /= ("driver_" + driver + DRIVER_EXTENSION);
info.driverFile = p.string();
}
/// Underlying implementation - hand it the preloaded json.
inline DriverLocationInfo findDriver(Json::Value const &json,
std::string const &driver) {
DriverLocationInfo info;
auto &runtimes = json["runtime"];
if (!runtimes.isArray()) {
return info;
}
for (auto &root : runtimes) {
info.steamVrRoot = root.asString();
info.driverName = driver;
computeDriverRootAndFilePath(info, driver);
#ifdef VIVELOADER_VERBOSE
std::cout << "Will try to load driver from:\n"
<< info.driverFile << std::endl;
if (exists(path{info.driverRoot})) {
std::cout << "Driver root exists" << std::endl;
}
if (exists(path{info.driverFile})) {
std::cout << "Driver file exists" << std::endl;
}
#endif
if (exists(path{info.driverRoot}) &&
exists(path{info.driverFile})) {
info.found = true;
return info;
}
}
info = DriverLocationInfo{};
return info;
}
DriverLocationInfo findDriver(std::string const &driver) {
return findDriver(getPathConfig(), driver);
}
std::string getToolLocation(std::string const &toolName,
std::string const &steamVrRoot) {
std::vector<std::string> searchPath;
if (!steamVrRoot.empty()) {
searchPath = {steamVrRoot};
} else {
searchPath = getSteamVRRoots();
}
for (auto &root : searchPath) {
auto p = path{root};
p /= "bin";
p /= getPlatformDirname();
p /= (toolName + TOOL_EXTENSION);
if (exists(p)) {
return p.string();
}
}
return std::string{};
}
/// Underlying implementation - hand it the preloaded json.
inline ConfigDirs findConfigDirs(Json::Value const &json,
std::string const &driver) {
ConfigDirs ret;
auto const &configLocations = json["config"];
if (!configLocations.isArray()) {
return ret;
}
for (auto &configDir : configLocations) {
auto configPath = path{configDir.asString()};
if (!exists(configPath)) {
continue;
}
ret.rootConfigDir = configPath.string();
ret.driverConfigDir = (configPath / path{driver}).string();
ret.valid = true;
return ret;
}
ret = ConfigDirs{};
return ret;
}
ConfigDirs findConfigDirs(std::string const & /*steamVrRoot*/,
std::string const &driver) {
return findConfigDirs(getPathConfig(), driver);
}
LocationInfo findLocationInfoForDriver(std::string const &driver) {
auto json = getPathConfig();
LocationInfo ret;
auto config = findConfigDirs(json, driver);
if (config.valid) {
ret.configFound = true;
ret.rootConfigDir = config.rootConfigDir;
ret.driverConfigDir = config.driverConfigDir;
}
auto driverLoc = findDriver(json, driver);
if (driverLoc.found) {
ret.driverFound = true;
ret.steamVrRoot = driverLoc.steamVrRoot;
ret.driverRoot = driverLoc.driverRoot;
ret.driverName = driverLoc.driverName;
ret.driverFile = driverLoc.driverFile;
}
ret.found = (driverLoc.found && config.valid);
return ret;
}
} // namespace vive
} // namespace osvr
| [
"ryan@sensics.com"
] | ryan@sensics.com |
80d47d7f9698b1570102fc263b511c5612f1f5ae | c261cc70f98c6ef802071743d86234e4c20d76f6 | /rclcpp/test/test_time.cpp | 448d123e700e867a4f0bf82c1f6e28a81fbf4705 | [
"Apache-2.0"
] | permissive | gaoethan/rclcpp | 741eb4906477d25c56cfcb3208675a90fd24a4df | bea1a52e24eaea0ad141a4d13dfa4606fcf190e7 | refs/heads/master | 2021-09-03T12:46:12.895651 | 2017-12-09T01:24:54 | 2017-12-09T02:06:51 | 109,950,139 | 0 | 0 | null | 2017-11-08T08:46:31 | 2017-11-08T08:46:31 | null | UTF-8 | C++ | false | false | 4,833 | cpp | // Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <algorithm>
#include <limits>
#include <string>
#include "rcl/error_handling.h"
#include "rcl/time.h"
#include "rclcpp/clock.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp/time.hpp"
class TestTime : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
rclcpp::init(0, nullptr);
}
};
TEST(TestTime, clock_type_access) {
rclcpp::Clock ros_clock(RCL_ROS_TIME);
EXPECT_EQ(RCL_ROS_TIME, ros_clock.get_clock_type());
rclcpp::Clock system_clock(RCL_SYSTEM_TIME);
EXPECT_EQ(RCL_SYSTEM_TIME, system_clock.get_clock_type());
rclcpp::Clock steady_clock(RCL_STEADY_TIME);
EXPECT_EQ(RCL_STEADY_TIME, steady_clock.get_clock_type());
}
TEST(TestTime, time_sources) {
using builtin_interfaces::msg::Time;
rclcpp::Clock ros_clock(RCL_ROS_TIME);
Time ros_now = ros_clock.now();
EXPECT_NE(0, ros_now.sec);
EXPECT_NE(0u, ros_now.nanosec);
rclcpp::Clock system_clock(RCL_ROS_TIME);
Time system_now = system_clock.now();
EXPECT_NE(0, system_now.sec);
EXPECT_NE(0u, system_now.nanosec);
rclcpp::Clock steady_clock(RCL_STEADY_TIME);
Time steady_now = steady_clock.now();
EXPECT_NE(0, steady_now.sec);
EXPECT_NE(0u, steady_now.nanosec);
}
TEST(TestTime, conversions) {
rclcpp::Clock system_clock(RCL_ROS_TIME);
rclcpp::Time now = system_clock.now();
builtin_interfaces::msg::Time now_msg = now;
rclcpp::Time now_again = now_msg;
EXPECT_EQ(now.nanoseconds(), now_again.nanoseconds());
builtin_interfaces::msg::Time msg;
msg.sec = 12345;
msg.nanosec = 67890;
rclcpp::Time time = msg;
EXPECT_EQ(
RCL_S_TO_NS(static_cast<uint64_t>(msg.sec)) + static_cast<uint64_t>(msg.nanosec),
time.nanoseconds());
EXPECT_EQ(static_cast<uint64_t>(msg.sec), RCL_NS_TO_S(time.nanoseconds()));
builtin_interfaces::msg::Time negative_time_msg;
negative_time_msg.sec = -1;
negative_time_msg.nanosec = 1;
EXPECT_ANY_THROW({
rclcpp::Time negative_time = negative_time_msg;
});
EXPECT_ANY_THROW(rclcpp::Time(-1, 1));
EXPECT_ANY_THROW({
rclcpp::Time assignment(1, 2);
assignment = negative_time_msg;
});
}
TEST(TestTime, operators) {
rclcpp::Time old(1, 0);
rclcpp::Time young(2, 0);
EXPECT_TRUE(old < young);
EXPECT_TRUE(young > old);
EXPECT_TRUE(old <= young);
EXPECT_TRUE(young >= old);
EXPECT_FALSE(young == old);
EXPECT_TRUE(young != old);
rclcpp::Duration sub = young - old;
EXPECT_EQ(sub.nanoseconds(), (rcl_duration_value_t)(young.nanoseconds() - old.nanoseconds()));
EXPECT_EQ(sub, young - old);
rclcpp::Time system_time(0, 0, RCL_SYSTEM_TIME);
rclcpp::Time steady_time(0, 0, RCL_STEADY_TIME);
EXPECT_ANY_THROW((void)(system_time == steady_time));
EXPECT_ANY_THROW((void)(system_time != steady_time));
EXPECT_ANY_THROW((void)(system_time <= steady_time));
EXPECT_ANY_THROW((void)(system_time >= steady_time));
EXPECT_ANY_THROW((void)(system_time < steady_time));
EXPECT_ANY_THROW((void)(system_time > steady_time));
EXPECT_ANY_THROW((void)(system_time - steady_time));
rclcpp::Clock system_clock(RCL_ROS_TIME);
rclcpp::Clock steady_clock(RCL_STEADY_TIME);
rclcpp::Time now = system_clock.now();
rclcpp::Time later = steady_clock.now();
EXPECT_ANY_THROW((void)(now == later));
EXPECT_ANY_THROW((void)(now != later));
EXPECT_ANY_THROW((void)(now <= later));
EXPECT_ANY_THROW((void)(now >= later));
EXPECT_ANY_THROW((void)(now < later));
EXPECT_ANY_THROW((void)(now > later));
EXPECT_ANY_THROW((void)(now - later));
for (auto time_source : {RCL_ROS_TIME, RCL_SYSTEM_TIME, RCL_STEADY_TIME}) {
rclcpp::Time time = rclcpp::Time(0, 0, time_source);
rclcpp::Time copy_constructor_time(time);
rclcpp::Time assignment_op_time = rclcpp::Time(1, 0, time_source);
assignment_op_time = time;
EXPECT_TRUE(time == copy_constructor_time);
EXPECT_TRUE(time == assignment_op_time);
}
}
TEST(TestTime, overflows) {
rclcpp::Time max_time(std::numeric_limits<rcl_time_point_value_t>::max());
rclcpp::Time min_time(std::numeric_limits<rcl_time_point_value_t>::min());
rclcpp::Duration one(1);
EXPECT_THROW(max_time + one, std::overflow_error);
EXPECT_THROW(min_time - one, std::underflow_error);
}
| [
"noreply@github.com"
] | gaoethan.noreply@github.com |
d801bb7b4935f11ab424b1e032bb16cf0b1fa993 | e2999855739caf786601dd9d49183cfd035dfb60 | /examples/hamilton/ej2.cpp | bbd0c19141c91dffe2053aad4a2498a19c31926a | [
"Apache-2.0"
] | permissive | tec-csf/tc2017-t3-primavera-2020-GerAng1 | 88454686fa01e31aec05a858524065fa74866fae | 49e70c48800062a8e7f1183a2db9233737bd1e35 | refs/heads/master | 2021-05-25T19:11:55.150847 | 2020-04-14T13:39:10 | 2020-04-14T13:39:10 | 253,885,783 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,205 | cpp | #include <algorithm> // std::find
#include <iostream> // cin y cout
#include <vector>
#include "../../sources/Graph.hpp"
/* Itera para regresar un apuntador al Vertex con menor coste.
* Toma como criterios que el Vertex no esté en vector yaesta;
* y que camino tiene el valor más bajo.*/
template <class V, class E>
Vertex<V, E> * busca(const int &num_nodes, Vertex<V, E> * &v_curso, std::vector< Vertex<V, E> * >& yaesta, std::vector<int>& costos, int j)
{
if (j < num_nodes)
{
auto mejor_edge = v_curso->minEdge(yaesta, num_nodes);
costos.push_back(mejor_edge->getInfo());
auto mejor_vertice = mejor_edge->getTarget();
yaesta.push_back(mejor_vertice);
return mejor_vertice;
}
}
int main(int argc, char const *argv[])
{
std::cout << "\n\n\t\t-----INICIO PROGRAMA CICLO HAMILTONIANO-----\n\n" << std::endl;
Graph<std::string, int> mapa("Ejemplo 2");
/* Crear vértices */
Vertex<std::string, int> * V0 = new Vertex<std::string, int>("V0");
Vertex<std::string, int> * V1 = new Vertex<std::string, int>("V1");
Vertex<std::string, int> * V2 = new Vertex<std::string, int>("V2");
Vertex<std::string, int> * V3 = new Vertex<std::string, int>("V3");
Vertex<std::string, int> * V4 = new Vertex<std::string, int>("V4");
Vertex<std::string, int> * V5 = new Vertex<std::string, int>("V5");
/* Adicionar vértices al grafo */
mapa.addVertex(V0);
mapa.addVertex(V1);
mapa.addVertex(V2);
mapa.addVertex(V3);
mapa.addVertex(V4);
mapa.addVertex(V5);
/* Adicionar aristas */
mapa.addEdge(V0, V1, 20);
mapa.addEdge(V0, V2, 10);
mapa.addEdge(V0, V5, 40);
mapa.addEdge(V1, V3, 40);
mapa.addEdge(V1, V5, 30);
mapa.addEdge(V2, V4, 30);
mapa.addEdge(V3, V4, 20);
mapa.addEdge(V3, V5, 50);
std::vector< Vertex<std::string, int> * > nodes = mapa.getNodes();
int num_nodes = nodes.size();
std::cout << "Nodos en grafo: " << num_nodes << std::endl;
std::vector< Vertex<std::string, int> * > yaesta;
std::vector<int> costos;
Vertex<std::string, int> * v_curso = nodes[0];
yaesta.push_back(v_curso);
std::cout << "Camino a tomar: " << std::endl;
for (int j = 0; j <= nodes.size(); ++j)
{
std::cout << v_curso->getInfo() << std::endl;
v_curso = busca(num_nodes, v_curso, yaesta, costos, j);
if(v_curso == nodes[0] && yaesta.size() != num_nodes + 1)
{
std::cout << v_curso->getInfo() << std::endl;
std::cout << "No se cumplió un circuito Hamiltoniano." << std::endl;
break;
}
}
std::cout << "Coste total: ";
int total = 0;
for (int i = 0; i < costos.size(); ++i)
{
if (i == 0) { std::cout << costos[i]; }
else { std::cout << " + " << costos[i]; }
total += costos[i];
}
std::cout << " = " << total << '\n' << std::endl;
char ans;
std::cout << "¿Ver grafo? [Y/N]: ";
std::cin >> ans;
if (ans == 'Y' || ans == 'y')
{
std::cout << mapa << std::endl;
}
std::cout << "\n\n\t\t----PROGRAMA CICLO HAMILTONIANO FINALIZADO----\n" << std::endl;
return 0;
}
| [
"ganglada.dlanda@outlook.com"
] | ganglada.dlanda@outlook.com |
6fa16ec662d9200c6a862729802ccc9c5efe07e1 | ffd1a3ce6ab76cfadd35d4a9198529904fe4bcd2 | /example/basic.cpp | ddf8ebead9e99ecd2bf4b09da888af5449e3b96c | [] | no_license | xinyang-go/gcpp | adeb6334ced81a018b655194463e51cdb242a440 | 6e62a2f3eecfe00932e1310806eeb1559ec46dfb | refs/heads/main | 2023-03-13T02:15:57.818657 | 2021-02-18T16:00:56 | 2021-02-18T16:00:56 | 340,101,734 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | cpp | //
// Created by xinyang on 2021/2/18.
//
#include <gcpp/gcpp.hpp>
#include <iostream>
struct A {
gcpp::gc_ptr<A> p_a;
~A() {
std::cout << "A destroy!" << std::endl;
}
};
int main() {
{
auto a1 = gcpp::gc_new<A>();
auto a2 = gcpp::gc_new<A>();
a1->p_a = a2;
a2->p_a = a1;
}
std::cout << "main stop!" << std::endl;
// optional: 线程结束时会自动GC当前线程。
gcpp::gc_collect();
return 0;
}
| [
"txy15436@gmail.com"
] | txy15436@gmail.com |
63f7de90de162415bb250e876f3e93fc50d5b303 | 51c035f61d4412c90fc44a0fb5b43cbd0f17761f | /Socket.cpp | b4a6d8ec774c5b57f0b21cb968c6125c4faf89b5 | [] | no_license | OldSchoolTeam/GalconGameServer | a62b85d6493d25f34ba90906232cabbc218f27d7 | 78413dcd04fc3f2fe563f31a88414a4069f87484 | refs/heads/master | 2021-01-23T02:58:51.938016 | 2011-06-15T11:22:23 | 2011-06-15T11:22:23 | 1,832,012 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 434 | cpp | #include "Socket.h"
CSocket::CSocket(int i_id, QObject *parent) : QTcpSocket(parent)
{
m_id = i_id;
}
int CSocket::GetId()
{
return m_id;
}
void CSocket::SendMsg(QString i_msg)
{
QByteArray msg;
QDataStream out(&msg, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);
out << quint16(0) << i_msg.toUtf8();
out.device()->seek(0);
out << quint16(msg.size()-sizeof(quint16));
write(msg);
}
| [
"ya.sashok@gmail.com"
] | ya.sashok@gmail.com |
f35529117e86fc5d90acb9df3d9b9e3e7f254a01 | 28e9e5cba227042acc62906d71ab9e4191c7728c | /code_rendu/src/Lab/SwarmBacterium.hpp | dac8388ec3b3a5b76da8ffb32ae1233693227974 | [] | no_license | harpine/projetsv2020 | 8e1c27a84c1dfb4f235d0f2fcf531aea7ecbaca4 | 3c5c9399a7506cf05a8b7c670bbc4f940508f400 | refs/heads/master | 2022-09-16T02:11:22.648991 | 2020-05-24T17:34:34 | 2020-05-24T17:34:34 | 246,159,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,077 | hpp | #ifndef SWARMBACTERIUM_HPP
#define SWARMBACTERIUM_HPP
#include "Bacterium.hpp"
#include "Swarm.hpp"
#include <SFML/Graphics.hpp>
#include <Utility/DiffEqSolver.hpp>
class SwarmBacterium: public Bacterium, public DiffEqFunction
{
public:
//Constructeur et destructeur:
SwarmBacterium(const Vec2d& poscenter, Swarm*& swarm);
virtual ~SwarmBacterium() override;
//Getters:
virtual j::Value& getConfig() const override;
//permet d'accéder aux configurations de Swarmbacterium
Vec2d getSpeedVector() const;
//renvoie la vitesse courante (direction * une valeur)
//Autres méthodes:
virtual void drawOn(sf::RenderTarget& target) const override;
//permet de dessiner une bactérie
virtual Bacterium* copie() override;
//copie une bactérie
virtual void move(sf::Time dt) override;
//permet à une bactérie de se déplacer
virtual Vec2d f(Vec2d position, Vec2d speed) const override;
//modélise la force d'attraction des bactéries
private:
//Attributs
Swarm* swarm_;
};
#endif // SWARMBACTERIUM_HPP
| [
"helena.binkova.uni@gmail.com"
] | helena.binkova.uni@gmail.com |
24fd8e7d84d625bc0a7c5142c200c4b7c270c280 | 33b2d2d14b34b03658f7954d136ec3dea68b86e0 | /src/qt/qrcodedialog.cpp | 6fb2221d957e5ce580cdd6dc9fdc8990e159828d | [
"MIT"
] | permissive | Jahare/Electric | 3b33aa1747a6099cb8f5069d36664a1d59bc1e0c | cc67c12b78b7693a7150ef7fd12369038451cece | refs/heads/master | 2021-08-23T17:51:05.378142 | 2014-03-04T22:35:13 | 2014-03-04T22:35:13 | 113,246,593 | 0 | 0 | null | 2017-12-06T00:00:36 | 2017-12-06T00:00:36 | null | UTF-8 | C++ | false | false | 4,311 | cpp | #include "qrcodedialog.h"
#include "ui_qrcodedialog.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include <QPixmap>
#include <QUrl>
#include <qrencode.h>
QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) :
QDialog(parent),
ui(new Ui::QRCodeDialog),
model(0),
address(addr)
{
ui->setupUi(this);
setWindowTitle(QString("%1").arg(address));
ui->chkReqPayment->setVisible(enableReq);
ui->lblAmount->setVisible(enableReq);
ui->lnReqAmount->setVisible(enableReq);
ui->lnLabel->setText(label);
ui->btnSaveAs->setEnabled(false);
genCode();
}
QRCodeDialog::~QRCodeDialog()
{
delete ui;
}
void QRCodeDialog::setModel(OptionsModel *model)
{
this->model = model;
if (model)
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void QRCodeDialog::genCode()
{
QString uri = getURI();
if (uri != "")
{
ui->lblQRCode->setText("");
QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code)
{
ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
return;
}
myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300));
ui->outUri->setPlainText(uri);
}
}
QString QRCodeDialog::getURI()
{
QString ret = QString("mooncoin:%1").arg(address);
int paramCount = 0;
ui->outUri->clear();
if (ui->chkReqPayment->isChecked())
{
if (ui->lnReqAmount->validate())
{
// even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21)
ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value()));
paramCount++;
}
else
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("The entered amount is invalid, please check."));
return QString("");
}
}
if (!ui->lnLabel->text().isEmpty())
{
QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text()));
ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
paramCount++;
}
if (!ui->lnMessage->text().isEmpty())
{
QString msg(QUrl::toPercentEncoding(ui->lnMessage->text()));
ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
paramCount++;
}
// limit URI length to prevent a DoS against the QR-Code dialog
if (ret.length() > MAX_URI_LENGTH)
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
return QString("");
}
ui->btnSaveAs->setEnabled(true);
return ret;
}
void QRCodeDialog::on_lnReqAmount_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnLabel_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnMessage_textChanged()
{
genCode();
}
void QRCodeDialog::on_btnSaveAs_clicked()
{
QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)"));
if (!fn.isEmpty())
myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn);
}
void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked)
{
if (!fChecked)
// if chkReqPayment is not active, don't display lnReqAmount as invalid
ui->lnReqAmount->setValid(true);
genCode();
}
void QRCodeDialog::updateDisplayUnit()
{
if (model)
{
// Update lnReqAmount with the current unit
ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit());
}
}
| [
"root@WebServer.HackShard.Com"
] | root@WebServer.HackShard.Com |
622411a96228910c05612fb15f47fe6f64a5d6d8 | 9cc0cdfb379d3da31899e4d9cb260136b55df382 | /src/examples/simple_quadratic_cone/simple_quadratic_cone.cpp | 6fa50b52c13445596163124392135eb76f75ba3b | [
"BSD-2-Clause"
] | permissive | stringhamc/Optizelle | c066b50a116e55d13a6f9b88a9b25edcf9d8ac21 | a826b7c4f6d66c31a01537d8b500ea2c0e9665c5 | refs/heads/master | 2021-01-18T16:34:26.892861 | 2015-12-06T15:44:39 | 2015-12-06T15:44:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,002 | cpp | // Optimize a simple problem with an optimal solution of (2.5,2.5)
#include <iostream>
#include <iomanip>
#include "optizelle/optizelle.h"
#include "optizelle/vspaces.h"
#include "optizelle/json.h"
// Squares its input
template <typename Real>
Real sq(Real x){
return x*x;
}
// Define a simple objective where
//
// f(x,y)=(x-3)^2+(y-2)^2
//
struct MyObj : public Optizelle::ScalarValuedFunction <double,Optizelle::Rm> {
typedef double Real;
typedef Optizelle::Rm <Real> X;
// Evaluation
double eval(const X::Vector& x) const {
return sq(x[0]-Real(3.))+sq(x[1]-Real(2.));
}
// Gradient
void grad(
const X::Vector& x,
X::Vector& g
) const {
g[0]=2*x[0]-6;
g[1]=2*x[1]-4;
}
// Hessian-vector product
void hessvec(
const X::Vector& x,
const X::Vector& dx,
X::Vector& H_dx
) const {
H_dx[0]= Real(2.)*dx[0];
H_dx[1]= Real(2.)*dx[1];
}
};
// Define a simple SOCP inequality
//
// h(x,y) = [ y >= |x| ]
// h(x,y) = (y,x) >=_Q 0
//
struct MyIneq :
public Optizelle::VectorValuedFunction <double,Optizelle::Rm,Optizelle::SQL>
{
typedef Optizelle::Rm <double> X;
typedef Optizelle::SQL <double> Y;
typedef double Real;
// y=h(x)
void eval(
const X::Vector& x,
Y::Vector& y
) const {
y(1,1)=x[1];
y(1,2)=x[0];
}
// y=h'(x)dx
void p(
const X::Vector& x,
const X::Vector& dx,
Y::Vector& y
) const {
y(1,1)= dx[1];
y(1,2)= dx[0];
}
// z=h'(x)*dy
void ps(
const X::Vector& x,
const Y::Vector& dy,
X::Vector& z
) const {
z[0]= dy(1,2);
z[1]= dy(1,1);
}
// z=(h''(x)dx)*dy
void pps(
const X::Vector& x,
const X::Vector& dx,
const Y::Vector& dy,
X::Vector& z
) const {
X::zero(z);
}
};
int main(int argc,char* argv[]){
// Create some type shortcuts
typedef Optizelle::Rm <double> X;
typedef Optizelle::SQL <double> Z;
typedef X::Vector X_Vector;
typedef Z::Vector Z_Vector;
// Read in the name for the input file
if(argc!=2) {
std::cerr << "simple_quadratic_cone <parameters>" << std::endl;
exit(EXIT_FAILURE);
}
std::string fname(argv[1]);
// Generate an initial guess for the primal
X_Vector x(2);
x[0]=1.2; x[1]=3.1;
// Generate an initial guess for the dual
std::vector <Optizelle::Natural> sizes(1);
sizes[0]=2;
std::vector <Optizelle::Cone::t> types(1);
types[0]=Optizelle::Cone::Quadratic;
Z_Vector z(types,sizes);
// Create an optimization state
Optizelle::InequalityConstrained <double,Optizelle::Rm,Optizelle::SQL>
::State::t state(x,z);
// Read the parameters from file
Optizelle::json::InequalityConstrained <double,Optizelle::Rm,Optizelle::SQL>
::read(Optizelle::Messaging(),fname,state);
// Create a bundle of functions
Optizelle::InequalityConstrained<double,Optizelle::Rm,Optizelle::SQL>
::Functions::t fns;
fns.f.reset(new MyObj);
fns.h.reset(new MyIneq);
// Solve the optimization problem
Optizelle::InequalityConstrained <double,Optizelle::Rm,Optizelle::SQL>
::Algorithms::getMin(Optizelle::Messaging(),fns,state);
// Print out the reason for convergence
std::cout << "The algorithm converged due to: " <<
Optizelle::StoppingCondition::to_string(state.opt_stop) << std::endl;
// Print out the final answer
std::cout << std::setprecision(16) << std::scientific
<< "The optimal point is: (" << state.x[0] << ','
<< state.x[1] << ')' << std::endl;
// Write out the final answer to file
Optizelle::json::InequalityConstrained <double,Optizelle::Rm,Optizelle::SQL>
::write_restart(Optizelle::Messaging(),"solution.json",state);
// Successful termination
return EXIT_SUCCESS;
}
| [
"joe@optimojoe.com"
] | joe@optimojoe.com |
6b965226713b7686cbe50896a87a12f023725d16 | 9da42e04bdaebdf0193a78749a80c4e7bf76a6cc | /third_party/gecko-2/win32/include/nsIXTFPrivate.h | 904b1a4dc23a2fe48db4ae018fb5170134c0fc59 | [
"Apache-2.0"
] | permissive | bwp/SeleniumWebDriver | 9d49e6069881845e9c23fb5211a7e1b8959e2dcf | 58221fbe59fcbbde9d9a033a95d45d576b422747 | refs/heads/master | 2021-01-22T21:32:50.541163 | 2012-11-09T16:19:48 | 2012-11-09T16:19:48 | 6,602,097 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,375 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/content/xtf/public/nsIXTFPrivate.idl
*/
#ifndef __gen_nsIXTFPrivate_h__
#define __gen_nsIXTFPrivate_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIXTFPrivate */
#define NS_IXTFPRIVATE_IID_STR "13ef3d54-1dd1-4a5c-a8d5-a04a327fb9b6"
#define NS_IXTFPRIVATE_IID \
{0x13ef3d54, 0x1dd1, 0x4a5c, \
{ 0xa8, 0xd5, 0xa0, 0x4a, 0x32, 0x7f, 0xb9, 0xb6 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIXTFPrivate : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IXTFPRIVATE_IID)
/* readonly attribute nsISupports inner; */
NS_SCRIPTABLE NS_IMETHOD GetInner(nsISupports **aInner) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIXTFPrivate, NS_IXTFPRIVATE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIXTFPRIVATE \
NS_SCRIPTABLE NS_IMETHOD GetInner(nsISupports **aInner);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIXTFPRIVATE(_to) \
NS_SCRIPTABLE NS_IMETHOD GetInner(nsISupports **aInner) { return _to GetInner(aInner); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIXTFPRIVATE(_to) \
NS_SCRIPTABLE NS_IMETHOD GetInner(nsISupports **aInner) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetInner(aInner); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsXTFPrivate : public nsIXTFPrivate
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIXTFPRIVATE
nsXTFPrivate();
private:
~nsXTFPrivate();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsXTFPrivate, nsIXTFPrivate)
nsXTFPrivate::nsXTFPrivate()
{
/* member initializers and constructor code */
}
nsXTFPrivate::~nsXTFPrivate()
{
/* destructor code */
}
/* readonly attribute nsISupports inner; */
NS_IMETHODIMP nsXTFPrivate::GetInner(nsISupports **aInner)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIXTFPrivate_h__ */
| [
"haleokekahuna@gmail.com"
] | haleokekahuna@gmail.com |
b9c4367f6127967b815a86527688bd4b08f27efe | 3c44e638b331b356aaa9c661b56fc490a5df538c | /Plugins/RakNet/Source/RakNet/Private/GetTime.cpp | d9fe10db19117e8447be1855abfd1dc8705744e0 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | jashking/RN4UE4 | 31a408224542fb090614f7ca6438100c5f44f060 | 50b17bedfe6bb7c28aae9d30f9a43ca51894d86c | refs/heads/master | 2021-01-19T12:47:43.071093 | 2017-04-21T05:42:15 | 2017-04-21T05:42:15 | 88,045,585 | 1 | 1 | null | 2017-04-12T11:44:48 | 2017-04-12T11:44:48 | null | UTF-8 | C++ | false | false | 4,703 | cpp | /*
* Copyright (c) 2014, Oculus VR, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/// \file
///
#include "RakNetPrivatePCH.h"
#if defined(_WIN32)
#include "WindowsIncludes.h"
#if !defined(WINDOWS_PHONE_8)
// To call timeGetTime
// on Code::Blocks, this needs to be libwinmm.a instead
#pragma comment(lib, "Winmm.lib")
#endif
#endif
#include "GetTime.h"
#if defined(_WIN32)
//DWORD mProcMask;
//DWORD mSysMask;
//HANDLE mThread;
#else
#include <sys/time.h>
#include <unistd.h>
RakNet::TimeUS initialTime;
#endif
static bool initialized=false;
#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0
#include "SimpleMutex.h"
RakNet::TimeUS lastNormalizedReturnedValue=0;
RakNet::TimeUS lastNormalizedInputValue=0;
/// This constraints timer forward jumps to 1 second, and does not let it jump backwards
/// See http://support.microsoft.com/kb/274323 where the timer can sometimes jump forward by hours or days
/// This also has the effect where debugging a sending system won't treat the time spent halted past 1 second as elapsed network time
RakNet::TimeUS NormalizeTime(RakNet::TimeUS timeIn)
{
RakNet::TimeUS diff, lastNormalizedReturnedValueCopy;
static RakNet::SimpleMutex mutex;
mutex.Lock();
if (timeIn>=lastNormalizedInputValue)
{
diff = timeIn-lastNormalizedInputValue;
if (diff > GET_TIME_SPIKE_LIMIT)
lastNormalizedReturnedValue+=GET_TIME_SPIKE_LIMIT;
else
lastNormalizedReturnedValue+=diff;
}
else
lastNormalizedReturnedValue+=GET_TIME_SPIKE_LIMIT;
lastNormalizedInputValue=timeIn;
lastNormalizedReturnedValueCopy=lastNormalizedReturnedValue;
mutex.Unlock();
return lastNormalizedReturnedValueCopy;
}
#endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0
RakNet::Time RakNet::GetTime( void )
{
return (RakNet::Time)(GetTimeUS()/1000);
}
RakNet::TimeMS RakNet::GetTimeMS( void )
{
return (RakNet::TimeMS)(GetTimeUS()/1000);
}
#if defined(_WIN32)
RakNet::TimeUS GetTimeUS_Windows( void )
{
if ( initialized == false)
{
initialized = true;
// Save the current process
#if !defined(_WIN32_WCE)
// HANDLE mProc = GetCurrentProcess();
// Get the current Affinity
#if _MSC_VER >= 1400 && defined (_M_X64)
// GetProcessAffinityMask(mProc, (PDWORD_PTR)&mProcMask, (PDWORD_PTR)&mSysMask);
#else
// GetProcessAffinityMask(mProc, &mProcMask, &mSysMask);
#endif
// mThread = GetCurrentThread();
#endif // _WIN32_WCE
}
// 9/26/2010 In China running LuDaShi, QueryPerformanceFrequency has to be called every time because CPU clock speeds can be different
RakNet::TimeUS curTime;
LARGE_INTEGER PerfVal;
LARGE_INTEGER yo1;
QueryPerformanceFrequency( &yo1 );
QueryPerformanceCounter( &PerfVal );
__int64 quotient, remainder;
quotient=((PerfVal.QuadPart) / yo1.QuadPart);
remainder=((PerfVal.QuadPart) % yo1.QuadPart);
curTime = (RakNet::TimeUS) quotient*(RakNet::TimeUS)1000000 + (remainder*(RakNet::TimeUS)1000000 / yo1.QuadPart);
#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0
return NormalizeTime(curTime);
#else
return curTime;
#endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0
}
#elif defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__)
RakNet::TimeUS GetTimeUS_Linux( void )
{
timeval tp;
if ( initialized == false)
{
gettimeofday( &tp, 0 );
initialized=true;
// I do this because otherwise RakNet::Time in milliseconds won't work as it will underflow when dividing by 1000 to do the conversion
initialTime = ( tp.tv_sec ) * (RakNet::TimeUS) 1000000 + ( tp.tv_usec );
}
// GCC
RakNet::TimeUS curTime;
gettimeofday( &tp, 0 );
curTime = ( tp.tv_sec ) * (RakNet::TimeUS) 1000000 + ( tp.tv_usec );
#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0
return NormalizeTime(curTime - initialTime);
#else
return curTime - initialTime;
#endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0
}
#endif
RakNet::TimeUS RakNet::GetTimeUS( void )
{
#if defined(_WIN32)
return GetTimeUS_Windows();
#else
return GetTimeUS_Linux();
#endif
}
bool RakNet::GreaterThan(RakNet::Time a, RakNet::Time b)
{
// a > b?
const RakNet::Time halfSpan =(RakNet::Time) (((RakNet::Time)(const RakNet::Time)-1)/(RakNet::Time)2);
return b!=a && b-a>halfSpan;
}
bool RakNet::LessThan(RakNet::Time a, RakNet::Time b)
{
// a < b?
const RakNet::Time halfSpan = ((RakNet::Time)(const RakNet::Time)-1)/(RakNet::Time)2;
return b!=a && b-a<halfSpan;
}
| [
"yujen.dev@gmail.com"
] | yujen.dev@gmail.com |
0a7f353369b13638c83f3275f26bbc55362751af | 20a06d71f4308446ecf0d7d2a3ef1879279ba2c1 | /src/qt/transactionview.h | 30b0b48b23546987ea76ebd5e672a37d18472097 | [
"MIT"
] | permissive | BTCGreen/BTC-Green---Cumulative-Update-01 | 3ee84ed15fe644cb2faa49de3c34bfbc15b6a8e9 | 39c783fad9b3e697970825ef28233d32e0b75cf0 | refs/heads/main | 2023-03-29T10:22:04.352030 | 2021-04-01T23:48:50 | 2021-04-01T23:48:50 | 353,640,271 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,123 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2017-2019 The bitcoingreen developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_TRANSACTIONVIEW_H
#define BITCOIN_QT_TRANSACTIONVIEW_H
#include "guiutil.h"
#include <QKeyEvent>
#include <QWidget>
#include <QAction>
class TransactionFilterProxy;
class WalletModel;
QT_BEGIN_NAMESPACE
class QComboBox;
class QDateTimeEdit;
class QFrame;
class QItemSelectionModel;
class QLineEdit;
class QMenu;
class QModelIndex;
class QSignalMapper;
class QTableView;
QT_END_NAMESPACE
/** Widget showing the transaction list for a wallet, including a filter row.
Using the filter row, the user can view or export a subset of the transactions.
*/
class TransactionView : public QWidget
{
Q_OBJECT
public:
explicit TransactionView(QWidget* parent = 0);
void setModel(WalletModel* model);
// Date ranges for filter
enum DateEnum {
All,
Today,
ThisWeek,
ThisMonth,
LastMonth,
ThisYear,
Range
};
enum ColumnWidths {
STATUS_COLUMN_WIDTH = 23,
WATCHONLY_COLUMN_WIDTH = 23,
DATE_COLUMN_WIDTH = 120,
TYPE_COLUMN_WIDTH = 240,
AMOUNT_MINIMUM_COLUMN_WIDTH = 120,
MINIMUM_COLUMN_WIDTH = 23
};
private:
WalletModel* model;
TransactionFilterProxy* transactionProxyModel;
QTableView* transactionView;
QComboBox* dateWidget;
QComboBox* typeWidget;
QComboBox* watchOnlyWidget;
QLineEdit* addressWidget;
QLineEdit* amountWidget;
QAction* hideOrphansAction;
QMenu* contextMenu;
QSignalMapper* mapperThirdPartyTxUrls;
QFrame* dateRangeWidget;
QDateTimeEdit* dateFrom;
QDateTimeEdit* dateTo;
QWidget* createDateRangeWidget();
GUIUtil::TableViewLastColumnResizingFixer* columnResizingFixer;
virtual void resizeEvent(QResizeEvent* event);
bool eventFilter(QObject* obj, QEvent* event);
private slots:
void contextualMenu(const QPoint&);
void dateRangeChanged();
void showDetails();
void copyAddress();
void editLabel();
void copyLabel();
void copyAmount();
void copyTxID();
void openThirdPartyTxUrl(QString url);
void updateWatchOnlyColumn(bool fHaveWatchOnly);
signals:
void doubleClicked(const QModelIndex&);
/** Fired when a message should be reported to the user */
void message(const QString& title, const QString& message, unsigned int style);
/** Send computed sum back to wallet-view */
void trxAmount(QString amount);
public slots:
void chooseDate(int idx);
void chooseType(int idx);
void hideOrphans(bool fHide);
void updateHideOrphans(bool fHide);
void chooseWatchonly(int idx);
void changedPrefix(const QString& prefix);
void changedAmount(const QString& amount);
void exportClicked();
void focusTransaction(const QModelIndex&);
void computeSum();
};
#endif // BITCOIN_QT_TRANSACTIONVIEW_H
| [
"81521327+BTCGreen@users.noreply.github.com"
] | 81521327+BTCGreen@users.noreply.github.com |
514bead86a82075e9c985bea44e0eb4cc2f34f4e | e50d5d22ba46f17097d5dc86d12ec9d247929468 | /python/kwiver/vital/algo/uv_unwrap_mesh.cxx | 277ba789a387c1b87ee784e7825af98835de800a | [
"BSD-3-Clause"
] | permissive | nrsyed/kwiver | 488a0495b8c3b523f6639669aff73931373d4ca4 | 990a93b637af06129a842be38b88908df358761b | refs/heads/master | 2023-02-25T20:22:10.813154 | 2021-01-21T16:51:23 | 2021-01-21T16:51:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,320 | cxx | /*ckwg +29
* Copyright 2020 by Kitware, Inc.
* 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 name of Kitware, Inc. nor the names of any 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 AUTHORS 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.
*/
#include <python/kwiver/vital/algo/trampoline/uv_unwrap_mesh_trampoline.txx>
#include <python/kwiver/vital/algo/uv_unwrap_mesh.h>
#include <pybind11/pybind11.h>
namespace kwiver {
namespace vital {
namespace python {
namespace py = pybind11;
void uv_unwrap_mesh(py::module &m)
{
py::class_< kwiver::vital::algo::uv_unwrap_mesh,
std::shared_ptr<kwiver::vital::algo::uv_unwrap_mesh>,
kwiver::vital::algorithm_def<kwiver::vital::algo::uv_unwrap_mesh>,
uv_unwrap_mesh_trampoline<> >(m, "UVUnwrapMesh")
.def(py::init())
.def_static("static_type_name",
&kwiver::vital::algo::uv_unwrap_mesh::static_type_name)
.def("unwrap",
&kwiver::vital::algo::uv_unwrap_mesh::unwrap);
}
}
}
}
| [
"john.parent@kitware.com"
] | john.parent@kitware.com |
791948409eb5e7422ba9386c26805763ca5d8f63 | 3009ccdaf935cacabba949b39d9582552292ff2e | /oving02/main.cpp | 93382798f7f51e17860ec36303efb2ff5f6111a9 | [] | no_license | Eliassoren/Cpp-for-Programmers | 65e74f7a6be703e31733ef60555c81c9d61c267f | 6302b36501b30a7cf196b40527deaea1bf4be80e | refs/heads/master | 2021-01-01T04:08:56.440652 | 2017-12-18T10:15:17 | 2017-12-18T10:15:17 | 97,132,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,144 | cpp | #include <iostream>
using namespace std;
void oppg1(){
//Oppg a)
int i = 3;
int j = 5;
int *p = &i;
int *q = &j;
cout << "i: " << i << " j: " << j << " *p: " << p << " *q: " << q << endl;
cout << "&i: " << &i << " &j: " << &j << " &p: " << &p << " &q: " << &q << endl;
//Oppg b)
*p = 7;
cout << "p: " << *p << endl;
*q += 4;
cout << "q: " << *q << endl;
*q = *p+1;
cout << "q: " << *q << endl;
p = q;
cout << "p: " << *p << endl;
}
void oppg4(){
/*/home/elias/Documents/git/cpp/Cpp-for-Programmers/oving02/main.cpp: In function ‘void oppg4()’:
/home/elias/Documents/git/cpp/Cpp-for-Programmers/oving02/main.cpp:27:8: error: ‘b’ declared as reference but not initialized
int &b;
^
/home/elias/Documents/git/cpp/Cpp-for-Programmers/oving02/main.cpp:30:4: error: invalid type argument of unary ‘*’ (have ‘int’)
*a = *b + *c;
^
/home/elias/Documents/git/cpp/Cpp-for-Programmers/oving02/main.cpp:30:9: error: invalid type argument of unary ‘*’ (have ‘int’)
*a = *b + *c;
^
/home/elias/Documents/git/cpp/Cpp-for-Programmers/oving02/main.cpp:31:6: error: lvalue required as left operand of assignment
&b = 2;
^*/
int a = 5;
int &b = a; // Referansen må initieres.
int *c = &b;
a = b + *c; // a og b er ikke definert som pekere
b = 2; //En referanse er allerede tildelt, og kan ikke endres på.
}
void oppg5(){
int num;
int *ptr = #
int &ref = num;
num = 1; // Metode 1
cout << "Num1: " << num << endl;
++*ptr; // Metode 2
cout << "Num2: " << num << endl;
++ref; // Metode 3
cout << "Num3: " << num << endl;
}
int sum(int *arr, int elems){
int sum = 0;
for(int i = 0; i < elems; ++i){
sum += arr[i];
}
return sum;
}
void oppg6(){
int len = 20;
int arr[len];
for(int i = 0; i < len;i++){
arr[i] = i;
}
// Oppg a)
cout << "Sum a): " << sum(arr,10) << endl;
// Oppg b)
cout << "Sum b): " << sum(&arr[9],5) << endl;
// Oppg c)
cout << "Sum c) " << sum(&arr[14],5) << endl;
}
int main() {
oppg1();
oppg4();
oppg5();
oppg6();
return 0;
} | [
"eliassorr@gmail.com"
] | eliassorr@gmail.com |
6b10b35b17bfb88d2a2b97363294f177d7c3779d | ec770bb5a9d30110ddec41584f6b5098b382abe6 | /store/common/backend/lockserver.cc | 5c9edfcdb55cddc11c2c1eeefb01a2d9429aef1e | [] | no_license | xygroup/tapir | 90b26ff72d0c409f8829bf6640d5c54d29262956 | 6d5fd429809cb6968abdcd7daab723a518ede4ba | refs/heads/master | 2020-06-14T03:09:18.040717 | 2016-08-10T00:37:57 | 2016-08-10T00:37:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,297 | cc | // -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*-
/***********************************************************************
*
* spanstore/lockserver.cc:
* Simple multi-reader, single-writer lock server
*
**********************************************************************/
#include "lockserver.h"
using namespace std;
LockServer::LockServer()
{
readers = 0;
writers = 0;
}
LockServer::~LockServer() { }
bool
LockServer::Waiter::checkTimeout(const struct timeval &now)
{
if (now.tv_sec > waitTime.tv_sec) {
return true;
} else {
ASSERT(now.tv_usec > waitTime.tv_usec && now.tv_sec == waitTime.tv_sec);
if (now.tv_usec - waitTime.tv_usec > LOCK_WAIT_TIMEOUT)
return true;
}
return false;
}
void
LockServer::Lock::waitForLock(uint64_t requester, bool write)
{
if (waiters.find(requester) != waiters.end()) {
// Already waiting
return;
}
Debug("[%lu] Adding me to the queue ...", requester);
// Otherwise
waiters[requester] = Waiter(write);
waitQ.push(requester);
}
bool
LockServer::Lock::tryAcquireLock(uint64_t requester, bool write)
{
if (waitQ.size() == 0) {
return true;
}
Debug("[%lu] Trying to get lock for %d", requester, (int)write);
struct timeval now;
uint64_t w = waitQ.front();
gettimeofday(&now, NULL);
// prune old requests out of the wait queue
while (waiters[w].checkTimeout(now)) {
waiters.erase(w);
waitQ.pop();
// if everyone else was old ...
if (waitQ.size() == 0) {
return true;
}
w = waitQ.front();
ASSERT(waiters.find(w) != waiters.end());
}
if (waitQ.front() == requester) {
// this lock is being reserved for the requester
waitQ.pop();
ASSERT(waiters.find(requester) != waiters.end());
ASSERT(waiters[requester].write == write);
waiters.erase(requester);
return true;
} else {
// otherwise, add me to the list
waitForLock(requester, write);
return false;
}
}
bool
LockServer::Lock::isWriteNext()
{
if (waitQ.size() == 0) return false;
struct timeval now;
uint64_t w = waitQ.front();
gettimeofday(&now, NULL);
// prune old requests out of the wait queue
while (waiters[w].checkTimeout(now)) {
waiters.erase(w);
waitQ.pop();
// if everyone else was old ...
if (waitQ.size() == 0) {
return false;
}
w = waitQ.front();
ASSERT(waiters.find(w) != waiters.end());
}
ASSERT(waiters.find(waitQ.front()) != waiters.end());
return waiters[waitQ.front()].write;
}
bool
LockServer::lockForRead(const string &lock, uint64_t requester)
{
Lock &l = locks[lock];
Debug("Lock for Read: %s [%lu %lu %lu %lu]", lock.c_str(),
readers, writers, l.holders.size(), l.waiters.size());
switch (l.state) {
case UNLOCKED:
// if you are next in the queue
if (l.tryAcquireLock(requester, false)) {
Debug("[%lu] I have acquired the read lock!", requester);
l.state = LOCKED_FOR_READ;
ASSERT(l.holders.size() == 0);
l.holders.insert(requester);
readers++;
return true;
}
return false;
case LOCKED_FOR_READ:
// if you already hold this lock
if (l.holders.find(requester) != l.holders.end()) {
return true;
}
// There is a write waiting, let's give up the lock
if (l.isWriteNext()) {
Debug("[%lu] Waiting on lock because there is a pending write request", requester);
l.waitForLock(requester, false);
return false;
}
l.holders.insert(requester);
readers++;
return true;
case LOCKED_FOR_WRITE:
case LOCKED_FOR_READ_WRITE:
if (l.holders.count(requester) > 0) {
l.state = LOCKED_FOR_READ_WRITE;
readers++;
return true;
}
ASSERT(l.holders.size() == 1);
Debug("Locked for write, held by %lu", *(l.holders.begin()));
l.waitForLock(requester, false);
return false;
}
NOT_REACHABLE();
return false;
}
bool
LockServer::lockForWrite(const string &lock, uint64_t requester)
{
Lock &l = locks[lock];
Debug("Lock for Write: %s [%lu %lu %lu %lu]", lock.c_str(),
readers, writers, l.holders.size(), l.waiters.size());
switch (l.state) {
case UNLOCKED:
// Got it!
if (l.tryAcquireLock(requester, true)) {
Debug("[%lu] I have acquired the write lock!", requester);
l.state = LOCKED_FOR_WRITE;
ASSERT(l.holders.size() == 0);
l.holders.insert(requester);
writers++;
return true;
}
return false;
case LOCKED_FOR_READ:
if (l.holders.size() == 1 && l.holders.count(requester) > 0) {
// if there is one holder of this read lock and it is the
// requester, then upgrade the lock
l.state = LOCKED_FOR_READ_WRITE;
writers++;
return true;
}
Debug("Locked for read by%s%lu other people", l.holders.count(requester) > 0 ? "you" : "", l.holders.size());
l.waitForLock(requester, true);
return false;
case LOCKED_FOR_WRITE:
case LOCKED_FOR_READ_WRITE:
ASSERT(l.holders.size() == 1);
if (l.holders.count(requester) > 0) {
return true;
}
Debug("Held by %lu for %s", *(l.holders.begin()), (l.state == LOCKED_FOR_WRITE) ? "write" : "read-write" );
l.waitForLock(requester, true);
return false;
}
NOT_REACHABLE();
return false;
}
void
LockServer::releaseForRead(const string &lock, uint64_t holder)
{
if (locks.find(lock) == locks.end()) {
return;
}
Lock &l = locks[lock];
if (l.holders.count(holder) == 0) {
Warning("[%ld] Releasing unheld read lock: %s", holder, lock.c_str());
return;
}
switch (l.state) {
case UNLOCKED:
case LOCKED_FOR_WRITE:
return;
case LOCKED_FOR_READ:
readers--;
if (l.holders.erase(holder) < 1) {
Warning("[%ld] Releasing unheld read lock: %s", holder, lock.c_str());
}
if (l.holders.empty()) {
l.state = UNLOCKED;
}
return;
case LOCKED_FOR_READ_WRITE:
readers--;
l.state = LOCKED_FOR_WRITE;
return;
}
}
void
LockServer::releaseForWrite(const string &lock, uint64_t holder)
{
if (locks.find(lock) == locks.end()) {
return;
}
Lock &l = locks[lock];
if (l.holders.count(holder) == 0) {
Warning("[%ld] Releasing unheld write lock: %s", holder, lock.c_str());
return;
}
switch (l.state) {
case UNLOCKED:
case LOCKED_FOR_READ:
return;
case LOCKED_FOR_WRITE:
writers--;
l.holders.erase(holder);
ASSERT(l.holders.size() == 0);
l.state = UNLOCKED;
return;
case LOCKED_FOR_READ_WRITE:
writers--;
l.state = LOCKED_FOR_READ;
ASSERT(l.holders.size() == 1);
return;
}
}
| [
"iyzhang@cs.washington.edu"
] | iyzhang@cs.washington.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.