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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c531b5893e585cb6dcd0e6e399b49ef9229667fb | 671181ddbc297ca1fb79106c077c17454cf05d7e | /kdecision.h | 85b2a30c73776cb70cb534ff065c1988ea2cca12 | [] | no_license | SimulationEverywhere-Models/CDPP-BATTLE | 171fd51dab664e63cf316254f695833b719f58aa | ff94046d883f31af3601d7fe9a27ca5407426791 | refs/heads/master | 2022-12-24T07:03:42.993825 | 2020-09-30T19:31:26 | 2020-09-30T19:31:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 943 | h | /*******************************************************************
*
* DESCRIPTION: Atomic Model Knight Decision
*
* AUTHOR: Meagan Leflar
*
* EMAIL: meagan_leflar@carleton.ca
*
* DATE: 15/10/2012
*
*******************************************************************/
#ifndef __KDECISION_H
#define __KDECISION_H
#include "atomic.h" // class Atomic
class Kdecision : public Atomic
{
public:
Kdecision( const string &name = "Kdecision" ); //Default constructor
~Kdecision();
virtual string className() const ;
protected:
Model &initFunction();
Model &externalFunction( const ExternalMessage & );
Model &internalFunction( const InternalMessage & );
Model &outputFunction( const InternalMessage & );
private:
const Port ∈
Port &out;
int packet;
int index;
int dist;
int hp;
}; // class Kdecision
// ** inline ** //
inline
string Kdecision::className() const
{
return "Kdecision" ;
}
#endif //__KDECISION_H
| [
"noreply@github.com"
] | SimulationEverywhere-Models.noreply@github.com |
cca896dc31be048ebf8cb4c284afe2f4fad0c698 | 6f16621b74eae36fe867786556244592140dda07 | /Code/Graph.cpp | f62be5e7802c6be819601249ba14bd97c94ca41d | [] | no_license | Anthony11234/Maps-Graphs | cf28c054fad2d099029a6a4489a9f054659232b8 | f10c7660664ed15717d459191a28b2e2461ee19d | refs/heads/master | 2023-04-16T04:22:46.894380 | 2017-12-11T20:32:58 | 2017-12-11T20:32:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,763 | cpp |
// Graph.cpp
// STL_DirGraph
//
// Created by Bill Komanetsky on 11/27/17.
// Copyright © 2017 Bill Komanetsky. All rights reserved.
//
#include <stack>
#include "Graph.hpp"
#include <iostream>
Graph::Graph() {
initGraph();
}//Graph()
//The Destructor will go through each array entry and delete the vertex at that array
//position if it has been created. It will then clear the vector of adjacent vertecies
//You don't need to worry about loosing those vertices because they will be deleted
//when we get to their position in the array
Graph::~Graph() {
for (int i=0; i<STARTSIZE; i++) {
if (edgeArray[i].first != nullptr) {
delete edgeArray[i].first; //Delete the vertex
edgeArray[i].first = nullptr; //Set its poiner to nullptr since it's been deleted
edgeArray[i].second->clear(); //Clear the vector of adjacent vertices
delete edgeArray[i].second; //Now, delete the dynamically allocated vector
}//if
else {}
}//for i
}//~Graph()
//Set everything up in the array so we can store vertices and their adjacent vertices (edges)
//Each of the array's memory locations shall contain a pair of data
// first: A vertex structure
// second: A vector of vertex structures
// Each of these will be the end-point of an edge eminating from the vertex (first)
void Graph::initGraph(void) {
for (int i=0; i<STARTSIZE; i++) {
edgeArray[i].first = nullptr;
edgeArray[i].second = new vector<GraphVertex*>;
}//for
}//initGraph
//Return the pointer to a vector of vertex pointers which shall contain all
//of the end-points for each edge eminating from the vertex (first) in that pair
vector<GraphVertex*>* Graph::getDestVertex(int sourceVertex) {
if (sourceVertex >= STARTSIZE) {
return nullptr;
}//if
else {
return edgeArray[sourceVertex].second;
}//else
}//getDestVertex(int)
//Add a vertex to the array if that vertex hasn't yet been created
//Will return doing nothing if that vertex has already been setup, or, if the value
//which the vertex shall contain is greater than the arrayt capacity or less than zero
void Graph::addVertex(int vertexValue) {
//If the vertex value is larger than the graph capacity or
// the vertex already exists, then leave.
if (vertexValue >= STARTSIZE || vertexValue < 0 || this->edgeArray[vertexValue].first != nullptr) {
return;
}//if
else {
//Create a new vertex and populate its value
GraphVertex* tempVertex = new GraphVertex;
tempVertex->Value = vertexValue;
tempVertex->Visited = false;
//Now, add it to the first of the pair
edgeArray[vertexValue].first = tempVertex;
}//else
}//addVertex
//Add a directed edge
//Will do nothing if the range of the source or destination values are beyond the size of the
//array, or, if the source or destination vertices have not yet been added, in other words, if
//you try to create an edge for a vertex that does not yet exist, this function will do nothing
void Graph::addEdgeDir(int source, int destination) {
//if the source or destination vertex values are grater than the size of the array of vectors
//or if the soruce or destination vertecis do not exist, then return
if (source >= STARTSIZE || source < 0 || destination >= STARTSIZE || destination < 0 ||
edgeArray[source].first == nullptr ||
edgeArray[destination].first == nullptr) {
return;
}//if
else {
//Add to the source vector an existing vertex located at destination in the array
edgeArray[source].second->push_back(edgeArray[destination].first);
}//else
}//adEdge(int, int)
//Add a directed edge
//Will do nothing if the range of the source or destination values are beyond the size of the
//array, or, if the source or destination vertices have not yet been added, in other words, if
//you try to create an edge for a vertex that does not yet exist, this function will do nothing
void Graph::addEdgeUnDir(int source, int destination) {
//if the source or destination vertex values are grater than the size of the array of vectors
//or if the soruce or destination vertecis do not exist, then return
if (source >= STARTSIZE || source < 0 || destination >= STARTSIZE || destination < 0 ||
edgeArray[source].first == nullptr ||
edgeArray[destination].first == nullptr) {
return;
}//if
else {
//Add to the source vector an existing vertex located at destination in the array
edgeArray[source].second->push_back(edgeArray[destination].first);
//Add to the destination vector an existing vertex located at source in the array
edgeArray[destination].second->push_back(edgeArray[source].first);
}//else
}//adEdge(int, int)
//Do a Depth first Search for the graph
//This function will return a vector of vertices showing how the graph was navigated
//If you try to start with a vertex which does not exist, this function will return
//an empty vector
vector<GraphVertex*> Graph::searchDFS(int start) {
vector<GraphVertex*> returnVector;
stack <GraphVertex*> tempStack;
vector <GraphVertex*> *temp;
GraphVertex *ptr;
if(start > STARTSIZE || start < 0 || edgeArray[start].first == nullptr){
cout << "No Position at Pounter " << start << endl;
return returnVector;
}
else{
clearAllVisited();
tempStack.push(edgeArray[start].first);
while(!tempStack.empty()){
ptr = tempStack.top();
tempStack.pop();
if (!edgeArray[ptr->Value].first->Visited){
returnVector.push_back(edgeArray[ptr->Value].first);
edgeArray[ptr->Value].first->Visited = true;
}
temp = getDestVertex(ptr->Value);
for (int i = 0; i < temp->size(); i++) {
if (!edgeArray[temp->at(i)->Value].first->Visited) {
tempStack.push(temp->at(i));
}
}
}
}
return returnVector;
}//searchDFS
//Do a Breadth first Search for the graph
//This function will return a vector of vertices showing how the graph was navigated
//If you try to start with a vertex which does not exist, this function will return
//an empty vector
vector<GraphVertex*> Graph::searchBFS(int start) {
vector<GraphVertex*> returnVector;
queue<GraphVertex*> tempQueue;
vector<GraphVertex*> *temp;
GraphVertex* ptr;
tempQueue.push(edgeArray[start].first);
if(start > STARTSIZE || start < 0 || edgeArray[start].first == nullptr){
cout << "No Position at Pounter " << start << endl;
return returnVector;
}
else{
clearAllVisited();
tempQueue.push(edgeArray[start].first);
while(!tempQueue.empty()){
ptr = tempQueue.front();
tempQueue.pop();
if (!edgeArray[ptr->Value].first->Visited){
returnVector.push_back(edgeArray[ptr->Value].first);
edgeArray[ptr->Value].first->Visited = true;
}
temp = getDestVertex(ptr->Value);
for (int i = 0; i < temp->size(); i++) {
if (!edgeArray[temp->at(i)->Value].first->Visited) {
tempQueue.push(temp->at(i));
}
}
}
}
return returnVector;
}//searchBFS
//This function shall set to false all vertices visited variable to false
void Graph::clearAllVisited(void) {
for (int i=0; i<STARTSIZE; i++) {
if (edgeArray[i].first != nullptr) {
edgeArray[i].first->Visited = false;
}//if
else {}
}//for
}//clearAllVisited
| [
"adamgonzalez005@gmail.com"
] | adamgonzalez005@gmail.com |
88c55fce40d692eb172d1f155926472ab461aab8 | c769df3c7ae8e03a01bbd5b351d2318f990bb212 | /3rd_party/cereal/include/cereal/types/unordered_map.hpp | 68ee9c4a8fecf858ee17c84a6358521d5ec799d7 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Segs/Segs | 0519ed2bc75963607fcb2d61a7162c1ce3216836 | bccea0b253ddece6254d2c6410ed2c7ec42a86f5 | refs/heads/develop | 2022-12-02T16:50:30.325109 | 2022-11-21T13:37:46 | 2022-11-21T13:37:46 | 8,205,781 | 231 | 113 | BSD-3-Clause | 2023-09-02T15:50:20 | 2013-02-14T19:15:30 | C++ | UTF-8 | C++ | false | false | 1,893 | hpp | /*! \file unordered_map.hpp
\brief Support for types found in \<unordered_map\>
\ingroup STLSupport */
/*
Copyright (c) 2014, Randolph Voorhies, Shane Grant
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of cereal 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 RANDOLPH VOORHIES OR SHANE GRANT 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 CEREAL_TYPES_UNORDERED_MAP_HPP_
#define CEREAL_TYPES_UNORDERED_MAP_HPP_
#include <cereal/types/concepts/pair_associative_container.hpp>
#include <unordered_map>
#endif // CEREAL_TYPES_UNORDERED_MAP_HPP_
| [
"nemerle5@gmail.com"
] | nemerle5@gmail.com |
eba43266885df2098b56c1fcaf96b24d7009c591 | 97112cac8c87e45b7b5b33d68745593d406e6ce2 | /OS/OSlab1/mainwindow.cpp | 6cd7237f9164b6fd6add75c1db0afb841ab87d30 | [] | no_license | PALinoleum/SEM5 | 1dde325361db1884e5fa33a4b9f5360db9610f23 | 9d138d9d4a36e914f1afed4cde151514af6d50bd | refs/heads/master | 2022-11-16T08:46:02.369247 | 2020-07-08T15:10:14 | 2020-07-08T15:10:14 | 278,112,469 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLabel>
#include "windows.h"
#include "base.h"
MainWindow::MainWindow(QWidget *parent):QMainWindow(parent), ui(new Ui::MainWindow)
{
char* computerName;
computerName = getComputerNameMY();
QLabel lLabel;
lLabel.setText ("ПОМОГИТЕ");
// lLabel.setGeometry ( 200, 200, 300, 150 );
lLabel.setAlignment (Qt::AlignHCenter | Qt::AlignVCenter );
QFont lBlackFont(" Arial Black ", 12);
lLabel.setFont(lBlackFont);
lLabel.show();
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
| [
"68017323+PALinoleum@users.noreply.github.com"
] | 68017323+PALinoleum@users.noreply.github.com |
75198f063f63a0c982d40f301cf94afabb6e49de | 9f692cefe135bd933b378b7f99e93d0697f608b2 | /Repository.cpp | 29ab7acc1c91e3b2be67ab1f60afa7fff6a9916c | [] | no_license | LauraDiosan-CS/lab04-macrinapacurar | 4a3ccc3ffde20ee839edf7ef7ab2e142ec0aa34c | 4f7f7c7f2094393f4f45d3e5fc9fe82ec65a9c00 | refs/heads/master | 2021-03-23T12:21:23.145527 | 2020-03-30T12:42:10 | 2020-03-30T12:42:10 | 247,452,305 | 0 | 0 | null | 2020-03-15T11:23:16 | 2020-03-15T11:23:10 | null | UTF-8 | C++ | false | false | 661 | cpp | #include "Repository.h"
Repository::Repository()
{
this->len = 0;
}
int Repository::get_len()
{
return this->len;
}
Evidenta* Repository::get_all()
{
return this->ev;
}
void Repository::insert(Evidenta newEv)
{
this->ev[this->len++] = newEv;
}
void Repository::update(Evidenta ev)
{
int n = this->get_len();
Evidenta* aux = this->get_all();
for (int i = 0; i < n; i++)
{
if (strcmp(ev.getNume(), aux[i].getNume()) == 0)
{
aux[i] = ev;
}
}
}
void Repository::delete_ev(int i)
{
while (i < this->len)
{
if (i + 1 < this->len)
this->ev[i] = this->ev[i + 1];
i++;
}
this->len--;
}
Repository::~Repository()
{
this->len = 0;
}
| [
"pacurarmacrina@yahoo.com"
] | pacurarmacrina@yahoo.com |
bc7719338d1770880ff63782e06a9de4d641778e | 58ed734eac33bfb073e794e95df8280b81dce883 | /Soul-Liberty/SlimeAttack.h | 2ed8eb5b917652a5f6340d3ea9c6bfa7f0fce214 | [] | no_license | syougun360/Soul-Liberty | 9fce5a85fd8dcde48252d5034230adb259c1f9a2 | d8abae71efdda1e7044d6df50183d08765ba2d1b | refs/heads/master | 2020-04-17T20:16:18.442404 | 2019-04-18T13:52:23 | 2019-04-18T13:52:23 | 24,497,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 319 | h | /**
*
* @author yamada masamitsu
* @date 2014.11.06
*
*/
#pragma once
#include "EnemyAttack.h"
class CSlimeAttack:public CEnemyAttack
{
public:
CSlimeAttack(const int power, const float jumpforce, const float mass, const float speed);
void Update(CEnemyActor *actor);
void Init(CEnemyActor *actor);
private:
};
| [
"syougun360@infoseek.jp"
] | syougun360@infoseek.jp |
113f995e3a0539c5a78e0b9455a7d56349748edf | c3c848ae6c90313fed11be129187234e487c5f96 | /VC6PLATSDK/samples/Com/Administration/Spy/comspyctl/ComSpyproppage.Cpp | 50ed78f38c26db5bfda475c3b7b611bb7d33dcba | [] | no_license | timxx/VC6-Platform-SDK | 247e117cfe77109cd1b1effcd68e8a428ebe40f0 | 9fd59ed5e8e25a1a72652b44cbefb433c62b1c0f | refs/heads/master | 2023-07-04T06:48:32.683084 | 2021-08-10T12:52:47 | 2021-08-10T12:52:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,713 | cpp | // ----------------------------------------------------------------------------
//
// This file is part of the Microsoft COM+ Samples.
//
// Copyright (C) 1995-2000 Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// ----------------------------------------------------------------------------
#include "stdafx.h"
#include "ComSpyCtl.h"
#include "ComSpyAudit.h"
#include "CComSpy.h"
#include "ComSpyPropPage.h"
#include "comsvcs.h"
#include "AppInfo.h"
TCHAR * szColNames[] =
{
_T("Count"),
_T("Event"),
_T("TickCount"),
_T("Application"),
_T("Parameter"),
_T("Value")
};
/////////////////////////////////////////////////////////////////////////////
// CComSpyPropPage
LRESULT CComSpyPropPage::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
m_ppUnk[0]->QueryInterface(IID_IComSpy, (void**)&m_pSpy);
_ASSERTE(m_pSpy);
CComBSTR bstr;
m_pSpy -> get_LogFile(&bstr);
SetDlgItemText(IDC_LOG_FILE, bstr);
// grid lines
BOOL bVal;
m_pSpy -> get_ShowGridLines(&bVal);
SendDlgItemMessage(IDC_SHOW_GRID_LINES, BM_SETCHECK, (bVal) ? BST_CHECKED : BST_UNCHECKED);
// show on screen
m_pSpy -> get_ShowOnScreen(&bVal);
SendDlgItemMessage(IDC_SHOW_ON_SCREEN, BM_SETCHECK, (bVal) ? BST_CHECKED : BST_UNCHECKED);
// log to file
m_pSpy -> get_LogToFile(&bVal);
SendDlgItemMessage(IDC_LOG_TO_FILE, BM_SETCHECK, (bVal) ? BST_CHECKED : BST_UNCHECKED);
int i;
for (i=0;i<sizeof(szColNames)/sizeof(szColNames[0]);i++)
SendDlgItemMessage(IDC_COLUMN_NAMES, CB_ADDSTRING, 0, (LPARAM)(LPTSTR)szColNames[i]);
SendDlgItemMessage(IDC_COLUMN_NAMES, CB_SETCURSEL, 0, 0);
BOOL bH;
OnSelectColumn(CBN_SELCHANGE, 0,0, bH);
return 0;
}
LRESULT CComSpyPropPage::OnSelectColumn(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
if (wNotifyCode == CBN_SELCHANGE)
{
int nSel = SendDlgItemMessage(IDC_COLUMN_NAMES, CB_GETCURSEL, 0, 0L);
if (nSel != CB_ERR)
{
// get the width
long lWidth;
_ASSERTE(m_pSpy);
m_pSpy -> get_ColWidth(nSel, &lWidth);
SetDlgItemInt(IDC_WIDTH, lWidth);
}
}
return 0;
}
STDMETHODIMP CComSpyPropPage::Apply()
{
ATLTRACE(_T("CComSpyPropPage::Apply\n"));
for (UINT i = 0; i < m_nObjects; i++)
{
CComQIPtr<IComSpy, &IID_IComSpy> pSpy(m_ppUnk[i]);
BSTR bstr;
GetDlgItemText(IDC_LOG_FILE, bstr);
pSpy -> put_LogFile(bstr);
::SysFreeString(bstr);
// grid lines
BOOL bVal = (SendDlgItemMessage(IDC_SHOW_GRID_LINES, BM_GETCHECK) == BST_CHECKED);
pSpy -> put_ShowGridLines(bVal);
// log to file
bVal = (SendDlgItemMessage(IDC_LOG_TO_FILE, BM_GETCHECK) == BST_CHECKED);
pSpy -> put_LogToFile(bVal);
// show on screen
bVal = (SendDlgItemMessage(IDC_SHOW_ON_SCREEN, BM_GETCHECK) == BST_CHECKED);
pSpy -> put_ShowOnScreen(bVal);
int j;
UINT nWidth;
for (j=0;j<sizeof(szColNames)/sizeof(szColNames[0]);j++)
{
nWidth = SendDlgItemMessage(IDC_COLUMN_NAMES, CB_GETITEMDATA, j) ;
if (nWidth)
{
pSpy -> put_ColWidth(j,nWidth);
SendDlgItemMessage(IDC_COLUMN_NAMES, CB_SETITEMDATA, j, 0);
}
}
}
SetDirty(FALSE);
m_bDirty = FALSE;
return S_OK;
}
| [
"radiowebmasters@gmail.com"
] | radiowebmasters@gmail.com |
842562ead4c4dd7b3d91142d5a3e4916bcfa57fd | 080a0047de59189518fdaa61249585e7ef4c5214 | /eg020-029/cpp020_validparentheses.cpp | 0bb81a8013f3b0f0c455c19d64da3a70e946cde0 | [] | no_license | jjeff-han/leetcode | ba9565e5e4c3e4468711ba6e7eb6bc3cbeca9dc5 | 30f3d0b31cccbe83a65a6527b5e2fee79ddd59ec | refs/heads/master | 2021-06-25T13:22:49.425376 | 2021-01-18T04:25:08 | 2021-01-18T04:25:08 | 195,916,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | cpp |
#include <stdio.h>
#include <string>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> parentheses;
for(int i=0; i<s.size(); i++) {
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
parentheses.push(s[i]);
else {
if(parentheses.empty())
return false;
if(s[i] == ')' && parentheses.top() != '(') return false;
if (s[i] == ']' && parentheses.top() != '[') return false;
if (s[i] == '}' && parentheses.top() != '{') return false;
parentheses.pop();
}
}
return parentheses.empty();
}
};
int main(void) {
Solution solve;
printf("the result is %d\n",solve.isValid("{([]){}}"));
printf("the result is %d\n",solve.isValid("([)){}"));
return 0;
}
| [
"hjf11aa@126.com"
] | hjf11aa@126.com |
2a8f6344508e16d848e9432a1dce482ef6608cc1 | 3e4fd5153015d03f147e0f105db08e4cf6589d36 | /Cpp/SDK/PhysicsCore_classes.h | 6c40400ea4dfaa19066a3c8d2eb21134d6927492 | [] | no_license | zH4x-SDK/zTorchlight3-SDK | a96f50b84e6b59ccc351634c5cea48caa0d74075 | 24135ee60874de5fd3f412e60ddc9018de32a95c | refs/heads/main | 2023-07-20T12:17:14.732705 | 2021-08-27T13:59:21 | 2021-08-27T13:59:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,787 | h | #pragma once
// Name: Torchlight3, Version: 4.26.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// Class PhysicsCore.BodySetupCore
// 0x0020 (FullSize[0x0048] - InheritedSize[0x0028])
class UBodySetupCore : public UObject
{
public:
struct FName BoneName; // 0x0028(0x0008) (Edit, ZeroConstructor, EditConst, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EPhysicsType> PhysicsType; // 0x0030(0x0001) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_ECollisionTraceFlag> CollisionTraceFlag; // 0x0031(0x0001) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EBodyCollisionResponse> CollisionReponse; // 0x0032(0x0001) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_HS64[0x15]; // 0x0033(0x0015) MISSED OFFSET (PADDING)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class PhysicsCore.BodySetupCore");
return ptr;
}
};
// Class PhysicsCore.ChaosPhysicalMaterial
// 0x0020 (FullSize[0x0048] - InheritedSize[0x0028])
class UChaosPhysicalMaterial : public UObject
{
public:
float Friction; // 0x0028(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float StaticFriction; // 0x002C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float Restitution; // 0x0030(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float LinearEtherDrag; // 0x0034(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float AngularEtherDrag; // 0x0038(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float SleepingLinearVelocityThreshold; // 0x003C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float SleepingAngularVelocityThreshold; // 0x0040(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_L3E1[0x4]; // 0x0044(0x0004) MISSED OFFSET (PADDING)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class PhysicsCore.ChaosPhysicalMaterial");
return ptr;
}
};
// Class PhysicsCore.PhysicalMaterial
// 0x0058 (FullSize[0x0080] - InheritedSize[0x0028])
class UPhysicalMaterial : public UObject
{
public:
float Friction; // 0x0028(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float StaticFriction; // 0x002C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EFrictionCombineMode> FrictionCombineMode; // 0x0030(0x0001) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bOverrideFrictionCombineMode; // 0x0031(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_PTAO[0x2]; // 0x0032(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
float Restitution; // 0x0034(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EFrictionCombineMode> RestitutionCombineMode; // 0x0038(0x0001) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bOverrideRestitutionCombineMode; // 0x0039(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_Q6WA[0x2]; // 0x003A(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
float Density; // 0x003C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float SleepLinearVelocityThreshold; // 0x0040(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float SleepAngularVelocityThreshold; // 0x0044(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int SleepCounterThreshold; // 0x0048(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float RaiseMassToPower; // 0x004C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float DestructibleDamageThresholdScale; // 0x0050(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_K6DO[0x4]; // 0x0054(0x0004) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
class UPhysicalMaterialPropertyBase* PhysicalMaterialProperty; // 0x0058(0x0008) (ZeroConstructor, Deprecated, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EPhysicalSurface> SurfaceType; // 0x0060(0x0001) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_P9ZM[0x1F]; // 0x0061(0x001F) MISSED OFFSET (PADDING)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class PhysicsCore.PhysicalMaterial");
return ptr;
}
};
// Class PhysicsCore.PhysicalMaterialPropertyBase
// 0x0000 (FullSize[0x0028] - InheritedSize[0x0028])
class UPhysicalMaterialPropertyBase : public UObject
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class PhysicsCore.PhysicalMaterialPropertyBase");
return ptr;
}
};
// Class PhysicsCore.PhysicsSettingsCore
// 0x00A8 (FullSize[0x00E0] - InheritedSize[0x0038])
class UPhysicsSettingsCore : public UDeveloperSettings
{
public:
float DefaultGravityZ; // 0x0038(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float DefaultTerminalVelocity; // 0x003C(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float DefaultFluidFriction; // 0x0040(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int SimulateScratchMemorySize; // 0x0044(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int RagdollAggregateThreshold; // 0x0048(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float TriangleMeshTriangleMinAreaThreshold; // 0x004C(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bEnableShapeSharing; // 0x0050(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bEnablePCM; // 0x0051(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bEnableStabilization; // 0x0052(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bWarnMissingLocks; // 0x0053(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bEnable2DPhysics; // 0x0054(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bDefaultHasComplexCollision; // 0x0055(0x0001) (ZeroConstructor, Config, Deprecated, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_JGVJ[0x2]; // 0x0056(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
float BounceThresholdVelocity; // 0x0058(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EFrictionCombineMode> FrictionCombineMode; // 0x005C(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EFrictionCombineMode> RestitutionCombineMode; // 0x005D(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_K5A3[0x2]; // 0x005E(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
float MaxAngularVelocity; // 0x0060(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float MaxDepenetrationVelocity; // 0x0064(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float ContactOffsetMultiplier; // 0x0068(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float MinContactOffset; // 0x006C(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float MaxContactOffset; // 0x0070(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bSimulateSkeletalMeshOnDedicatedServer; // 0x0074(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_ECollisionTraceFlag> DefaultShapeComplexity; // 0x0075(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_XI7H[0x2]; // 0x0076(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
struct FChaosSolverConfiguration SolverOptions; // 0x0078(0x0068) (Edit, Config, NoDestructor, NativeAccessSpecifierPublic)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class PhysicsCore.PhysicsSettingsCore");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
7f006805928c077d4fc766eff39e417999b982e2 | 0c40e97b69dcd00f0b0b05f249d0fce448320fd8 | /src/logging.cpp | 4e1a94ffa9556d850a6d84f72ea1ec69ba960e85 | [
"MIT"
] | permissive | Arhipovladimir/Earthcoin | 9908912df9b10b97512c545b855c3670767039d9 | bc5b5ee538c76e7232e93434aedd8688bae70792 | refs/heads/main | 2023-07-16T05:50:52.755250 | 2021-08-25T09:19:40 | 2021-08-25T09:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,885 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Earthcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <logging.h>
#include <utiltime.h>
const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
/**
* NOTE: the logger instances is leaked on exit. This is ugly, but will be
* cleaned up by the OS/libc. Defining a logger as a global object doesn't work
* since the order of destruction of static/global objects is undefined.
* Consider if the logger gets destroyed, and then some later destructor calls
* LogPrintf, maybe indirectly, and you get a core dump at shutdown trying to
* access the logger. When the shutdown sequence is fully audited and tested,
* explicit destruction of these objects can be implemented by changing this
* from a raw pointer to a std::unique_ptr.
*
* This method of initialization was originally introduced in
* ee3374234c60aba2cc4c5cd5cac1c0aefc2d817c.
*/
BCLog::Logger* const g_logger = new BCLog::Logger();
bool fLogIPs = DEFAULT_LOGIPS;
static int FileWriteStr(const std::string &str, FILE *fp)
{
return fwrite(str.data(), 1, str.size(), fp);
}
bool BCLog::Logger::OpenDebugLog()
{
std::lock_guard<std::mutex> scoped_lock(m_file_mutex);
assert(m_fileout == nullptr);
assert(!m_file_path.empty());
m_fileout = fsbridge::fopen(m_file_path, "a");
if (!m_fileout) {
return false;
}
setbuf(m_fileout, nullptr); // unbuffered
// dump buffered messages from before we opened the log
while (!m_msgs_before_open.empty()) {
FileWriteStr(m_msgs_before_open.front(), m_fileout);
m_msgs_before_open.pop_front();
}
return true;
}
void BCLog::Logger::EnableCategory(BCLog::LogFlags flag)
{
m_categories |= flag;
}
bool BCLog::Logger::EnableCategory(const std::string& str)
{
BCLog::LogFlags flag;
if (!GetLogCategory(flag, str)) return false;
EnableCategory(flag);
return true;
}
void BCLog::Logger::DisableCategory(BCLog::LogFlags flag)
{
m_categories &= ~flag;
}
bool BCLog::Logger::DisableCategory(const std::string& str)
{
BCLog::LogFlags flag;
if (!GetLogCategory(flag, str)) return false;
DisableCategory(flag);
return true;
}
bool BCLog::Logger::WillLogCategory(BCLog::LogFlags category) const
{
return (m_categories.load(std::memory_order_relaxed) & category) != 0;
}
bool BCLog::Logger::DefaultShrinkDebugFile() const
{
return m_categories == BCLog::NONE;
}
struct CLogCategoryDesc
{
BCLog::LogFlags flag;
std::string category;
};
const CLogCategoryDesc LogCategories[] =
{
{BCLog::NONE, "0"},
{BCLog::NONE, "none"},
{BCLog::NET, "net"},
{BCLog::TOR, "tor"},
{BCLog::MEMPOOL, "mempool"},
{BCLog::HTTP, "http"},
{BCLog::BENCH, "bench"},
{BCLog::ZMQ, "zmq"},
{BCLog::DB, "db"},
{BCLog::RPC, "rpc"},
{BCLog::ESTIMATEFEE, "estimatefee"},
{BCLog::ADDRMAN, "addrman"},
{BCLog::SELECTCOINS, "selectcoins"},
{BCLog::REINDEX, "reindex"},
{BCLog::CMPCTBLOCK, "cmpctblock"},
{BCLog::RAND, "rand"},
{BCLog::PRUNE, "prune"},
{BCLog::PROXY, "proxy"},
{BCLog::MEMPOOLREJ, "mempoolrej"},
{BCLog::LIBEVENT, "libevent"},
{BCLog::COINDB, "coindb"},
{BCLog::QT, "qt"},
{BCLog::LEVELDB, "leveldb"},
{BCLog::ALL, "1"},
{BCLog::ALL, "all"},
};
bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str)
{
if (str == "") {
flag = BCLog::ALL;
return true;
}
for (const CLogCategoryDesc& category_desc : LogCategories) {
if (category_desc.category == str) {
flag = category_desc.flag;
return true;
}
}
return false;
}
std::string ListLogCategories()
{
std::string ret;
int outcount = 0;
for (const CLogCategoryDesc& category_desc : LogCategories) {
// Omit the special cases.
if (category_desc.flag != BCLog::NONE && category_desc.flag != BCLog::ALL) {
if (outcount != 0) ret += ", ";
ret += category_desc.category;
outcount++;
}
}
return ret;
}
std::vector<CLogCategoryActive> ListActiveLogCategories()
{
std::vector<CLogCategoryActive> ret;
for (const CLogCategoryDesc& category_desc : LogCategories) {
// Omit the special cases.
if (category_desc.flag != BCLog::NONE && category_desc.flag != BCLog::ALL) {
CLogCategoryActive catActive;
catActive.category = category_desc.category;
catActive.active = LogAcceptCategory(category_desc.flag);
ret.push_back(catActive);
}
}
return ret;
}
std::string BCLog::Logger::LogTimestampStr(const std::string &str)
{
std::string strStamped;
if (!m_log_timestamps)
return str;
if (m_started_new_line) {
int64_t nTimeMicros = GetTimeMicros();
strStamped = FormatISO8601DateTime(nTimeMicros/1000000);
if (m_log_time_micros) {
strStamped.pop_back();
strStamped += strprintf(".%06dZ", nTimeMicros%1000000);
}
int64_t mocktime = GetMockTime();
if (mocktime) {
strStamped += " (mocktime: " + FormatISO8601DateTime(mocktime) + ")";
}
strStamped += ' ' + str;
} else
strStamped = str;
if (!str.empty() && str[str.size()-1] == '\n')
m_started_new_line = true;
else
m_started_new_line = false;
return strStamped;
}
void BCLog::Logger::LogPrintStr(const std::string &str)
{
std::string strTimestamped = LogTimestampStr(str);
if (m_print_to_console) {
// print to console
fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
fflush(stdout);
}
if (m_print_to_file) {
std::lock_guard<std::mutex> scoped_lock(m_file_mutex);
// buffer if we haven't opened the log yet
if (m_fileout == nullptr) {
m_msgs_before_open.push_back(strTimestamped);
}
else
{
// reopen the log file, if requested
if (m_reopen_file) {
m_reopen_file = false;
m_fileout = fsbridge::freopen(m_file_path, "a", m_fileout);
if (!m_fileout) {
return;
}
setbuf(m_fileout, nullptr); // unbuffered
}
FileWriteStr(strTimestamped, m_fileout);
}
}
}
void BCLog::Logger::ShrinkDebugFile()
{
// Amount of debug.log to save at end when shrinking (must fit in memory)
constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
assert(!m_file_path.empty());
// Scroll debug.log if it's getting too big
FILE* file = fsbridge::fopen(m_file_path, "r");
// Special files (e.g. device nodes) may not have a size.
size_t log_size = 0;
try {
log_size = fs::file_size(m_file_path);
} catch (boost::filesystem::filesystem_error &) {}
// If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
// trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
{
// Restart the file with some of the end
std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
if (fseek(file, -((long)vch.size()), SEEK_END)) {
LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
fclose(file);
return;
}
int nBytes = fread(vch.data(), 1, vch.size(), file);
fclose(file);
file = fsbridge::fopen(m_file_path, "w");
if (file)
{
fwrite(vch.data(), 1, nBytes, file);
fclose(file);
}
}
else if (file != nullptr)
fclose(file);
}
| [
"mail@deveac.com"
] | mail@deveac.com |
e392f94a9fbba8d01fd90b6d5a49b676911830f2 | 5c0bc7d833e37161ad7409d2e56fd1207e3234b2 | /HW_6/simpsons.cpp | 92ce9d0b62bfc0180d963378eaddc6ad43ba605e | [] | no_license | gabrieletrata/MTH_3300 | 9888c00b2c75cca307817fd7c19cdfe36123fe77 | 24030cac363181b50841bf73ad8ee0547393d6a3 | refs/heads/master | 2020-03-24T05:56:59.347450 | 2018-07-27T00:58:38 | 2018-07-27T00:58:38 | 142,510,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,230 | cpp | //******************************************************************************
// simpsons.cpp
// Approximates the integral of the probability density function using Simpson's rule.
//******************************************************************************
// Name: Gabriel Etrata
// Class: MTH 3300
// Professor: Evan Fink
// Homework_6
//******************************************************************************
// Collaborators/outside sources used: NONE
//******************************************************************************
// @author Gabriel Etrata
// @version 1.0 03/27/17
#include <iostream>
#include <stdlib.h>
#include <cmath>
using namespace std;
double exp (float);
double const pi = 4 * atan(1);
/** Probability density function
@param x input value
@return phi value of the function at x
*/
double PDF(double x){
double phi = (1/sqrt(2*pi)) * exp( -0.5 * pow(x, 2));
return phi;
}
/** Simpson's rule for approximating an integral
@param a lower limit
@param b upper limit
@param n number of intervals
@return sum
*/
double simpson(double a, double b, int n){
double deltaX = (b - a) / n;
double sum = 0;
for(int i = 0; i <= n; i++){
double x_i = a + i * deltaX;
if(i == 0 || i == n){ // checks if i the first or last term of the sum (coefficient of 1)
sum += PDF(x_i);
} else if (i % 2 == 0 && i != 0 && i != n) { // checks if i is an even term of the of the sum (multiply by coefficient of 2)
sum += 2 * PDF(x_i);
} else {
sum += 4 * PDF(x_i); // checks if i is an odd term of the of the sum (multiply by coefficient of 4)
}
}
sum *= (deltaX / 3); //multiply the sum of terms by (delta x) / 3
cout << "The area under the curve is approximately: " << sum << endl;
return sum;
}
//Initializes the program and prompts user input
int main()
{
double a, b;
int n;
cout << "Input the upper limit." << endl;
cin >> b;
cout << "Input the lower limit." << endl;
cin >> a;
cout << "How many intervals? (N must be even)." << endl;
cin >> n;
simpson(a, b, n);
system("pause");
return 0;
}
| [
"gabrieletrata@gmail.com"
] | gabrieletrata@gmail.com |
462e368f4932ab2345c061c3805646e75d8f18e2 | 9f59296d69ad77f192b24ee64d3e20425e125d28 | /Plugins/SceneFusion/Source/SceneFusion/Private/UI/sfUI.h | 74e9989d2e9abf1f6ed38edc6f2908eab07af7f4 | [] | no_license | Carp3d/SPARAJJ_World | 67420f60500f2ca2bdaca627a6b1bc20857a1bc9 | 7fbb6bb2cc039c855c52f419137fb535d35dd1a9 | refs/heads/master | 2022-12-18T23:33:34.085627 | 2020-09-26T18:24:26 | 2020-09-26T18:24:26 | 238,057,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,883 | h | #pragma once
#include "sfUISessionsPanel.h"
#include "sfUILoginPanel.h"
#include "sfUIOnlinePanel.h"
#include "sfOutlinerManager.h"
#include "../sfSessionInfo.h"
#include <sfSession.h>
#include <ksEvent.h>
#include <CoreMinimal.h>
#include <Widgets/Layout/SWidgetSwitcher.h>
using namespace KS::SceneFusion2;
/**
* Scene Fusion User Interface
*/
class sfUI : public TSharedFromThis<sfUI>
{
public:
/**
* Initialize the styles and UI components used by Scene Fusion.
*/
void Initialize();
/**
* Clean up the styles and UI components used by Scene Fusion.
*/
void Cleanup();
/**
* Gets delegate for go to camera.
*
* @return sfUIOnlinePanel::OnGoToDelegate&
*/
sfUIOnlinePanel::OnGoToDelegate& OnGoToUser();
/**
* Gets delegate for follow camera.
*
* @return sfUIOnlinePanel::OnFollowDelegate&
*/
sfUIOnlinePanel::OnFollowDelegate& OnFollowUser();
/**
* Unfollows camera.
*/
void UnfollowCamera();
/**
* Connects to a session.
*
* @param TSharedPtr<sfSessionInfo> sessionInfoPtr - determines where to connect.
*/
void JoinSession(TSharedPtr<sfSessionInfo> sessionInfoPtr);
private:
// Commands
TSharedPtr<class FUICommandList> m_UICommandListPtr;
// UI components
TSharedPtr<SWidgetSwitcher> m_panelSwitcherPtr;
TSharedPtr<SWidget> m_activeWidget;
sfUISessionsPanel m_sessionsPanel;
sfUIOnlinePanel m_onlinePanel;
sfUILoginPanel m_loginPanel;
// Event pointers
KS::ksEvent<sfSession::SPtr&, const std::string&>::SPtr m_disconnectEventPtr;
KS::ksEvent<sfUser::SPtr&>::SPtr m_userJoinEventPtr;
KS::ksEvent<sfUser::SPtr&>::SPtr m_userLeaveEventPtr;
KS::ksEvent<sfUser::SPtr&>::SPtr m_userColorChangeEventPtr;
TSharedPtr<sfOutlinerManager> m_outlinerManagerPtr;
/**
* Initialize styles.
*/
void InitializeStyles();
/**
* Initialise commands.
*/
void InitializeCommands();
/**
* Extend the level editor tool bar with a SF button
*/
void ExtendToolBar();
/**
* Register a SF Tab panel with a tab spawner.
*/
void RegisterSFTab();
/**
* Register Scene Fusion event handlers.
*/
void RegisterSFHandlers();
/**
* Register UI event handlers
*/
void RegisterUIHandlers();
/**
* Show the login panel, and hide other panels.
*/
void ShowLoginPanel();
/**
* Show the sessions panel, and hide other panels.
*/
void ShowSessionsPanel();
/**
* Show the online panel, and hide other panels.
*/
void ShowOnlinePanel();
/**
* Called when a connection attempt completes.
*
* @param sfSession::SPtr sessionPtr we connected to. nullptr if the connection failed.
* @param const std::string& errorMessage. Empty string if the connection was successful.
*/
void OnConnectComplete(sfSession::SPtr sessionPtr, const std::string& errorMessage);
/**
* Called when we disconnect from a session.
*
* @param sfSession::SPtr sessionPtr we disconnected from.
* @param const std::string& errorMessage. Empty string if no error occurred.
*/
void OnDisconnect(sfSession::SPtr sessionPtr, const std::string& errorMessage);
/**
* Create the widgets used in the toolbar.
*
* @param FToolBarBuilder& - toolbar builder
*/
void OnExtendToolBar(FToolBarBuilder& builder);
/**
* Create tool bar menu.
*
* @return TSharedRef<SWidget>
*/
TSharedRef<SWidget> OnCreateToolBarMenu();
/**
* Create the Scene Fusion tab.
*
* @param const FSpawnTabArgs& - tab spawning arguments
* @return TSharedRef<SDockTab>
*/
TSharedRef<SDockTab> OnCreateSFTab(const FSpawnTabArgs& args);
}; | [
"57542114+nyxxaltios@users.noreply.github.com"
] | 57542114+nyxxaltios@users.noreply.github.com |
b1673cbbbf61af41ac3b650fd9284bbd20434620 | e365802f226810094ad5fc5715838e263509a8fe | /cf_447_A.cpp | ce9d871c4635bc7ea250174117b0f36f33fbd571 | [] | no_license | shivansofficial/Competitive | 1a2e781f149b5917302d69f879f7b6bf8949dc5b | b3c30da789b4375db3474ddff26cc9d0e194f327 | refs/heads/master | 2020-06-17T21:46:44.823023 | 2019-09-04T19:29:34 | 2019-09-04T19:29:34 | 196,067,168 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,276 | cpp | #include<iostream>
#include<iomanip>
#include<vector>
#include<stack>
#include<queue>
#include<deque>
#include<map>
#include<set>
#include<string>
#include<algorithm>
#include<math.h>
using namespace std;
#define X first
#define Y second
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define mp make_pair
#define mod 1000000007
//#define max 100007
#define itr ::iterator it
#define gcd(a,b) __gcd((a),(b))
#define lcm(a,b) ((a)*(b))/gcd((a),(b))
#define rep(X,Y) for (int (X) = 0;(X) < (Y);++(X))
#define repp(X,a,Y) for (int (X) = a;(X) < (Y);++(X))
#define set(a, b) memset(a, b, sizeof(a));
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<double> vd;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef vector<vd> vvd;
typedef vector<pii> vii;
typedef vector<string> vs;
#define endl '\n'
int count(string a,string b,int m,int n)
{
if((m==0 && n==0)||n==0)
return 1;
if(m==0)
return 0;
if(a[m-1]==b[n-1])
return count(a,b,m-1,n-1)+count(a,b,m-1,n);
else
return count(a,b,m-1,n);
}
int main()
{
string a;
cin>>a;
string b="QAQ";
cout<<count(a,b,a.size(),b.size())<<endl;
return 0;
}
| [
"shivanssingh82@Shivanss-MacBook-Air.local"
] | shivanssingh82@Shivanss-MacBook-Air.local |
be6d005f044be4b577d83b616c5a8202be94fa85 | fcc8a86c2b16ddb2777bd3b850027db3c2910094 | /arduino/museomix.ino | 72a101b4562409c51ded9db42d210a3d8a9b576d | [] | no_license | MuseomixCH/Equipe-2 | bddc815a8b2af01b25305bc29adfa8a1e9b92bd4 | eddaf9c037df03ea52eee576d54c608cea68afda | refs/heads/master | 2021-01-18T00:46:19.273340 | 2014-11-21T12:08:06 | 2014-11-21T12:08:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,519 | ino | #define trigPin 13
#define echoPin 12
#define led1 9
//#define led2 6
float color1=0;
//float color2=0;
boolean growAlpha=true;
int freq;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led1, OUTPUT);
// pinMode(led2, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
// delayMicroseconds(1000); - Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 10 and distance <= 175){
growAlpha=true;
freq=1;
Serial.print(distance);
Serial.println(" right");
}
else {
growAlpha=false;
freq=3;
Serial.print(distance);
Serial.println(" cm");
}
Serial.print(color1);
Serial.println(" color1");
//Serial.print(color2);
//Serial.println(" color2");
color1=changeAlpha(color1, freq, 255, 0, growAlpha);
// color2=changeAlpha(color2, 1, 15, 0, growAlpha);
analogWrite(led1, color1);
//analogWrite(led2, color2);
delay(40);
}
float changeAlpha(float value, int frequence,int limitUp, int limitDown, boolean grow){
if(value < limitUp and grow){
value+= frequence;
}
else if(value>limitDown and !grow){
value-= frequence;
}
if(value>limitUp)
value=limitUp;
if(value<limitDown)
value=limitDown;
return value;
}
| [
"andrea.rovescalli@etu.hesge.ch"
] | andrea.rovescalli@etu.hesge.ch |
f8af2fa8e551ddbd0beba239fee02db5f87c3783 | 1217c20270a48a0cdaab73a5a11d050c11f33416 | /transcode_audio/src/AddSamplesToFifo.cpp | c32b0fac628a838f2e5e61471a4fa6d8cfb73ea2 | [] | no_license | yurychu/media_decoding | 3b31d2ba4c85f6226d20d157affb1d1221204b3a | fda34f20323a4d71a3cefe71563273e8decea0ac | refs/heads/master | 2023-03-31T21:31:35.054591 | 2021-03-23T14:34:29 | 2021-03-23T14:34:29 | 271,351,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | cpp | #include <transcode_audio/AddSamplesToFifo.hpp>
int tr_au::add_samples_to_fifo(AVAudioFifo *fifo,
uint8_t **converted_input_samples,
const int frame_size)
{
int error;
/* Make the FIFO as large as it needs to be to hold both,
* the old and the new samples. */
if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
fprintf(stderr, "Could not reallocate FIFO\n");
return error;
}
/* Store the new samples in the FIFO buffer. */
if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
frame_size) < frame_size) {
fprintf(stderr, "Could not write data to FIFO\n");
return AVERROR_EXIT;
}
return 0;
}
| [
"yury_chugunov@mail.ru"
] | yury_chugunov@mail.ru |
263a5255ffcf304ce9166efa554c7924bc86125b | dd592941bbce7bfe3b3eac1e149ec3f79505fe8e | /Array Programs/Record Breaking Day (Google Kickstart).cc | d67e1ea5df7291173be286aaa23f49fad8032e39 | [] | no_license | arzav18/Cpp-Codes | 387d8799f83c9d3ca3490b103effa15b75cf61c4 | 08d71ddaee082da4d9fa7416cd25e9a4bd9240a0 | refs/heads/main | 2023-08-16T02:18:31.145677 | 2021-10-24T18:13:43 | 2021-10-24T18:13:43 | 418,608,488 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | cc | #include<iostream>
#include<math.h>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n+1];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
if(n==1)
{
cout<<"1"<<endl;
return 0;
}
int ans=0;
int mx=-1;
for(int i=0;i<n;i++)
{
if(a[i]>mx && a[i]>a[i+1])
{
ans++;
}
mx=max(mx,a[i]);
}
cout<<ans<<endl;
return 0;
}
| [
"noreply@github.com"
] | arzav18.noreply@github.com |
01e3f197482d7dc1280ac6c27b85f62a87e110ce | e8b9e24cf5cbd96178dbc4cb08c38d62dab6bdce | /Source/Designer/support.cpp | 91a9603061090509686c5499fb3d4a8f6f26f9c0 | [] | no_license | pbarounis/ActiveBar2 | 3116aa48c6dde179ee06ff53108d55644b797550 | efbe8b367e975813677da68414a4f1457d4c812e | refs/heads/master | 2021-01-10T05:25:21.717387 | 2016-03-06T00:33:50 | 2016-03-06T00:33:50 | 53,230,406 | 0 | 2 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 15,280 | cpp | //
// Copyright © 1995-1999, Data Dynamics. All rights reserved.
//
// Unpublished -- rights reserved under the copyright laws of the United
// States. USE OF A COPYRIGHT NOTICE IS PRECAUTIONARY ONLY AND DOES NOT
// IMPLY PUBLICATION OR DISCLOSURE.
//
//
#include "precomp.h"
#include <stddef.h>
#include "ipserver.h"
#include "Resource.h"
#include "Globals.h"
#include "..\EventLog.h"
#include "support.h"
#include "debug.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern HINSTANCE g_hInstance;
const WCHAR wszCtlSaveStream [] = L"CONTROLSAVESTREAM";
short _SpecialKeyState()
{
// don't appear to be able to reduce number of calls to GetKeyState
//
BOOL bShift = (GetKeyState(VK_SHIFT) < 0);
BOOL bCtrl = (GetKeyState(VK_CONTROL) < 0);
BOOL bAlt = (GetKeyState(VK_MENU) < 0);
return (short)(bShift + (bCtrl << 1) + (bAlt << 2));
}
LPWSTR MakeWideStrFromAnsi(LPSTR psz,BYTE bType)
{
LPWSTR pwsz;
int i;
// arg checking.
//
if (!psz)
return NULL;
// compute the length of the required BSTR
//
i = MultiByteToWideChar(CP_ACP, 0, psz, -1, NULL, 0);
if (i <= 0) return NULL;
// allocate the widestr
//
switch (bType) {
case STR_BSTR:
// -1 since it'll add it's own space for a NULL terminator
//
pwsz = (LPWSTR) SysAllocStringLen(NULL, i - 1);
break;
case STR_OLESTR:
pwsz = (LPWSTR) CoTaskMemAlloc(i * sizeof(WCHAR));
break;
default:
TRACE(1, "Bogus String Type in MakeWideStrFromAnsi.\n");
return NULL;
}
if (!pwsz) return NULL;
MultiByteToWideChar(CP_ACP, 0, psz, -1, pwsz, i);
pwsz[i - 1] = 0;
return pwsz;
}
//=--------------------------------------------------------------------------=
// MakeWideStrFromResId
//=--------------------------------------------------------------------------=
// given a resource ID, load it, and allocate a wide string for it.
//
// Parameters:
// WORD - [in] resource id.
// BYTE - [in] type of string desired.
//
// Output:
// LPWSTR - needs to be cast to desired string type.
//
// Notes:
//
LPWSTR MakeWideStrFromResourceId(WORD wId,BYTE bType)
{
int i;
TCHAR szTmp[512];
#ifdef UNICODE
LPWSTR pwszTmp;
#endif
i = LoadString(g_hInstance, wId, szTmp, 512*sizeof(TCHAR));
// load the string from the resources.
if (!i)
return NULL;
#ifdef UNICODE
pwszTmp = (LPWSTR)CoTaskMemAlloc((i * sizeof(WCHAR)) + sizeof(WCHAR));
memcpy(pwszTmp,szTmp,(i * sizeof(WCHAR)) + sizeof(WCHAR));
return pwszTmp;
#else
return MakeWideStrFromAnsi(szTmp, bType);
#endif
}
//=--------------------------------------------------------------------------=
// MakeWideStrFromWide
//=--------------------------------------------------------------------------=
// given a wide string, make a new wide string with it of the given type.
//
// Parameters:
// LPWSTR - [in] current wide str.
// BYTE - [in] desired type of string.
//
// Output:
// LPWSTR
//
// Notes:
//
LPWSTR MakeWideStrFromWide
(
LPWSTR pwsz,
BYTE bType
)
{
LPWSTR pwszTmp;
int i;
if (!pwsz) return NULL;
// just copy the string, depending on what type they want.
//
switch (bType) {
case STR_OLESTR:
i = lstrlenW(pwsz);
pwszTmp = (LPWSTR)CoTaskMemAlloc((i * sizeof(WCHAR)) + sizeof(WCHAR));
if (!pwszTmp) return NULL;
memcpy(pwszTmp, pwsz, (sizeof(WCHAR) * i) + sizeof(WCHAR));
break;
case STR_BSTR:
pwszTmp = (LPWSTR)SysAllocString(pwsz);
break;
}
return pwszTmp;
}
//////////////// IOLEOBJECT
void WINAPI CopyOLEVERB(void *pvDest,const void *pvSrc,DWORD cbCopy)
{
memcpy(pvDest,pvSrc,cbCopy);
((OLEVERB *)pvDest)->lpszVerbName=MakeWideStrFromResourceId((UINT)(((OLEVERB *)pvSrc)->lpszVerbName), STR_OLESTR);
}
int s_iXppli; // Pixels per logical inch along width
int s_iYppli; // Pixels per logical inch along height
static BYTE s_fGotScreenMetrics; // Are above valid?
void CacheScreenMetrics(void)
{
HDC hDCScreen;
// we have to critical section this in case two threads are converting
// things at the same time
//
#ifdef DEF_CRITSECTION
EnterCriticalSection(&g_CriticalSection);
#endif
if (s_fGotScreenMetrics)
goto Done;
// we want the metrics for the screen
//
hDCScreen = GetDC(NULL);
ASSERT(hDCScreen, "couldn't get a DC for the screen.");
s_iXppli = GetDeviceCaps(hDCScreen, LOGPIXELSX);
s_iYppli = GetDeviceCaps(hDCScreen, LOGPIXELSY);
ReleaseDC(NULL, hDCScreen);
s_fGotScreenMetrics = TRUE;
// we're done with our critical seciton. clean it up
//
Done:;
#ifdef DEF_CRITSECTION
LeaveCriticalSection(&g_CriticalSection);
#endif
}
void PixelToHiMetric(const SIZEL *pixsizel,SIZEL *hisizel)
{
CacheScreenMetrics();
hisizel->cx = MAP_PIX_TO_LOGHIM(pixsizel->cx, s_iXppli);
hisizel->cy = MAP_PIX_TO_LOGHIM(pixsizel->cy, s_iYppli);
}
void HiMetricToPixel(const SIZEL *hisizel,SIZEL *pixsizel)
{
CacheScreenMetrics();
pixsizel->cx = MAP_LOGHIM_TO_PIX(hisizel->cx, s_iXppli);
pixsizel->cy = MAP_LOGHIM_TO_PIX(hisizel->cy, s_iYppli);
}
void PixelToTwips(const SIZEL *pixsizel,SIZEL *twipssizel)
{
CacheScreenMetrics();
twipssizel->cx = MAP_PIX_TO_TWIPS(pixsizel->cx, s_iXppli);
twipssizel->cy = MAP_PIX_TO_TWIPS(pixsizel->cy, s_iYppli);
}
void TwipsToPixel(const SIZEL *twipssizel, SIZEL *pixsizel)
{
CacheScreenMetrics();
pixsizel->cx = MAP_TWIPS_TO_PIX(twipssizel->cx, s_iXppli);
pixsizel->cy = MAP_TWIPS_TO_PIX(twipssizel->cy, s_iYppli);
}
//=--------------------------------------------------------------------------=
// _CreateOleDC
//=--------------------------------------------------------------------------=
// creates an HDC given a DVTARGETDEVICE structure.
HDC _CreateOleDC(DVTARGETDEVICE *ptd)
{
LPDEVMODEW pDevModeW;
HDC hdc;
LPOLESTR lpwszDriverName;
LPOLESTR lpwszDeviceName;
LPOLESTR lpwszPortName;
// return screen DC for NULL target device
if (!ptd)
return CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
if (ptd->tdExtDevmodeOffset == 0)
pDevModeW = NULL;
else
pDevModeW = (LPDEVMODEW)((LPSTR)ptd + ptd->tdExtDevmodeOffset);
lpwszDriverName = (LPOLESTR)((BYTE*)ptd + ptd->tdDriverNameOffset);
lpwszDeviceName = (LPOLESTR)((BYTE*)ptd + ptd->tdDeviceNameOffset);
lpwszPortName = (LPOLESTR)((BYTE*)ptd + ptd->tdPortNameOffset);
#ifdef UNICODE
hdc = CreateDC(lpwszDriverName, lpwszDeviceName, lpwszPortName, pDevModeW);
#else
DEVMODEA DevModeA, *pDevModeA;
MAKE_ANSIPTR_FROMWIDE(pszDriverName, lpwszDriverName);
MAKE_ANSIPTR_FROMWIDE(pszDeviceName, lpwszDeviceName);
MAKE_ANSIPTR_FROMWIDE(pszPortName, lpwszPortName);
if (pDevModeW)
{
WideCharToMultiByte(CP_ACP, 0, pDevModeW->dmDeviceName, -1, (LPSTR)DevModeA.dmDeviceName, CCHDEVICENAME, NULL, NULL);
memcpy(&DevModeA.dmSpecVersion, &pDevModeW->dmSpecVersion,
offsetof(DEVMODEA, dmFormName) - offsetof(DEVMODEA, dmSpecVersion));
WideCharToMultiByte(CP_ACP, 0, pDevModeW->dmFormName, -1, (LPSTR)DevModeA.dmFormName, CCHFORMNAME, NULL, NULL);
memcpy(&DevModeA.dmLogPixels, &pDevModeW->dmLogPixels, sizeof(DEVMODEA) - offsetof(DEVMODEA, dmLogPixels));
if (pDevModeW->dmDriverExtra)
{
pDevModeA = (DEVMODEA *)HeapAlloc(g_hHeap, 0, sizeof(DEVMODEA) + pDevModeW->dmDriverExtra);
if (!pDevModeA)
return NULL;
memcpy(pDevModeA, &DevModeA, sizeof(DEVMODEA));
memcpy(pDevModeA + 1, pDevModeW + 1, pDevModeW->dmDriverExtra);
}
else
pDevModeA = &DevModeA;
DevModeA.dmSize = sizeof(DEVMODEA);
}
else
pDevModeA = NULL;
hdc = CreateDC(pszDriverName, pszDeviceName, pszPortName, pDevModeA);
if (pDevModeA != &DevModeA)
HeapFree(g_hHeap, 0, pDevModeA);
#endif
return hdc;
}
LPTSTR g_szReflectClassName= _T("XBuilderReflector");
BYTE g_fRegisteredReflect=FALSE;
HWND CreateReflectWindow(BOOL fVisible,HWND hwndParent,int x,int y,SIZEL *pSize,CALLBACKFUNC pReflectWindowProc)
{
WNDCLASS wndclass;
// first thing to do is register the window class. crit sect this
// so we don't have to move it into the control
//
#ifdef DEF_CRITSECTION
EnterCriticalSection(&g_CriticalSection);
#endif
if (!g_fRegisteredReflect)
{
memset(&wndclass, 0, sizeof(wndclass));
wndclass.lpfnWndProc = pReflectWindowProc;
wndclass.hInstance = g_hInstance;
wndclass.lpszClassName = g_szReflectClassName;
if (!RegisterClass(&wndclass))
{
TRACE(1,"Couldn't Register Parking Window Class!");
#ifdef DEF_CRITSECTION
LeaveCriticalSection(&g_CriticalSection);
#endif
return NULL;
}
g_fRegisteredReflect = TRUE;
}
#ifdef DEF_CRITSECTION
LeaveCriticalSection(&g_CriticalSection);
#endif
// go and create the window.
return CreateWindowEx(0, g_szReflectClassName, NULL,
WS_CHILD | WS_CLIPSIBLINGS |((fVisible) ? WS_VISIBLE : 0),
x, y, pSize->cx, pSize->cy,
hwndParent,
NULL, g_hInstance, NULL);
}
LPTSTR szparkingclass=_T("XBuilder_Parking");
WNDPROC g_ParkingWindowProc = NULL;
HWND g_hwndParking=NULL;
HWND GetParkingWindow(void)
{
WNDCLASS wndclass;
// crit sect this creation for apartment threading support.
//
// EnterCriticalSection(&g_CriticalSection);
if (g_hwndParking)
goto CleanUp;
ZeroMemory(&wndclass, sizeof(wndclass));
wndclass.lpfnWndProc = (g_ParkingWindowProc) ? g_ParkingWindowProc : DefWindowProc;
wndclass.hInstance = g_hInstance;
wndclass.lpszClassName = szparkingclass;
if (!RegisterClass(&wndclass)) {
TRACE(1, "Couldn't Register Parking Window Class!");
goto CleanUp;
}
g_hwndParking = CreateWindow(szparkingclass, NULL, WS_POPUP, 0, 0, 0, 0, NULL, NULL, g_hInstance, NULL);
if (g_hwndParking != NULL)
++g_cLocks;
ASSERT(g_hwndParking, "Couldn't Create Global parking window!!");
CleanUp:
// LeaveCriticalSection(&g_CriticalSection);
return g_hwndParking;
}
void WINAPI CopyAndAddRefObject(void *pDest,const void *pSource,DWORD dwSize)
{
*((IUnknown **)pDest) = *((IUnknown **)pSource);
if ((*((IUnknown **)pDest))!=NULL)
(*((IUnknown **)pDest))->AddRef();
return;
}
///////////////// PERSISTANCE
void PersistBin(IStream *pStream,void *ptr,int size,BOOL save)
{
if (save)
pStream->Write(ptr,size,NULL);
else
pStream->Read(ptr,size,NULL);
}
void PersistBSTR(IStream *pStream,BSTR *pbstr,BOOL save)
{
short size;
BSTR bstr;
if (save)
{
bstr=*pbstr;
if (bstr==NULL || *bstr==0)
size=0;
else
size=(wcslen(bstr)+1)*sizeof(WCHAR);
pStream->Write(&size,sizeof(short),NULL);
if (size)
pStream->Write(bstr,size,0);
}
else
{
pStream->Read(&size,sizeof(short),NULL);
SysFreeString(*pbstr);
if (size!=0)
{
*pbstr=SysAllocStringByteLen(NULL,size);
pStream->Read(*pbstr,size,NULL);
}
else
*pbstr=NULL;
}
}
void PersistPict(IStream *pStream,CPictureHolder *pict,BOOL save)
{
}
void PersistVariant(IStream *pStream,VARIANT *v,BOOL save)
{
}
HRESULT PersistBagI2(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,short *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_I2;
if (save)
{
v.iVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.iVal;
}
return hr;
}
HRESULT PersistBagI4(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,long *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_I4;
if (save)
{
v.lVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.lVal;
}
return hr;
}
HRESULT PersistBagR4(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,float *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_R4;
if (save)
{
v.fltVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.fltVal;
}
return hr;
}
HRESULT PersistBagR8(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,double *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_R8;
if (save)
{
v.dblVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.dblVal;
}
return hr;
}
HRESULT PersistBagBSTR(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,BSTR *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_BSTR;
if (save)
{
v.bstrVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
v.bstrVal=NULL;
hr=pPropBag->Read(propName,&v,pErrorLog);
SysFreeString(*ptr);
if (SUCCEEDED(hr))
*ptr=v.bstrVal;
else
*ptr=NULL;
}
return hr;
}
HRESULT PersistBagBOOL(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,VARIANT_BOOL *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_BOOL;
if (save)
{
v.boolVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.boolVal;
}
return hr;
}
HRESULT PersistBagCurrency(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,CY *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_CY;
if (save)
{
v.cyVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.cyVal;
}
return hr;
}
HRESULT PersistBagDate(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,DATE *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_DATE;
if (save)
{
v.date=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.date;
}
return hr;
}
HRESULT PersistBagPict(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,CPictureHolder *pict,BOOL save)
{
return E_FAIL;
}
HRESULT PersistBagVariant(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,VARIANT *ptr,BOOL save)
{
HRESULT hr;
if (save)
hr=pPropBag->Write(propName,ptr);
else
hr=pPropBag->Read(propName,ptr,pErrorLog);
return hr;
}
| [
"pbarounis@yahoo.com"
] | pbarounis@yahoo.com |
8d4105f2d11d087ab048c81cebf1a89b7e4b6930 | ba4db75b9d1f08c6334bf7b621783759cd3209c7 | /src_main/game/shared/dod/weapon_dodfullauto_punch.cpp | 1a8dd1014e3ee70b3eada79182d6201b8dc6a638 | [] | no_license | equalent/source-2007 | a27326c6eb1e63899e3b77da57f23b79637060c0 | d07be8d02519ff5c902e1eb6430e028e1b302c8b | refs/heads/master | 2020-03-28T22:46:44.606988 | 2017-03-27T18:05:57 | 2017-03-27T18:05:57 | 149,257,460 | 2 | 0 | null | 2018-09-18T08:52:10 | 2018-09-18T08:52:09 | null | WINDOWS-1252 | C++ | false | false | 1,830 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "weapon_dodfullauto_punch.h"
#include "in_buttons.h"
#include "dod_shareddefs.h"
#ifndef CLIENT_DLL
#include "dod_player.h"
#endif
IMPLEMENT_NETWORKCLASS_ALIASED( DODFullAutoPunchWeapon, DT_FullAutoPunchWeapon )
BEGIN_NETWORK_TABLE( CDODFullAutoPunchWeapon, DT_FullAutoPunchWeapon )
END_NETWORK_TABLE()
#ifdef CLIENT_DLL
BEGIN_PREDICTION_DATA( CDODFullAutoPunchWeapon )
END_PREDICTION_DATA()
#endif
void CDODFullAutoPunchWeapon::Spawn( void )
{
m_iAltFireHint = HINT_USE_MELEE;
BaseClass::Spawn();
}
void CDODFullAutoPunchWeapon::SecondaryAttack( void )
{
if ( m_bInReload )
{
m_bInReload = false;
GetPlayerOwner()->m_flNextAttack = gpGlobals->curtime;
}
else if ( GetPlayerOwner()->m_flNextAttack > gpGlobals->curtime )
{
return;
}
Punch();
// start calling ItemPostFrame
GetPlayerOwner()->m_flNextAttack = gpGlobals->curtime;
m_flNextPrimaryAttack = m_flNextSecondaryAttack;
#ifndef CLIENT_DLL
CDODPlayer *pPlayer = GetDODPlayerOwner();
if ( pPlayer )
{
pPlayer->RemoveHintTimer( m_iAltFireHint );
}
#endif
}
bool CDODFullAutoPunchWeapon::Reload( void )
{
bool bSuccess = BaseClass::Reload();
if ( bSuccess )
{
m_flNextSecondaryAttack = gpGlobals->curtime;
}
return bSuccess;
}
void CDODFullAutoPunchWeapon::ItemBusyFrame( void )
{
BaseClass::ItemBusyFrame();
CBasePlayer *pPlayer = GetPlayerOwner();
if ( pPlayer && (pPlayer->m_nButtons & IN_ATTACK2) && (m_flNextSecondaryAttack <= gpGlobals->curtime))
{
SecondaryAttack();
pPlayer->m_nButtons &= ~IN_ATTACK2;
}
}
| [
"sean@csnxs.uk"
] | sean@csnxs.uk |
9e1ade56117da77e379292797fe85acc658429f2 | ab350b170cf12aee36b0ebed48e436b96bacbc5e | /Sources/Audio/Mp3/SoundBufferMp3.hpp | 260b4aec8645a3e5c1bfaa4365d35c902d800f3f | [
"MIT"
] | permissive | Sondro/Acid | 742398265684d5370423ce36bbb699dca3e9ee2f | 3d66868256c8c0dcc50b661f5922be6f35481b1c | refs/heads/master | 2023-04-13T00:02:51.727143 | 2020-01-31T13:52:45 | 2020-01-31T13:52:45 | 237,893,969 | 1 | 0 | MIT | 2023-04-04T01:37:35 | 2020-02-03T05:44:41 | null | UTF-8 | C++ | false | false | 371 | hpp | #pragma once
#include "Audio/SoundBuffer.hpp"
namespace acid {
class ACID_EXPORT SoundBufferMp3 : public SoundBuffer::Registrar<SoundBufferMp3> {
public:
static void Load(SoundBuffer *soundBuffer, const std::filesystem::path &filename);
static void Write(const SoundBuffer *soundBuffer, const std::filesystem::path &filename);
private:
static bool registered;
};
}
| [
"mattparks5855@gmail.com"
] | mattparks5855@gmail.com |
e00d89ec55278b761a1267e31ab560504c2e6201 | 2010b9614ac48465975aab90a0172bf49699e630 | /Lab5-Quicksort/QSInterface.h | 9ef93ca808a32d2217c0072a32687db56ac4836c | [] | no_license | JaeMoon94/CS235 | e2feffcf8bc36a5bfcf536ad087518b9266dc1c3 | de61244d1c61f0237a21279343a775ef41873afe | refs/heads/main | 2023-02-06T07:48:08.829746 | 2020-12-10T17:07:33 | 2020-12-10T17:07:33 | 320,334,416 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,906 | h | /*
* QSInterface.h
*
* Created on: May 1, 2014
* Last Updated on: March 30, 2015
*/
#ifndef QSINTERFACE_H_
#define QSINTERFACE_H_
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
/*
* WARNING: You may not modify any part of this document, including its name
*/
class QSInterface
{
public:
QSInterface() {}
virtual ~QSInterface() {}
/*
* sortAll()
*
* Sorts elements of the array. After this function is called, every
* element in the array is less than or equal its successor.
*
* Does nothing if the array is empty.
*/
void sortAll();
/*
* medianOfThree()
*
* The median of three pivot selection has two parts:
*
* 1) Calculates the middle index by averaging the given left and right indices:
*
* middle = (left + right)/2
*
* 2) Then bubble-sorts the values at the left, middle, and right indices.
*
* After this method is called, data[left] <= data[middle] <= data[right].
* The middle index will be returned.
*
* Returns -1 if the array is empty, if either of the given integers
* is out of bounds, or if the left index is not less than the right
* index.
*
* @param left
* the left boundary for the subarray from which to find a pivot
* @param right
* the right boundary for the subarray from which to find a pivot
* @return
* the index of the pivot (middle index); -1 if provided with invalid input
*/
int medianOfThree(int left, int right);
/*
* Partitions a subarray around a pivot value selected according to
* median-of-three pivot selection. Because there are multiple ways to partition a list,
* we will follow the algorithm on page 611 of the course text when testing this function.
*
* The values which are smaller than the pivot should be placed to the left
* of the pivot; the values which are larger than the pivot should be placed
* to the right of the pivot.
*
* Returns -1 if the array is null, if either of the given integers is out of
* bounds, or if the first integer is not less than the second integer, or if the
* pivot is not within the sub-array designated by left and right.
*
* @param left
* the left boundary for the subarray to partition
* @param right
* the right boundary for the subarray to partition
* @param pivotIndex
* the index of the pivot in the subarray
* @return
* the pivot's ending index after the partition completes; -1 if
* provided with bad input
*/
int partition(int left, int right, int pivotIndex);
/*
* Produces a comma delimited string representation of the array. For example: if my array
* looked like {5,7,2,9,0}, then the string to be returned would look like "5,7,2,9,0"
* with no trailing comma. The number of cells included equals the number of values added.
* Do not include the entire array if the array has yet to be filled.
*
* Returns an empty string, if the array is NULL or empty.
*
* @return
* the string representation of the current array
*/
string getArray() const;
/*
* Returns the number of elements which have been added to the array.
*/
int getSize() const;
/*
* Adds the given value to the end of the array starting at index 0.
* For example, the first time addToArray is called,
* the give value should be found at index 0.
* 2nd time, value should be found at index 1.
* 3rd, index 2, etc up to its max capacity.
*
* If the array is filled, do nothing.
* returns true if a value was added, false otherwise.
*/
bool addToArray(int value);
/*
* Dynamically allocates an array with the given capacity.
* If a previous array had been allocated, delete the previous array.
* Returns false if the given capacity is non-positive, true otherwise.
*
* @param
* size of array
* @return
* true if the array was created, false otherwise
*/
bool createArray(int capacity);
/*
* Resets the array to an empty or NULL state.
*/
void clear();
};
#endif /* QSINTERFACE_H_ */
| [
"noreply@github.com"
] | JaeMoon94.noreply@github.com |
ff6d365e0843ef66070a3f87c7c7c0c669d2c385 | 693e799b1388422562d89c1fd7d0429e527a4d21 | /qtrobot_ws/devel_isolated/moveit_msgs/include/moveit_msgs/SaveRobotStateToWarehouseRequest.h | c7d4e5192e20d8d7f0a0dc29bf56b7708e3a0d0e | [] | no_license | ZouJennie/iReCheck | bb777a8524b0d1d23c65ac4be9c87a073a888de4 | 00e64899989869be6bcb82d6919ab1fb69fc0dea | refs/heads/master | 2022-12-06T15:13:41.873122 | 2020-08-19T13:42:42 | 2020-08-19T13:42:42 | 248,212,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,357 | h | // Generated by gencpp from file moveit_msgs/SaveRobotStateToWarehouseRequest.msg
// DO NOT EDIT!
#ifndef MOVEIT_MSGS_MESSAGE_SAVEROBOTSTATETOWAREHOUSEREQUEST_H
#define MOVEIT_MSGS_MESSAGE_SAVEROBOTSTATETOWAREHOUSEREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <moveit_msgs/RobotState.h>
namespace moveit_msgs
{
template <class ContainerAllocator>
struct SaveRobotStateToWarehouseRequest_
{
typedef SaveRobotStateToWarehouseRequest_<ContainerAllocator> Type;
SaveRobotStateToWarehouseRequest_()
: name()
, robot()
, state() {
}
SaveRobotStateToWarehouseRequest_(const ContainerAllocator& _alloc)
: name(_alloc)
, robot(_alloc)
, state(_alloc) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _name_type;
_name_type name;
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _robot_type;
_robot_type robot;
typedef ::moveit_msgs::RobotState_<ContainerAllocator> _state_type;
_state_type state;
typedef boost::shared_ptr< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> const> ConstPtr;
}; // struct SaveRobotStateToWarehouseRequest_
typedef ::moveit_msgs::SaveRobotStateToWarehouseRequest_<std::allocator<void> > SaveRobotStateToWarehouseRequest;
typedef boost::shared_ptr< ::moveit_msgs::SaveRobotStateToWarehouseRequest > SaveRobotStateToWarehouseRequestPtr;
typedef boost::shared_ptr< ::moveit_msgs::SaveRobotStateToWarehouseRequest const> SaveRobotStateToWarehouseRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace moveit_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'shape_msgs': ['/opt/ros/kinetic/share/shape_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'moveit_msgs': ['/home/jennie/irecheck/iReCheck/qtrobot_ws/devel_isolated/moveit_msgs/share/moveit_msgs/msg', '/home/jennie/irecheck/iReCheck/qtrobot_ws/src/moveit_msgs/msg'], 'trajectory_msgs': ['/opt/ros/kinetic/share/trajectory_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'object_recognition_msgs': ['/opt/ros/kinetic/share/object_recognition_msgs/cmake/../msg'], 'octomap_msgs': ['/opt/ros/kinetic/share/octomap_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
{
static const char* value()
{
return "2b4f627ca3cd5a0cdeac277b421f5197";
}
static const char* value(const ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x2b4f627ca3cd5a0cULL;
static const uint64_t static_value2 = 0xdeac277b421f5197ULL;
};
template<class ContainerAllocator>
struct DataType< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
{
static const char* value()
{
return "moveit_msgs/SaveRobotStateToWarehouseRequest";
}
static const char* value(const ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
{
static const char* value()
{
return "string name\n\
string robot\n\
moveit_msgs/RobotState state\n\
\n\
\n\
================================================================================\n\
MSG: moveit_msgs/RobotState\n\
# This message contains information about the robot state, i.e. the positions of its joints and links\n\
sensor_msgs/JointState joint_state\n\
\n\
# Joints that may have multiple DOF are specified here\n\
sensor_msgs/MultiDOFJointState multi_dof_joint_state\n\
\n\
# Attached collision objects (attached to some link on the robot)\n\
AttachedCollisionObject[] attached_collision_objects\n\
\n\
# Flag indicating whether this scene is to be interpreted as a diff with respect to some other scene\n\
# This is mostly important for handling the attached bodies (whether or not to clear the attached bodies\n\
# of a moveit::core::RobotState before updating it with this message)\n\
bool is_diff\n\
\n\
================================================================================\n\
MSG: sensor_msgs/JointState\n\
# This is a message that holds data to describe the state of a set of torque controlled joints. \n\
#\n\
# The state of each joint (revolute or prismatic) is defined by:\n\
# * the position of the joint (rad or m),\n\
# * the velocity of the joint (rad/s or m/s) and \n\
# * the effort that is applied in the joint (Nm or N).\n\
#\n\
# Each joint is uniquely identified by its name\n\
# The header specifies the time at which the joint states were recorded. All the joint states\n\
# in one message have to be recorded at the same time.\n\
#\n\
# This message consists of a multiple arrays, one for each part of the joint state. \n\
# The goal is to make each of the fields optional. When e.g. your joints have no\n\
# effort associated with them, you can leave the effort array empty. \n\
#\n\
# All arrays in this message should have the same size, or be empty.\n\
# This is the only way to uniquely associate the joint name with the correct\n\
# states.\n\
\n\
\n\
Header header\n\
\n\
string[] name\n\
float64[] position\n\
float64[] velocity\n\
float64[] effort\n\
\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
\n\
================================================================================\n\
MSG: sensor_msgs/MultiDOFJointState\n\
# Representation of state for joints with multiple degrees of freedom, \n\
# following the structure of JointState.\n\
#\n\
# It is assumed that a joint in a system corresponds to a transform that gets applied \n\
# along the kinematic chain. For example, a planar joint (as in URDF) is 3DOF (x, y, yaw)\n\
# and those 3DOF can be expressed as a transformation matrix, and that transformation\n\
# matrix can be converted back to (x, y, yaw)\n\
#\n\
# Each joint is uniquely identified by its name\n\
# The header specifies the time at which the joint states were recorded. All the joint states\n\
# in one message have to be recorded at the same time.\n\
#\n\
# This message consists of a multiple arrays, one for each part of the joint state. \n\
# The goal is to make each of the fields optional. When e.g. your joints have no\n\
# wrench associated with them, you can leave the wrench array empty. \n\
#\n\
# All arrays in this message should have the same size, or be empty.\n\
# This is the only way to uniquely associate the joint name with the correct\n\
# states.\n\
\n\
Header header\n\
\n\
string[] joint_names\n\
geometry_msgs/Transform[] transforms\n\
geometry_msgs/Twist[] twist\n\
geometry_msgs/Wrench[] wrench\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Transform\n\
# This represents the transform between two coordinate frames in free space.\n\
\n\
Vector3 translation\n\
Quaternion rotation\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Vector3\n\
# This represents a vector in free space. \n\
# It is only meant to represent a direction. Therefore, it does not\n\
# make sense to apply a translation to it (e.g., when applying a \n\
# generic rigid transformation to a Vector3, tf2 will only apply the\n\
# rotation). If you want your data to be translatable too, use the\n\
# geometry_msgs/Point message instead.\n\
\n\
float64 x\n\
float64 y\n\
float64 z\n\
================================================================================\n\
MSG: geometry_msgs/Quaternion\n\
# This represents an orientation in free space in quaternion form.\n\
\n\
float64 x\n\
float64 y\n\
float64 z\n\
float64 w\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Twist\n\
# This expresses velocity in free space broken into its linear and angular parts.\n\
Vector3 linear\n\
Vector3 angular\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Wrench\n\
# This represents force in free space, separated into\n\
# its linear and angular parts.\n\
Vector3 force\n\
Vector3 torque\n\
\n\
================================================================================\n\
MSG: moveit_msgs/AttachedCollisionObject\n\
# The CollisionObject will be attached with a fixed joint to this link\n\
string link_name\n\
\n\
#This contains the actual shapes and poses for the CollisionObject\n\
#to be attached to the link\n\
#If action is remove and no object.id is set, all objects\n\
#attached to the link indicated by link_name will be removed\n\
CollisionObject object\n\
\n\
# The set of links that the attached objects are allowed to touch\n\
# by default - the link_name is already considered by default\n\
string[] touch_links\n\
\n\
# If certain links were placed in a particular posture for this object to remain attached \n\
# (e.g., an end effector closing around an object), the posture necessary for releasing\n\
# the object is stored here\n\
trajectory_msgs/JointTrajectory detach_posture\n\
\n\
# The weight of the attached object, if known\n\
float64 weight\n\
\n\
================================================================================\n\
MSG: moveit_msgs/CollisionObject\n\
# A header, used for interpreting the poses\n\
Header header\n\
\n\
# The id of the object (name used in MoveIt)\n\
string id\n\
\n\
# The object type in a database of known objects\n\
object_recognition_msgs/ObjectType type\n\
\n\
# The collision geometries associated with the object.\n\
# Their poses are with respect to the specified header\n\
\n\
# Solid geometric primitives\n\
shape_msgs/SolidPrimitive[] primitives\n\
geometry_msgs/Pose[] primitive_poses\n\
\n\
# Meshes\n\
shape_msgs/Mesh[] meshes\n\
geometry_msgs/Pose[] mesh_poses\n\
\n\
# Bounding planes (equation is specified, but the plane can be oriented using an additional pose)\n\
shape_msgs/Plane[] planes\n\
geometry_msgs/Pose[] plane_poses\n\
\n\
# Named subframes on the object. Use these to define points of interest on the object that you want\n\
# to plan with (e.g. \"tip\", \"spout\", \"handle\"). The id of the object will be prepended to the subframe.\n\
# If an object with the id \"screwdriver\" and a subframe \"tip\" is in the scene, you can use the frame\n\
# \"screwdriver/tip\" for planning.\n\
# The length of the subframe_names and subframe_poses has to be identical.\n\
string[] subframe_names\n\
geometry_msgs/Pose[] subframe_poses\n\
\n\
# Adds the object to the planning scene. If the object previously existed, it is replaced.\n\
byte ADD=0\n\
\n\
# Removes the object from the environment entirely (everything that matches the specified id)\n\
byte REMOVE=1\n\
\n\
# Append to an object that already exists in the planning scene. If the object does not exist, it is added.\n\
byte APPEND=2\n\
\n\
# If an object already exists in the scene, new poses can be sent (the geometry arrays must be left empty)\n\
# if solely moving the object is desired\n\
byte MOVE=3\n\
\n\
# Operation to be performed\n\
byte operation\n\
\n\
================================================================================\n\
MSG: object_recognition_msgs/ObjectType\n\
################################################## OBJECT ID #########################################################\n\
\n\
# Contains information about the type of a found object. Those two sets of parameters together uniquely define an\n\
# object\n\
\n\
# The key of the found object: the unique identifier in the given db\n\
string key\n\
\n\
# The db parameters stored as a JSON/compressed YAML string. An object id does not make sense without the corresponding\n\
# database. E.g., in object_recognition, it can look like: \"{'type':'CouchDB', 'root':'http://localhost'}\"\n\
# There is no conventional format for those parameters and it's nice to keep that flexibility.\n\
# The object_recognition_core as a generic DB type that can read those fields\n\
# Current examples:\n\
# For CouchDB:\n\
# type: 'CouchDB'\n\
# root: 'http://localhost:5984'\n\
# collection: 'object_recognition'\n\
# For SQL household database:\n\
# type: 'SqlHousehold'\n\
# host: 'wgs36'\n\
# port: 5432\n\
# user: 'willow'\n\
# password: 'willow'\n\
# name: 'household_objects'\n\
# module: 'tabletop'\n\
string db\n\
\n\
================================================================================\n\
MSG: shape_msgs/SolidPrimitive\n\
# Define box, sphere, cylinder, cone \n\
# All shapes are defined to have their bounding boxes centered around 0,0,0.\n\
\n\
uint8 BOX=1\n\
uint8 SPHERE=2\n\
uint8 CYLINDER=3\n\
uint8 CONE=4\n\
\n\
# The type of the shape\n\
uint8 type\n\
\n\
\n\
# The dimensions of the shape\n\
float64[] dimensions\n\
\n\
# The meaning of the shape dimensions: each constant defines the index in the 'dimensions' array\n\
\n\
# For the BOX type, the X, Y, and Z dimensions are the length of the corresponding\n\
# sides of the box.\n\
uint8 BOX_X=0\n\
uint8 BOX_Y=1\n\
uint8 BOX_Z=2\n\
\n\
\n\
# For the SPHERE type, only one component is used, and it gives the radius of\n\
# the sphere.\n\
uint8 SPHERE_RADIUS=0\n\
\n\
\n\
# For the CYLINDER and CONE types, the center line is oriented along\n\
# the Z axis. Therefore the CYLINDER_HEIGHT (CONE_HEIGHT) component\n\
# of dimensions gives the height of the cylinder (cone). The\n\
# CYLINDER_RADIUS (CONE_RADIUS) component of dimensions gives the\n\
# radius of the base of the cylinder (cone). Cone and cylinder\n\
# primitives are defined to be circular. The tip of the cone is\n\
# pointing up, along +Z axis.\n\
\n\
uint8 CYLINDER_HEIGHT=0\n\
uint8 CYLINDER_RADIUS=1\n\
\n\
uint8 CONE_HEIGHT=0\n\
uint8 CONE_RADIUS=1\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Pose\n\
# A representation of pose in free space, composed of position and orientation. \n\
Point position\n\
Quaternion orientation\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Point\n\
# This contains the position of a point in free space\n\
float64 x\n\
float64 y\n\
float64 z\n\
\n\
================================================================================\n\
MSG: shape_msgs/Mesh\n\
# Definition of a mesh\n\
\n\
# list of triangles; the index values refer to positions in vertices[]\n\
MeshTriangle[] triangles\n\
\n\
# the actual vertices that make up the mesh\n\
geometry_msgs/Point[] vertices\n\
\n\
================================================================================\n\
MSG: shape_msgs/MeshTriangle\n\
# Definition of a triangle's vertices\n\
uint32[3] vertex_indices\n\
\n\
================================================================================\n\
MSG: shape_msgs/Plane\n\
# Representation of a plane, using the plane equation ax + by + cz + d = 0\n\
\n\
# a := coef[0]\n\
# b := coef[1]\n\
# c := coef[2]\n\
# d := coef[3]\n\
\n\
float64[4] coef\n\
\n\
================================================================================\n\
MSG: trajectory_msgs/JointTrajectory\n\
Header header\n\
string[] joint_names\n\
JointTrajectoryPoint[] points\n\
================================================================================\n\
MSG: trajectory_msgs/JointTrajectoryPoint\n\
# Each trajectory point specifies either positions[, velocities[, accelerations]]\n\
# or positions[, effort] for the trajectory to be executed.\n\
# All specified values are in the same order as the joint names in JointTrajectory.msg\n\
\n\
float64[] positions\n\
float64[] velocities\n\
float64[] accelerations\n\
float64[] effort\n\
duration time_from_start\n\
";
}
static const char* value(const ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.name);
stream.next(m.robot);
stream.next(m.state);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct SaveRobotStateToWarehouseRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator>& v)
{
s << indent << "name: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.name);
s << indent << "robot: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.robot);
s << indent << "state: ";
s << std::endl;
Printer< ::moveit_msgs::RobotState_<ContainerAllocator> >::stream(s, indent + " ", v.state);
}
};
} // namespace message_operations
} // namespace ros
#endif // MOVEIT_MSGS_MESSAGE_SAVEROBOTSTATETOWAREHOUSEREQUEST_H
| [
"zjl93128@hotmail.com"
] | zjl93128@hotmail.com |
cdf63a4c67f8ae5d1b0e47f71a31e10301047dfc | a95b32b1001c157ca62cf4dbf782b5109010f122 | /agchess/libagchess/Bitboard.h | 1068f7d159fdc33e5b1f17661564ab3c20211ade | [] | no_license | shyamalschandra/kivy-chess | 2306e98e9f91b915bbff70102433c57fbb19202d | 08a238632a552d52c33b960e3d07ff3e6822b5bc | refs/heads/master | 2021-01-22T00:52:03.912163 | 2014-10-09T16:32:28 | 2014-10-09T16:32:28 | 26,282,941 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,252 | h | /*
libagchess, a chess library in C++.
Copyright (C) 2010-2011 Austen Green.
libagchess 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.
libagchess 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 libagchess. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef AGCHESS_BITBOARD_H
#define AGCHESS_BITBOARD_H
#include <stdint.h>
#include <iostream>
#include "Square.h"
#include "ColoredPiece.h"
namespace AGChess {
typedef uint64_t Bitboard;
enum Direction{
noWe = 7, nort = 8, noEa = 9,
west = -1, east = 1,
soWe = -9, sout = -8, soEa = -7
};
extern const Bitboard RanksBB[8];
extern const Bitboard FilesBB[8];
extern const Bitboard SquaresBB[65];
extern const Bitboard PieceMovesBB[5][64];
extern const unsigned char occupancy_bitboards[8][256];
const Bitboard EmptyBB = 0;
const Bitboard notAFile = 0xfefefefefefefefeULL;
const Bitboard notHFile = 0x7f7f7f7f7f7f7f7fULL;
const Bitboard longDiag = 0x8040201008040201ULL; // Long diagonal a1-h8
const Bitboard longAdiag =0x0102040810204080ULL; // Long antidiagonal a8-h1
Bitboard pieceMoves(Piece, Square);
Bitboard generate_ray(Square, Direction);
unsigned char generate_first_rank(unsigned char, signed char);
/* Basic shifts */
inline Bitboard nortOne(const Bitboard& b) {return b << 8;}
inline Bitboard soutOne(const Bitboard& b) {return b >> 8;}
inline Bitboard eastOne(const Bitboard& b) {return (b << 1) & notAFile;}
inline Bitboard noEaOne(const Bitboard& b) {return (b << 9) & notAFile;}
inline Bitboard soEaOne(const Bitboard& b) {return (b >> 7) & notAFile;}
inline Bitboard westOne(const Bitboard& b) {return (b >> 1) & notHFile;}
inline Bitboard soWeOne(const Bitboard& b) {return (b >> 9) & notHFile;}
inline Bitboard noWeOne(const Bitboard& b) {return (b << 7) & notHFile;}
inline Bitboard nortX(const Bitboard& b, unsigned char x) {return (x < 8) ? b << (8 * x) : EmptyBB;}
inline Bitboard soutX(const Bitboard& b, unsigned char x) {return (x < 8) ? b >> (8 * x) : EmptyBB;}
inline Bitboard eastX(const Bitboard& b, unsigned char x) {
Bitboard bb = b;
for (int i = 0; i < x; i++) {
bb = eastOne(bb);
}
return bb;
}
inline Bitboard westX(const Bitboard& b, unsigned char x) {
Bitboard bb = b;
for (int i = 0; i < x; i++) {
bb = westOne(bb);
}
return bb;
}
/* The following four methods use kindergarten bitboards to generate a bitboard
* of attacked squares for sliding pieces along a given line (rank, file, or diagonal).
* The returned set of squares represents those squares which can be attacked
* by a sliding piece, and must be filtered based on color to make sure that a sliding
* piece cannot move to a square occupied by a friendly piece. */
Bitboard rank_attacks(Bitboard occupied, Square s);
Bitboard file_attacks(Bitboard occupied, Square s);
Bitboard diagonal_attacks(Bitboard occupied, Square s);
Bitboard antidiagonal_attacks(Bitboard occupied, Square s);
inline const Bitboard& squareBB(Square s) { return SquaresBB[char(s)]; }
//inline const Bitboard& squareBB(int s) { return SquaresBB[s]; } // Is this method really needed?
inline const Bitboard& ranksBB(unsigned char rank) {return RanksBB[rank]; }
inline const Bitboard& filesBB(unsigned char file) {return FilesBB[file]; }
Square squareForBitboard(Bitboard);
int BBPopCount(Bitboard);
// Debug
extern void print_bitboard(const Bitboard&);
inline void print_hex(const Bitboard& bb) {
printf("0x%016llXULL,\n", bb);
}
}
#endif | [
"sshivaji@gmail.com"
] | sshivaji@gmail.com |
9620b3d5a6800c3207a7a523da3dd41f9a1b6869 | de41e2930dbbb64f10116ce8361ca1099a2794fb | /APTrader/APTrader/System/Win32/NamedPipeListener.h | 4c30c1af9b1bb9d9bffbacf719efea0126718c0c | [] | no_license | alexfordc/APTrader | 4c8c6151c8e4465f28a2f16f08bbebb6f224ff8c | 905015d0dfd9612158ef30b0be21fbeffc810586 | refs/heads/master | 2021-05-24T17:18:04.904225 | 2018-04-12T10:05:22 | 2018-04-12T10:05:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | h | #pragma once
#include <string>
#include <Windows.h>
#include "../../Common/InitializableObject.h"
#include <mutex>
#include <thread>
#include "../../Common/Singleton.h"
typedef void(*PipeCallback)(std::string msg);
class NamedPipeListener : public InitializableObject
{
public:
NamedPipeListener(std::string pipeName);
~NamedPipeListener();
virtual void init();
void start();
void listenPipe();
void setRun(bool run);
void registerPipeCallback(PipeCallback callback);
protected:
std::string m_pipeName;
std::mutex m_mutex;
std::thread m_listenThread;
HANDLE m_hPipe;
bool m_run;
LPCRITICAL_SECTION m_criticalSection;
HANDLE m_semaphore;
PipeCallback m_pipeCallback;
}; | [
"7cronaldo@sina.com"
] | 7cronaldo@sina.com |
155ee5523a5b2dc01bea84e1790abc596eecb40e | 2071cbd28d3ddd961e0043c3cb161ca8a4770e23 | /AtCoderBeginnerContest122/A.cpp | a31f18643284198ea1a8d3e9dec075615d92d8ba | [] | no_license | ciws009/AtCoder-Beginner-Contest-122 | e57968c5cc1df3bc50611fbf3c97c2a309ecfa7b | bd008cbddf2a7df25cbb0e97883a77733237a743 | refs/heads/master | 2020-05-01T16:41:56.042911 | 2019-03-25T14:17:32 | 2019-03-25T14:17:32 | 177,579,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | cpp | #include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
string s; cin >> s;
string before = "ATCG";
string after = "TAGC";
map<char, char> m;
for(int i = 0; i < before.size(); i++) {
m[before[i]] = after[i];
}
char ans = m[s[0]];
cout << ans << endl;
}
| [
"stariver0812@gmail.com"
] | stariver0812@gmail.com |
dfdde0f8a4affd5c5acb586f1f18e3f975db1d7d | b511bb6461363cf84afa52189603bd9d1a11ad34 | /code/11384.cpp | 6f90da00edf67a7e5d57fd8fab7a453e0c1e8c93 | [] | no_license | masumr/problem_solve | ec0059479425e49cc4c76a107556972e1c545e89 | 1ad4ec3e27f28f10662c68bbc268eaad9f5a1a9e | refs/heads/master | 2021-01-16T19:07:01.198885 | 2017-08-12T21:21:59 | 2017-08-12T21:21:59 | 100,135,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | #include<cstdio>
using namespace std;
int main(){
int n;
while(scanf("%d",&n)==1){
int count=0;
while(n!=0){
n>>=1;
count++;
}
printf("%d\n",count);
}
}
| [
"masumr455@gmial.com"
] | masumr455@gmial.com |
451e5f08377d7343c4c49ac1c1c3d366c27252fa | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5630113748090880_0/C++/Lucaskywalker/cjb.cpp | 5f45550c9bacb01b6dd816517f8f57304cebbe57 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int te;
cin>>te;
int ocor[2505];
for(int t=1;t<=te;t++)
{
for(int i=0;i<2505;i++) ocor[i]=0;
int n;
cin>>n;
for(int i=0;i<2*n-1;i++)
{
for(int j=0;j<n;j++)
{
int a;
cin>>a;
ocor[a]++;
}
}
vector<int> resp;
for(int i=0;i<2505;i++)
{
if(ocor[i]&1)
{
resp.push_back(i);
}
}
cout<<"Case #"<<t<<": ";
for(int i=0;i<resp.size();i++)
{
cout<<resp[i]<<" ";
}
cout<<endl;
}
return 0;
}
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
d056be42398a824424abbbf96808bc015406bef1 | ad273708d98b1f73b3855cc4317bca2e56456d15 | /aws-cpp-sdk-medialive/include/aws/medialive/model/AacVbrQuality.h | b751faca5d055ab19e32b0990300eadcfcb823a2 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | novaquark/aws-sdk-cpp | b390f2e29f86f629f9efcf41c4990169b91f4f47 | a0969508545bec9ae2864c9e1e2bb9aff109f90c | refs/heads/master | 2022-08-28T18:28:12.742810 | 2020-05-27T15:46:18 | 2020-05-27T15:46:18 | 267,351,721 | 1 | 0 | Apache-2.0 | 2020-05-27T15:08:16 | 2020-05-27T15:08:15 | null | UTF-8 | C++ | false | false | 1,132 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/medialive/MediaLive_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace MediaLive
{
namespace Model
{
enum class AacVbrQuality
{
NOT_SET,
HIGH,
LOW,
MEDIUM_HIGH,
MEDIUM_LOW
};
namespace AacVbrQualityMapper
{
AWS_MEDIALIVE_API AacVbrQuality GetAacVbrQualityForName(const Aws::String& name);
AWS_MEDIALIVE_API Aws::String GetNameForAacVbrQuality(AacVbrQuality value);
} // namespace AacVbrQualityMapper
} // namespace Model
} // namespace MediaLive
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
b43cfd47951f05ac44cfba4944e45889f31f4958 | 431bc209251c67ed68b69ca12a34f79da4be946c | /src/libs/blueprint/conduit_blueprint_mesh_examples_julia.cpp | 6b8398f7d6a3e7212cf968e97020a1c9f797f1e6 | [
"BSD-3-Clause"
] | permissive | LLNL/conduit | 4ae3157e8e9a83643f9479506f3b5f1def7b99fa | a6b0b179716eb804a0749cc20083c24c21ed682b | refs/heads/develop | 2023-09-04T00:04:32.475102 | 2023-09-01T16:00:30 | 2023-09-01T16:00:30 | 40,552,086 | 168 | 58 | NOASSERTION | 2023-09-05T21:33:19 | 2015-08-11T16:14:10 | C++ | UTF-8 | C++ | false | false | 22,682 | cpp | // Copyright (c) Lawrence Livermore National Security, LLC and other Conduit
// Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
// other details. No copyright assignment is required to contribute to Conduit.
//-----------------------------------------------------------------------------
///
/// file: conduit_blueprint_mesh_examples_julia.cpp
///
//-----------------------------------------------------------------------------
#if defined(CONDUIT_PLATFORM_WINDOWS)
#define NOMINMAX
#undef min
#undef max
#include "windows.h"
#endif
//-----------------------------------------------------------------------------
// std lib includes
//-----------------------------------------------------------------------------
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <limits>
#include <algorithm>
#include <cassert>
#include <limits>
#include <map>
#include <set>
#include <vector>
#include <queue>
//-----------------------------------------------------------------------------
// conduit includes
//-----------------------------------------------------------------------------
#include "conduit_blueprint_mesh_examples.hpp"
#include "conduit_blueprint_mesh.hpp"
//-----------------------------------------------------------------------------
// -- begin conduit:: --
//-----------------------------------------------------------------------------
namespace conduit
{
//-----------------------------------------------------------------------------
// -- begin conduit::blueprint:: --
//-----------------------------------------------------------------------------
namespace blueprint
{
//-----------------------------------------------------------------------------
// -- begin conduit::blueprint::mesh --
//-----------------------------------------------------------------------------
namespace mesh
{
//-----------------------------------------------------------------------------
// -- begin conduit::blueprint::mesh::examples --
//-----------------------------------------------------------------------------
namespace examples
{
void julia_fill_values(index_t nx,
index_t ny,
float64 x_min,
float64 x_max,
float64 y_min,
float64 y_max,
float64 c_re,
float64 c_im,
int32_array &out)
{
index_t idx = 0;
for(index_t j = 0; j < ny; j++)
{
for(index_t i = 0; i < nx; i++)
{
float64 zx = float64(i) / float64(nx-1);
float64 zy = float64(j) / float64(ny-1);
zx = x_min + (x_max - x_min) * zx;
zy = y_min + (y_max - y_min) * zy;
int32 iter = 0;
int32 max_iter = 1000;
while( (zx * zx) + (zy * zy ) < 4.0 && iter < max_iter)
{
float64 x_temp = zx*zx - zy*zy;
zy = 2*zx*zy + c_im;
zx = x_temp + c_re;
iter++;
}
if(iter == max_iter)
{
out[idx] = 0;
}
else
{
out[idx] = iter;
}
idx++;
}
}
}
//---------------------------------------------------------------------------//
void paint_2d_nestsets(conduit::Node &domain,
const std::string topo_name)
{
if(!domain.has_path("topologies/"+topo_name))
{
CONDUIT_ERROR("Paint nestsets: no topology named: "<<topo_name);
}
const Node &topo = domain["topologies/"+topo_name];
if(topo["type"].as_string() == "unstructured")
{
CONDUIT_ERROR("Paint nestsets: cannot paint on unstructured topology");
}
int el_dims[2] = {1,1};
if(topo["type"].as_string() == "structured")
{
el_dims[0] = topo["elements/dims/i"].to_int32();
el_dims[1] = topo["elements/dims/j"].to_int32();
}
else
{
const std::string coord_name = topo["coordset"].as_string();
const Node &coords = domain["coordsets/"+coord_name];
if(coords["type"].as_string() == "uniform")
{
el_dims[0] = coords["dims/i"].as_int32() - 1;
el_dims[1] = coords["dims/j"].as_int32() - 1;
}
else if(coords["type"].as_string() == "rectilinear")
{
el_dims[0] = (int)(coords["values/x"].dtype().number_of_elements() - 1);
el_dims[1] = (int)(coords["values/y"].dtype().number_of_elements() - 1);
}
else
{
CONDUIT_ERROR("unknown coord type");
}
}
const int32 field_size = el_dims[0] * el_dims[1];
Node &levels_field = domain["fields/mask"];
levels_field["association"] = "element";
levels_field["topology"] = topo_name;
levels_field["values"] = DataType::int32(field_size);
int32_array levels = levels_field["values"].value();
for(int i = 0; i < field_size; ++i)
{
levels[i] = 0;
}
int nest_id = -1;
for(int i = 0; i < domain["nestsets"].number_of_children(); ++i)
{
const Node &nestset = domain["nestsets"].child(0);
if(nestset["topology"].as_string() == topo_name)
{
nest_id = i;
break;
}
}
if(nest_id == -1) return;
const Node &nestset = domain["nestsets"].child(nest_id);
const index_t windows = nestset["windows"].number_of_children();
for(index_t i = 0; i < windows; ++i)
{
const Node &window = nestset["windows"].child(i);
if(window["domain_type"].as_string() != "child")
{
continue;
}
int origin[2];
origin[0] = window["origin/i"].to_int32();
origin[1] = window["origin/j"].to_int32();
int dims[2];
dims[0] = window["dims/i"].to_int32();
dims[1] = window["dims/j"].to_int32();
// all the nesting relationship is local
for(int y = origin[1]; y < origin[1] + dims[1]; ++y)
{
const int32 y_offset = y * el_dims[0];
for(int x = origin[0]; x < origin[0] + dims[0]; ++x)
{
levels[y_offset + x] += 1;
}
}
}
}
//---------------------------------------------------------------------------//
void gap_scanner(const std::vector<int32> &values,
const index_t start,
const index_t end,
const index_t offset,
int32 gap[2])
{
bool in_gap = false;
int32 gap_length = 0;
gap[0] = -1; // index of gap
gap[1] = 0; // length of gap
for(index_t i = start - offset; i <= end - offset; ++i)
{
if(values[i] == 0)
{
if(in_gap) gap_length++;
else
{
gap_length = 1;
in_gap = true;
}
}
else
{
if(in_gap)
{
if(gap_length > gap[1])
{
gap[0] = (int32)(i + offset);
gap[1] = gap_length;
}
in_gap = false;
}
}
}
}
//---------------------------------------------------------------------------//
void inflection_scanner(const std::vector<int32> &values,
const index_t start,
const index_t end,
const index_t offset,
int32 crit[2])
{
crit[0] = -1;
crit[1] = 0;
int32 prev = 0;
for(index_t i = start + 1 - offset; i <= end - 1 - offset; ++i)
{
// second derivitive using finite differences
int32 deriv = values[i + 1] - 2 * values[i] + values[i-1];
// inflection point
if((prev < 0 && deriv > 0) || (prev > 0 && deriv < 0))
{
int32 mag = abs(deriv - prev);
if(mag > crit[1])
{
crit[0] = (int32)(i + offset);
crit[1] = mag;
}
}
prev = deriv;
}
}
struct AABB
{
index_t box[3][2];
AABB()
{
box[0][0] = std::numeric_limits<index_t>::max();
box[0][1] = std::numeric_limits<index_t>::min();
box[1][0] = std::numeric_limits<index_t>::max();
box[1][1] = std::numeric_limits<index_t>::min();
box[2][0] = std::numeric_limits<index_t>::max();
box[2][1] = std::numeric_limits<index_t>::min();
}
bool valid(index_t axis)
{
return box[axis][0] <= box[axis][1];
}
index_t size()
{
index_t res = 0;
res = (box[0][1] - box[0][0] + 1) * (box[1][1] - box[1][0] + 1);
if(valid(2))
{
res *= box[2][1] - box[2][0] + 1;
}
return res;
}
void print()
{
std::cout<<"size "<<size()<<" "
<<"("<<box[0][0]<<","<<box[0][1]<<") - "
<<"("<<box[1][0]<<","<<box[1][0]<<")\n";
}
index_t length(index_t axis)
{
return (box[axis][1] - box[axis][0] + 1);
}
index_t min(index_t axis)
{
return box[axis][0];
}
index_t max(index_t axis)
{
return box[axis][1];
}
void split(const index_t axis,
const index_t index,
AABB &left,
AABB &right)
{
for(index_t i = 0; i < 3; ++i)
{
if(i == axis)
{
left.box[i][0] = box[i][0];
left.box[i][1] = index;
right.box[i][0] = index + 1;
right.box[i][1] = box[i][1];
}
else
{
left.box[i][0] = box[i][0];
left.box[i][1] = box[i][1];
right.box[i][0] = box[i][0];
right.box[i][1] = box[i][1];
}
}
}
void include(int axis, index_t pos)
{
box[axis][0] = std::min(pos, box[axis][0]);
box[axis][1] = std::max(pos, box[axis][1]);
}
void mid_split(AABB &left, AABB &right)
{
index_t axis = 0;
index_t len = 0;
for(index_t i = 0; i < 3; i++)
{
if(valid(i))
{
index_t size = length(i);
if(size > len)
{
axis = i;
len = size;
}
}
}
index_t pos = len/2 + box[axis][0] - 1;
split(axis, pos, left, right);
}
};
//---------------------------------------------------------------------------//
// creates a vector of sub boxs using a list of
// flags that marks 'interesting' zones
void
sub_boxs(const std::vector<int32> &flags,
const index_t nx,
const index_t ny,
const float64 efficiency,
const int32 min_size,
std::vector<AABB> &refined)
{
AABB mesh_box;
mesh_box.include(0,0);
mesh_box.include(0,nx-1);
mesh_box.include(1,0);
mesh_box.include(1,ny-1);
std::queue<AABB> aabbs;
aabbs.push(mesh_box);
while(!aabbs.empty())
{
AABB current = aabbs.front();
index_t dx = current.length(0);
index_t dy = current.length(1);
std::vector<int32> x_bins(dx, 0);
std::vector<int32> y_bins(dy, 0);
int32 flag_count = 0;
AABB aabb;
// find the tight AABB containing flags
for(index_t y = current.min(1); y <= current.max(1); ++y)
{
for(index_t x = current.min(0); x <= current.max(0); ++x)
{
index_t offset = y * nx + x;
int32 flag = flags[offset];
if(flag == 1)
{
aabb.include(0, x);
aabb.include(1, y);
}
x_bins[x - current.min(0)] += flag;
y_bins[y - current.min(1)] += flag;
flag_count += flag;
}
}
// terminating conditions
if(flag_count == 0)
{
aabbs.pop();
continue;
}
index_t subsize = aabb.size();
float64 ratio = float64(flag_count) / float64(subsize);
if(ratio > efficiency || subsize < min_size)
{
refined.push_back(aabb);
aabbs.pop();
continue;
}
// find a split
// look for the longest gap that divides two 'clusters' of flags
// this is the best kind of split
int32 x_gap[2];
int32 y_gap[2];
gap_scanner(x_bins, aabb.min(0), aabb.max(0), current.min(0), x_gap);
gap_scanner(y_bins, aabb.min(1), aabb.max(1), current.min(1), y_gap);
if((x_gap[0] != -1 || y_gap[0] != -1) &&
x_gap[0] != aabb.min(0) &&
x_gap[0] != aabb.max(0) &&
y_gap[0] != aabb.min(1) &&
y_gap[0] != aabb.max(1))
{
AABB left, right;
if(x_gap[1] > y_gap[1])
{
aabb.split(0, x_gap[0], left, right);
}
else
{
aabb.split(1, y_gap[0], left, right);
}
aabbs.pop();
aabbs.push(left);
aabbs.push(right);
continue;
}
// look for splits defined by zero crossovers of the
// second derivitive.
int32 x_crit[2];
int32 y_crit[2];
inflection_scanner(x_bins, aabb.min(0), aabb.max(0), current.min(0),x_crit);
inflection_scanner(y_bins, aabb.min(1), aabb.max(1), current.min(1),y_crit);
if((x_crit[0] != -1 || y_crit[0] != -1) &&
x_crit[0] != aabb.min(0) &&
x_crit[0] != aabb.max(0) &&
y_crit[0] != aabb.min(1) &&
y_crit[0] != aabb.max(1))
{
AABB left, right;
if(x_crit[1] > y_crit[1])
{
aabb.split(0, x_crit[0], left, right);
}
else
{
aabb.split(1, y_crit[0], left, right);
}
aabbs.pop();
aabbs.push(left);
aabbs.push(right);
continue;
}
// if we are here then gaps and inflection failed
// so split on the longest axis
AABB left, right;
aabb.mid_split(left, right);
aabbs.pop();
aabbs.push(left);
aabbs.push(right);
}
}
//---------------------------------------------------------------------------//
void julia(index_t nx,
index_t ny,
float64 x_min,
float64 x_max,
float64 y_min,
float64 y_max,
float64 c_re,
float64 c_im,
Node &res)
{
res.reset();
// create a rectilinear coordset
res["coordsets/coords/type"] = "rectilinear";
res["coordsets/coords/values/x"] = DataType::float64(nx+1);
res["coordsets/coords/values/y"] = DataType::float64(ny+1);
float64_array x_coords = res["coordsets/coords/values/x"].value();
float64_array y_coords = res["coordsets/coords/values/y"].value();
float64 dx = (x_max - x_min) / float64(nx);
float64 dy = (y_max - y_min) / float64(ny);
float64 vx = x_min;
for(index_t i =0; i< nx+1; i++)
{
x_coords[i] = vx;
vx+=dx;
}
float64 vy = y_min;
for(index_t i =0; i< ny+1; i++)
{
y_coords[i] = vy;
vy+=dy;
}
// create the topology
res["topologies/topo/type"] = "rectilinear";
res["topologies/topo/coordset"] = "coords";
// create the fields
res["fields/iters/association"] = "element";
res["fields/iters/topology"] = "topo";
res["fields/iters/values"] = DataType::int32(nx * ny);
int32_array out = res["fields/iters/values"].value();
julia_fill_values(nx,ny,
x_min, x_max,
y_min, y_max,
c_re, c_im,
out);
}
//---------------------------------------------------------------------------//
int32 refine(int32 domain_index,
int32 domain_id_start,
float64 threshold,
float64 efficiency,
int32 min_size,
float64 c_re,
float64 c_im,
Node &res)
{
Node &domain = res.child(domain_index);
domain["nestsets/nest/association"] = "element";
domain["nestsets/nest/topology"] = "topo";
index_t nx = domain["coordsets/coords/values/x"].dtype().number_of_elements() - 1;
index_t ny = domain["coordsets/coords/values/y"].dtype().number_of_elements() - 1;
float64_array x_coords = domain["coordsets/coords/values/x"].value();
float64_array y_coords = domain["coordsets/coords/values/y"].value();
int32_array iters = domain["fields/iters/values"].value();
std::vector<int32> flags(nx*ny);
std::vector<int32> der(nx*ny);
// perform a 2d stencil and calculate the mag
// of the second derivitive of iters using
// central differences
for(index_t i = 0; i < nx*ny; ++i)
{
int32 flag = 0;
index_t x = i % nx;
index_t y = i / nx;
float32 x_vals[3];
float32 y_vals[3];
for(index_t o = 0; o < 3; ++o)
{
index_t x_o = std::min(std::max(x+o-1,index_t(0)),nx-1);
index_t y_o = std::min(std::max(y+o-1,index_t(0)),ny-1);
x_vals[o] = float32(iters[y * nx + x_o]);
y_vals[o] = float32(iters[y_o * nx + x]);
}
float32 ddx = std::abs(x_vals[0] - 2.f * x_vals[1] + x_vals[2]);
float32 ddy = std::abs(y_vals[0] - 2.f * y_vals[1] + y_vals[2]);
float32 eps = sqrt(ddx*ddx + ddy*ddy);
// TODO, should der be a floating point # here?
der[i] = eps;
if(eps > threshold)
{
flag = 1;
}
flags[i] = flag;
}
// split the current domain based on the
// flags
std::vector<AABB> boxs;
sub_boxs(flags, nx, ny, efficiency, min_size, boxs);
// create, fill and update nestsets of refined domains
int domain_id = domain_id_start;
for(size_t i = 0; i < boxs.size(); ++i)
{
// create the current domain
std::ostringstream oss;
oss << "domain_" << std::setw(6) << std::setfill('0') << domain_id;
std::string domain_name = oss.str();
domain_id++;
Node &child = res[domain_name];
AABB aabb = boxs[i];
index_t cnx = aabb.length(0);
index_t cny = aabb.length(1);
float64 cx_min = x_coords[aabb.min(0)];
float64 cx_max = x_coords[aabb.max(0)+1];
float64 cy_min = y_coords[aabb.min(1)];
float64 cy_max = y_coords[aabb.max(1)+1];
julia(cnx * 2,
cny * 2,
cx_min,
cx_max,
cy_min,
cy_max,
c_re,
c_im,
child);
child["nestsets/nest/association"] = "element";
child["nestsets/nest/topology"] = "topo";
std::string window1, window2;
oss.str("");
oss << "window_" <<domain_index << "_" << domain_id;
window1 = oss.str();
oss.str("");
oss << "window_" <<domain_id<< "_" << domain_index;
window2 = oss.str();
Node &pwindow = domain["nestsets/nest/windows/"+window1];
pwindow["domain_id"] = domain_id;
pwindow["domain_type"] = "child";
pwindow["origin/i"] = aabb.min(0);
pwindow["origin/j"] = aabb.min(1);
pwindow["dims/i"] = cnx;
pwindow["dims/j"] = cny;
pwindow["ratio/i"] = 2;
pwindow["ratio/j"] = 2;
child["nestsets/nest/association"] = "element";
child["nestsets/nest/topology"] = "topo";
Node &cwindow = child["nestsets/nest/windows/"+window2];
cwindow["domain_id"] = domain_index;
cwindow["domain_type"] = "parent";
cwindow["origin/i"] = 0;
cwindow["origin/j"] = 0;
cwindow["dims/i"] = cnx * 2;
cwindow["dims/j"] = cny * 2;
cwindow["ratio/i"] = 2;
cwindow["ratio/j"] = 2;
}
return (int32)boxs.size();
}
void julia_nestsets_complex(index_t nx,
index_t ny,
float64 x_min,
float64 x_max,
float64 y_min,
float64 y_max,
float64 c_re,
float64 c_im,
index_t levels,
Node &res)
{
res.reset();
// create the top level
Node &parent = res["domain_000000"];
julia(nx, ny, x_min, x_max, y_min, y_max, c_re, c_im, parent);
// AMR knobs
float64 threshold = 10.; // 2nd derivitive flag threshold
int32 min_size = 4; // min num zones for refine
float64 efficiency = .80; // target boxs count(flags)/size > effeciency
int32 domain_count = 1;
int32 children = 1;
for(int32 i = 0; i < levels; ++i)
{
int32 level_count = 0;
int32 offset = domain_count - children;
for(int32 d = 0; d < children; ++d)
{
int32 count = refine(d + offset,
domain_count,
threshold,
efficiency,
min_size,
c_re,
c_im,
res);
domain_count += count;
level_count += count;
}
children = level_count;
// for each level refinement threshold and min size
threshold += 20;
min_size *= 2;
}
// create a field on the mesh that flags zones that
// are covered by a lower level of refinement
for(int32 i = 0; i < res.number_of_children(); ++i)
{
paint_2d_nestsets(res.child(i), "topo");
}
}
//---------------------------------------------------------------------------//
void julia_nestsets_simple(float64 x_min,
float64 x_max,
float64 y_min,
float64 y_max,
float64 c_re,
float64 c_im,
Node &res)
{
res.reset();
// create the top level
Node &parent = res["domain_000000"];
julia(8, 8, x_min, x_max, y_min, y_max, c_re, c_im, parent);
float64_array x_coords = parent["coordsets/coords/values/x"].value();
float64_array y_coords = parent["coordsets/coords/values/y"].value();
float64 c_x_min= x_coords[2];
float64 c_x_max= x_coords[6];
float64 c_y_min= y_coords[2];
float64 c_y_max= y_coords[6];
Node &child = res["domain_000001"];
julia(8, 8, c_x_min, c_x_max, c_y_min, c_y_max, c_re, c_im, child);
parent["nestsets/nest/association"] = "element";
parent["nestsets/nest/topology"] = "topo";
Node &pwindow = parent["nestsets/nest/windows/window_0_1"];
pwindow["domain_id"] = 1;
pwindow["domain_type"] = "child";
pwindow["origin/i"] = 2;
pwindow["origin/j"] = 2;
pwindow["dims/i"] = 4;
pwindow["dims/j"] = 4;
pwindow["ratio/i"] = 2;
pwindow["ratio/j"] = 2;
child["nestsets/nest/association"] = "element";
child["nestsets/nest/topology"] = "topo";
Node &cwindow = child["nestsets/nest/windows/window_1_0"];
cwindow["domain_id"] = 0;
cwindow["domain_type"] = "parent";
cwindow["origin/i"] = 0;
cwindow["origin/j"] = 0;
cwindow["dims/i"] = 8;
cwindow["dims/j"] = 8;
cwindow["ratio/i"] = 2;
cwindow["ratio/j"] = 2;
for(int i = 0; i < res.number_of_children(); ++i)
{
paint_2d_nestsets(res.child(i), "topo");
}
}
}
//-----------------------------------------------------------------------------
// -- end conduit::blueprint::mesh::examples --
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
// -- end conduit::blueprint::mesh --
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
// -- end conduit::blueprint:: --
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
// -- end conduit:: --
//-----------------------------------------------------------------------------
| [
"noreply@github.com"
] | LLNL.noreply@github.com |
cd866c529f18d60802f9a207234c75ea84651818 | 90047daeb462598a924d76ddf4288e832e86417c | /chromeos/network/network_configuration_handler.cc | f6a128a22cf4048063bc561519e9f143f6f74b27 | [
"BSD-3-Clause"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 26,756 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/network/network_configuration_handler.h"
#include <stddef.h>
#include "base/bind.h"
#include "base/format_macros.h"
#include "base/guid.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/shill_manager_client.h"
#include "chromeos/dbus/shill_profile_client.h"
#include "chromeos/dbus/shill_service_client.h"
#include "chromeos/network/network_device_handler.h"
#include "chromeos/network/network_state.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/shill_property_util.h"
#include "components/device_event_log/device_event_log.h"
#include "dbus/object_path.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
namespace {
// Strip surrounding "" from keys (if present).
std::string StripQuotations(const std::string& in_str) {
size_t len = in_str.length();
if (len >= 2 && in_str[0] == '"' && in_str[len - 1] == '"')
return in_str.substr(1, len - 2);
return in_str;
}
void InvokeErrorCallback(const std::string& service_path,
const network_handler::ErrorCallback& error_callback,
const std::string& error_name) {
std::string error_msg = "Config Error: " + error_name;
NET_LOG(ERROR) << error_msg << ": " << service_path;
network_handler::RunErrorCallback(error_callback, service_path, error_name,
error_msg);
}
void SetNetworkProfileErrorCallback(
const std::string& service_path,
const std::string& profile_path,
const network_handler::ErrorCallback& error_callback,
const std::string& dbus_error_name,
const std::string& dbus_error_message) {
network_handler::ShillErrorCallbackFunction(
"Config.SetNetworkProfile Failed: " + profile_path, service_path,
error_callback, dbus_error_name, dbus_error_message);
}
void LogConfigProperties(const std::string& desc,
const std::string& path,
const base::DictionaryValue& properties) {
for (base::DictionaryValue::Iterator iter(properties); !iter.IsAtEnd();
iter.Advance()) {
std::string v = "******";
if (shill_property_util::IsLoggableShillProperty(iter.key()))
base::JSONWriter::Write(iter.value(), &v);
NET_LOG(USER) << desc << ": " << path + "." + iter.key() + "=" + v;
}
}
} // namespace
// Helper class to request from Shill the profile entries associated with a
// Service and delete the service from each profile. Triggers either
// |callback| on success or |error_callback| on failure, and calls
// |handler|->ProfileEntryDeleterCompleted() on completion to delete itself.
class NetworkConfigurationHandler::ProfileEntryDeleter {
public:
ProfileEntryDeleter(NetworkConfigurationHandler* handler,
const std::string& service_path,
const std::string& guid,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback)
: owner_(handler),
service_path_(service_path),
guid_(guid),
source_(source),
callback_(callback),
error_callback_(error_callback),
weak_ptr_factory_(this) {}
void RestrictToProfilePath(const std::string& profile_path) {
restrict_to_profile_path_ = profile_path;
}
void Run() {
DBusThreadManager::Get()
->GetShillServiceClient()
->GetLoadableProfileEntries(
dbus::ObjectPath(service_path_),
base::Bind(&ProfileEntryDeleter::GetProfileEntriesToDeleteCallback,
weak_ptr_factory_.GetWeakPtr()));
}
private:
void GetProfileEntriesToDeleteCallback(
DBusMethodCallStatus call_status,
const base::DictionaryValue& profile_entries) {
if (call_status != DBUS_METHOD_CALL_SUCCESS) {
InvokeErrorCallback(service_path_, error_callback_,
"GetLoadableProfileEntriesFailed");
// ProfileEntryDeleterCompleted will delete this.
owner_->ProfileEntryDeleterCompleted(service_path_, guid_, source_,
false /* failed */);
return;
}
for (base::DictionaryValue::Iterator iter(profile_entries); !iter.IsAtEnd();
iter.Advance()) {
std::string profile_path = StripQuotations(iter.key());
std::string entry_path;
iter.value().GetAsString(&entry_path);
if (profile_path.empty() || entry_path.empty()) {
NET_LOG(ERROR) << "Failed to parse Profile Entry: " << profile_path
<< ": " << entry_path;
continue;
}
if (profile_delete_entries_.count(profile_path) != 0) {
NET_LOG(ERROR) << "Multiple Profile Entries: " << profile_path << ": "
<< entry_path;
continue;
}
if (!restrict_to_profile_path_.empty() &&
profile_path != restrict_to_profile_path_) {
NET_LOG(DEBUG) << "Skip deleting Profile Entry: " << profile_path
<< ": " << entry_path << " - removal is restricted to "
<< restrict_to_profile_path_ << " profile";
continue;
}
NET_LOG(DEBUG) << "Delete Profile Entry: " << profile_path << ": "
<< entry_path;
profile_delete_entries_[profile_path] = entry_path;
DBusThreadManager::Get()->GetShillProfileClient()->DeleteEntry(
dbus::ObjectPath(profile_path), entry_path,
base::Bind(&ProfileEntryDeleter::ProfileEntryDeletedCallback,
weak_ptr_factory_.GetWeakPtr(), profile_path, entry_path),
base::Bind(&ProfileEntryDeleter::ShillErrorCallback,
weak_ptr_factory_.GetWeakPtr(), profile_path, entry_path));
}
RunCallbackIfDone();
}
void ProfileEntryDeletedCallback(const std::string& profile_path,
const std::string& entry) {
NET_LOG(DEBUG) << "Profile Entry Deleted: " << profile_path << ": "
<< entry;
profile_delete_entries_.erase(profile_path);
RunCallbackIfDone();
}
void RunCallbackIfDone() {
if (!profile_delete_entries_.empty())
return;
// Run the callback if this is the last pending deletion.
if (!callback_.is_null())
callback_.Run();
// ProfileEntryDeleterCompleted will delete this.
owner_->ProfileEntryDeleterCompleted(service_path_, guid_, source_,
true /* success */);
}
void ShillErrorCallback(const std::string& profile_path,
const std::string& entry,
const std::string& dbus_error_name,
const std::string& dbus_error_message) {
// Any Shill Error triggers a failure / error.
network_handler::ShillErrorCallbackFunction(
"GetLoadableProfileEntries Failed", profile_path, error_callback_,
dbus_error_name, dbus_error_message);
// Delete this even if there are pending deletions; any callbacks will
// safely become no-ops (by invalidating the WeakPtrs).
owner_->ProfileEntryDeleterCompleted(service_path_, guid_, source_,
false /* failed */);
}
NetworkConfigurationHandler* owner_; // Unowned
std::string service_path_;
// Non empty if the service has to be removed only from a single profile. This
// value is the profile path of the profile in question.
std::string restrict_to_profile_path_;
std::string guid_;
NetworkConfigurationObserver::Source source_;
base::Closure callback_;
network_handler::ErrorCallback error_callback_;
// Map of pending profile entry deletions, indexed by profile path.
std::map<std::string, std::string> profile_delete_entries_;
base::WeakPtrFactory<ProfileEntryDeleter> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ProfileEntryDeleter);
};
// NetworkConfigurationHandler
void NetworkConfigurationHandler::AddObserver(
NetworkConfigurationObserver* observer) {
observers_.AddObserver(observer);
}
void NetworkConfigurationHandler::RemoveObserver(
NetworkConfigurationObserver* observer) {
observers_.RemoveObserver(observer);
}
void NetworkConfigurationHandler::GetShillProperties(
const std::string& service_path,
const network_handler::DictionaryResultCallback& callback,
const network_handler::ErrorCallback& error_callback) {
NET_LOG(USER) << "GetShillProperties: " << service_path;
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (network_state &&
NetworkTypePattern::Tether().MatchesType(network_state->type())) {
// If this is a Tether network, use the properties present in the
// NetworkState object provided by NetworkStateHandler. Tether networks are
// not present in Shill, so the Shill call below will not work.
base::DictionaryValue dictionary;
network_state->GetStateProperties(&dictionary);
callback.Run(service_path, dictionary);
return;
}
DBusThreadManager::Get()->GetShillServiceClient()->GetProperties(
dbus::ObjectPath(service_path),
base::Bind(&NetworkConfigurationHandler::GetPropertiesCallback,
weak_ptr_factory_.GetWeakPtr(), callback, error_callback,
service_path));
}
void NetworkConfigurationHandler::SetShillProperties(
const std::string& service_path,
const base::DictionaryValue& shill_properties,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
if (shill_properties.empty()) {
if (!callback.is_null())
callback.Run();
return;
}
NET_LOG(USER) << "SetShillProperties: " << service_path;
std::unique_ptr<base::DictionaryValue> properties_to_set(
shill_properties.DeepCopy());
// Make sure that the GUID is saved to Shill when setting properties.
std::string guid;
properties_to_set->GetStringWithoutPathExpansion(shill::kGuidProperty, &guid);
if (guid.empty()) {
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
guid = network_state ? network_state->guid() : base::GenerateGUID();
properties_to_set->SetStringWithoutPathExpansion(shill::kGuidProperty,
guid);
}
LogConfigProperties("SetProperty", service_path, *properties_to_set);
std::unique_ptr<base::DictionaryValue> properties_copy(
properties_to_set->DeepCopy());
DBusThreadManager::Get()->GetShillServiceClient()->SetProperties(
dbus::ObjectPath(service_path), *properties_to_set,
base::Bind(&NetworkConfigurationHandler::SetPropertiesSuccessCallback,
weak_ptr_factory_.GetWeakPtr(), service_path,
base::Passed(&properties_copy), source, callback),
base::Bind(&NetworkConfigurationHandler::SetPropertiesErrorCallback,
weak_ptr_factory_.GetWeakPtr(), service_path, error_callback));
// If we set the StaticIPConfig property, request an IP config refresh
// after calling SetProperties.
if (properties_to_set->HasKey(shill::kStaticIPConfigProperty))
RequestRefreshIPConfigs(service_path);
}
void NetworkConfigurationHandler::ClearShillProperties(
const std::string& service_path,
const std::vector<std::string>& names,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
if (names.empty()) {
if (!callback.is_null())
callback.Run();
return;
}
NET_LOG(USER) << "ClearShillProperties: " << service_path;
for (std::vector<std::string>::const_iterator iter = names.begin();
iter != names.end(); ++iter) {
NET_LOG(DEBUG) << "ClearProperty: " << service_path << "." << *iter;
}
DBusThreadManager::Get()->GetShillServiceClient()->ClearProperties(
dbus::ObjectPath(service_path), names,
base::Bind(&NetworkConfigurationHandler::ClearPropertiesSuccessCallback,
weak_ptr_factory_.GetWeakPtr(), service_path, names, callback),
base::Bind(&NetworkConfigurationHandler::ClearPropertiesErrorCallback,
weak_ptr_factory_.GetWeakPtr(), service_path, error_callback));
}
void NetworkConfigurationHandler::CreateShillConfiguration(
const base::DictionaryValue& shill_properties,
NetworkConfigurationObserver::Source source,
const network_handler::ServiceResultCallback& callback,
const network_handler::ErrorCallback& error_callback) {
ShillManagerClient* manager =
DBusThreadManager::Get()->GetShillManagerClient();
std::string type;
shill_properties.GetStringWithoutPathExpansion(shill::kTypeProperty, &type);
DCHECK(!type.empty());
std::string network_id =
shill_property_util::GetNetworkIdFromProperties(shill_properties);
if (NetworkTypePattern::Ethernet().MatchesType(type)) {
InvokeErrorCallback(network_id, error_callback,
"ConfigureServiceForProfile: Invalid type: " + type);
return;
}
std::unique_ptr<base::DictionaryValue> properties_to_set(
shill_properties.DeepCopy());
NET_LOG(USER) << "CreateShillConfiguration: " << type << ": " << network_id;
std::string profile_path;
properties_to_set->GetStringWithoutPathExpansion(shill::kProfileProperty,
&profile_path);
DCHECK(!profile_path.empty());
// Make sure that the GUID is saved to Shill when configuring networks.
std::string guid;
properties_to_set->GetStringWithoutPathExpansion(shill::kGuidProperty, &guid);
if (guid.empty()) {
guid = base::GenerateGUID();
properties_to_set->SetStringWithoutPathExpansion(
::onc::network_config::kGUID, guid);
}
LogConfigProperties("Configure", type, *properties_to_set);
std::unique_ptr<base::DictionaryValue> properties_copy(
properties_to_set->DeepCopy());
manager->ConfigureServiceForProfile(
dbus::ObjectPath(profile_path), *properties_to_set,
base::Bind(&NetworkConfigurationHandler::ConfigurationCompleted,
weak_ptr_factory_.GetWeakPtr(), profile_path, source,
base::Passed(&properties_copy), callback),
base::Bind(&network_handler::ShillErrorCallbackFunction,
"Config.CreateConfiguration Failed", "", error_callback));
}
void NetworkConfigurationHandler::RemoveConfiguration(
const std::string& service_path,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
RemoveConfigurationFromProfile(service_path, "", source, callback,
error_callback);
}
void NetworkConfigurationHandler::RemoveConfigurationFromCurrentProfile(
const std::string& service_path,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (!network_state || network_state->profile_path().empty()) {
InvokeErrorCallback(service_path, error_callback, "NetworkNotConfigured");
return;
}
RemoveConfigurationFromProfile(service_path, network_state->profile_path(),
source, callback, error_callback);
}
void NetworkConfigurationHandler::RemoveConfigurationFromProfile(
const std::string& service_path,
const std::string& profile_path,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
// Service.Remove is not reliable. Instead, request the profile entries
// for the service and remove each entry.
if (base::ContainsKey(profile_entry_deleters_, service_path)) {
InvokeErrorCallback(service_path, error_callback,
"RemoveConfigurationInProgress");
return;
}
std::string guid;
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (network_state)
guid = network_state->guid();
NET_LOG(USER) << "Remove Configuration: " << service_path
<< " from profiles: "
<< (!profile_path.empty() ? profile_path : "all");
ProfileEntryDeleter* deleter = new ProfileEntryDeleter(
this, service_path, guid, source, callback, error_callback);
if (!profile_path.empty())
deleter->RestrictToProfilePath(profile_path);
profile_entry_deleters_[service_path] = base::WrapUnique(deleter);
deleter->Run();
}
void NetworkConfigurationHandler::SetNetworkProfile(
const std::string& service_path,
const std::string& profile_path,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
NET_LOG(USER) << "SetNetworkProfile: " << service_path << ": "
<< profile_path;
base::Value profile_path_value(profile_path);
DBusThreadManager::Get()->GetShillServiceClient()->SetProperty(
dbus::ObjectPath(service_path), shill::kProfileProperty,
profile_path_value,
base::Bind(&NetworkConfigurationHandler::SetNetworkProfileCompleted,
weak_ptr_factory_.GetWeakPtr(), service_path, profile_path,
source, callback),
base::Bind(&SetNetworkProfileErrorCallback, service_path, profile_path,
error_callback));
}
// NetworkStateHandlerObserver methods
void NetworkConfigurationHandler::NetworkListChanged() {
for (auto iter = configure_callbacks_.begin();
iter != configure_callbacks_.end();) {
const std::string& service_path = iter->first;
const NetworkState* state =
network_state_handler_->GetNetworkStateFromServicePath(service_path,
true);
if (!state) {
NET_LOG(ERROR) << "Configured network not in list: " << service_path;
++iter;
continue;
}
network_handler::ServiceResultCallback& callback = iter->second;
callback.Run(service_path, state->guid());
iter = configure_callbacks_.erase(iter);
}
}
void NetworkConfigurationHandler::OnShuttingDown() {
network_state_handler_->RemoveObserver(this, FROM_HERE);
}
// NetworkConfigurationHandler Private methods
NetworkConfigurationHandler::NetworkConfigurationHandler()
: network_state_handler_(nullptr), weak_ptr_factory_(this) {}
NetworkConfigurationHandler::~NetworkConfigurationHandler() {
}
void NetworkConfigurationHandler::Init(
NetworkStateHandler* network_state_handler,
NetworkDeviceHandler* network_device_handler) {
network_state_handler_ = network_state_handler;
network_device_handler_ = network_device_handler;
// Observer is removed in OnShuttingDown() observer override.
network_state_handler_->AddObserver(this, FROM_HERE);
}
void NetworkConfigurationHandler::ConfigurationCompleted(
const std::string& profile_path,
NetworkConfigurationObserver::Source source,
std::unique_ptr<base::DictionaryValue> configure_properties,
const network_handler::ServiceResultCallback& callback,
const dbus::ObjectPath& service_path) {
// Shill should send a network list update, but to ensure that Shill sends
// the newly configured properties immediately, request an update here.
network_state_handler_->RequestUpdateForNetwork(service_path.value());
// Notify observers immediately. (Note: Currently this is primarily used
// by tests).
for (auto& observer : observers_) {
observer.OnConfigurationCreated(service_path.value(), profile_path,
*configure_properties, source);
}
if (callback.is_null())
return;
// |configure_callbacks_| will get triggered when NetworkStateHandler
// notifies this that a state list update has occurred. |service_path|
// is unique per configuration. In the unlikely case that an existing
// configuration is reconfigured twice without a NetworkStateHandler update,
// (the UI should prevent that) the first callback will not get called.
configure_callbacks_[service_path.value()] = callback;
}
void NetworkConfigurationHandler::ProfileEntryDeleterCompleted(
const std::string& service_path,
const std::string& guid,
NetworkConfigurationObserver::Source source,
bool success) {
if (success) {
for (auto& observer : observers_)
observer.OnConfigurationRemoved(service_path, guid, source);
}
auto iter = profile_entry_deleters_.find(service_path);
DCHECK(iter != profile_entry_deleters_.end());
profile_entry_deleters_.erase(iter);
}
void NetworkConfigurationHandler::SetNetworkProfileCompleted(
const std::string& service_path,
const std::string& profile_path,
NetworkConfigurationObserver::Source source,
const base::Closure& callback) {
if (!callback.is_null())
callback.Run();
for (auto& observer : observers_)
observer.OnConfigurationProfileChanged(service_path, profile_path, source);
}
void NetworkConfigurationHandler::GetPropertiesCallback(
const network_handler::DictionaryResultCallback& callback,
const network_handler::ErrorCallback& error_callback,
const std::string& service_path,
DBusMethodCallStatus call_status,
const base::DictionaryValue& properties) {
if (call_status != DBUS_METHOD_CALL_SUCCESS) {
// Because network services are added and removed frequently, we will see
// failures regularly, so don't log these.
network_handler::RunErrorCallback(error_callback, service_path,
network_handler::kDBusFailedError,
network_handler::kDBusFailedErrorMessage);
return;
}
if (callback.is_null())
return;
// Get the correct name from WifiHex if necessary.
std::unique_ptr<base::DictionaryValue> properties_copy(properties.DeepCopy());
std::string name =
shill_property_util::GetNameFromProperties(service_path, properties);
if (!name.empty())
properties_copy->SetStringWithoutPathExpansion(shill::kNameProperty, name);
// Get the GUID property from NetworkState if it is not set in Shill.
std::string guid;
properties.GetStringWithoutPathExpansion(::onc::network_config::kGUID, &guid);
if (guid.empty()) {
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (network_state) {
properties_copy->SetStringWithoutPathExpansion(
::onc::network_config::kGUID, network_state->guid());
}
}
callback.Run(service_path, *properties_copy.get());
}
void NetworkConfigurationHandler::SetPropertiesSuccessCallback(
const std::string& service_path,
std::unique_ptr<base::DictionaryValue> set_properties,
NetworkConfigurationObserver::Source source,
const base::Closure& callback) {
if (!callback.is_null())
callback.Run();
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (!network_state)
return; // Network no longer exists, do not notify or request update.
for (auto& observer : observers_) {
observer.OnPropertiesSet(service_path, network_state->guid(),
*set_properties, source);
}
network_state_handler_->RequestUpdateForNetwork(service_path);
}
void NetworkConfigurationHandler::SetPropertiesErrorCallback(
const std::string& service_path,
const network_handler::ErrorCallback& error_callback,
const std::string& dbus_error_name,
const std::string& dbus_error_message) {
network_handler::ShillErrorCallbackFunction(
"Config.SetProperties Failed", service_path, error_callback,
dbus_error_name, dbus_error_message);
// Some properties may have changed so request an update regardless.
network_state_handler_->RequestUpdateForNetwork(service_path);
}
void NetworkConfigurationHandler::ClearPropertiesSuccessCallback(
const std::string& service_path,
const std::vector<std::string>& names,
const base::Closure& callback,
const base::ListValue& result) {
const std::string kClearPropertiesFailedError("Error.ClearPropertiesFailed");
DCHECK(names.size() == result.GetSize())
<< "Incorrect result size from ClearProperties.";
for (size_t i = 0; i < result.GetSize(); ++i) {
bool success = false;
result.GetBoolean(i, &success);
if (!success) {
// If a property was cleared that has never been set, the clear will fail.
// We do not track which properties have been set, so just log the error.
NET_LOG(ERROR) << "ClearProperties Failed: " << service_path << ": "
<< names[i];
}
}
if (!callback.is_null())
callback.Run();
network_state_handler_->RequestUpdateForNetwork(service_path);
}
void NetworkConfigurationHandler::ClearPropertiesErrorCallback(
const std::string& service_path,
const network_handler::ErrorCallback& error_callback,
const std::string& dbus_error_name,
const std::string& dbus_error_message) {
network_handler::ShillErrorCallbackFunction(
"Config.ClearProperties Failed", service_path, error_callback,
dbus_error_name, dbus_error_message);
// Some properties may have changed so request an update regardless.
network_state_handler_->RequestUpdateForNetwork(service_path);
}
void NetworkConfigurationHandler::RequestRefreshIPConfigs(
const std::string& service_path) {
if (!network_device_handler_)
return;
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (!network_state || network_state->device_path().empty())
return;
network_device_handler_->RequestRefreshIPConfigs(
network_state->device_path(), base::Bind(&base::DoNothing),
network_handler::ErrorCallback());
}
// static
NetworkConfigurationHandler* NetworkConfigurationHandler::InitializeForTest(
NetworkStateHandler* network_state_handler,
NetworkDeviceHandler* network_device_handler) {
NetworkConfigurationHandler* handler = new NetworkConfigurationHandler();
handler->Init(network_state_handler, network_device_handler);
return handler;
}
} // namespace chromeos
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
612ef14b3b9cc9de5143c6e96170daec7bd2e987 | acea6cd23fa94e2361c8a2bc8a85fe25d00b9d16 | /src/algorithm/cpp/count-and-say/Solution.cpp | 85bbe031c2a63f459cef6dad0f12948bdd9d56cc | [] | no_license | huaxiufeng/leetcode | 77742e90a11263475a49ce9beadfa923515d3109 | 5c5dec2044897e3ccb82d310e15ca608ec30e588 | refs/heads/master | 2021-06-04T08:50:59.125768 | 2019-10-21T09:11:42 | 2019-10-21T09:11:42 | 27,822,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,062 | cpp | class Solution
{
public:
string countAndSay(int n) {
if (1 == n) {
return "1";
} else {
return next(countAndSay(n-1));
}
}
private:
string next(string s) {
if (!s.length()) {
return s;
}
string result;
char c = s.at(0);
char count_str[256];
int count = 0;
for (size_t i = 0; i < s.length(); i++) {
if (count == 0) {
c = s.at(i);
count++;
} else {
if (c == s.at(i)) {
count++;
} else {
snprintf(count_str, sizeof(count_str), "%d", count);
result += count_str;
result += c;
c = s.at(i);
count = 1;
}
}
}
if (count > 0) {
snprintf(count_str, sizeof(count_str), "%d", count);
result += count_str;
result += c;
}
return result;
}
};
| [
"huaxiufeng@kaisquare.com.cn"
] | huaxiufeng@kaisquare.com.cn |
f8ecc2502607a4232866b7fe37b885abf171ac25 | 8309d4d3f6d7185541d0486fc92362aaac169481 | /libraries/MySQL_Connector_Arduino-master/examples/basic_insert_esp8266/basic_insert_esp8266.ino | 24ce11494bf4f09f63d8090b7f0bd42f998df915 | [] | no_license | jrfadrigalan/Arduino | cf9a1d5137e2b5961cb4ba7ddcc33fb73c29a43b | 795cee5d7891f2132132a4ebb5d984cdcabadb38 | refs/heads/master | 2021-03-27T20:06:34.132694 | 2018-03-07T00:50:22 | 2018-03-07T00:50:22 | 124,159,587 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,482 | ino | /*
MySQL Connector/Arduino Example : connect by wifi
This example demonstrates how to connect to a MySQL server from an
Arduino using an Arduino-compatible Wifi shield. Note that "compatible"
means it must conform to the Ethernet class library or be a derivative
thereof. See the documentation located in the /docs folder for more
details.
INSTRUCTIONS FOR USE
1) Change the address of the server to the IP address of the MySQL server
2) Change the user and password to a valid MySQL user and password
3) Change the SSID and pass to match your WiFi network
4) Connect a USB cable to your Arduino
5) Select the correct board and port
6) Compile and upload the sketch to your Arduino
7) Once uploaded, open Serial Monitor (use 115200 speed) and observe
If you do not see messages indicating you have a connection, refer to the
manual for troubleshooting tips. The most common issues are the server is
not accessible from the network or the user name and password is incorrect.
Created by: Dr. Charles A. Bell
*/
#include <ESP8266WiFi.h> // Use this for WiFi instead of Ethernet.h
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
IPAddress server_addr(10,0,1,35); // IP of the MySQL *server* here
char user[] = "root"; // MySQL user login username
char password[] = "secret"; // MySQL user login password
// Sample query
char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";
// WiFi card example
char ssid[] = "your-ssid"; // your SSID
char pass[] = "ssid-password"; // your SSID Password
WiFiClient client; // Use this for WiFi instead of EthernetClient
MySQL_Connection conn(&client);
MySQL_Cursor cursor(&conn);
void setup()
{
Serial.begin(115200);
while (!Serial); // wait for serial port to connect. Needed for Leonardo only
// Begin WiFi section
Serial.printf("\nConnecting to %s", ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// print out info about the connection:
Serial.println("\nConnected to network");
Serial.print("My IP address is: ");
Serial.println(WiFi.localIP());
Serial.print("Connecting to SQL... ");
if (conn.connect(server_addr, 3306, user, password))
Serial.println("OK.");
else
Serial.println("FAILED.");
}
void loop()
{
if (conn.connected())
cursor.execute(INSERT_SQL);
delay(5000);
}
| [
"jrfadrigalan1@gmail.com"
] | jrfadrigalan1@gmail.com |
ce4a3e558bbdd266534d36360288e4463582d8a3 | 9f81d77e028503dcbb6d7d4c0c302391b8fdd50c | /google/cloud/dialogflow_cx/samples/security_settings_client_samples.cc | 704152277e7f2a389647286a02f78197c417e6cb | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | googleapis/google-cloud-cpp | b96a6ee50c972371daa8b8067ddd803de95f54ba | 178d6581b499242c52f9150817d91e6c95b773a5 | refs/heads/main | 2023-08-31T09:30:11.624568 | 2023-08-31T03:29:11 | 2023-08-31T03:29:11 | 111,860,063 | 450 | 351 | Apache-2.0 | 2023-09-14T21:52:02 | 2017-11-24T00:19:31 | C++ | UTF-8 | C++ | false | false | 6,720 | cc | // Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/dialogflow/cx/v3/security_settings.proto
#include "google/cloud/dialogflow_cx/security_settings_client.h"
#include "google/cloud/dialogflow_cx/security_settings_connection_idempotency_policy.h"
#include "google/cloud/dialogflow_cx/security_settings_options.h"
#include "google/cloud/common_options.h"
#include "google/cloud/credentials.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/testing_util/example_driver.h"
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
// clang-format off
// main-dox-marker: dialogflow_cx::SecuritySettingsServiceClient
// clang-format on
namespace {
void SetClientEndpoint(std::vector<std::string> const& argv) {
if (!argv.empty()) {
throw google::cloud::testing_util::Usage{"set-client-endpoint"};
}
//! [set-client-endpoint]
// This configuration is common with Private Google Access:
// https://cloud.google.com/vpc/docs/private-google-access
auto options = google::cloud::Options{}.set<google::cloud::EndpointOption>(
"private.googleapis.com");
auto client = google::cloud::dialogflow_cx::SecuritySettingsServiceClient(
google::cloud::dialogflow_cx::MakeSecuritySettingsServiceConnection(
options));
//! [set-client-endpoint]
}
//! [custom-idempotency-policy]
class CustomIdempotencyPolicy
: public google::cloud::dialogflow_cx::
SecuritySettingsServiceConnectionIdempotencyPolicy {
public:
~CustomIdempotencyPolicy() override = default;
std::unique_ptr<google::cloud::dialogflow_cx::
SecuritySettingsServiceConnectionIdempotencyPolicy>
clone() const override {
return std::make_unique<CustomIdempotencyPolicy>(*this);
}
// Override inherited functions to define as needed.
};
//! [custom-idempotency-policy]
void SetRetryPolicy(std::vector<std::string> const& argv) {
if (!argv.empty()) {
throw google::cloud::testing_util::Usage{"set-client-retry-policy"};
}
//! [set-retry-policy]
auto options =
google::cloud::Options{}
.set<google::cloud::dialogflow_cx::
SecuritySettingsServiceConnectionIdempotencyPolicyOption>(
CustomIdempotencyPolicy().clone())
.set<google::cloud::dialogflow_cx::
SecuritySettingsServiceRetryPolicyOption>(
google::cloud::dialogflow_cx::
SecuritySettingsServiceLimitedErrorCountRetryPolicy(3)
.clone())
.set<google::cloud::dialogflow_cx::
SecuritySettingsServiceBackoffPolicyOption>(
google::cloud::ExponentialBackoffPolicy(
/*initial_delay=*/std::chrono::milliseconds(200),
/*maximum_delay=*/std::chrono::seconds(45),
/*scaling=*/2.0)
.clone());
auto connection =
google::cloud::dialogflow_cx::MakeSecuritySettingsServiceConnection(
options);
// c1 and c2 share the same retry policies
auto c1 =
google::cloud::dialogflow_cx::SecuritySettingsServiceClient(connection);
auto c2 =
google::cloud::dialogflow_cx::SecuritySettingsServiceClient(connection);
// You can override any of the policies in a new client. This new client
// will share the policies from c1 (or c2) *except* for the retry policy.
auto c3 = google::cloud::dialogflow_cx::SecuritySettingsServiceClient(
connection, google::cloud::Options{}
.set<google::cloud::dialogflow_cx::
SecuritySettingsServiceRetryPolicyOption>(
google::cloud::dialogflow_cx::
SecuritySettingsServiceLimitedTimeRetryPolicy(
std::chrono::minutes(5))
.clone()));
// You can also override the policies in a single call:
// c3.SomeRpc(..., google::cloud::Options{}
// .set<google::cloud::dialogflow_cx::SecuritySettingsServiceRetryPolicyOption>(
// google::cloud::dialogflow_cx::SecuritySettingsServiceLimitedErrorCountRetryPolicy(10).clone()));
//! [set-retry-policy]
}
void WithServiceAccount(std::vector<std::string> const& argv) {
if (argv.size() != 1 || argv[0] == "--help") {
throw google::cloud::testing_util::Usage{"with-service-account <keyfile>"};
}
//! [with-service-account]
[](std::string const& keyfile) {
auto is = std::ifstream(keyfile);
is.exceptions(std::ios::badbit); // Minimal error handling in examples
auto contents = std::string(std::istreambuf_iterator<char>(is.rdbuf()), {});
auto options =
google::cloud::Options{}.set<google::cloud::UnifiedCredentialsOption>(
google::cloud::MakeServiceAccountCredentials(contents));
return google::cloud::dialogflow_cx::SecuritySettingsServiceClient(
google::cloud::dialogflow_cx::MakeSecuritySettingsServiceConnection(
options));
}
//! [with-service-account]
(argv.at(0));
}
void AutoRun(std::vector<std::string> const& argv) {
namespace examples = ::google::cloud::testing_util;
using ::google::cloud::internal::GetEnv;
if (!argv.empty()) throw examples::Usage{"auto"};
examples::CheckEnvironmentVariablesAreSet(
{"GOOGLE_CLOUD_CPP_TEST_SERVICE_ACCOUNT_KEYFILE"});
auto const keyfile =
GetEnv("GOOGLE_CLOUD_CPP_TEST_SERVICE_ACCOUNT_KEYFILE").value();
std::cout << "\nRunning SetClientEndpoint() example" << std::endl;
SetClientEndpoint({});
std::cout << "\nRunning SetRetryPolicy() example" << std::endl;
SetRetryPolicy({});
std::cout << "\nRunning WithServiceAccount() example" << std::endl;
WithServiceAccount({keyfile});
}
} // namespace
int main(int argc, char* argv[]) { // NOLINT(bugprone-exception-escape)
google::cloud::testing_util::Example example({
{"set-client-endpoint", SetClientEndpoint},
{"set-retry-policy", SetRetryPolicy},
{"with-service-account", WithServiceAccount},
{"auto", AutoRun},
});
return example.Run(argc, argv);
}
| [
"noreply@github.com"
] | googleapis.noreply@github.com |
c1f40c4b97e93e31ccdf37ebb721c1a69f127e0c | 9b32c32592460960ba322719aec6dd9bc3151ced | /eudaq/main/include/eudaq/LogSender.hh | 703ef5198b442afa7287becb9cbee5e219a0edbc | [] | no_license | beam-telescopes/USBpix | 1c867ad6060404652dc44305a002bbd876da2cca | f5350163a2675982b013711546edb72701d49fb0 | refs/heads/master | 2021-05-02T02:30:34.944845 | 2017-01-09T16:04:11 | 2017-01-09T16:04:11 | 120,883,980 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,058 | hh | #ifndef EUDAQ_INCLUDED_LogSender
#define EUDAQ_INCLUDED_LogSender
#include "eudaq/TransportClient.hh"
#include "eudaq/Serializer.hh"
#include "eudaq/Status.hh"
#include "Platform.hh"
#include <string>
namespace eudaq {
class LogMessage;
class DLLEXPORT LogSender {
public:
LogSender();
~LogSender();
void Connect(const std::string & type, const std::string & name, const std::string & server);
void SendLogMessage(const LogMessage &);
void SetLevel(int level) { m_level = level; }
void SetLevel(const std::string & level) { SetLevel(Status::String2Level(level)); }
void SetErrLevel(int level) { m_errlevel = level; }
void SetErrLevel(const std::string & level) { SetErrLevel(Status::String2Level(level)); }
bool IsLogged(const std::string & level) { return Status::String2Level(level) >= m_level; }
private:
std::string m_name;
TransportClient * m_logclient;
int m_level;
int m_errlevel;
bool m_shownotconnected;
};
}
#endif // EUDAQ_INCLUDED_LogSender
| [
"jgrosse1@uni-goettingen.de"
] | jgrosse1@uni-goettingen.de |
93d9909f8b5f849870b08bf4e5d3d5ab081f1d5b | 278a5c98068425520a1dedf47aba3dda09df0c8a | /src/yb/redisserver/cpp_redis/includes/cpp_redis/replies/array_reply.hpp | bc5475b72ea0a2810bf6c11731927b28bb993210 | [
"Apache-2.0",
"BSD-3-Clause",
"CC0-1.0",
"Unlicense",
"bzip2-1.0.6",
"dtoa",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | jchristov/yugabyte-db | d5c76090e4ec0e11bd6698df1c5140cce28bd816 | 7a15f6441e781b51afc5fc6d7f0e6b9606637231 | refs/heads/master | 2020-03-16T16:16:02.627739 | 2017-12-11T19:49:31 | 2017-12-11T19:49:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 915 | hpp | #pragma once
#include <vector>
#include "cpp_redis/replies/reply.hpp"
namespace cpp_redis {
class reply;
namespace replies {
class array_reply : public reply {
public:
//! ctor & dtor
array_reply(const std::vector<cpp_redis::reply>& rows = {});
~array_reply(void) = default;
//! copy ctor & assignment operator
array_reply(const array_reply&) = default;
array_reply& operator=(const array_reply&) = default;
public:
//! getters
unsigned int size(void) const;
const std::vector<cpp_redis::reply>& get_rows(void) const;
const cpp_redis::reply& get(unsigned int idx) const;
const cpp_redis::reply& operator[](unsigned int idx) const;
//! setters
void set_rows(const std::vector<cpp_redis::reply>& rows);
void add_row(const cpp_redis::reply& row);
void operator<<(const cpp_redis::reply& row);
private:
std::vector<cpp_redis::reply> m_rows;
};
} //! replies
} //! cpp_redis
| [
"amitanandaiyer@users.noreply.github.com"
] | amitanandaiyer@users.noreply.github.com |
7586707fe3b50e9c579b72514013902326947b81 | f2bfe92bcb233798fc9c49ed22748d8c7571706a | /SkyEngine/old/DirectInputHadler.cpp | e80b1d55f8ef098f8aecd52105227f2c59a3af68 | [] | no_license | am17/SkyEngine | d5ed9064daa00151a3dec182cd328b2f369555eb | 5882ba9a267fbfb134e1eff44cb026a3ebd30302 | refs/heads/master | 2021-01-23T02:05:44.370183 | 2017-06-19T20:27:47 | 2017-06-19T20:27:47 | 92,908,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,047 | cpp | #include "stdafx.h"
#include "DirectInputHadler.h"
#include "Log.h"
namespace sky
{
DirectInputHandler::DirectInputHandler(HINSTANCE hInstance, HWND hwnd)
:defaultCommand(nullptr),
upArrowKeyPadCommand(nullptr),
downArrowKeyPadCommand(nullptr),
leftArrowKeyPadCommand(nullptr),
rightArrowKeyPadCommand(nullptr)
{
init(hInstance, hwnd);
}
DirectInputHandler::~DirectInputHandler()
{
if (defaultCommand)
{
delete defaultCommand;
defaultCommand = nullptr;
}
DIKeyboard->Unacquire();
DIMouse->Unacquire();
DirectInput->Release();
}
bool DirectInputHandler::init(HINSTANCE hInstance, HWND hwnd)
{
HRESULT hr = DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&DirectInput, nullptr);
hr = DirectInput->CreateDevice(GUID_SysKeyboard, &DIKeyboard, nullptr);
hr = DirectInput->CreateDevice(GUID_SysMouse, &DIMouse, nullptr);
hr = DIKeyboard->SetDataFormat(&c_dfDIKeyboard);
hr = DIKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
hr = DIMouse->SetDataFormat(&c_dfDIMouse);
hr = DIMouse->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_NOWINKEY | DISCL_FOREGROUND);
defaultCommand = new DefaultCommand();
upArrowKeyPadCommand = defaultCommand;
downArrowKeyPadCommand = defaultCommand;
leftArrowKeyPadCommand = defaultCommand;
rightArrowKeyPadCommand = defaultCommand;
return true;
}
void DirectInputHandler::handleInput()
{
BYTE keyboardState[256];
DIKeyboard->Acquire();
HRESULT HR = DIKeyboard->GetDeviceState(sizeof(keyboardState), (LPVOID)&keyboardState);
if (keyboardState[DIK_ESCAPE] & 0x80)
{
//PostMessage(hwnd, WM_DESTROY, 0, 0);
}
if (keyboardState[DIK_LEFT] & 0x80)
{
leftArrowKeyPadCommand->execute(EKEYBOARD_COMMAND::EKC_ARROWLEFT);
}
if (keyboardState[DIK_RIGHT] & 0x80)
{
rightArrowKeyPadCommand->execute(EKEYBOARD_COMMAND::EKC_ARROWRIGHT);
}
if (keyboardState[DIK_UP] & 0x80)
{
upArrowKeyPadCommand->execute(EKEYBOARD_COMMAND::EKC_ARROWUP);
}
if (keyboardState[DIK_DOWN] & 0x80)
{
downArrowKeyPadCommand->execute(EKEYBOARD_COMMAND::EKC_ARROWDOWN);
}
DIMOUSESTATE mouseCurrState;
//mouse
DIMouse->Acquire();
DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseCurrState);
if (mouseCurrState.lX != mouseLastState.lX)
{
//Log::write("MOUSEX");
}
if (mouseCurrState.lY != mouseLastState.lY)
{
//Log::write("MOUSEY");
}
mouseLastState = mouseCurrState;
}
void DirectInputHandler::bindKeyCommand(EKEYBOARD_COMMAND keyboardCommand, ICommand *command)
{
assert(command != nullptr);
switch (keyboardCommand)
{
case sky::EKEYBOARD_COMMAND::EKC_ARROWUP:
upArrowKeyPadCommand = command;
break;
case sky::EKEYBOARD_COMMAND::EKC_ARROWDOWN:
downArrowKeyPadCommand = command;
break;
case sky::EKEYBOARD_COMMAND::EKC_ARROWLEFT:
leftArrowKeyPadCommand = command;
break;
case sky::EKEYBOARD_COMMAND::EKC_ARROWRIGHT:
rightArrowKeyPadCommand = command;
break;
default:
break;
}
}
}
| [
"eugene.voronov@girngm.ru"
] | eugene.voronov@girngm.ru |
f6ab9f7a054f41256d39583659286569a6ecf60d | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/068/847/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_memmove_53a.cpp | e86c8fbd5ddea3d3ff2462db672464e07db6c1a9 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,389 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_memmove_53a.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml
Template File: sources-sink-53a.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sink: memmove
* BadSink : Copy int64_t array to data using memmove
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_memmove_53
{
#ifndef OMITBAD
/* bad function declaration */
void badSink_b(int64_t * data);
void bad()
{
int64_t * data;
data = NULL;
/* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = new int64_t[50];
badSink_b(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
void goodG2BSink_b(int64_t * data);
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
int64_t * data;
data = NULL;
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new int64_t[100];
goodG2BSink_b(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_memmove_53; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
8b33c6ada746f8fe1af64cc7412aa6e2e61f834f | 8a5c59b7650e5eb6032728bc7e956031741a6add | /visualisationsettingswidget.h | 0b8d226fa07f8461bc0a44475607a67c653c5be7 | [] | no_license | amezin/citnetvis2 | d5a6d1cb6334c74a6fc021234aeebca16718734f | cd5ef48bdb88767623ea965783801e6c7e51cd82 | refs/heads/master | 2020-04-13T03:07:53.765823 | 2013-06-05T06:06:47 | 2013-06-05T06:06:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 888 | h | #ifndef VISUALISATIONSETTINGSWIDGET_H
#define VISUALISATIONSETTINGSWIDGET_H
#include <QWidget>
#include <QDoubleSpinBox>
#include <QFormLayout>
#include <QSet>
#include "scene.h"
#include "persistentwidget.h"
class VisualisationSettingsWidget : public QWidget, public PersistentWidget
{
Q_OBJECT
public:
explicit VisualisationSettingsWidget(Scene *scene, QWidget *parent = 0);
virtual void saveState(QSettings *) const;
virtual void loadState(const QSettings *);
private slots:
void updateSceneParameters();
private:
void addSpinBox(Scene::Parameter, const QString &title,
double minValue, double maxValue, int prec = 1);
Scene *scene;
QDoubleSpinBox *spinBox[Scene::NParameters];
QFormLayout *layout;
bool blockUpdates;
QSet<int> changesColor, changesSize, changesLabel;
};
#endif // VISUALISATIONSETTINGSWIDGET_H
| [
"mezin.alexander@gmail.com"
] | mezin.alexander@gmail.com |
04d311eddc6017991d14cd0674f8835d51d0f73d | b3439873c106d69b6ae8110c36bcd77264e8c5a7 | /server/Server/Skills/ImpactLogic/StdImpact040.cpp | 90b1063863814cfb56c81bf29ada97c23a7c318f | [] | no_license | cnsuhao/web-pap | b41356411dc8dad0e42a11e62a27a1b4336d91e2 | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | refs/heads/master | 2021-05-28T01:01:18.122567 | 2013-11-19T06:49:41 | 2013-11-19T06:49:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,381 | cpp | #include "stdafx.h"
///////////////////////////////////////////////////////////////////////////////
// 文件名:StdImpact040.cpp
// 功能说明:效果--在一定时间内,增加效果所有者的移动速度,并且下一次打击驱散目标怒气
//
// 修改记录:
//
//
//
///////////////////////////////////////////////////////////////////////////////
#include "StdImpact040.h"
namespace Combat_Module
{
using namespace Combat_Module::Skill_Module;
namespace Impact_Module
{
BOOL StdImpact040_T::InitFromData(OWN_IMPACT& rImp, ImpactData_T const& rData) const
{
__ENTER_FUNCTION
SetActivateTimes(rImp, GetActivateTimesInTable(rImp));
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
VOID StdImpact040_T::MarkModifiedAttrDirty(OWN_IMPACT & rImp, Obj_Character & rMe) const
{
__ENTER_FUNCTION
if(0!=GetMoveSpeedRefix(rImp))
{
rMe.MarkMoveSpeedRefixDirtyFlag();
}
__LEAVE_FUNCTION
}
BOOL StdImpact040_T::GetIntAttrRefix(OWN_IMPACT & rImp, Obj_Character& rMe, CharIntAttrRefixs_T::Index_T nIdx, INT & rIntAttrRefix) const
{
__ENTER_FUNCTION
if(CharIntAttrRefixs_T::REFIX_MOVE_SPEED==nIdx)
{
if(0!=GetMoveSpeedRefix(rImp))
{
rIntAttrRefix += rMe.GetBaseMoveSpeed()*GetMoveSpeedRefix(rImp)/100;
return TRUE;
}
}
__LEAVE_FUNCTION
return FALSE;
}
VOID StdImpact040_T::OnHitTarget(OWN_IMPACT & rImp, Obj_Character & rMe, Obj_Character & rTar) const
{
__ENTER_FUNCTION
if(Obj::OBJ_TYPE_HUMAN==rTar.GetObjType())
{
INT nActivateTimes = GetActivateTimes(rImp);
if(0==nActivateTimes)
{
return;
}
INT nImpact = GetSubImpact(rImp);
g_ImpactCore.SendImpactToUnit(rTar, nImpact, rMe.GetID(), 500);
if(0<nActivateTimes)
{
--nActivateTimes;
SetActivateTimes(rImp, nActivateTimes);
}
}
__LEAVE_FUNCTION
}
};
};
| [
"viticm@126.com"
] | viticm@126.com |
f87b0a88cc368e32425eb589bc21e458a43cba02 | d09945668f19bb4bc17087c0cb8ccbab2b2dd688 | /yuki/0001-1000/601-700/626.cpp | c7d5d4e49bc44505053864d0d5194bb08e619294 | [] | no_license | kmjp/procon | 27270f605f3ae5d80fbdb28708318a6557273a57 | 8083028ece4be1460150aa3f0e69bdb57e510b53 | refs/heads/master | 2023-09-04T11:01:09.452170 | 2023-09-03T15:25:21 | 2023-09-03T15:25:21 | 30,825,508 | 23 | 2 | null | 2023-08-18T14:02:07 | 2015-02-15T11:25:23 | C++ | UTF-8 | C++ | false | false | 1,388 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------
int N;
ll W;
pair<ll,ll> P[5050];
ll ma=0;
bool cmp(pair<ll,ll> L,pair<ll,ll> R) {
return L.first*1.0/L.second>R.first*1.0/R.second;
}
void solve() {
int i,j,k,l,r,x,y; string s;
cin>>N>>W;
FOR(i,N) {
cin>>P[i].first>>P[i].second;
}
sort(P,P+N,cmp);
vector<pair<ll,ll>> V;
V.push_back({0,0});
FOR(i,N) {
ll v=P[i].first,w=P[i].second;
vector<pair<ll,ll>> V2=V;
FORR(vv,V) if(vv.second+w<=W) V2.push_back({vv.first+v,vv.second+w});
V.clear();
sort(ALL(V2));
reverse(ALL(V2));
ll pre=W+1;
FORR(vv,V2) if(vv.second<pre) V.push_back(vv), pre=vv.second;
}
ll ma=0;
FORR(v,V) ma=max(ma,v.first);
cout<<ma<<endl;
}
int main(int argc,char** argv){
string s;int i;
if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
cout.tie(0); solve(); return 0;
}
| [
"kmjp@users.noreply.github.com"
] | kmjp@users.noreply.github.com |
756cd563fa1759e4bbfb23c662bb6e0ec0247a99 | 27ae6b58577f38891e12fa5665548803e86df08b | /Mincho/UI.cpp | 34e13aa0e6321da1809f1e201cc0c6f042ba497c | [] | no_license | DaLae37/RiotOfMincho | 194eaea462fe65e2d0965ebc6a344aaa7d619e00 | e0702c9e9c6d2fdc112257c56ac9d8477fbfad1c | refs/heads/master | 2023-05-01T09:27:24.793458 | 2023-04-20T03:57:00 | 2023-04-20T03:57:00 | 99,400,643 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,079 | cpp | #include "stdafx.h"
#include "UI.h"
UI::UI()
{
player1Index = 0;
player2Index = 1;
player1 = new ZeroSprite("Resource/UI/player1.png");
player1->SetPos(0, 20);
PushScene(player1);
player2 = new ZeroSprite("Resource/UI/player2.png");
player2->SetPos(1000, 20);
PushScene(player2);
for (int i = 0; i < 3; i++) {
if (i < 2) {
P1isDone[i] = false;
P2isDone[i] = false;
for (int j = 0; j < 2; j++) {
CircleP1[i][j] = new ZeroSprite("Resource/UI/Circle%d.png", j);
CircleP1[i][j]->SetPos(45 + 100 * i, 500);
CircleP2[i][j] = new ZeroSprite("Resource/UI/Circle%d.png", j);
CircleP2[i][j]->SetPos(1045+ 100 * i, 500);
}
}
player1Heart[i] = new ZeroSprite("Resource/UI/Heart.png");
player1Heart[i]->SetPos(i * 95, 115);
player2Heart[i] = new ZeroSprite("Resource/UI/Heart.png");
player2Heart[i]->SetPos(1190 - i * 95, 115);
character[i] = new ZeroSprite("Resource/UI/Character%d.png", i+1);
player1HeartRender[i] = true;
player2HeartRender[i] = true;
}
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if ((new Def)->map[i][j]) {
Tile[i][j] = new ZeroSprite("Resource/Background/enableTile.png");
}
else {
Tile[i][j] = new ZeroSprite("Resource/Background/unableTile.png");
}
Tile[i][j]->SetPos(280 + j * MAP_SIZE, 0 + i * MAP_SIZE);
}
}
}
UI::~UI()
{
}
void UI::Render() {
ZeroIScene::Render();
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
Tile[i][j]->Render();
}
}
player1->Render();
player2->Render();
for (int i = 0; i < 3; i++) {
if (i < 2) {
CircleP1[i][(int)P1isDone[i]]->Render();
CircleP2[i][(int)P2isDone[i]]->Render();
}
if (player1Index == i) {
character[player1Index]->SetPos(5,210);
character[player1Index]->Render();
}
else if (player2Index == i) {
character[player2Index]->SetPos(1005,210);
character[player2Index]->Render();
}
if(player1HeartRender[i])
player1Heart[i]->Render();
if(player2HeartRender[i])
player2Heart[i]->Render();
}
}
void UI::Update(float eTime) {
ZeroIScene::Update(eTime);
} | [
"dalae37@gmail.com"
] | dalae37@gmail.com |
bad5f72692e51c7c85bae20268c67e1c83e9026b | e68e8ef755fed83cf751b582f68999bcbb3ccbef | /Tests/Test_State.h | 1123a43808814b9cfa23372432beffd86e098427 | [] | no_license | Sketcher14/TortoiseStash | a161b68eeac89afab315736075d58c1905b16921 | db36d8afcafe6622447295092b474fc95897c192 | refs/heads/main | 2022-10-12T07:28:01.938051 | 2022-10-02T14:03:57 | 2022-10-02T14:03:57 | 190,795,224 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | h | #pragma once
#include <QtTest>
class Test_State : public QObject
{
Q_OBJECT
private slots:
void Test_AddRoundKey();
void Test_SubstituteBytes();
void Test_ShiftRows();
void Test_MixColumns();
};
| [
"www.vitaliy_14@mail.ru"
] | www.vitaliy_14@mail.ru |
33f043cfbd1aab60c68950c16cc0c75e60dd4ea7 | baebe8a00a7b3aa662b8078bd000c424bb214cc6 | /src/texture/texture.cpp | c85820a512036d476b2835d007dd42180207e513 | [
"MIT"
] | permissive | jonike/lumen | 8ffd85f64018eba0d5adea401c44f740b6ea0032 | c35259f45a265d470afccb8b6282c8520eabdc95 | refs/heads/master | 2021-04-25T04:03:36.864204 | 2017-06-02T17:49:11 | 2017-07-15T00:10:37 | 115,495,859 | 2 | 0 | null | 2017-12-27T07:45:31 | 2017-12-27T07:45:31 | null | UTF-8 | C++ | false | false | 2,389 | cpp | #include <cmath>
#include <IL\il.h>
#include <IL\ilu.h>
#include <film.h>
#include <stdexcept>
#include <texture.h>
namespace lumen {
texture::texture(const std::string& file) :
texels(6),
width_(0),
height_(0)
{
if (!ilLoadImage(file.c_str())) {
throw std::invalid_argument(iluErrorString(ilGetError()));
}
ilConvertImage(IL_RGB, IL_FLOAT);
iluBuildMipmaps();
ILuint img = ilGetInteger(IL_CUR_IMAGE);
ILint width = ilGetInteger(IL_IMAGE_WIDTH);
ILint height = ilGetInteger(IL_IMAGE_HEIGHT);
ILint num_faces = ilGetInteger(IL_NUM_FACES);
std::unique_ptr<ILfloat[]> data(new ILfloat[width * height * 3]);
int stride = 3 * width;
for (ILint face = 0; face <= num_faces; ++face) {
ilBindImage(img);
ilActiveFace(face);
texels[face].reserve(width * height);
ilCopyPixels(0, 0, 0, width, height, 1, IL_RGB, IL_FLOAT, data.get());
for (ILint i = 0; i < height; ++i) {
for (ILint j = 0; j < width; ++j) {
int offset = i * stride + 3 * j;
// texture colors are already gamma corrected so each color
// needs to have the inverse gamma applied otherwise the image
// will gamma correct the colors a second time and saturate
// the textures
nex::color texel(
std::powf(data[offset + 0], GAMMA_VALUE),
std::powf(data[offset + 1], GAMMA_VALUE),
std::powf(data[offset + 2], GAMMA_VALUE),
1.0f);
texels[face].push_back(texel);
}
}
}
ilDeleteImages(1, &img);
width_ = width;
height_ = height;
}
nex::color texture::fetch_2d(int x, int y)
{
return texels[0][x + y * width_];
}
nex::color texture::fetch_cube(int face, int x, int y)
{
return texels[face][x + y * width_];
}
int texture::width() const
{
return width_;
}
int texture::height() const
{
return height_;
}
}
| [
"jeremy.adam.lukacs@gmail.com"
] | jeremy.adam.lukacs@gmail.com |
a158007f9d5f4e04917f51bb25852416b963f6bc | be22fc9c0814d6186400f97e7c47d3c359bd44ca | /3rd-party/ff/distributed/ff_dsender.hpp | 9a06cdbbedb694e2774b9b4ef96bf78daf870318 | [
"MIT"
] | permissive | taskflow/taskflow | 76258cc5c5c4549aacb84c5307837b810fbc42d1 | 9316d98937e992968f1fb3a5836bf3500f756df7 | refs/heads/master | 2023-07-05T06:27:08.883646 | 2023-06-13T11:38:21 | 2023-06-13T11:38:21 | 130,068,982 | 5,616 | 716 | NOASSERTION | 2023-09-12T23:32:21 | 2018-04-18T13:45:30 | C++ | UTF-8 | C++ | false | false | 17,827 | hpp | /* ***************************************************************************
*
* FastFlow is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3 as
* published by the Free Software Foundation.
* Starting from version 3.0.1 FastFlow is dual licensed under the GNU LGPLv3
* or MIT License (https://github.com/ParaGroup/WindFlow/blob/vers3.x/LICENSE.MIT)
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
****************************************************************************
*/
/* Authors:
* Nicolo' Tonci
* Massimo Torquati
*/
#ifndef FF_DSENDER_H
#define FF_DSENDER_H
#include <iostream>
#include <map>
#include <ff/ff.hpp>
#include <ff/distributed/ff_network.hpp>
#include <ff/distributed/ff_batchbuffer.hpp>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/uio.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netdb.h>
#include <cmath>
#include <thread>
#include <cereal/cereal.hpp>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/polymorphic.hpp>
using namespace ff;
using precomputedRT_t = std::map<std::string, std::pair<std::vector<int>, ChannelType>>;
class ff_dsender: public ff_minode_t<message_t> {
protected:
size_t neos=0;
std::vector<std::pair<ChannelType, ff_endpoint>> dest_endpoints;
precomputedRT_t* precomputedRT;
std::map<std::pair<int, ChannelType>, int> dest2Socket;
std::vector<int> sockets;
int last_rr_socket = -1;
std::map<int, unsigned int> socketsCounters;
std::map<int, ff_batchBuffer> batchBuffers;
std::string gName;
int batchSize;
int messageOTF;
int coreid;
fd_set set, tmpset;
int fdmax = -1;
virtual int handshakeHandler(const int sck, ChannelType t){
size_t sz = htobe64(gName.size());
struct iovec iov[3];
iov[0].iov_base = &t;
iov[0].iov_len = sizeof(ChannelType);
iov[1].iov_base = &sz;
iov[1].iov_len = sizeof(sz);
iov[2].iov_base = (char*)(gName.c_str());
iov[2].iov_len = gName.size();
if (writevn(sck, iov, 3) < 0){
error("Error writing on socket\n");
return -1;
}
return 0;
}
int create_connect(const ff_endpoint& destination){
int socketFD;
#ifdef LOCAL
socketFD = socket(AF_LOCAL, SOCK_STREAM, 0);
if (socketFD < 0){
error("\nError creating socket \n");
return socketFD;
}
struct sockaddr_un serv_addr;
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sun_family = AF_LOCAL;
strncpy(serv_addr.sun_path, destination.address.c_str(), destination.address.size()+1);
if (connect(socketFD, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){
close(socketFD);
return -1;
}
#endif
#ifdef REMOTE
struct addrinfo hints;
struct addrinfo *result, *rp;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* Stream socket */
hints.ai_flags = 0;
hints.ai_protocol = IPPROTO_TCP; /* Allow only TCP */
// resolve the address
if (getaddrinfo(destination.address.c_str() , std::to_string(destination.port).c_str() , &hints, &result) != 0)
return -1;
// try to connect to a possible one of the resolution results
for (rp = result; rp != NULL; rp = rp->ai_next) {
socketFD = socket(rp->ai_family, rp->ai_socktype,
rp->ai_protocol);
if (socketFD == -1)
continue;
if (connect(socketFD, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */
close(socketFD);
}
free(result);
if (rp == NULL) { /* No address succeeded */
return -1;
}
#endif
// receive the reachable destination from this sockets
return socketFD;
}
int tryConnect(const ff_endpoint &destination){
int fd = -1, retries = 0;
while((fd = this->create_connect(destination)) < 0 && ++retries < MAX_RETRIES)
if (retries < AGGRESSIVE_TRESHOLD)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
else
std::this_thread::sleep_for(std::chrono::milliseconds(200));
//std::this_thread::sleep_for(std::chrono::milliseconds((long)std::pow(2, retries - AGGRESSIVE_TRESHOLD)));
return fd;
}
int sendToSck(int sck, message_t* task){
task->sender = htonl(task->sender);
task->chid = htonl(task->chid);
size_t sz = htobe64(task->data.getLen());
struct iovec iov[4];
iov[0].iov_base = &task->sender;
iov[0].iov_len = sizeof(task->sender);
iov[1].iov_base = &task->chid;
iov[1].iov_len = sizeof(task->chid);
iov[2].iov_base = &sz;
iov[2].iov_len = sizeof(sz);
iov[3].iov_base = task->data.getPtr();
iov[3].iov_len = task->data.getLen();
if (writevn(sck, iov, 4) < 0){
error("Error writing on socket\n");
return -1;
}
return 0;
}
int waitAckFrom(int sck){
while (socketsCounters[sck] == 0){
for(auto& [sck_, counter] : socketsCounters){
int r; ack_t a;
if ((r = recvnnb(sck_, reinterpret_cast<char*>(&a), sizeof(ack_t))) != sizeof(ack_t)){
if (errno == EWOULDBLOCK){
assert(r == -1);
continue;
}
perror("recvnnb ack");
return -1;
} else
counter++;
}
if (socketsCounters[sck] == 0){
tmpset = set;
if (select(fdmax + 1, &tmpset, NULL, NULL, NULL) == -1){
perror("select");
return -1;
}
}
}
return 1;
}
int getMostFilledBufferSck(bool feedback){
int sckMax = 0;
int sizeMax = 0;
for(auto& [sck, buffer] : batchBuffers){
if ((feedback && buffer.ct != ChannelType::FBK) || (!feedback && buffer.ct != ChannelType::FWD)) continue;
if (buffer.size > sizeMax) sckMax = sck;
}
if (sckMax > 0) return sckMax;
do {
last_rr_socket = (last_rr_socket + 1) % this->sockets.size();
} while (batchBuffers[sockets[last_rr_socket]].ct != (feedback ? ChannelType::FBK : ChannelType::FWD));
return sockets[last_rr_socket];
}
public:
ff_dsender(std::pair<ChannelType, ff_endpoint> dest_endpoint, precomputedRT_t* rt, std::string gName = "", int batchSize = DEFAULT_BATCH_SIZE, int messageOTF = DEFAULT_MESSAGE_OTF, int coreid=-1): precomputedRT(rt), gName(gName), batchSize(batchSize), messageOTF(messageOTF), coreid(coreid) {
this->dest_endpoints.push_back(std::move(dest_endpoint));
}
ff_dsender( std::vector<std::pair<ChannelType, ff_endpoint>> dest_endpoints_, precomputedRT_t* rt, std::string gName = "", int batchSize = DEFAULT_BATCH_SIZE, int messageOTF = DEFAULT_MESSAGE_OTF, int coreid=-1) : dest_endpoints(std::move(dest_endpoints_)), precomputedRT(rt), gName(gName), batchSize(batchSize), messageOTF(messageOTF), coreid(coreid) {}
int svc_init() {
if (coreid!=-1)
ff_mapThreadToCpu(coreid);
FD_ZERO(&set);
FD_ZERO(&tmpset);
//sockets.resize(dest_endpoints.size());
for(auto& [ct, ep] : this->dest_endpoints){
int sck = tryConnect(ep);
if (sck <= 0) return -1;
sockets.push_back(sck);
socketsCounters[sck] = messageOTF;
batchBuffers.emplace(std::piecewise_construct, std::forward_as_tuple(sck), std::forward_as_tuple(this->batchSize, ct, [this, sck](struct iovec* v, int size) -> bool {
if (this->socketsCounters[sck] == 0 && this->waitAckFrom(sck) == -1){
error("Errore waiting ack from socket inside the callback\n");
return false;
}
if (writevn(sck, v, size) < 0){
error("Error sending the iovector inside the callback!\n");
return false;
}
this->socketsCounters[sck]--;
return true;
}));
// compute the routing table!
for(int dest : precomputedRT->operator[](ep.groupName).first)
dest2Socket[std::make_pair(dest, ct)] = sck;
if (handshakeHandler(sck, ct) < 0) {
error("svc_init ff_dsender failed");
return -1;
}
FD_SET(sck, &set);
if (sck > fdmax) fdmax = sck;
}
// we can erase the list of endpoints
this->dest_endpoints.clear();
return 0;
}
message_t *svc(message_t* task) {
int sck;
//if (task->chid == -1) task->chid = 0;
if (task->chid != -1)
sck = dest2Socket[{task->chid, (task->feedback ? ChannelType::FBK : ChannelType::FWD)}];
else {
sck = getMostFilledBufferSck(task->feedback); // get the most filled buffer socket or a rr socket
}
if (batchBuffers[sck].push(task) == -1) {
return EOS;
}
return this->GO_ON;
}
void eosnotify(ssize_t id) {
for (const auto& sck : sockets)
batchBuffers[sck].push(new message_t(id, -2));
if (++neos >= this->get_num_inchannels()) {
// all input EOS received, now sending the EOS to all connections
for(const auto& sck : sockets) {
if (batchBuffers[sck].sendEOS()<0) {
error("sending EOS to external connections (ff_dsender)\n");
}
shutdown(sck, SHUT_WR);
}
}
}
void svc_end() {
// here we wait all acks from all connections
size_t totalack = sockets.size()*messageOTF;
size_t currentack = 0;
for(const auto& [_, counter] : socketsCounters)
currentack += counter;
ack_t a;
while(currentack<totalack) {
for(auto scit = socketsCounters.begin(); scit != socketsCounters.end();) {
auto sck = scit->first;
auto& counter = scit->second;
switch(recvnnb(sck, (char*)&a, sizeof(a))) {
case 0:
case -1:
if (errno==EWOULDBLOCK) { ++scit; continue; }
currentack += (messageOTF-counter);
socketsCounters.erase(scit++);
break;
default: {
currentack++;
counter++;
++scit;
}
}
}
}
for(auto& sck : sockets) close(sck);
}
};
class ff_dsenderH : public ff_dsender {
std::vector<int> internalSockets;
int last_rr_socket_Internal = -1;
int internalMessageOTF;
bool squareBoxEOS = false;
/*int getNextReadyInternal(){
for(size_t i = 0; i < this->internalSockets.size(); i++){
int actualSocketIndex = (last_rr_socket_Internal + 1 + i) % this->internalSockets.size();
int sck = internalSockets[actualSocketIndex];
if (socketsCounters[sck] > 0) {
last_rr_socket_Internal = actualSocketIndex;
return sck;
}
}
int sck;
decltype(internalSockets)::iterator it;
do {
sck = waitAckFromAny(); // FIX: error management!
if (sck < 0) {
error("waitAckFromAny failed in getNextReadyInternal");
return -1;
}
} while ((it = std::find(internalSockets.begin(), internalSockets.end(), sck)) != internalSockets.end());
last_rr_socket_Internal = it - internalSockets.begin();
return sck;
}*/
int getMostFilledInternalBufferSck(){
int sckMax = 0;
int sizeMax = 0;
for(int sck : internalSockets){
auto& b = batchBuffers[sck];
if (b.size > sizeMax) {
sckMax = sck;
sizeMax = b.size;
}
}
if (sckMax > 0) return sckMax;
last_rr_socket_Internal = (last_rr_socket_Internal + 1) % this->internalSockets.size();
return internalSockets[last_rr_socket_Internal];
}
public:
ff_dsenderH(std::pair<ChannelType, ff_endpoint> e, precomputedRT_t* rt, std::string gName = "", int batchSize = DEFAULT_BATCH_SIZE, int messageOTF = DEFAULT_MESSAGE_OTF, int internalMessageOTF = DEFAULT_INTERNALMSG_OTF, int coreid=-1) : ff_dsender(e, rt, gName, batchSize, messageOTF, coreid), internalMessageOTF(internalMessageOTF) {}
ff_dsenderH(std::vector<std::pair<ChannelType, ff_endpoint>> dest_endpoints_, precomputedRT_t* rt, std::string gName = "", int batchSize = DEFAULT_BATCH_SIZE, int messageOTF = DEFAULT_MESSAGE_OTF, int internalMessageOTF = DEFAULT_INTERNALMSG_OTF, int coreid=-1) : ff_dsender(dest_endpoints_, rt, gName, batchSize, messageOTF, coreid), internalMessageOTF(internalMessageOTF) {}
int svc_init() {
if (coreid!=-1)
ff_mapThreadToCpu(coreid);
FD_ZERO(&set);
FD_ZERO(&tmpset);
for(const auto& [ct, endpoint] : this->dest_endpoints){
int sck = tryConnect(endpoint);
if (sck <= 0) return -1;
bool isInternal = ct == ChannelType::INT;
if (isInternal) internalSockets.push_back(sck);
else sockets.push_back(sck);
socketsCounters[sck] = isInternal ? internalMessageOTF : messageOTF;
batchBuffers.emplace(std::piecewise_construct, std::forward_as_tuple(sck), std::forward_as_tuple(this->batchSize, ct, [this, sck](struct iovec* v, int size) -> bool {
if (this->socketsCounters[sck] == 0 && this->waitAckFrom(sck) == -1){
error("Errore waiting ack from socket inside the callback\n");
return false;
}
if (writevn(sck, v, size) < 0){
error("Error sending the iovector inside the callback (errno=%d) %s\n", errno);
return false;
}
this->socketsCounters[sck]--;
return true;
})); // change with the correct size
for(int dest : precomputedRT->operator[](endpoint.groupName).first)
dest2Socket[std::make_pair(dest, ct)] = sck;
if (handshakeHandler(sck, ct) < 0) return -1;
FD_SET(sck, &set);
if (sck > fdmax) fdmax = sck;
}
// we can erase the list of endpoints
this->dest_endpoints.clear();
return 0;
}
message_t *svc(message_t* task) {
if (this->get_channel_id() == (ssize_t)(this->get_num_inchannels() - 1)){
int sck;
// pick destination from the list of internal connections!
if (task->chid != -1){ // roundrobin over the destinations
sck = dest2Socket[{task->chid, ChannelType::INT}];
} else
sck = getMostFilledInternalBufferSck();
if (batchBuffers[sck].push(task) == -1) {
return EOS;
}
return this->GO_ON;
}
return ff_dsender::svc(task);
}
void eosnotify(ssize_t id) {
if (id == (ssize_t)(this->get_num_inchannels() - 1)){
// send the EOS to all the internal connections
if (squareBoxEOS) return;
squareBoxEOS = true;
for(const auto& sck : internalSockets) {
if (batchBuffers[sck].sendEOS()<0) {
error("sending EOS to internal connections\n");
}
shutdown(sck, SHUT_WR);
}
}
if (++neos >= this->get_num_inchannels()) {
// all input EOS received, now sending the EOS to all
// others connections
for(const auto& sck : sockets) {
if (batchBuffers[sck].sendEOS()<0) {
error("sending EOS to external connections (ff_dsenderH)\n");
}
shutdown(sck, SHUT_WR);
}
}
}
void svc_end() {
// here we wait all acks from all connections
size_t totalack = internalSockets.size()*internalMessageOTF;
totalack += sockets.size()*messageOTF;
size_t currentack = 0;
for(const auto& [sck, counter] : socketsCounters) {
currentack += counter;
}
ack_t a;
while(currentack<totalack) {
for(auto scit = socketsCounters.begin(); scit != socketsCounters.end();) {
auto sck = scit->first;
auto& counter = scit->second;
switch(recvnnb(sck, (char*)&a, sizeof(a))) {
case 0:
case -1: {
if (errno == EWOULDBLOCK) {
++scit;
continue;
}
decltype(internalSockets)::iterator it;
it = std::find(internalSockets.begin(), internalSockets.end(), sck);
if (it != internalSockets.end())
currentack += (internalMessageOTF-counter);
else
currentack += (messageOTF-counter);
socketsCounters.erase(scit++);
} break;
default: {
currentack++;
counter++;
++scit;
}
}
}
}
for(const auto& [sck, _] : socketsCounters) close(sck);
}
};
#endif
| [
"chchiu@pass-2.ece.utah.edu"
] | chchiu@pass-2.ece.utah.edu |
43fe69ad51df6d89beed75348bda058a0ca42613 | 0d9076293349241af62d00eff4c4107e51426ea5 | /coding interview guide/二叉树/在二叉树中找到一个节点的后继结点.cpp | 65d198da7322878c93dca8207909d616f07e4e6f | [] | no_license | zonasse/Algorithm | f6445616d0cde04e5ef5f475e7f9c8ec68638dd0 | cda4ba606b66040a54c44d95db51220a2df47414 | refs/heads/master | 2020-03-23T12:12:00.525247 | 2019-08-10T03:42:53 | 2019-08-10T03:42:53 | 141,543,243 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 686 | cpp | //
// Created by 钟奇龙 on 2019-05-03.
//
//
// Created by 钟奇龙 on 2019-05-01.
//
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *parent;
Node *left;
Node *right;
Node(int x):data(x),left(NULL),right(NULL),parent(NULL){}
};
Node* getNextNode(Node *root){
if(!root) return NULL;
if(root->right){
Node *right = root->right;
while(right->left){
right = right->left;
}
return right;
}else{
Node *parent = root->parent;
while(parent && parent->left != root){
root = parent;
parent = root->parent;
}
return parent;
}
} | [
"992903713@qq.com"
] | 992903713@qq.com |
444a6c436cf83f38fc6a6c1cdd9ab80aca4c2b4d | adecc7f08d1a16947f3a3d134822d8ff955cab04 | /src/compressor.cpp | e3e9b182e8c1bec811ea42e3c2be8c3fad6bc43e | [
"MIT"
] | permissive | NodeZeroCoin/nodezerocore | 75af6bb7a3bb94207deb18c6ca2d9d377ed406e2 | 852034254f8ebc5611f8ffe12104628b27207100 | refs/heads/master | 2021-02-11T11:17:44.408776 | 2020-05-12T22:51:21 | 2020-05-12T22:51:21 | 244,486,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,139 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017-2018 The PIVX developers
// Copyright (c) 2019 The CryptoDev developers
// Copyright (c) 2019 The NodeZero developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "compressor.h"
#include "hash.h"
#include "pubkey.h"
#include "script/standard.h"
bool CScriptCompressor::IsToKeyID(CKeyID& hash) const
{
if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) {
memcpy(&hash, &script[3], 20);
return true;
}
return false;
}
bool CScriptCompressor::IsToScriptID(CScriptID& hash) const
{
if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20 && script[22] == OP_EQUAL) {
memcpy(&hash, &script[2], 20);
return true;
}
return false;
}
bool CScriptCompressor::IsToPubKey(CPubKey& pubkey) const
{
if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG && (script[1] == 0x02 || script[1] == 0x03)) {
pubkey.Set(&script[1], &script[34]);
return true;
}
if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG && script[1] == 0x04) {
pubkey.Set(&script[1], &script[66]);
return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible
}
return false;
}
bool CScriptCompressor::Compress(std::vector<unsigned char>& out) const
{
CKeyID keyID;
if (IsToKeyID(keyID)) {
out.resize(21);
out[0] = 0x00;
memcpy(&out[1], &keyID, 20);
return true;
}
CScriptID scriptID;
if (IsToScriptID(scriptID)) {
out.resize(21);
out[0] = 0x01;
memcpy(&out[1], &scriptID, 20);
return true;
}
CPubKey pubkey;
if (IsToPubKey(pubkey)) {
out.resize(33);
memcpy(&out[1], &pubkey[1], 32);
if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
out[0] = pubkey[0];
return true;
} else if (pubkey[0] == 0x04) {
out[0] = 0x04 | (pubkey[64] & 0x01);
return true;
}
}
return false;
}
unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
{
if (nSize == 0 || nSize == 1)
return 20;
if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
return 32;
return 0;
}
bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char>& in)
{
switch (nSize) {
case 0x00:
script.resize(25);
script[0] = OP_DUP;
script[1] = OP_HASH160;
script[2] = 20;
memcpy(&script[3], &in[0], 20);
script[23] = OP_EQUALVERIFY;
script[24] = OP_CHECKSIG;
return true;
case 0x01:
script.resize(23);
script[0] = OP_HASH160;
script[1] = 20;
memcpy(&script[2], &in[0], 20);
script[22] = OP_EQUAL;
return true;
case 0x02:
case 0x03:
script.resize(35);
script[0] = 33;
script[1] = nSize;
memcpy(&script[2], &in[0], 32);
script[34] = OP_CHECKSIG;
return true;
case 0x04:
case 0x05:
unsigned char vch[33] = {};
vch[0] = nSize - 2;
memcpy(&vch[1], &in[0], 32);
CPubKey pubkey(&vch[0], &vch[33]);
if (!pubkey.Decompress())
return false;
assert(pubkey.size() == 65);
script.resize(67);
script[0] = 65;
memcpy(&script[1], pubkey.begin(), 65);
script[66] = OP_CHECKSIG;
return true;
}
return false;
}
// Amount compression:
// * If the amount is 0, output 0
// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
// * call the result n
// * output 1 + 10*(9*n + d - 1) + e
// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
// (this is decodable, as d is in [1-9] and e is in [0-9])
uint64_t CTxOutCompressor::CompressAmount(uint64_t n)
{
if (n == 0)
return 0;
int e = 0;
while (((n % 10) == 0) && e < 9) {
n /= 10;
e++;
}
if (e < 9) {
int d = (n % 10);
assert(d >= 1 && d <= 9);
n /= 10;
return 1 + (n * 9 + d - 1) * 10 + e;
} else {
return 1 + (n - 1) * 10 + 9;
}
}
uint64_t CTxOutCompressor::DecompressAmount(uint64_t x)
{
// x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
if (x == 0)
return 0;
x--;
// x = 10*(9*n + d - 1) + e
int e = x % 10;
x /= 10;
uint64_t n = 0;
if (e < 9) {
// x = 9*n + d - 1
int d = (x % 9) + 1;
x /= 9;
// x = n
n = x * 10 + d;
} else {
n = x + 1;
}
while (e) {
n *= 10;
e--;
}
return n;
}
| [
"61714747+NodeZeroCoin@users.noreply.github.com"
] | 61714747+NodeZeroCoin@users.noreply.github.com |
b5551a7b5c0e3a5e5b886e999322c4b6be13fb92 | dccaab4cb32470d58399750d457d89f3874a99e3 | /3rdparty/include/Poco/Net/MediaType.h | 6c841a435830848e8cd340517aad89ae2ca87c5a | [] | no_license | Pan-Rongtao/mycar | 44832b0b5fdbb6fb713fddff98afbbe90ced6415 | 05b1f0f52c309607c4c64a06b97580101e30d424 | refs/heads/master | 2020-07-15T20:31:28.183703 | 2019-12-20T07:45:00 | 2019-12-20T07:45:00 | 205,642,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,594 | h | //
// MediaType.h
//
// Library: Net
// Package: Messages
// Module: MediaType
//
// Definition of the MediaType class.
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Net_MediaType_INCLUDED
#define Net_MediaType_INCLUDED
#include "Poco/Net/Net.h"
#include "Poco/Net/NameValueCollection.h"
namespace Poco {
namespace Net {
class Net_API MediaType
/// This class represents a MIME media type, consisting of
/// a top-level type, a subtype and an optional set of
/// parameters.
///
/// The implementation conforms with RFC 2045 and RFC 2046.
{
public:
MediaType(const std::string& mediaType);
/// Creates the MediaType from the given string, which
/// must have the format <type>/<subtype>{;<parameter>=<value>}.
MediaType(const std::string& type, const std::string& subType);
/// Creates the MediaType, using the given type and subtype.
MediaType(const MediaType& mediaType);
/// Creates a MediaType from another one.
~MediaType();
/// Destroys the MediaType.
MediaType& operator = (const MediaType& mediaType);
/// Assigns another media type.
MediaType& operator = (const std::string& mediaType);
/// Assigns another media type.
void swap(MediaType& mediaType);
/// Swaps the MediaType with another one.
void setType(const std::string& type);
/// Sets the top-level type.
const std::string& getType() const;
/// Returns the top-level type.
void setSubType(const std::string& subType);
/// Sets the sub type.
const std::string& getSubType() const;
/// Returns the sub type.
void setParameter(const std::string& name, const std::string& value);
/// Sets the parameter with the given name.
const std::string& getParameter(const std::string& name) const;
/// Returns the parameter with the given name.
///
/// Throws a NotFoundException if the parameter does not exist.
bool hasParameter(const std::string& name) const;
/// Returns true iff a parameter with the given name exists.
void removeParameter(const std::string& name);
/// Removes the parameter with the given name.
const NameValueCollection& parameters() const;
/// Returns the parameters.
std::string toString() const;
/// Returns the string representation of the media type
/// which is <type>/<subtype>{;<parameter>=<value>}
bool matches(const MediaType& mediaType) const;
/// Returns true iff the type and subtype match
/// the type and subtype of the given media type.
/// Matching is case insensitive.
bool matches(const std::string& type, const std::string& subType) const;
/// Returns true iff the type and subtype match
/// the given type and subtype.
/// Matching is case insensitive.
bool matches(const std::string& type) const;
/// Returns true iff the type matches the given type.
/// Matching is case insensitive.
bool matchesRange(const MediaType& mediaType) const;
/// Returns true if the type and subtype match
/// the type and subtype of the given media type.
/// If the MIME type is a range of types it matches
/// any media type within the range (e.g. "image/*" matches
/// any image media type, "*/*" matches anything).
/// Matching is case insensitive.
bool matchesRange(const std::string& type, const std::string& subType) const;
/// Returns true if the type and subtype match
/// the given type and subtype.
/// If the MIME type is a range of types it matches
/// any media type within the range (e.g. "image/*" matches
/// any image media type, "*/*" matches anything).
/// Matching is case insensitive.
bool matchesRange(const std::string& type) const;
/// Returns true if the type matches the given type or
/// the type is a range of types denoted by "*".
/// Matching is case insensitive.
protected:
void parse(const std::string& mediaType);
private:
MediaType();
std::string _type;
std::string _subType;
NameValueCollection _parameters;
};
//
// inlines
//
inline const std::string& MediaType::getType() const
{
return _type;
}
inline const std::string& MediaType::getSubType() const
{
return _subType;
}
inline const NameValueCollection& MediaType::parameters() const
{
return _parameters;
}
inline void swap(MediaType& m1, MediaType& m2)
{
m1.swap(m2);
}
} } // namespace Poco::Net
#endif // Net_MediaType_INCLUDED
| [
"Rongtao.Pan@desay-svautomotive.com"
] | Rongtao.Pan@desay-svautomotive.com |
f98d98f961850a1b80cb13aee34a412148983d14 | 8c79fbda535452688910f6ef34d9902a8e08070f | /src/main.cpp | c90f0cf6fc71ddf4c9a86e1e86830f0d38c11ff3 | [] | no_license | tetraoxygen/KnightsTour | ebc5dde72d0df69455d31936c1265764d2c5a4a1 | 89cbe96720f82fca282183bcdf2c3f783d6076d0 | refs/heads/master | 2023-03-18T01:27:08.459358 | 2021-03-15T05:07:26 | 2021-03-15T05:07:26 | 347,785,732 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,885 | cpp | /** ---------------------------
* @file main.cpp
* @author Charlie Welsh
* @version 1.0
*
* CS162-01 - Assignment 5.1
* The Knight's Tour assignment
*
* --------------------------- */
#include <iostream>
#include <iomanip>
const int BOARD_SIZE = 5;
struct Board {
int array [BOARD_SIZE][BOARD_SIZE] = {{0}};
};
/**
* Recursively solves the knights tour using brute force
* Prints any solutions it finds.
*
* @param board - the board we’re working with (contains all moves-to-date)
* @param row - the row we’re going to attempt to place the knight on this move (zero-indexed).
* @param col - the column we’re going to attempt place the knight on this move (zero-indexed).
* @param currentMoveNumber - the move number we’re making (1 = first move)
*
* @return The number of solutions the given board and move leads to
*
*/
int solveKnightsTour(Board board, int row, int col, int currentMoveNum = 1);
/**
* Prints the contents of a Board object.
*
* @param board - the board we’re working with (contains all moves-to-date)
*
*/
void printBoard(Board board);
int main() {
Board board;
std::cout << solveKnightsTour(board, 2, 2) << " solutions found" << std::endl;
}
// -------------------
void printBoard(Board board) {
for (int col = 0; col < BOARD_SIZE; col++) {
for (int row = 0; row < BOARD_SIZE; row++) {
std::cout << std::setfill('0') << std::setw(2) << board.array[row][col] << " ";
}
std::cout << '\n';
}
std::cout << std::endl;
}
// -------------------
int solveKnightsTour(Board board, int row, int col, int currentMoveNum) {
const int startCol = col;
const int startRow = row;
bool shortHorizontal = false;
int solutions = 0;
board.array[row][col] = currentMoveNum;
if (currentMoveNum != BOARD_SIZE * BOARD_SIZE) {
for (int rotation = 0; rotation < 4; rotation++) {
switch(rotation) {
case 0:
col = startCol + 2;
shortHorizontal = true;
break;
case 1:
row = startRow + 2;
shortHorizontal = false;
break;
case 2:
col = startCol - 2;
shortHorizontal = true;
break;
case 3:
row = startRow - 2;
shortHorizontal = false;
break;
}
for (int direction = 0; direction < 2; direction++) {
if (shortHorizontal) {
switch (direction) {
case 0:
row = startRow - 1;
break;
case 1:
row = startRow + 1;
break;
}
} else {
switch (direction) {
case 0:
col = startCol - 1;
break;
case 1:
col = startCol + 1;
break;
}
}
if (
row < BOARD_SIZE &&
row >= 0 &&
col < BOARD_SIZE &&
col >= 0 &&
board.array[row][col] == 0
) {
solutions = solutions + solveKnightsTour(board, row, col, currentMoveNum + 1);
}
}
}
} else {
printBoard(board);
solutions = 1;
}
return solutions;
} | [
"charlie@allotrope.xyz"
] | charlie@allotrope.xyz |
d17e28b44bd53a2614adaacac3022a656d1b489e | 7710234d428e3e9b7a696ca8525f847f8df23402 | /SystemHelper.h | 91bbff32a2d6fd8cb67d7d6aff0b5e07bf82e711 | [] | no_license | xitaofeng/win32_cplusplus_code | b39e3baf6e922db20ec280c164c26b5781fee857 | a740af3637dddc8d1988e4139d1f48f1baf31766 | refs/heads/master | 2020-05-27T21:29:28.876620 | 2016-08-03T06:20:29 | 2016-08-03T06:20:29 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,320 | h | /**
* @file SystemHelper.h windows系统常用函数整理
*
* 日期 作者 描述
* 2016/07/20 gxl create
*/
#ifndef G_SYSTEMHELPER_H_
#define G_SYSTEMHELPER_H_
#include <string>
#include <windows.h>
#include <Tlhelp32.h>
using namespace std;
/**
* @brief windows系统常用函数帮助类
*/
class CSystemHelper
{
public:
/**
* @brief 检查当前程序互斥量
*
* @param cMutexName[in] 互斥量名称
*
* @return true-已运行 false-未运行
*
* @code
int main(int argc, char* argv[])
{
bool bRunning = CSystemHelper::CheckProcessMutex("Single.test");
if (bRunning){
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
::system("pause");
return 0;
}
* @endcode
*/
static bool CheckProcessMutex(const char* cMutexName)
{
HANDLE hSingleton = CreateMutexA(NULL, FALSE, cMutexName);
if ((hSingleton != NULL) && (GetLastError() == ERROR_ALREADY_EXISTS))
{
return true;
}
return false;
}
/**
* @brief 检查进程是否存在
*
* @param cProcessName[in] 进程名称
*
* @return true-存在 false-不存在
*
* @code
int main(int argc, char* argv[])
{
bool bExist = CSystemHelper::CheckProcessExist("demo.exe");
if (bExist){
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
::system("pause");
return 0;
}
* @endcode
*/
static bool CheckProcessExist(const char* cProcessName)
{
bool bRet = false;
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
{
return bRet;
}
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
BOOL bMore = Process32First(hProcessSnap, &pe32);
while (bMore)
{
if (strcmp(cProcessName, pe32.szExeFile) == 0 &&
pe32.th32ProcessID != GetCurrentProcessId())
{
bRet = true;
}
bMore = ::Process32Next(hProcessSnap, &pe32);
}
CloseHandle(hProcessSnap);
return bRet;
}
/**
* @brief 开启进程
*
* @param cProcessPath[in] 进程路径
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::OpenProcess("c:\\demo.exe");
::system("pause");
return 0;
}
* @endcode
*/
static void OpenProcess(char* cProcessPath)
{
PROCESS_INFORMATION processInfo;
STARTUPINFO startupInfo;
::ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
::CreateProcess(NULL, cProcessPath, NULL, NULL, FALSE,
0, NULL, NULL, &startupInfo, &processInfo);
}
/**
* @brief 销毁进程
*
* @param cProcessName[in] 进程名称
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::DestoryProcess("demo.exe");
::system("pause");
return 0;
}
* @endcode
*/
static void DestoryProcess(const char* cProcessName)
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(pe32);
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
{
return;
}
BOOL bMore = ::Process32First(hProcessSnap, &pe32);
while (bMore)
{
if (strcmp(cProcessName, pe32.szExeFile) == 0 &&
pe32.th32ProcessID != GetCurrentProcessId())
{
HANDLE hHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
if (hHandle)
{
::TerminateProcess(hHandle, 0);
::CloseHandle(hHandle);
}
}
bMore = ::Process32Next(hProcessSnap, &pe32);
}
CloseHandle(hProcessSnap);
}
/**
* @brief 开机自运行本程序
*
* @param cProcessName[in] 程序名称
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::SetAutoStartup("demo");
::system("pause");
return 0;
}
* @endcode
*/
static bool SetAutoStartup(const char* cProcessName)
{
char filename[MAX_PATH];
GetModuleFileName(NULL, filename, MAX_PATH);
//判断环境是否为WOW64
BOOL isWOW64;
REGSAM samDesired;
IsWow64Process(GetCurrentProcess(), &isWOW64);
samDesired = isWOW64 ? KEY_WRITE | KEY_WOW64_64KEY : KEY_WRITE;
HKEY hKey;
LONG lRet = RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), 0, NULL, 0, samDesired, NULL, &hKey, NULL);
if (lRet != ERROR_SUCCESS)
{
return false;
}
lRet = RegSetValueEx(hKey, cProcessName, 0, REG_SZ, (BYTE*)filename, MAX_PATH);
if (lRet != ERROR_SUCCESS)
{
return false;
}
RegCloseKey(hKey);
return true;
}
/**
* @brief 取消开机自运行本程序
*
* @param cProcessName[in] 程序名称
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::CancelAutoStartup("测试程序");
::system("pause");
return 0;
}
* @endcode
*/
static bool CancelAutoStartup(const char* cProcessName)
{
//判断环境是否为WOW64
BOOL isWOW64;
REGSAM samDesired;
IsWow64Process(GetCurrentProcess(), &isWOW64);
samDesired = isWOW64 ? KEY_WRITE | KEY_WOW64_64KEY : KEY_WRITE;
HKEY hKey;
LONG lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), 0, samDesired, &hKey);
if (lRet == ERROR_SUCCESS)
{
RegDeleteValue(hKey, cProcessName);
RegCloseKey(hKey);
return true;
}
return false;
}
/**
* @brief 重新运行一个本程序实例
*
* 可在异常退出时,重启本程序时使用。
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::ReStartProcess();
::system("pause");
return 0;
}
* @endcode
*/
static void ReStartProcess()
{
char szPath[MAX_PATH] = {0};
GetModuleFileName(NULL, szPath, MAX_PATH);
STARTUPINFO startupInfo;
PROCESS_INFORMATION procInfo;
memset(&startupInfo, 0x00, sizeof(STARTUPINFO));
startupInfo.cb = sizeof(STARTUPINFO);
::CreateProcess(szPath, NULL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &procInfo);
}
/**
* @brief 打开某个文件夹
*
* @param chPath[in] 文件夹路径
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::OpenFolder("c://");
::system("pause");
return 0;
}
* @endcode
*/
static void OpenFolder(const char* chPath)
{
ShellExecute(NULL, NULL, "explorer", chPath, NULL, SW_SHOW);
}
};
#endif // G_SYSTEMHELPER_H_ | [
"931047642@qq.com"
] | 931047642@qq.com |
17093e4a8f4d50d82480a93a3535008494f8ee4f | 68336b429ac97a617956792f7377a61d19080a7b | /c++/Complexity/Complexity2.cpp | 69ed947ed4f8badcbe69df83b47d6b08c2ee8047 | [] | no_license | ibrahimisad8/algorithm-implementations | 8e2da60a756b2e252fe2b7536584fcfa00cc6ace | 5dcc95f101cd53162f7de2e9a49d7dd1e8f96944 | refs/heads/master | 2020-04-10T08:52:53.624728 | 2019-01-03T14:28:08 | 2019-01-03T14:28:08 | 160,918,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 364 | cpp | // you can use includes, for example:
// #include <algorithm>
#include <algorithm>
#include <functional>
#include <numeric>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &A)
{
return std::accumulate(A.begin(), A.end(), (A.size()+1) * (A.size()+2) / 2, std::minus<int>());
} | [
"ibrahimisa.d8@gmail.com"
] | ibrahimisa.d8@gmail.com |
f26d750323c43ab9fd182438e5cd36eaa96503a8 | 5ec1b39dacbd1fcc96fef81466f9ff25b15cad39 | /CodingTaskWeek2/CodingTaskWeek2/John.h | 75587593856c069b29c7b49c92193993892d5458 | [] | no_license | Olli3J/Coding_Task_Week_2 | abbf9ce65b82cef87996df8b261e96c85f83cc6e | c0d9d33d79fd23e769cf81d19fd4c2b9207bc7c1 | refs/heads/main | 2023-04-20T18:17:06.350031 | 2021-05-10T15:06:45 | 2021-05-10T15:06:45 | 366,083,269 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 225 | h | #pragma once
#include "npc.h"
class John : public npc // this class inherits from npc class
{
public:
John();
bool IsABoss() { return true; };
virtual void PrintName() override { cout << "Generic npc"; }
};
| [
"noreply@github.com"
] | Olli3J.noreply@github.com |
9a0f79338a9018dd5684d6c79b0c620466698b4e | 7a81be09ee6f278b7061eeb83f408d822a617dde | /cpp/datastructures/schaumDS/SODSWCPP/Pr0602.cpp | 3ef3034614bb51edf6126f1380a3e788e8922a56 | [] | no_license | amithjkamath/codesamples | dba2ef77abc3b2604b8202ed67ef516bbc971a76 | d3147d743ba9431d42423d0fa78b0e1048922458 | refs/heads/master | 2022-03-23T23:25:35.171973 | 2022-02-28T21:22:23 | 2022-02-28T21:22:23 | 67,352,584 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | cpp | // Data Structures with C++ by John R. Hubbard
// Copyright McGraw-Hill, 2000
// Example 6.2 page 121
// Testing reverse() function for queues
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
template <class T> void print(queue<T>);
template <class T> void reverse(queue<T>&);
int main()
{ queue<char> q;
q.push('A');
q.push('B');
q.push('C');
q.push('D');
q.push('E');
print(q);
reverse(q);
print(q);
}
template <class T>
void print(queue<T> q)
{ cout << "size=" << q.size();
if (q.size()>0)
{ cout << ",\tfront=" << q.front() << ":\t(" << q.front();
q.pop();
while (!q.empty())
{ cout << "," << q.front();
q.pop();
}
cout << ")";
}
cout << "\n";
}
template <class T> void reverse(queue<T>& q)
{ stack<T> s;
while (!q.empty())
{ s.push(q.front());
q.pop();
}
while (!s.empty())
{ q.push(s.top());
s.pop();
}
}
| [
"kamath.quaero@gmail.com"
] | kamath.quaero@gmail.com |
fa89713a838dae0e7a66f61003266ed0273a4940 | 1f184676c51ff1f621ce2e867608b10770ad6f03 | /signal/linux_signal_manager.h | 6ea60fe70ae305aecaee2880eb20b40adfdcc913 | [
"MIT"
] | permissive | swarupkotikalapudi/chat-app-linux | 6b2406443eb4a1310794b58cf53adb9782643331 | 18f3d3116893f1f499b2bc7c6492371afa438c4e | refs/heads/master | 2021-01-10T03:09:38.803839 | 2016-01-17T17:04:42 | 2016-01-17T17:04:42 | 49,811,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 850 | h | #ifndef _LINUX_SIGNAL_MANAGER_H
#define _LINUX_SIGNAL_MANAGER_H
#include<iosfwd>
#include<set>
#include<algorithm>
#include<memory>
class IsignalListner;
/* this class is used by source where some event(e.g. signal) happened, these event need to be informed to subscriber */
class linuxSignalManager
{
private:
typedef void(*fptrSignalHandler)(int);
fptrSignalHandler m_SignalHandler;
std::set<std::shared_ptr<IsignalListner>> m_listners;
protected:
public:
linuxSignalManager();
~linuxSignalManager();
virtual int registerSignalListner(std::shared_ptr<IsignalListner> p_listen);
virtual int unregisterSignalListner(std::shared_ptr<IsignalListner> p_listen);
virtual void informSignalListner(int sig = 0);
virtual int registerSignalHandler(fptrSignalHandler sigHandler);
};
#endif /* _LINUX_SIGNAL_MANAGER_H */
| [
"swarupkotikalapudi@gmail.com"
] | swarupkotikalapudi@gmail.com |
c0b385007402bfbd470ddb3986bccbd6c6a7ef6f | f530448ab4c5ea4dc76e7303825fbd27957c514c | /AntibodyV4-CodeBlocks/WeaponPlNinjaStar.h | eb97cea1b394a9e9c27e54dfe1f32ea839a59a31 | [] | no_license | joeaoregan/LIT-Yr3-Project-Antibody | 677c038e0688bb96125c2687025d1e505837be6b | 22135f4fdb1e0dc2faa5691492ebd6e11011a9d6 | refs/heads/master | 2020-04-21T16:48:26.317244 | 2019-02-13T20:27:36 | 2019-02-13T20:27:36 | 169,714,493 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,188 | h | /* ---------------------------------------------------------------------------------------------------------------------
- Name: WeaponPlNinjaStar.h
- Description: Header file for the Weapon Player Ninja Star class.
- Information: Ninja stars are rotating objects, and they have a slower speed than Lasers but a higher
points value. Like lasers the player automatically has unlimited ninja stars. Ninja stars
can be used to cut Enemy Virus in two. Each player has a differnt colour ninja star, and
sound effect.
- Log:
2017/03/18 Added the Ninja Stars texture to the texture map in Texture class
Ninja star rotations are updated in the move() function instead of setRotatingAngle() in Game class
A texture ID has been added for both Player 1 and Player 2 types of ninja star
And the angle of rotation is now assigned to the Ninja Star class instead of the Texture class
Destroy function is inherited from Game Object base class
2017/03/04 Moved smaller class files functionality into their headers
2017/02/10 Fixed velocity for ninja star after spawning, ninja stars are no longer static
2017/01/30 Added rotation angle to constructors for Textures that rotate
2017/01/25 Fixed Ninja Star scoring for Player 2
2017/01/20 Fixed problem for ninja stars only scoring for Player 1
2017/01/17 Added collision detection for Ninja Stars
2017/01/09 Ninja Star Weapon
Added spawnNinjaStar() function to create ninja star weapon
2017/02/21 Added check so only Ninja Stars and Saws split viruses
2017/01/30 Added rotation angle to constructors for Textures that rotate
2017/01/17 Added player decision to spawnNinjaStar() function - determines player to spawn for and their coords
2017/01/09 Add Ninja Star weapon class
2017/03/18 Rendering functionality has been moved back to class
----------------------------------------------------------------------------------------------------------------------*/
#ifndef NINJA_STAR_H
#define NINJA_STAR_H
#include "Weapon.h"
class WeaponPlNinjaStar : public Weapon {
public:
/*
Ninja Star Constructor
Initializes the variables
The ninja star name, texture ID, sub-type, type, angle of rotation, and assigned player are set
Along with dimensions, velocity on X axis, collider width and height, and the object is set alive.
*/
WeaponPlNinjaStar(int player) {
if (player == PLAYER1) {
setName("Ninja Star P1"); // 2017/03/18 Name of Ninja Star for info / error messages
setTextureID("nsP1ID"); // 2017/03/18 Texture ID for Player 1 Ninja Star
setSubType(NINJA_STAR_P1); // The sub-type of weapon
}
else if (player == PLAYER2) {
setName("Ninja Star P2"); // 2017/03/18 Name of Ninja Star for info / error messages
setTextureID("nsP2ID"); // 2017/03/18 Texture ID for Player 2 Ninja Star
setSubType(NINJA_STAR_P2); // The sub-type of weapon
}
setType(PLAYER_WEAPON); // The type of game object is Player Weapon
setAngle(5); // 2017/03/18 Angle of rotation for Ninja Stars, rotates clockwise 5 degrees each frame
setPlayer(player); // 2017/01/17 Set the player the laser belongs too
setWidth(25); // Set width for texture and collider
setHeight(25); // Set Height for texture and collider
setVelX(10); // Set velocity on X axis as 10 --- NOT WORKING HERE???
setColliderWidth(getWidth());
setColliderHeight(getHeight());
setAlive(true);
/*
// Older variables set elsewhere e.g. velocity set in spawn function in Game class
std::cout << "NinjaStar constuctor called.\n";
if (player == PLAYER1) setSubType(NINJA_STAR_P1);
else if (player == PLAYER2) setSubType(NINJA_STAR_P2);
setVelocity(10); // The speed the object moves at
*/
};
// Ninja Star Destructor
~WeaponPlNinjaStar() {
std::cout << "NinjaStar destructor called." << std::endl;
};
/*
Ninja stars have basic movement, inherited move function from Game Object base class
The ninja star rotation is updated as it moves across the screen, similar to Blood Cells
*/
virtual void move(int x = 0, int y = 0) {
GameObject::move(); // Movement is inherited from Game Object base class
setAngle(getAngle() + 5); // 2017/03/18 The angle of rotation is set, similar to Blood Cell, functionality moved from Game class
};
/*
Ninja Stars are destroyed when they move off screen
This functionality is inherited from the Game Object base class
*/
virtual void destroy() {
GameObject::destroy(); // 2017/03/18 destroy method inherited from Game Object base class
};
/*
2017/03/18 Render Ninja Stars
The Ninja Stars texture is loaded from the texture map using the stored ID
Ninja Stars rotate similar to Blood Cells but in only one direction
*/
virtual void render() {
SDL_Rect renderQuad = { getX(), getY(), getWidth(), getHeight() }; // Set rendering space and render to screen
// Similar to Blood Cell rotation but rotating in only one direction
SDL_RenderCopyEx(Game::Instance()->getRenderer(), Texture::Instance()->getTexture(getTextureID()), NULL, &renderQuad, getAngle(), NULL, SDL_FLIP_NONE); // Render to screen
}
};
#endif | [
"k00203642@student.lit.ie"
] | k00203642@student.lit.ie |
c30fb82b959ad04f11150ea262c6efa199487142 | ecd866fe9df43a2d7d9f286d72f23b113491564c | /algorithms/algorithms/robot.cpp | fa45104f2450ef664c54b2028538dbecdd053a7e | [] | no_license | LeeBoHyoung/algorithm | c8f58eb118bb63bb62117a2a8cb11287507020bf | c6255d229bfb550b38fe4e951fdbc614a9e57dfd | refs/heads/master | 2021-06-21T08:53:56.681106 | 2021-04-24T03:35:23 | 2021-04-24T03:35:23 | 206,602,984 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 1,785 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct robot {
int dir;
int r;
int c;
};
int n, m;
int map[50][50];
bool visited[50][50];
int dr[4] = { -1, 0, 0, 1 };
int dc[4] = { 0, -1, 1, 0 }; //북 서 남 동
int ans = 1;
pair<int, int> route(int dir, int r, int c) {
int nr, nc;
if (dir == 0) { // 북
nr = r + dr[1];
nc = c + dc[1];
}
else if (dir == 1) { // 동
nr = r + dr[0];
nc = c + dc[0];
}
else if (dir == 2) { // 남
nr = r + dr[2];
nc = c + dc[2];
}
else if (dir == 3) { // 서
nr = r + dr[3];
nc = c + dc[3];
}
return make_pair(nr, nc);
}
pair<int, int> direct(int dir, int r, int c) {
if (dir == 0)
return make_pair(r - 1, c);
else if (dir == 1)
return make_pair(r, c + 1);
else if (dir == 2)
return make_pair(r + 1, c);
else if (dir == 3)
return make_pair(r, c - 1);
}
int nr, nc;
void dfs(int r, int c, int dir) {
visited[r][c] = true;
pair<int, int> next;
int check = 0;
for (int i = 0; i < 4; i++) {
//dir = (dir + i) % 4;
next = route(dir, r, c);
dir = (dir + 3) % 4;
nr = next.first; nc = next.second;
if (nr >= 0 && nr < n && nc >= 0 && nc < m) {
if (visited[nr][nc] == false && map[nr][nc] == 0) {
check = 1;
ans++;
dfs(nr, nc, dir);
return;
}
}
}
if (check == 0) {
pair<int, int> back = direct((dir + 2) % 4, r, c);
if (map[back.first][back.second] == 1 || !(back.first >= 0 && back.first < n && back.second >= 0 && back.second < m))
return;
else {
dfs(back.first, back.second, dir);
}
}
}
int main() {
robot init;
cin >> n >> m;
cin >> init.r;
cin >> init.c;
cin >> init.dir;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
}
}
dfs(init.r, init.c, init.dir);
cout << ans;
} | [
"dlqhgud11@naver.com"
] | dlqhgud11@naver.com |
bbde99aeda2b4fafde1176486f27529acf864e33 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/dash/2017/12/blockchain.cpp | cf7307861281b0d3f1e2e49022925534931a55f1 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 58,544 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "coins.h"
#include "consensus/validation.h"
#include "validation.h"
#include "policy/policy.h"
#include "primitives/transaction.h"
#include "rpc/server.h"
#include "streams.h"
#include "sync.h"
#include "txdb.h"
#include "txmempool.h"
#include "util.h"
#include "utilstrencodings.h"
#include "hash.h"
#include <stdint.h>
#include <univalue.h>
#include <boost/thread/thread.hpp> // boost::thread::interrupt
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (chainActive.Tip() == NULL)
return 1.0;
else
blockindex = chainActive.Tip();
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
UniValue blockheaderToJSON(const CBlockIndex* blockindex)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", blockindex->nVersion));
result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion)));
result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
result.push_back(Pair("time", (int64_t)blockindex->nTime));
result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce));
result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
return result;
}
UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion)));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
UniValue txs(UniValue::VARR);
BOOST_FOREACH(const CTransaction&tx, block.vtx)
{
if(txDetails)
{
UniValue objTx(UniValue::VOBJ);
TxToJSON(tx, uint256(), objTx);
txs.push_back(objTx);
}
else
txs.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txs));
result.push_back(Pair("time", block.GetBlockTime()));
result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
result.push_back(Pair("nonce", (uint64_t)block.nNonce));
result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
return result;
}
UniValue getblockcount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"\nReturns the number of blocks in the longest block chain.\n"
"\nResult:\n"
"n (numeric) The current block count\n"
"\nExamples:\n"
+ HelpExampleCli("getblockcount", "")
+ HelpExampleRpc("getblockcount", "")
);
LOCK(cs_main);
return chainActive.Height();
}
UniValue getbestblockhash(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"\nReturns the hash of the best (tip) block in the longest block chain.\n"
"\nResult\n"
"\"hex\" (string) the block hash hex encoded\n"
"\nExamples\n"
+ HelpExampleCli("getbestblockhash", "")
+ HelpExampleRpc("getbestblockhash", "")
);
LOCK(cs_main);
return chainActive.Tip()->GetBlockHash().GetHex();
}
UniValue getdifficulty(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nResult:\n"
"n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nExamples:\n"
+ HelpExampleCli("getdifficulty", "")
+ HelpExampleRpc("getdifficulty", "")
);
LOCK(cs_main);
return GetDifficulty();
}
std::string EntryDescriptionString()
{
return " \"size\" : n, (numeric) transaction size in bytes\n"
" \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
" \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n"
" \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
" \"height\" : n, (numeric) block height when transaction entered pool\n"
" \"startingpriority\" : n, (numeric) priority when transaction entered pool\n"
" \"currentpriority\" : n, (numeric) transaction priority now\n"
" \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
" \"descendantsize\" : n, (numeric) size of in-mempool descendants (including this one)\n"
" \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n"
" \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n"
" \"ancestorsize\" : n, (numeric) size of in-mempool ancestors (including this one)\n"
" \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n"
" \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
" \"transactionid\", (string) parent transaction id\n"
" ... ]\n";
}
void entryToJSON(UniValue &info, const CTxMemPoolEntry &e)
{
AssertLockHeld(mempool.cs);
info.push_back(Pair("size", (int)e.GetTxSize()));
info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee())));
info.push_back(Pair("time", e.GetTime()));
info.push_back(Pair("height", (int)e.GetHeight()));
info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight())));
info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height())));
info.push_back(Pair("descendantcount", e.GetCountWithDescendants()));
info.push_back(Pair("descendantsize", e.GetSizeWithDescendants()));
info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants()));
info.push_back(Pair("ancestorcount", e.GetCountWithAncestors()));
info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors()));
info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors()));
const CTransaction& tx = e.GetTx();
set<string> setDepends;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
if (mempool.exists(txin.prevout.hash))
setDepends.insert(txin.prevout.hash.ToString());
}
UniValue depends(UniValue::VARR);
BOOST_FOREACH(const string& dep, setDepends)
{
depends.push_back(dep);
}
info.push_back(Pair("depends", depends));
}
UniValue mempoolToJSON(bool fVerbose = false)
{
if (fVerbose)
{
LOCK(mempool.cs);
UniValue o(UniValue::VOBJ);
BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx)
{
const uint256& hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.push_back(Pair(hash.ToString(), info));
}
return o;
}
else
{
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
UniValue a(UniValue::VARR);
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
}
UniValue getrawmempool(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawmempool ( verbose )\n"
"\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
"\nArguments:\n"
"1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
"\nResult: (for verbose = false):\n"
"[ (json array of string)\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nResult: (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples\n"
+ HelpExampleCli("getrawmempool", "true")
+ HelpExampleRpc("getrawmempool", "true")
);
bool fVerbose = false;
if (params.size() > 0)
fVerbose = params[0].get_bool();
return mempoolToJSON(fVerbose);
}
UniValue getmempoolancestors(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2) {
throw runtime_error(
"getmempoolancestors txid (verbose)\n"
"\nIf txid is in the mempool, returns all in-mempool ancestors.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"2. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
"\nResult (for verbose=false):\n"
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n"
" ,...\n"
"]\n"
"\nResult (for verbose=true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples\n"
+ HelpExampleCli("getmempoolancestors", "\"mytxid\"")
+ HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
);
}
bool fVerbose = false;
if (params.size() > 1)
fVerbose = params[1].get_bool();
uint256 hash = ParseHashV(params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setAncestors;
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
if (!fVerbose) {
UniValue o(UniValue::VARR);
BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) {
o.push_back(ancestorIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) {
const CTxMemPoolEntry &e = *ancestorIt;
const uint256& hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.push_back(Pair(hash.ToString(), info));
}
return o;
}
}
UniValue getmempooldescendants(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2) {
throw runtime_error(
"getmempooldescendants txid (verbose)\n"
"\nIf txid is in the mempool, returns all in-mempool descendants.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"2. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
"\nResult (for verbose=false):\n"
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n"
" ,...\n"
"]\n"
"\nResult (for verbose=true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples\n"
+ HelpExampleCli("getmempooldescendants", "\"mytxid\"")
+ HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
);
}
bool fVerbose = false;
if (params.size() > 1)
fVerbose = params[1].get_bool();
uint256 hash = ParseHashV(params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setDescendants;
mempool.CalculateDescendants(it, setDescendants);
// CTxMemPool::CalculateDescendants will include the given tx
setDescendants.erase(it);
if (!fVerbose) {
UniValue o(UniValue::VARR);
BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) {
o.push_back(descendantIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) {
const CTxMemPoolEntry &e = *descendantIt;
const uint256& hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.push_back(Pair(hash.ToString(), info));
}
return o;
}
}
UniValue getmempoolentry(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1) {
throw runtime_error(
"getmempoolentry txid\n"
"\nReturns mempool data for given transaction\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"\nResult:\n"
"{ (json object)\n"
+ EntryDescriptionString()
+ "}\n"
"\nExamples\n"
+ HelpExampleCli("getmempoolentry", "\"mytxid\"")
+ HelpExampleRpc("getmempoolentry", "\"mytxid\"")
);
}
uint256 hash = ParseHashV(params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
const CTxMemPoolEntry &e = *it;
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
return info;
}
UniValue getblockhashes(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"getblockhashes timestamp\n"
"\nReturns array of hashes of blocks within the timestamp range provided.\n"
"\nArguments:\n"
"1. high (numeric, required) The newer block timestamp\n"
"2. low (numeric, required) The older block timestamp\n"
"\nResult:\n"
"[\n"
" \"hash\" (string) The block hash\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhashes", "1231614698 1231024505")
+ HelpExampleRpc("getblockhashes", "1231614698, 1231024505")
);
unsigned int high = params[0].get_int();
unsigned int low = params[1].get_int();
std::vector<uint256> blockHashes;
if (!GetTimestampIndex(high, low, blockHashes)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes");
}
UniValue result(UniValue::VARR);
for (std::vector<uint256>::const_iterator it=blockHashes.begin(); it!=blockHashes.end(); it++) {
result.push_back(it->GetHex());
}
return result;
}
UniValue getblockhash(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash index\n"
"\nReturns hash of block in best-block-chain at index provided.\n"
"\nArguments:\n"
"1. index (numeric, required) The block index\n"
"\nResult:\n"
"\"hash\" (string) The block hash\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhash", "1000")
+ HelpExampleRpc("getblockhash", "1000")
);
LOCK(cs_main);
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > chainActive.Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
CBlockIndex* pblockindex = chainActive[nHeight];
return pblockindex->GetBlockHash().GetHex();
}
UniValue getblockheader(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblockheader \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
"If verbose is true, returns an Object with information about blockheader <hash>.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n"
+ HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
);
LOCK(cs_main);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockheaderToJSON(pblockindex);
}
UniValue getblockheaders(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"getblockheaders \"hash\" ( count verbose )\n"
"\nReturns an array of items with information about <count> blockheaders starting from <hash>.\n"
"\nIf verbose is false, each item is a string that is serialized, hex-encoded data for a single blockheader.\n"
"If verbose is true, each item is an Object with information about a single blockheader.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. count (numeric, optional, default/max=" + strprintf("%s", MAX_HEADERS_RESULTS) +")\n"
"3. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"[ {\n"
" \"hash\" : \"hash\", (string) The block hash\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
"}, {\n"
" ...\n"
" },\n"
"...\n"
"]\n"
"\nResult (for verbose=false):\n"
"[\n"
" \"data\", (string) A string that is serialized, hex-encoded data for block header.\n"
" ...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000")
+ HelpExampleRpc("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000")
);
LOCK(cs_main);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
int nCount = MAX_HEADERS_RESULTS;
if (params.size() > 1)
nCount = params[1].get_int();
if (nCount <= 0 || nCount > (int)MAX_HEADERS_RESULTS)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Count is out of range");
bool fVerbose = true;
if (params.size() > 2)
fVerbose = params[2].get_bool();
CBlockIndex* pblockindex = mapBlockIndex[hash];
UniValue arrHeaders(UniValue::VARR);
if (!fVerbose)
{
for (; pblockindex; pblockindex = chainActive.Next(pblockindex))
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
arrHeaders.push_back(strHex);
if (--nCount <= 0)
break;
}
return arrHeaders;
}
for (; pblockindex; pblockindex = chainActive.Next(pblockindex))
{
arrHeaders.push_back(blockheaderToJSON(pblockindex));
if (--nCount <= 0)
break;
}
return arrHeaders;
}
UniValue getblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
"If verbose is true, returns an Object with information about block <hash>.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n"
+ HelpExampleCli("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
+ HelpExampleRpc("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
);
LOCK(cs_main);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)");
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex);
}
struct CCoinsStats
{
int nHeight;
uint256 hashBlock;
uint64_t nTransactions;
uint64_t nTransactionOutputs;
uint256 hashSerialized;
uint64_t nDiskSize;
CAmount nTotalAmount;
CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nTotalAmount(0) {}
};
static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs)
{
assert(!outputs.empty());
ss << hash;
ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase);
stats.nTransactions++;
for (const auto output : outputs) {
ss << VARINT(output.first + 1);
ss << *(const CScriptBase*)(&output.second.out.scriptPubKey);
ss << VARINT(output.second.out.nValue);
stats.nTransactionOutputs++;
stats.nTotalAmount += output.second.out.nValue;
}
ss << VARINT(0);
}
//! Calculate statistics about the unspent transaction output set
static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
{
boost::scoped_ptr<CCoinsViewCursor> pcursor(view->Cursor());
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = pcursor->GetBestBlock();
{
LOCK(cs_main);
stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
}
ss << stats.hashBlock;
uint256 prevkey;
std::map<uint32_t, Coin> outputs;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
COutPoint key;
Coin coin;
if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
if (!outputs.empty() && key.hash != prevkey) {
ApplyStats(stats, ss, prevkey, outputs);
outputs.clear();
}
prevkey = key.hash;
outputs[key.n] = std::move(coin);
} else {
return error("%s: unable to read value", __func__);
}
pcursor->Next();
}
if (!outputs.empty()) {
ApplyStats(stats, ss, prevkey, outputs);
}
stats.hashSerialized = ss.GetHash();
stats.nDiskSize = view->EstimateSize();
return true;
}
UniValue gettxoutsetinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gettxoutsetinfo\n"
"\nReturns statistics about the unspent transaction output set.\n"
"Note this call may take some time.\n"
"\nResult:\n"
"{\n"
" \"height\":n, (numeric) The current block height (index)\n"
" \"bestblock\": \"hex\", (string) the best block hash hex\n"
" \"transactions\": n, (numeric) The number of transactions\n"
" \"txouts\": n, (numeric) The number of output transactions\n"
" \"hash_serialized\": \"hash\", (string) The serialized hash\n"
" \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n"
" \"total_amount\": x.xxx (numeric) The total amount\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("gettxoutsetinfo", "")
+ HelpExampleRpc("gettxoutsetinfo", "")
);
UniValue ret(UniValue::VOBJ);
CCoinsStats stats;
FlushStateToDisk();
if (GetUTXOStats(pcoinsdbview, stats)) {
ret.push_back(Pair("height", (int64_t)stats.nHeight));
ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
ret.push_back(Pair("hash_serialized_2", stats.hashSerialized.GetHex()));
ret.push_back(Pair("disk_size", stats.nDiskSize));
ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
}
return ret;
}
UniValue gettxout(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"gettxout \"txid\" n ( includemempool )\n"
"\nReturns details about an unspent transaction output.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. n (numeric, required) vout number\n"
"3. includemempool (boolean, optional) Whether to include the mem pool\n"
"\nResult:\n"
"{\n"
" \"bestblock\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"code\", (string) \n"
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
" \"addresses\" : [ (array of string) array of dash addresses\n"
" \"dashaddress\" (string) dash address\n"
" ,...\n"
" ]\n"
" },\n"
" \"version\" : n, (numeric) The version\n"
" \"coinbase\" : true|false (boolean) Coinbase or not\n"
"}\n"
"\nExamples:\n"
"\nGet unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nView the details\n"
+ HelpExampleCli("gettxout", "\"txid\" 1") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("gettxout", "\"txid\", 1")
);
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
int n = params[1].get_int();
COutPoint out(hash, n);
bool fMempool = true;
if (params.size() > 2)
fMempool = params[2].get_bool();
Coin coin;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(pcoinsTip, mempool);
if (!view.GetCoin(out, coin) || mempool.isSpent(out)) { // TODO: filtering spent coins should be done by the CCoinsViewMemPool
return NullUniValue;
}
} else {
if (!pcoinsTip->GetCoin(out, coin)) {
return NullUniValue;
}
}
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
CBlockIndex *pindex = it->second;
ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
if (coin.nHeight == MEMPOOL_HEIGHT) {
ret.push_back(Pair("confirmations", 0));
} else {
ret.push_back(Pair("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1)));
}
ret.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(coin.out.scriptPubKey, o, true);
ret.push_back(Pair("scriptPubKey", o));
ret.push_back(Pair("coinbase", (bool)coin.fCoinBase));
return ret;
}
UniValue verifychain(const UniValue& params, bool fHelp)
{
int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL);
int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
if (fHelp || params.size() > 2)
throw runtime_error(
"verifychain ( checklevel numblocks )\n"
"\nVerifies blockchain database.\n"
"\nArguments:\n"
"1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n"
"2. numblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n"
"\nResult:\n"
"true|false (boolean) Verified or not\n"
"\nExamples:\n"
+ HelpExampleCli("verifychain", "")
+ HelpExampleRpc("verifychain", "")
);
LOCK(cs_main);
if (params.size() > 0)
nCheckLevel = params[0].get_int();
if (params.size() > 1)
nCheckDepth = params[1].get_int();
return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth);
}
/** Implementation of IsSuperMajority with better feedback */
static UniValue SoftForkMajorityDesc(int minVersion, CBlockIndex* pindex, int nRequired, const Consensus::Params& consensusParams)
{
int nFound = 0;
CBlockIndex* pstart = pindex;
for (int i = 0; i < consensusParams.nMajorityWindow && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
UniValue rv(UniValue::VOBJ);
rv.push_back(Pair("status", nFound >= nRequired));
rv.push_back(Pair("found", nFound));
rv.push_back(Pair("required", nRequired));
rv.push_back(Pair("window", consensusParams.nMajorityWindow));
return rv;
}
static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
UniValue rv(UniValue::VOBJ);
rv.push_back(Pair("id", name));
rv.push_back(Pair("version", version));
rv.push_back(Pair("enforce", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams)));
rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityRejectBlockOutdated, consensusParams)));
return rv;
}
static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
{
UniValue rv(UniValue::VOBJ);
const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
switch (thresholdState) {
case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break;
case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break;
case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break;
case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break;
case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break;
}
if (THRESHOLD_STARTED == thresholdState)
{
rv.push_back(Pair("bit", consensusParams.vDeployments[id].bit));
}
rv.push_back(Pair("startTime", consensusParams.vDeployments[id].nStartTime));
rv.push_back(Pair("timeout", consensusParams.vDeployments[id].nTimeout));
return rv;
}
void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
{
// Deployments with timeout value of 0 are hidden.
// A timeout value of 0 guarantees a softfork will never be activated.
// This is used when softfork codes are merged without specifying the deployment schedule.
if (consensusParams.vDeployments[id].nTimeout > 0)
bip9_softforks.push_back(Pair(name, BIP9SoftForkDesc(consensusParams, id)));
}
UniValue getblockchaininfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockchaininfo\n"
"Returns an object containing various state info regarding block chain processing.\n"
"\nResult:\n"
"{\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
" \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"mediantime\": xxxxxx, (numeric) median time for the current best block\n"
" \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
" \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
" \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
" \"pruneheight\": xxxxxx, (numeric) heighest block available\n"
" \"softforks\": [ (array) status of softforks in progress\n"
" {\n"
" \"id\": \"xxxx\", (string) name of softfork\n"
" \"version\": xx, (numeric) block version\n"
" \"enforce\": { (object) progress toward enforcing the softfork rules for new-version blocks\n"
" \"status\": xx, (boolean) true if threshold reached\n"
" \"found\": xx, (numeric) number of blocks with the new version found\n"
" \"required\": xx, (numeric) number of blocks required to trigger\n"
" \"window\": xx, (numeric) maximum size of examined window of recent blocks\n"
" },\n"
" \"reject\": { ... } (object) progress toward rejecting pre-softfork blocks (same fields as \"enforce\")\n"
" }, ...\n"
" ],\n"
" \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n"
" \"xxxx\" : { (string) name of the softfork\n"
" \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n"
" \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n"
" \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n"
" \"timeout\": xx (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n"
" }\n"
" }\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblockchaininfo", "")
+ HelpExampleRpc("getblockchaininfo", "")
);
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("chain", Params().NetworkIDString()));
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast()));
obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(Params().Checkpoints(), chainActive.Tip())));
obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
obj.push_back(Pair("pruned", fPruneMode));
const Consensus::Params& consensusParams = Params().GetConsensus();
CBlockIndex* tip = chainActive.Tip();
UniValue softforks(UniValue::VARR);
UniValue bip9_softforks(UniValue::VOBJ);
softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV);
BIP9SoftForkDescPushBack(bip9_softforks, "dip0001", consensusParams, Consensus::DEPLOYMENT_DIP0001);
obj.push_back(Pair("softforks", softforks));
obj.push_back(Pair("bip9_softforks", bip9_softforks));
if (fPruneMode)
{
CBlockIndex *block = chainActive.Tip();
while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA))
block = block->pprev;
obj.push_back(Pair("pruneheight", block->nHeight));
}
return obj;
}
/** Comparison function for sorting the getchaintips heads. */
struct CompareBlocksByHeight
{
bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
{
/* Make sure that unequal blocks with the same height do not compare
equal. Use the pointers themselves to make a distinction. */
if (a->nHeight != b->nHeight)
return (a->nHeight > b->nHeight);
return a < b;
}
};
UniValue getchaintips(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getchaintips ( count branchlen )\n"
"Return information about all known tips in the block tree,"
" including the main chain as well as orphaned branches.\n"
"\nArguments:\n"
"1. count (numeric, optional) only show this much of latest tips\n"
"2. branchlen (numeric, optional) only show tips that have equal or greater length of branch\n"
"\nResult:\n"
"[\n"
" {\n"
" \"height\": xxxx, (numeric) height of the chain tip\n"
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"branchlen\": 0 (numeric) zero for main chain\n"
" \"status\": \"active\" (string) \"active\" for the main chain\n"
" },\n"
" {\n"
" \"height\": xxxx,\n"
" \"hash\": \"xxxx\",\n"
" \"difficulty\" : x.xxx,\n"
" \"chainwork\" : \"0000...1f3\"\n"
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
" }\n"
"]\n"
"Possible values for status:\n"
"1. \"invalid\" This branch contains at least one invalid block\n"
"2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
"3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
"4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
"5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
"\nExamples:\n"
+ HelpExampleCli("getchaintips", "")
+ HelpExampleRpc("getchaintips", "")
);
LOCK(cs_main);
/*
* Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them.
* Algorithm:
* - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
* - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
* - add chainActive.Tip()
*/
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
std::set<const CBlockIndex*> setOrphans;
std::set<const CBlockIndex*> setPrevs;
BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
{
if (!chainActive.Contains(item.second)) {
setOrphans.insert(item.second);
setPrevs.insert(item.second->pprev);
}
}
for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)
{
if (setPrevs.erase(*it) == 0) {
setTips.insert(*it);
}
}
// Always report the currently active tip.
setTips.insert(chainActive.Tip());
int nBranchMin = -1;
int nCountMax = INT_MAX;
if(params.size() >= 1)
nCountMax = params[0].get_int();
if(params.size() == 2)
nBranchMin = params[1].get_int();
/* Construct the output array. */
UniValue res(UniValue::VARR);
BOOST_FOREACH(const CBlockIndex* block, setTips)
{
const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
if(branchLen < nBranchMin) continue;
if(nCountMax-- < 1) break;
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("height", block->nHeight));
obj.push_back(Pair("hash", block->phashBlock->GetHex()));
obj.push_back(Pair("difficulty", GetDifficulty(block)));
obj.push_back(Pair("chainwork", block->nChainWork.GetHex()));
obj.push_back(Pair("branchlen", branchLen));
string status;
if (chainActive.Contains(block)) {
// This block is part of the currently active chain.
status = "active";
} else if (block->nStatus & BLOCK_FAILED_MASK) {
// This block or one of its ancestors is invalid.
status = "invalid";
} else if (block->nChainTx == 0) {
// This block cannot be connected because full block data for it or one of its parents is missing.
status = "headers-only";
} else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
// This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
status = "valid-fork";
} else if (block->IsValid(BLOCK_VALID_TREE)) {
// The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
status = "valid-headers";
} else {
// No clue.
status = "unknown";
}
obj.push_back(Pair("status", status));
res.push_back(obj);
}
return res;
}
UniValue mempoolInfoToJSON()
{
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("size", (int64_t) mempool.size()));
ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
size_t maxmempool = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
ret.push_back(Pair("maxmempool", (int64_t) maxmempool));
ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK())));
return ret;
}
UniValue getmempoolinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmempoolinfo\n"
"\nReturns details on the active state of the TX memory pool.\n"
"\nResult:\n"
"{\n"
" \"size\": xxxxx, (numeric) Current tx count\n"
" \"bytes\": xxxxx, (numeric) Sum of all tx sizes\n"
" \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
" \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
" \"mempoolminfee\": xxxxx (numeric) Minimum fee for tx to be accepted\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolinfo", "")
+ HelpExampleRpc("getmempoolinfo", "")
);
return mempoolInfoToJSON();
}
UniValue invalidateblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"invalidateblock \"hash\"\n"
"\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
"\nArguments:\n"
"1. hash (string, required) the hash of the block to mark as invalid\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("invalidateblock", "\"blockhash\"")
+ HelpExampleRpc("invalidateblock", "\"blockhash\"")
);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
CValidationState state;
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
InvalidateBlock(state, Params(), pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state, Params(), NULL);
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
UniValue reconsiderblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"reconsiderblock \"hash\"\n"
"\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
"This can be used to undo the effects of invalidateblock.\n"
"\nArguments:\n"
"1. hash (string, required) the hash of the block to reconsider\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("reconsiderblock", "\"blockhash\"")
+ HelpExampleRpc("reconsiderblock", "\"blockhash\"")
);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
ResetBlockFailureFlags(pblockindex);
}
CValidationState state;
ActivateBestChain(state, Params(), NULL);
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
static const CRPCCommand commands[] =
{ // category name actor (function) okSafeMode
// --------------------- ------------------------ ----------------------- ----------
{ "blockchain", "getblockchaininfo", &getblockchaininfo, true },
{ "blockchain", "getbestblockhash", &getbestblockhash, true },
{ "blockchain", "getblockcount", &getblockcount, true },
{ "blockchain", "getblock", &getblock, true },
{ "blockchain", "getblockhashes", &getblockhashes, true },
{ "blockchain", "getblockhash", &getblockhash, true },
{ "blockchain", "getblockheader", &getblockheader, true },
{ "blockchain", "getblockheaders", &getblockheaders, true },
{ "blockchain", "getchaintips", &getchaintips, true },
{ "blockchain", "getdifficulty", &getdifficulty, true },
{ "blockchain", "getmempoolancestors", &getmempoolancestors, true },
{ "blockchain", "getmempooldescendants", &getmempooldescendants, true },
{ "blockchain", "getmempoolentry", &getmempoolentry, true },
{ "blockchain", "getmempoolinfo", &getmempoolinfo, true },
{ "blockchain", "getrawmempool", &getrawmempool, true },
{ "blockchain", "gettxout", &gettxout, true },
{ "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true },
{ "blockchain", "verifychain", &verifychain, true },
/* Not shown in help */
{ "hidden", "invalidateblock", &invalidateblock, true },
{ "hidden", "reconsiderblock", &reconsiderblock, true },
};
void RegisterBlockchainRPCCommands(CRPCTable &tableRPC)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
tableRPC.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
13d251596a3fae6c8075e1d94805ad098f83dbcc | 4365cdadad0026cabdf008bb46cacbaa397122f3 | /Taewoo/problem_solving/personal/self/miro.cpp | 0f3368e28e48190664547eb8ce7926d7cf20ced1 | [] | no_license | thalals/Algorithm_Study | 31e124df727fb0af9bf9d4905f3eade35a722813 | 3d067442e5e0d6ca6896a0b0c8e58a0dc41e717e | refs/heads/main | 2023-07-06T05:52:04.679220 | 2021-08-19T06:11:56 | 2021-08-19T06:11:56 | 331,019,217 | 1 | 1 | null | 2021-01-19T15:10:19 | 2021-01-19T15:10:18 | null | UTF-8 | C++ | false | false | 1,207 | cpp | #include<bits/stdc++.h>
using namespace std;
int N, M;
int graph[201][201];
int visited[201][201];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
void bfs(int x, int y) {
queue<pair<int, int>> q;
q.push({x, y});
visited[x][y] = 1;
bool flag = false;
while(!q.empty()) {
pair<int, int> p = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int X = p.first + dx[i];
int Y = p.second + dy[i];
if(X < 0 || X == N || Y < 0 || Y == M) continue;
if(!graph[X][Y] || visited[X][Y]) continue;
q.push({X, Y});
visited[X][Y] = visited[p.first][p.second] + 1;
if(X == N - 1 && Y == M - 1) {
flag = true;
break;
}
}
if(flag) break;
}
}
int main() {
cin >> N >> M;
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
scanf("%1d", &graph[i][j]);
memset(visited, 0, sizeof(visited));
bfs(0, 0);
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
cout << visited[i][j] << ' ';
}cout << '\n';
}
cout << visited[N-1][M-1] << '\n';
} | [
"skaxodn97@gmail.com"
] | skaxodn97@gmail.com |
acb8419ba3aad88c0deddb8a4c73928eb5d2b817 | ba8689a6e4f0e4f6e78c1864e6a1f448b9d04aef | /Calculator/src/ReversePolishNotation.cpp | c5f103b6dcd84f6d28f6c240c220f0597c2895a4 | [] | no_license | YlmzCmlttn/Calculator | 591ffd109a3f9e3f3cd05d17f1c919fa27f7e103 | ba4dcad575abf3931c608ba088982358373d4666 | refs/heads/main | 2023-04-30T06:35:17.043533 | 2021-05-07T00:46:57 | 2021-05-07T00:46:57 | 363,385,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,705 | cpp | #include "ReversePolishNotation.h"
#include <stack>
#include <iostream>
namespace ReversePolishNotation
{
bool isLeftAssociative(std::string str) {
return g_BinaryFunctions[str].m_Left;
}
// get function precedence
short getPrecedence(std::string str) {
if (isContain<std::string>(keys(g_BinaryFunctions), str)) {
return g_BinaryFunctions[str].m_Precendence;
}
return 0;
}
bool isNumber(char c,bool decimal, bool negative){
if (c >= '0' && c <= '9') {
return true;
}
else if ((!decimal) && c == '.') {
return true;
}
else if (!negative && c == '-') {
return true;
}
return false;
}
std::string findElement(const int& index, const std::string& equation, std::vector<std::string> list){
for (std::string item : list) {
int n = (int)item.size();
if (equation.substr(index, n) == item) {
return item;
}
}
return "";
}
RPN reversePolishNotation(const std::string& equation){
std::vector<std::string> queue;
std::stack<std::string> stack;
std::string element = "";
std::pair<TokenTypes,TokenTypes> types = std::make_pair<TokenTypes,TokenTypes>(TokenTypes::UNKNOW,TokenTypes::UNKNOW);
bool isDecimal = false;
bool isNegative =false;
const int equationLength = equation.size();
for (int i = 0; i < equationLength; i++)
{
bool condition = true;
char c = equation[i];
if(isNumber(c)){
types.first = TokenTypes::CONSTANT;
if(c == '.'){
isDecimal = true;
}else if(c == '-'){
isNegative = true;
if((types.second == TokenTypes::CONSTANT || types.second == TokenTypes::UNKNOW) && i != 0){
condition = false;
}
}
int startIndex = i;
if(i<equationLength-1){
if(condition){
while(isNumber(equation[i+1],isDecimal,isNegative)){
if(equation[i+1]=='-'){
break;
}
i++;
if(i == equationLength-1){
break;
}
}
}
}
element = equation.substr(startIndex,i-startIndex+1);
if(element=="-"){
types.first = TokenTypes::OPERATOR;
}
types.second = types.first;
}else{
element = findElement(i,equation,g_FunctionNames);
if(element != ""){
types.first = isContain<char>(g_Operators,element[0]) ? TokenTypes::OPERATOR : TokenTypes::FUNCTION;
}
else{
element = findElement(i,equation,g_ConstantNames);
if(element != ""){
types.first = TokenTypes::CONSTANT;
}else{
if(isContain<char>(g_LeftBrackets,equation[i])){
types.first = TokenTypes::LEFTPARANTESIS;
element = "(";
}else if(isContain<char>(g_RightBrackets,equation[i])){
types.first = TokenTypes::RIGHTPARANTESIS;
element = ")";
}else{
types.first = TokenTypes::UNKNOW;
}
}
}
i += element.size()-1;
}
std::string last_stack = (stack.size() > 0) ? stack.top() : "";
switch (types.first)
{
case TokenTypes::CONSTANT:
queue.push_back(element);
break;
case TokenTypes::FUNCTION:
stack.push(element);
break;
case TokenTypes::OPERATOR:
if(stack.size()!=0){
while((
(isContain<std::string>(g_FunctionNames, last_stack) && !isContain<char>(g_Operators, last_stack.c_str()[0])) ||
getPrecedence(last_stack) > getPrecedence(element) || ((getPrecedence(last_stack) == getPrecedence(element)) && isLeftAssociative(last_stack))) &&
!isContain<char>(g_LeftBrackets, last_stack.c_str()[0])
){
queue.push_back(stack.top());
stack.pop();
if(stack.size()==0){
break;
}
last_stack = stack.top();
}
}
stack.push(element);
break;
case TokenTypes::LEFTPARANTESIS:
stack.push(element);
break;
case TokenTypes::RIGHTPARANTESIS:
while(last_stack[0] != '('){
queue.push_back(stack.top());
stack.pop();
last_stack = stack.top();
}
stack.pop();
break;
default:
return queue;
}
types.second = types.first;
}
while(stack.size()>0){
queue.push_back(stack.top());
stack.pop();
}
return queue;
}
std::map<std::string, Function> g_UnaryFunctions = {
{"sin",Function(static_cast<double(*)(double)>(std::sin))}
};
std::map<std::string, Function> g_BinaryFunctions = {
{ "+", Function([](double x, double y) -> double { return x + y; }, TokenTypes::OPERATOR, 2) },
{ "-", Function([](double x, double y) -> double { return x - y; }, TokenTypes::OPERATOR, 2) },
{ "*", Function([](double x, double y) -> double { return x * y; }, TokenTypes::OPERATOR, 3) },
{ "/", Function([](double x, double y) -> double { return x / y; }, TokenTypes::OPERATOR, 3) },
{ "^", Function(static_cast<double(*)(double,double)>(std::pow), TokenTypes::OPERATOR, 4, false) }
};
std::vector<std::string> g_FunctionNames = keys<Function>(g_UnaryFunctions, g_BinaryFunctions);
// constants
std::map<std::string, double> g_Constants = {
{ "pi", std::atan(1) * 4 },
{ "e", std::exp(1) }
};
std::vector<std::string> g_ConstantNames = keys<double>(g_Constants);
} // namespace ReversePolishNotation
//256+874159+878745sadasd+sad5589741-8895478-
//3+4*2/(1-5)^2^3 | [
"ylmzcmlttn@gmail.com"
] | ylmzcmlttn@gmail.com |
4c1e9a8982abfc3f5073c40e6244f3157026d16d | e05ecd8947dc56f1c16e6882124cd53646aa84ed | /src/EKF_learning/KF/test/kalam_roll_pich_test_01.cpp | 8b8537ebc0cbbf82a0b94a243950807dfba0bc0a | [] | no_license | xiazhenyu555/msckf_mono | 2a8195d65393fcc0012691365168d25f09c97e00 | 37013fdd9ccd1a14d433e287961d7392d3b57fe8 | refs/heads/master | 2023-05-13T13:35:24.475342 | 2019-04-06T13:41:48 | 2019-04-06T13:41:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 154 | cpp | #include <iostream>
#include "imu_data_reader.h"
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
/**/
return 0;
}
| [
"xinliangzhong@foxmail.com"
] | xinliangzhong@foxmail.com |
fe7ea14fd2d79e7da9ec5ca98613081d3c3e0a49 | f5bab0feb337491bb9d6c1a7658818238f87f690 | /apps/netpipe/hosted/src/netpipe.cc | a50e98ba9ee706d380ad67648b14b452256dc21a | [] | no_license | jimcadden/ebbrt-contrib | 0cb18653a396e59bc894556f394537de0f82b57a | 76a1fe0c96a7fccc4958ad6cc5916d7923b6f7a4 | refs/heads/master | 2021-09-20T03:37:38.826638 | 2018-08-02T23:00:38 | 2018-08-02T23:00:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,142 | cc | // Copyright Boston University SESA Group 2013 - 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <signal.h>
#include <boost/filesystem.hpp>
#include <ebbrt/Context.h>
#include <ebbrt/ContextActivation.h>
#include <ebbrt/GlobalIdMap.h>
#include <ebbrt/StaticIds.h>
#include <ebbrt/NodeAllocator.h>
#include <ebbrt/Runtime.h>
#include "Printer.h"
int main(int argc, char** argv) {
auto bindir = boost::filesystem::system_complete(argv[0]).parent_path() /
"/bm/netpipe.elf32";
ebbrt::Runtime runtime;
ebbrt::Context c(runtime);
boost::asio::signal_set sig(c.io_service_, SIGINT);
{
ebbrt::ContextActivation activation(c);
// ensure clean quit on ctrl-c
sig.async_wait([&c](const boost::system::error_code& ec,
int signal_number) { c.io_service_.stop(); });
Printer::Init().Then([bindir](ebbrt::Future<void> f) {
f.Get();
ebbrt::node_allocator->AllocateNode(bindir.string(), 1);
});
}
c.Run();
return 0;
}
| [
"jmcadden@bu.edu"
] | jmcadden@bu.edu |
76c4fe80c1c6de89d32606babba8040acba5af8a | 7f2e3ef75e6ab9ff292d0df3673faf5d044c2bd6 | /TitanEngine/SDK/Samples/Unpackers/x86/C/Dynamic unpackers/ExeFog 1.x/RL!deExeFog/unpacker.cpp | e5086ec9df771495a67ece72d648e92484c48e45 | [] | no_license | 0xFF1E071F/fuu | 53929f5fe5c312b58f3879914cd992c79e6b9e13 | 696a819e23808d3e4711d3a73122a317785ad3da | refs/heads/master | 2021-05-29T23:33:42.855092 | 2015-04-27T15:51:28 | 2015-04-27T15:51:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,730 | cpp | #include "unpacker.h"
#include <cstdio>
#include <cstring>
#include <cstdarg>
cUnpacker cUnpacker::lInstance;
HWND cUnpacker::Window = NULL;
void (*cUnpacker::LogCallback)(const char*) = &cUnpacker::DefLogCallback;
char cUnpacker::lPath[MAX_PATH], cUnpacker::lOut[MAX_PATH];
PROCESS_INFORMATION* cUnpacker::lProcess;
bool cUnpacker::lRealign, cUnpacker::lCopyOverlay;
PE32Struct cUnpacker::lPEInfo;
ULONG_PTR cUnpacker::lEP;
ULONG_PTR cUnpacker::SFXSectionVA;
DWORD cUnpacker::SFXSectionSize;
void cUnpacker::Log(const char* pFormat, ...)
{
va_list ArgList;
char Buffer[iMaxString];
va_start(ArgList, pFormat);
vsprintf_s(Buffer, sizeof Buffer, pFormat, ArgList);
va_end(ArgList);
LogCallback(Buffer);
}
void cUnpacker::Abort()
{
StopDebug();
Log("[Fatal Error] Unpacking has been aborted.");
}
bool cUnpacker::Unpack(const char* pPath, bool pRealign, bool pCopyOverlay)
{
HANDLE HFile, HMap;
DWORD FileSize;
ULONG_PTR MapVA;
bool Return = false;
lRealign = pRealign;
lCopyOverlay = pCopyOverlay;
strncpy(lPath, pPath, sizeof lPath - 1);
lPath[sizeof lPath - 1] = '\0';
char* ExtChar = strrchr(lPath, '.');
if(ExtChar)
{
*ExtChar = '\0';
sprintf_s(lOut, MAX_PATH, "%s.unpacked.%s", lPath, ExtChar+1);
*ExtChar = '.';
}
else
{
sprintf_s(lOut, MAX_PATH, "%s.unpacked", lPath);
}
DeleteFileA(lOut);
Log("-> Unpack started...");
if(StaticFileLoad(lPath, UE_ACCESS_READ, false, &HFile, &FileSize, &HMap, &MapVA))
{
if(GetPE32DataFromMappedFileEx(MapVA, &lPEInfo))
{
lEP = lPEInfo.ImageBase + lPEInfo.OriginalEntryPoint;
WORD SFXSectionIndex = GetPE32SectionNumberFromVA(MapVA, lEP);
SFXSectionVA = lPEInfo.ImageBase + GetPE32DataFromMappedFile(MapVA, SFXSectionIndex, UE_SECTIONVIRTUALOFFSET);
SFXSectionSize = GetPE32DataFromMappedFile(MapVA, SFXSectionIndex, UE_SECTIONVIRTUALSIZE);
lProcess = (PROCESS_INFORMATION*)InitDebugEx(lPath, 0, 0, &OnEp);
if(lProcess)
{
DebugLoop();
ImporterCleanup();
Return = true;
}
else Log("[Error] Engine initialization failed!");
}
else Log("[Error] Selected file is not a valid PE32 file!");
StaticFileUnload(lPath, false, HFile, FileSize, HMap, MapVA);
}
else Log("[Error] Can't open selected file!");
Log("-> Unpack ended...");
return Return;
}
void __stdcall cUnpacker::OnEp()
{
BYTE WildCard = 0xFF;
const BYTE DecryptPattern[] = {0x90, 0xEB, 0x04, 0x01, 0x07, 0x01, 0x07, 0xBB, 0xFF, 0xFF, 0xFF, 0xFF, 0xB9, 0xC8, 0x03, 0x00, 0x00, 0xB0, 0xFF, 0x30, 0x04, 0x0B, 0x8A, 0x04, 0x0B, 0xE2, 0xF8};
/*
NOP
JMP @SKIP
ADD DWORD PTR DS:[EDI],EAX
ADD DWORD PTR DS:[EDI],EAX
SKIP:
MOV EBX, XXXXXXXX ; code after LOOPD
MOV ECX, 3C8 ; constant value
MOV AL, XX
@DECRYPT:
XOR BYTE PTR DS:[EBX+ECX],AL
MOV AL,BYTE PTR DS:[EBX+ECX]
LOOPD DECRYPT
*/
ImporterInit(iImporterSize, lPEInfo.ImageBase);
ULONG_PTR DecryptCode = Find((void*)lEP, SFXSectionVA+SFXSectionSize-lEP, (void*)DecryptPattern, sizeof DecryptPattern, &WildCard);
if(!DecryptCode)
{
Log("[Error] Cannot find decryption code, probably not packed with a supported version?");
Abort();
return;
}
if(!SetHardwareBreakPoint(DecryptCode + sizeof DecryptPattern, NULL, UE_HARDWARE_EXECUTE, UE_HARDWARE_SIZE_1, &OnDecrypted))
{
Log("[Error] Unable to set breakpoint on decryption code.");
Abort();
}
}
void __stdcall cUnpacker::OnDecrypted()
{
BYTE WildCard = 0xEE;
const BYTE LoadLibraryAPattern[] = {0xB9, 0xEE, 0xEE, 0xEE, 0xEE, 0x01, 0xE9, 0x83, 0x79, 0x0C, 0x00, 0x0F, 0x84, 0xEE, 0xEE, 0xEE, 0xEE, 0x8B, 0x59, 0x0C, 0x01, 0xEB, 0x51, 0x53, 0xFF, 0xD7, 0x59, 0x85, 0xC0};
/*
MOV ECX, XXXXXXXX
ADD ECX,EBP
CMP DWORD PTR DS:[ECX+C],0
JE XXXXXXXX
MOV EBX,DWORD PTR DS:[ECX+C]
0ADD EBX,EBP
PUSH ECX
PUSH EBX
CALL EDI
POP ECX
TEST EAX,EAX
*/
const BYTE GetProcAddressPattern[] = {0x8B, 0x07, 0x83, 0xC7, 0x04, 0xA9, 0x00, 0x00, 0x00, 0x80, 0x74, 0x08, 0x25, 0xFF, 0xFF, 0x00, 0x00, 0x50, 0xEB, 0x06, 0x01, 0xE8, 0x83, 0xC0, 0x02, 0x50, 0x53, 0xFF, 0xD6, 0x5A, 0x59, 0x85, 0xC0};
/*
MOV EAX,DWORD PTR DS:[EDI]
ADD EDI,4
TEST EAX,80000000
JE SHORT Nag_exeF.00404491
AND EAX,0FFFF
PUSH EAX
JMP SHORT Nag_exeF.00404497
ADD EAX,EBP
ADD EAX,2
PUSH EAX
PUSH EBX
CALL ESI
POP EDX
POP ECX
TEST EAX,EAX
*/
const size_t LoadLibraryABreakpointOffset = 24;
const size_t GetProcAddressBreakpointOffset = 27;
const BYTE OepPattern[] = {0x01, 0x2C, 0x24, 0xC3, 0x13, 0x13, 0x13, 0x13};
/*
ADD DWORD PTR SS:[ESP],EBP
RETN
ADC EDX,DWORD PTR DS:[EBX]
ADC EDX,DWORD PTR DS:[EBX]
*/
ULONG_PTR DecryptedCode = GetContextData(UE_CIP);
ULONG_PTR LoadLibraryACode = Find((void*)DecryptedCode, SFXSectionVA+SFXSectionSize-DecryptedCode, (void*)LoadLibraryAPattern, sizeof LoadLibraryAPattern, &WildCard);
ULONG_PTR GetProcAddressCode = Find((void*)DecryptedCode, SFXSectionVA+SFXSectionSize-DecryptedCode, (void*)GetProcAddressPattern, sizeof GetProcAddressPattern, NULL);
if(!LoadLibraryACode || !GetProcAddressCode)
{
Log("[Error] Cannot find imports handling code, probably not packed with a supported version?");
Abort();
return;
}
SetBPX(LoadLibraryACode + LoadLibraryABreakpointOffset, UE_BREAKPOINT, &OnLoadLibraryACall);
SetBPX(GetProcAddressCode + GetProcAddressBreakpointOffset, UE_BREAKPOINT, &OnGetProcAddressCall);
ULONG_PTR OepCode = Find((void*)DecryptedCode, SFXSectionVA+SFXSectionSize-DecryptedCode, (void*)OepPattern, sizeof OepPattern, NULL);
if(!OepCode)
{
Log("[Error] Cannot find OEP code, probably not packed with a supported version?");
Abort();
return;
}
SetBPX(OepCode, UE_BREAKPOINT, &OnOepCode);
}
void __stdcall cUnpacker::OnLoadLibraryACall()
{
/*
We're currently on the call to LoadLibraryA
To get the parameter pushed to the API, we need to decrease the index we pass to GetFunctionParameter by 1
This is because the return address has not yet been pushed to the stack and parameters are set off by one DWORD
*/
// Get name param pushed to LoadLibraryA
char* DLLName = (char*)GetFunctionParameter(lProcess->hProcess, UE_FUNCTION_STDCALL, 0, UE_PARAMETER_STRING);
// Add Dll (next call to ImporterAddNew[Ordinal]API sets first thunk)
ImporterAddNewDll(DLLName, NULL);
Log("[i] Imported DLL: %s", DLLName);
}
void __stdcall cUnpacker::OnGetProcAddressCall()
{
char APIName[iMaxString];
/*
Get second parameter pushed to GetProcAddress (API name or ordinal)
See OnGetModuleHandleACall as to why we use 1 instead of 2 for the index
*/
ULONG_PTR APIParam = GetFunctionParameter(lProcess->hProcess, UE_FUNCTION_STDCALL, 1, UE_PARAMETER_DWORD);
// Get address of IAT thunk for this API
// It is located at [ESP+8], we can use GetFunctionParameter to easily get its value
// since effectively it's the 3rd param
ULONG_PTR ThunkAddr = GetFunctionParameter(lProcess->hProcess, UE_FUNCTION_STDCALL, 2, UE_PARAMETER_DWORD);
if(!HIWORD(APIParam)) // Is this an ordinal API?
{
// Add ordinal API (pushed value = ordinal #)
ImporterAddNewOrdinalAPI(APIParam, ThunkAddr);
Log(" + [%08X]: #%d", ThunkAddr, APIParam);
}
else
{
// Add API name (pushed value = address to string)
GetRemoteString(lProcess->hProcess, (void*)APIParam, APIName, sizeof APIName);
ImporterAddNewAPI(APIName, ThunkAddr);
Log(" + [%08X]: %s", ThunkAddr, APIName);
}
}
void __stdcall cUnpacker::OnOepCode()
{
RemoveAllBreakPoints(UE_OPTION_REMOVEALL);
// Lazy man's way of getting the value at [ESP]
ULONG_PTR OEP = lPEInfo.ImageBase + GetFunctionParameter(lProcess->hProcess, UE_FUNCTION_STDCALL, 0, UE_PARAMETER_DWORD);
Log("[x] Reached OEP: %08X.", OEP);
// Dump the unpacked module to disk
if(!DumpProcess(lProcess->hProcess, (void*)lPEInfo.ImageBase, lOut, OEP))
{
Log("[Error] Cannot dump process.");
Abort();
return;
}
Log("[x] Dumping process.");
// Create a new import table from the data added through ImporterAddNewDll + ImporterAddNew[Ordinal]API
if(!ImporterExportIATEx(lOut, ".revlabs"))
{
Log("[Error] Cannot fix imports.");
Abort();
return;
}
Log("[x] Fixing imports.");
if(lRealign)
{
// Realign sections, shrink file size
if(!RealignPEEx(lOut, NULL, NULL))
{
Log("[Error] Realigning failed.");
Abort();
return;
}
Log("[x] Realigning file.");
}
if(lCopyOverlay)
{
// Copy overlay from the original file to the dump
if(CopyOverlay(lPath, lOut))
Log("[x] Copying overlay.");
else
Log("[x] No overlay found.");
}
StopDebug();
Log("[x] File successfully unpacked to %s.", lOut);
}
| [
"safin@smartdec.ru"
] | safin@smartdec.ru |
89fbcf507920f2b30fb05a0c221d7e1276c7f74c | a26fef3708b8f5308827cc9d8d25a520faf7a24c | /ManipulatorMain.ino | 29455008a1ce6ff6b18c12d1a830d13ec1648929 | [
"MIT"
] | permissive | igorgrebenev/ManipulatorMain | c3b44a2c75fc7e4814c7c26cdeb4b68e80d13bc1 | df22b016b0d2a58a74b840336a2191664df5c49b | refs/heads/master | 2020-04-10T23:15:14.387259 | 2019-02-13T01:05:25 | 2019-02-13T01:05:25 | 161,346,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | ino | // Maksim Grebenev 2018
#import "SGServo.h"
#import "ROT3U6DOF.h"
void setup() {
setupROT3U6DOF(0, 0); // 500-900Initialize servos ROT3U6DOF_SERVO_COUNT/ROT3U6DOF_SERVO_START_PORT
resetROT3U6DOF(); // установим кутяплю в исходное положение
delay(6000); // подождем 1 мин для прогрева потенцииометра
}
void loop() {
int positions00[] = {27, 65, 120, 180, 15, 20};
performAllServos(positions00);
int positions01[] = {UNDEFINED, 64, UNDEFINED, 131, UNDEFINED, UNDEFINED};
performAllServos(positions01);
int positions02[] = {UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, 70};
performAllServos(positions02);
int positions03[] = {UNDEFINED, 90, 45, UNDEFINED, UNDEFINED, UNDEFINED};
performAllServos(positions03);
int positions04[] = {142, 0, 102, 0, 0, UNDEFINED};
performAllServos(positions04);
// бросить шарик
int positions05[] = {UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, 20};
performAllServos(positions05);
// подготовка у подъему манипулятора
int positions06a[] = {UNDEFINED, UNDEFINED, 0, 0, UNDEFINED, UNDEFINED};
performAllServos(positions06a);
int positions06[] = {UNDEFINED, 90, 45, 20, UNDEFINED, UNDEFINED};
performAllServos(positions06);
delay(3000);
}
| [
"igor.grebenev@quantumsoft.ru"
] | igor.grebenev@quantumsoft.ru |
f96475a3d34bb906414217396da8d46db9dad585 | 947a4b48f592700a06cb332758ef8406a3808809 | /banking_system_step7_v0.7/Account.h | 2110055cae1ce2bed64eccec40c79533528d8947 | [] | no_license | 95kim1/banking-system | b5da741a6aa4f11164c326ff1d76da01e9f23da3 | 78d79969840310a04e97f3a771efea2ef670e0e7 | refs/heads/main | 2023-08-01T11:36:57.642701 | 2021-09-06T14:01:56 | 2021-09-06T14:01:56 | 401,977,902 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 825 | h | /*
* 파일이름: Account.h
* 작성자: sh.kim
* 업데이트 정보: [2021, 09, 04] 파일버전 0.7
*/
#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__
/*
* 클래스명: Account
* 유형: Entity class
*/
class Account
{
int mId; // 계좌번호
unsigned long long mBalance; // 계좌잔액
char* mName; // 고객이름
public:
Account(const int id, const unsigned long long balance, const char* name);
Account(const Account& accunt);
~Account();
int GetId() const;
unsigned long long GetBalance() const;
char* GetName() const;
void SetId(const int id);
void SetBalance(const unsigned long long balance);
void SetName(const char* name);
virtual void DepositeMoney(const unsigned long long money);
void WithdrawMoney(const unsigned long long money);
virtual void ShowInfo();
};
#endif
| [
"95kim1@naver.com"
] | 95kim1@naver.com |
07f40104e025217a721eb5dffa9222e3c851b1bf | a73d4adcd66759fa67bc9e55c770b56b3ab5471b | /tutes/tute01/extra-q2.cpp | 2db6fb86f15073aa767490ef0b064495d210a960 | [] | no_license | patrick-forks/cs6771 | 1695d0ee530a782ffc4c5683ba469291966aade8 | f70373b71da44faf169521bc8068847cc76ab91c | refs/heads/master | 2023-04-09T02:35:38.456908 | 2016-10-31T12:44:56 | 2016-10-31T12:44:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 200 | cpp | #include <iostream>
int i;
int f() { return i++; }
int g() { return i == 1 ? i + 3 : i - 1; }
int h() { return i == 2 ? i - 3 : i + 2; }
int main() {
std::cout << f() + g() * h() << std::endl;
}
| [
"jessqnnguyen@gmail.com"
] | jessqnnguyen@gmail.com |
c1a9202af8e5412d41bbb57ba8d2809acea262ed | 1afb5e6cf8d6638a43e352a941fdb51161494c83 | /Assignment2/HighScoreManager.h | 6e346eb51249e5f342f70d41b24f300a94697a02 | [] | no_license | Sukhmanbir/Assignment2 | 4064271a7132b1c27ce93910840b766f1d5ff34a | 1dc57ff03ab31426fad348ee71178c633d485193 | refs/heads/master | 2021-01-09T20:40:03.472621 | 2016-07-19T01:36:08 | 2016-07-19T01:36:08 | 63,277,343 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 238 | h | #pragma once
#include <string>
using namespace std;
class HighScoreManager {
public:
void createHighScore();
void updateHighScore();
void printHighScore();
private:
struct user {
string username;
int score;
string date;
};
}; | [
"code@douglasbrunner.name"
] | code@douglasbrunner.name |
01f79fbab6e5b6605209beeb2e399a8e059e1b82 | f71fe728904863239420d52a11f6972240166c11 | /Lib/src/tim.cpp | 75ffc031971b5c88431229d645fa69ea34846bf8 | [
"Apache-2.0"
] | permissive | joson1/thunderlib32-AC6 | 1ccc3bd1ec2e7f3b6d1e2c7b2d69335e7be61d54 | d3e551eb3d4aada0bfdd0a129349e25dd7400584 | refs/heads/master | 2020-04-17T14:46:07.515133 | 2019-04-15T13:58:32 | 2019-04-15T13:58:32 | 166,671,006 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,749 | cpp | #include "tim.h"
#include "STDDEF.H"
void (*TIM2_update_Irq)() = NULL;
void (*TIM3_update_Irq)() = NULL;
void (*TIM4_update_Irq)() = NULL;
void (*TIM5_update_Irq)() = NULL;
void (*TIM6_update_Irq)() = NULL;
void (*TIM7_update_Irq)() = NULL;
TIM::TIM(TIM_TypeDef* TIMn)
{
}
TIM::TIM()
{
}
TIM::~TIM()
{
}
void TIM::set_Remap(uint16_t Remap)
{
if((uint32_t)this->TIMn<(uint32_t)APB2PERIPH_BASE)
{
uint8_t timx = ((uint32_t)this->TIMn - (uint32_t)0x40000000) >>10;
switch (timx)
{
case 0:
AFIO->MAPR &= ~(Remap<<8);
AFIO->MAPR |= (Remap<<8);
break;
case 1:
AFIO->MAPR &= ~(Remap<<10);
AFIO->MAPR |= (Remap<<10);
break;
case 2:
AFIO->MAPR &= ~(Remap<<12);
AFIO->MAPR |= (Remap<<12);
break;
case 3:
AFIO->MAPR &= ~(Remap<<16);
AFIO->MAPR |= (Remap<<16);
break;
default:
break;
}
}else
{
AFIO->MAPR &= ~(Remap<<6);
AFIO->MAPR |= (Remap<<6);
}
}
void TIM::set_Remap(TIM_TypeDef* TIMn,uint16_t Remap)
{
if((uint32_t)TIMn<(uint32_t)APB2PERIPH_BASE)
{
uint8_t timx = ((uint32_t)TIMn - (uint32_t)0x40000000) >>10;
switch (timx)
{
case 0:
AFIO->MAPR &= ~(Remap<<8);
AFIO->MAPR |= (Remap<<8);
break;
case 1:
AFIO->MAPR &= ~(Remap<<10);
AFIO->MAPR |= (Remap<<10);
break;
case 2:
AFIO->MAPR &= ~(Remap<<12);
AFIO->MAPR |= (Remap<<12);
break;
case 3:
AFIO->MAPR &= ~(Remap<<16);
AFIO->MAPR |= (Remap<<16);
break;
default:
break;
}
}else
{
AFIO->MAPR &= ~(Remap<<6);
AFIO->MAPR |= (Remap<<6);
}
}
extern "C"{
void TIM2_IRQHandler()
{
if((TIM2->SR)&0X0001)
{
(*TIM2_update_Irq)();
}
TIM2->SR &= 0XFFFE;
}
void TIM3_IRQHandler()
{
if(TIM3->SR&0x0001)
{
(*TIM3_update_Irq)();
}
TIM3->SR &= 0XFFFE;
}
void TIM4_IRQHandler()
{
if(TIM4->SR & 0x0001)
{
(*TIM4_update_Irq)();
}
TIM4->SR &= 0XFFFE;
}
void TIM5_IRQHandler()
{
if(TIM5->SR&0x0001)
{
(*TIM5_update_Irq)();
}
TIM5->SR &= 0XFFFE;
}
void TIM6_IRQHandler()
{
if(TIM6->SR & 0x0001)
{
(*TIM6_update_Irq)();
}
TIM6->SR &= 0XFFFE;
}
void TIM7_IRQHandler()
{
if(TIM7->SR & 0x0001)
{
(*TIM7_update_Irq)();
}
TIM7->SR &= 0XFFFE;
}
}
| [
"wjy1063896722@outlook.com"
] | wjy1063896722@outlook.com |
55f7426e010878ebaa36c45ded778ae5fcbf818e | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/mutt/gumtree/mutt_repos_function_1997_mutt-1.7.2.cpp | 38734f00eac107895199bc6aeedd12f2b6c3abbf | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220 | cpp | void imap_munge_mbox_name (IMAP_DATA *idata, char *dest, size_t dlen, const char *src)
{
char *buf;
buf = safe_strdup (src);
imap_utf_encode (idata, &buf);
imap_quote_string (dest, dlen, buf);
FREE (&buf);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
e988b195f3a55f2edcb4b978a4c459cfcf323261 | cc126b413c764161648e00e61c3a32c92ce65572 | /tests/mt_session_unittest.cpp | 61c4d0de9e524b8588449e979be1d8ccf07ac546 | [] | no_license | LiKun-8/sthread | 6b5fc6ebe3377d6b85aa37e524179584d352d9a6 | 64766a692c17228d29a366a3f585bfbdf963d5af | refs/heads/master | 2020-07-11T23:42:33.511576 | 2019-05-11T09:51:10 | 2019-05-11T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | cpp | #include "gtest/googletest/include/gtest/gtest.h"
#include "../include/mt_ext.h"
MTHREAD_NAMESPACE_USING
TEST(SessionTest, session)
{
}
// 测试所有的功能
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | [
"zhoulv2000@163.com"
] | zhoulv2000@163.com |
03003e8014899fe5903ade8629d30b869c3c3df9 | 87ff77a23c76065db79b12687926024be6d086ab | /jrTest12/InitDataManager.cpp | 741fc4d4646aa28da8d0542d67d149ed134e9bf5 | [] | no_license | lesbox/jrTest12_2.10.0 | b3030e7a250ad419190afa2acd1f4568635b44f3 | ece8f2d903e2e73870d4c4393f2ae3db258d2c77 | refs/heads/master | 2021-01-19T19:02:18.041612 | 2017-04-18T07:21:49 | 2017-04-18T07:21:49 | 88,393,490 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,644 | cpp | #include "InitDataManager.h"
MiniShipCard::MiniShipCard() {
this->cid = 0;
this->type = 0;
this->evoCid = 0;
this->evoToCid = 0;
this->repairOilModulus = 0;
this->repairSteelModulus = 0;
this->repairTime = 0;
}
MiniShipCard::~MiniShipCard() {
}
bool MiniShipCard::fromQJsonObject(QJsonObject data, ErrorManager & errorManager) {
int flagTemp;
int valueTemp;
this->cid = (int)getDoubleFromQJsonObject(data, "cid", flagTemp);
if (flagTemp != 0) {
errorManager.pushErrorInfo("cid");
return false;
}
this->type = (int)getDoubleFromQJsonObject(data, "type", flagTemp);
if (flagTemp != 0) {
errorManager.pushErrorInfo("type");
return false;
}
this->dismantle.clear();
if (data.contains("dismantle")) {
QJsonObject dismantle = data["dismantle"].toObject();
bool flagTemp1;
int valueTemp1;
for each(QString key in dismantle.keys()) {
valueTemp1 = key.toInt(&flagTemp1);
if (flagTemp1 == false) {
errorManager.pushErrorInfo(key);
errorManager.pushErrorInfo("dismantle");
return false;
}
valueTemp = (int)getDoubleFromQJsonObject(dismantle, key, flagTemp);
if (flagTemp != 0) {
errorManager.pushErrorInfo(key);
errorManager.pushErrorInfo("dismantle");
return false;
}
this->dismantle.insert(valueTemp1, valueTemp);
}
}
this->evoCid = (int)getDoubleFromQJsonObject(data, "evoCid", flagTemp);
if (flagTemp == 1) {
errorManager.pushErrorInfo("evoCid");
return false;
}
this->evoToCid = (int)getDoubleFromQJsonObject(data, "evoToCid", flagTemp);
if (flagTemp == 1) {
errorManager.pushErrorInfo("evoToCid");
return false;
}
this->repairOilModulus = getDoubleFromQJsonObject(data, "repairOilModulus", flagTemp);
if (flagTemp == 1) {
errorManager.pushErrorInfo("repairOilModulus");
return false;
}
this->repairSteelModulus = getDoubleFromQJsonObject(data, "repairSteelModulus", flagTemp);
if (flagTemp == 1) {
errorManager.pushErrorInfo("repairSteelModulus");
return false;
}
this->repairTime = getDoubleFromQJsonObject(data, "repairTime", flagTemp);
if (flagTemp == 1) {
errorManager.pushErrorInfo("repairTime");
return false;
}
return true;
}
MiniGlobalConfig::MiniGlobalConfig() {
}
MiniGlobalConfig::~MiniGlobalConfig() {
}
bool MiniGlobalConfig::fromQJsonObject(QJsonObject data, ErrorManager & errorManager) {
int flagTemp;
int valueTemp;
this->resourceRecoveryTime.clear();
if (!data.contains("resourceRecoveryTime") || !data["resourceRecoveryTime"].isArray()) {
errorManager.pushErrorInfo("resourceRecoveryTime");
return false;
}
else {
QJsonArray resourceRecoveryTime = data["resourceRecoveryTime"].toArray();
for (int count = 0; count < resourceRecoveryTime.size(); count++) {
valueTemp = (int)getDoubleFromQJsonValueRef(resourceRecoveryTime[count], flagTemp);
if (flagTemp != 0) {
return false;
}
this->resourceRecoveryTime.append(valueTemp);
}
}
this->resourceRecoveryNum.clear();
if (!data.contains("resourceRecoveryNum") || !data["resourceRecoveryNum"].isArray()) {
errorManager.errorInfo = "resourceRecoveryNum";
return false;
}
else {
QJsonArray resourceRecoveryNum = data["resourceRecoveryNum"].toArray();
for (int count = 0; count < resourceRecoveryNum.size(); count++) {
valueTemp = (int)getDoubleFromQJsonValueRef(resourceRecoveryNum[count], flagTemp);
if (flagTemp != 0) {
errorManager.pushErrorInfo(QString::number(count));
errorManager.pushErrorInfo("resourceRecoveryNum/");
return false;
}
this->resourceRecoveryNum.append(valueTemp);
}
}
return true;
}
MiniInitDataManager::MiniInitDataManager() {
}
MiniInitDataManager::~MiniInitDataManager() {
}
bool MiniInitDataManager::fromQJsonObject(QJsonObject data, ErrorManager & errorManager) {
int flagTemp;
int valueTemp;
this->shipCard.clear();
if (!data.contains("shipCard") || !data["shipCard"].isArray()) {
errorManager.errorInfo = "shipCard";
return false;
}
else {
QJsonArray shipCard = data["shipCard"].toArray();
MiniShipCard shipCardTemp;
for (int count = 0; count < shipCard.size(); count++) {
if (!shipCard[count].isObject()) {
errorManager.pushErrorInfo(QString::number(count));
errorManager.pushErrorInfo("shipCard");
return false;
}
if (false == shipCardTemp.fromQJsonObject(shipCard[count].toObject(), errorManager)) {
errorManager.pushErrorInfo(QString::number(count));
errorManager.pushErrorInfo("shipCard");
return false;
}
this->shipCard.insert(shipCardTemp.cid, shipCardTemp);
}
}
if (!data.contains("globalConfig") || !data["globalConfig"].isObject()) {
errorManager.pushErrorInfo("globalConfig");
return false;
}
else {
if (false == this->globalConfig.fromQJsonObject(data["globalConfig"].toObject(), errorManager)) {
errorManager.pushErrorInfo("globalConfig");
return false;
}
}
this->errorCode.clear();
if (!data.contains("errorCode") || !data["errorCode"].isObject()) {
errorManager.errorInfo = "errorCode";
return false;
}
else {
QJsonObject errorCode = data["errorCode"].toObject();
int keyValueTemp;
QString stringValueTemp;
bool flagTemp1;
for each(QString key in errorCode.keys()) {
keyValueTemp = key.toInt(&flagTemp1);
if (flagTemp1 == false) {
errorManager.pushErrorInfo(key);
errorManager.pushErrorInfo("errorCode");
return false;
}
stringValueTemp = getStringFromQJsonObject(errorCode, key, flagTemp);
if (flagTemp != 0) {
errorManager.pushErrorInfo(key);
errorManager.pushErrorInfo("errorCode");
return false;
}
this->errorCode.insert(keyValueTemp, stringValueTemp);
}
}
return true;
} | [
"pwwndg@gmail.com"
] | pwwndg@gmail.com |
9be704bfadf8b6b654d997f70ef19893afce170f | 9097a08fa13a298a0c47abaed6b253597f926310 | /Lab 1/Class carpool.cpp | 89d75232f446cbf74927053ff902cd72ddcc2051 | [] | no_license | andrewkaldani/CS60lab | 2ea6f8890224f424c5eefca54bd4adedbf470d42 | 55ed901e2cdc52688f56db614b78497199682ff2 | refs/heads/master | 2021-07-30T21:14:08.181167 | 2021-07-20T23:56:57 | 2021-07-20T23:56:57 | 238,364,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
struct Time{//military time, no am/pm
int hour;
int minute;
};
Time earlier(Time t1, Time t2){
Time ret;
if(t1.hour == t2.hour){
if(t1.minute<t2.minute)
ret = t1;
else
ret = t2;
}
else if(t1.hour<t2.hour){
ret = t1;
}
else{
ret = t2;
}
return ret;
}
class Carpool{
public:
int numPeople;
string group[10];
Time arrive;
void combineCarpool(Carpool car1, Carpool car2)
{
if(car1.numPeople + car2.numPeople <= 5){
int n = 0;
arrive = earlier(car1.arrive, car2.arrive);
numPeople = car1.numPeople + car2.numPeople;
for(int i = 0; i <= car1.numPeople; i++){
group[i]=car1.group[i];
}
for(int i = car1.numPeople; i <= 5; i++){
group[i]=car2.group[n];
n++;
}
}
else if(car1.numPeople + car2.numPeople > 5){
std::cout << "Carpool to big fam" << '\n';
}
}
void printName(){
for(int i = 0; i <= 5; i++){
std::cout << group[i] << '\n';
}
}
};
int main(){
Carpool car1;
Carpool car2;
Carpool car3;
car1.group[0]="Olaf";
car1.group[1]="Sven";
car2.group[0]="Will";
car2.group[1]= "Steve";
car2.group[2]="Jeff";
car1.arrive.hour = 7;
car1.arrive.minute = 20;
car2.arrive.hour= 6;
car2.arrive.minute = 35;
car1.numPeople = 2;
car2.numPeople = 3;
car3.combineCarpool(car1, car2);
std::cout << car3.numPeople << '\n';
car3.printName();
}
| [
"noreply@github.com"
] | andrewkaldani.noreply@github.com |
a41de61a403a4e956df0e02fe0676cc65a4e3816 | 897ef84932251c57a790b75b1410a147b9b64792 | /sysexevent.cpp | db0df88841ea5efb02e5a9677b74b12651df66eb | [] | no_license | erophames/CamX | a92b789d758e514d43e6fd676dbb9eed1b7b3468 | 56b08ed02d976621f538feca10e1aaa58926aa5a | refs/heads/master | 2021-06-21T21:14:27.776691 | 2017-07-22T11:46:09 | 2017-07-22T11:46:09 | 98,467,657 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,404 | cpp | Seq_Event *SysEx::CloneNewAndSortToPattern(MidiPattern *p)
{
SysEx *newsys=(SysEx *)CloneNew();
if(newsys)
{
p->AddSortEvent(newsys);
if(sysexend.pattern)
{
p->AddSortVirtual(&newsys->sysexend);
newsys->sysexend.pattern=p;
}
}
return newsys;
}
Seq_Event *SysEx::CloneNewAndSortToPattern(MidiPattern *p,long diff)
{
SysEx *newsys=(SysEx *)CloneNew();
if(newsys)
{
newsys->objectstart+=diff;
newsys->sysexend.objectstart+=diff;
newsys->staticstartposition+=diff;
newsys->sysexend.staticstartposition+=diff;
p->AddSortEvent(newsys);
if(sysexend.pattern)
{
p->AddSortVirtual(&newsys->sysexend);
newsys->sysexend.pattern=p;
}
}
return newsys;
}
void SysEx::DeleteFromPattern()
{
pattern->events.DeleteObject(this); // Remove from Event list
if(sysexend.pattern)
{
pattern->DeleteVirtual(&sysexend);
sysexend.pattern=0;
}
}
void SysEx::CalcSysTicks()
{
if(data && length && mainmidi.baudrate)
{
double h=mainmidi.baudrate;
double h2=length;
// start/stopbits ->bytes/sec
h/=10;
h/=h2;
// h2=ms
ticklength=mainvar.ConvertMilliSecToTicks(h);
}
else
ticklength=0;
}
void SysEx::CheckSysExEnd()
{
if(ticklength>=16) // add virtual 0xF7
{
pattern->AddSortVirtual(&sysexend,objectstart+ticklength);
}
else
{
if(sysexend.pattern)
{
pattern->DeleteVirtual(&sysexend);
sysexend.pattern=0;
}
}
}
| [
"matthieu.brucher@gmail.com"
] | matthieu.brucher@gmail.com |
6ab49fe29655583a2e7bff96344b2cb5bbff279a | 370c147753310d348fef4e16ae4b31ee07be0acd | /src/test/test_common.h | 79d419dd64b6e024e55351ebb85f1776ed55c229 | [] | no_license | rushad/filetransfer | c4971de66a4e2d78135c7641e2696963068815df | 13ded7c6444daf5a0f3cb1c3569c73f4f6ffc321 | refs/heads/master | 2020-05-15T19:56:09.089811 | 2014-02-07T12:20:24 | 2014-02-07T12:20:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,741 | h | #pragma once
#include "../observer.h"
#include "../progress_calculator.h"
#include "../queue.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
#include <string>
namespace FileTransfer
{
namespace Test
{
using boost::posix_time::ptime;
using boost::posix_time::millisec;
const size_t CHUNK_SIZE = 100;
const unsigned CHUNK_DELAY = 2;
const unsigned CHUNK_NUMBER = 10;
static ptime CurrentTime()
{
return boost::posix_time::microsec_clock::universal_time();
}
static void usleep(unsigned ms)
{
boost::this_thread::sleep_for(boost::chrono::milliseconds(ms));
}
static Queue::Chunk MakeChunk(const std::string& str)
{
Queue::Chunk chunk(str.size());
chunk.assign(str.data(), str.data() + str.size());
return chunk;
}
static Queue::Chunk MakeChunk(const Queue::Chunk& chunk1, const Queue::Chunk& chunk2)
{
Queue::Chunk chunk(chunk1);
chunk.insert(chunk.end(), chunk2.begin(), chunk2.end());
return chunk;
}
class FakeObserver : public Observer
{
public:
virtual void UpdateProgress(const unsigned dlPerc, const unsigned ulPerc)
{
DlProgress = dlPerc;
UlProgress = ulPerc;
}
unsigned DlProgress;
unsigned UlProgress;
typedef boost::shared_ptr<FakeObserver> Ptr;
};
class FakeProgressCalculator : public ProgressCalculator
{
public:
FakeProgressCalculator()
: Calls(0)
{
}
virtual void Calculate()
{
++Calls;
}
public:
unsigned Calls;
};
}
} | [
"rushad@bk.ru"
] | rushad@bk.ru |
6f910ff0e839dfd20098818417cf896a999e2fb6 | 2fa54a1de361602fae80fa8a76ff2052f238223c | /squarefactory.cpp | aa040aad0d73fb5fa03499bc740a10ddcc55b0f0 | [] | no_license | rlmaso2/Shape_Factory | 660d656e9ca959265a742bbc49916d4d8937409f | e740a7ef8a94428b003ac67106314d018d0a3f57 | refs/heads/master | 2020-04-05T23:45:42.940631 | 2015-07-15T19:49:26 | 2015-07-15T19:49:26 | 39,095,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 388 | cpp | #include "squarefactory.h"
#include <cassert>
static SquareFactory squareFactory;
SquareFactory::SquareFactory() {
ShapeFactory::registerShape("square", this);
}
Square* SquareFactory::createShape(const QDomElement& element) const {
assert(!element.isNull());
assert(element.tagName()=="square");
Square* square = new Square(element);
return square;
} | [
"Ricky.Mason@BionicInnovations.com"
] | Ricky.Mason@BionicInnovations.com |
33e844320b7c9866b0432e6148f6d63ec959bd4a | 0da071c412415402b669bc3733e36058f4fd1877 | /src/ListViewGroups.h | a509f082a83c87e2f0fc8af21d65e2c467dfd1fb | [
"MIT"
] | permissive | Michael-prog/ExplorerListView | 3d50d4e09bfdff06e06b9b80f62075a942b07644 | 8bc0299b7d58def5393527f518fd857f5122b42d | refs/heads/master | 2022-01-25T09:02:24.411107 | 2019-02-27T19:43:42 | 2019-02-27T19:43:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,208 | h | //////////////////////////////////////////////////////////////////////
/// \class ListViewGroups
/// \author Timo "TimoSoft" Kunze
/// \brief <em>Manages a collection of \c ListViewGroup objects</em>
///
/// This class provides easy access to collections of \c ListViewGroup objects. A \c ListViewGroups
/// object is used to group the control's groups.
///
/// \remarks Requires comctl32.dll version 6.0 or higher.
///
/// \if UNICODE
/// \sa ExLVwLibU::IListViewGroups, ListViewGroup, ExplorerListView
/// \else
/// \sa ExLVwLibA::IListViewGroups, ListViewGroup, ExplorerListView
/// \endif
//////////////////////////////////////////////////////////////////////
#pragma once
#include "res/resource.h"
#ifdef UNICODE
#include "ExLVwU.h"
#else
#include "ExLVwA.h"
#endif
#include "_IListViewGroupsEvents_CP.h"
#include "helpers.h"
#include "ExplorerListView.h"
#include "ListViewGroup.h"
class ATL_NO_VTABLE ListViewGroups :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<ListViewGroups, &CLSID_ListViewGroups>,
public ISupportErrorInfo,
public IConnectionPointContainerImpl<ListViewGroups>,
public Proxy_IListViewGroupsEvents<ListViewGroups>,
public IEnumVARIANT,
#ifdef UNICODE
public IDispatchImpl<IListViewGroups, &IID_IListViewGroups, &LIBID_ExLVwLibU, /*wMajor =*/ VERSION_MAJOR, /*wMinor =*/ VERSION_MINOR>
#else
public IDispatchImpl<IListViewGroups, &IID_IListViewGroups, &LIBID_ExLVwLibA, /*wMajor =*/ VERSION_MAJOR, /*wMinor =*/ VERSION_MINOR>
#endif
{
friend class ExplorerListView;
friend class ClassFactory;
public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
DECLARE_REGISTRY_RESOURCEID(IDR_LISTVIEWGROUPS)
BEGIN_COM_MAP(ListViewGroups)
COM_INTERFACE_ENTRY(IListViewGroups)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(IConnectionPointContainer)
COM_INTERFACE_ENTRY(IEnumVARIANT)
END_COM_MAP()
BEGIN_CONNECTION_POINT_MAP(ListViewGroups)
CONNECTION_POINT_ENTRY(__uuidof(_IListViewGroupsEvents))
END_CONNECTION_POINT_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
#endif
//////////////////////////////////////////////////////////////////////
/// \name Implementation of ISupportErrorInfo
///
//@{
/// \brief <em>Retrieves whether an interface supports the \c IErrorInfo interface</em>
///
/// \param[in] interfaceToCheck The IID of the interface to check.
///
/// \return \c S_OK if the interface identified by \c interfaceToCheck supports \c IErrorInfo;
/// otherwise \c S_FALSE.
///
/// \sa <a href="https://msdn.microsoft.com/en-us/library/ms221233.aspx">IErrorInfo</a>
virtual HRESULT STDMETHODCALLTYPE InterfaceSupportsErrorInfo(REFIID interfaceToCheck);
//@}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// \name Implementation of IEnumVARIANT
///
//@{
/// \brief <em>Clones the \c VARIANT iterator used to iterate the groups</em>
///
/// Clones the \c VARIANT iterator including its current state. This iterator is used to iterate
/// the \c ListViewGroup objects managed by this collection object.
///
/// \param[out] ppEnumerator Receives the clone's \c IEnumVARIANT implementation.
///
/// \return An \c HRESULT error code.
///
/// \sa Next, Reset, Skip,
/// <a href="https://msdn.microsoft.com/en-us/library/ms221053.aspx">IEnumVARIANT</a>,
/// <a href="https://msdn.microsoft.com/en-us/library/ms690336.aspx">IEnumXXXX::Clone</a>
virtual HRESULT STDMETHODCALLTYPE Clone(IEnumVARIANT** ppEnumerator);
/// \brief <em>Retrieves the next x groups</em>
///
/// Retrieves the next \c numberOfMaxItems groups from the iterator.
///
/// \param[in] numberOfMaxItems The maximum number of groups the array identified by \c pItems can
/// contain.
/// \param[in,out] pItems An array of \c VARIANT values. On return, each \c VARIANT will contain
/// the pointer to a group's \c IListViewGroup implementation.
/// \param[out] pNumberOfItemsReturned The number of groups that actually were copied to the array
/// identified by \c pItems.
///
/// \return An \c HRESULT error code.
///
/// \sa Clone, Reset, Skip, ListViewGroup,
/// <a href="https://msdn.microsoft.com/en-us/library/ms695273.aspx">IEnumXXXX::Next</a>
virtual HRESULT STDMETHODCALLTYPE Next(ULONG numberOfMaxItems, VARIANT* pItems, ULONG* pNumberOfItemsReturned);
/// \brief <em>Resets the \c VARIANT iterator</em>
///
/// Resets the \c VARIANT iterator so that the next call of \c Next or \c Skip starts at the first
/// group in the collection.
///
/// \return An \c HRESULT error code.
///
/// \sa Clone, Next, Skip,
/// <a href="https://msdn.microsoft.com/en-us/library/ms693414.aspx">IEnumXXXX::Reset</a>
virtual HRESULT STDMETHODCALLTYPE Reset(void);
/// \brief <em>Skips the next x groups</em>
///
/// Instructs the \c VARIANT iterator to skip the next \c numberOfItemsToSkip groups.
///
/// \param[in] numberOfItemsToSkip The number of groups to skip.
///
/// \return An \c HRESULT error code.
///
/// \sa Clone, Next, Reset,
/// <a href="https://msdn.microsoft.com/en-us/library/ms690392.aspx">IEnumXXXX::Skip</a>
virtual HRESULT STDMETHODCALLTYPE Skip(ULONG numberOfItemsToSkip);
//@}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// \name Implementation of IListViewGroups
///
//@{
/// \brief <em>Retrieves a \c ListViewGroup object from the collection</em>
///
/// Retrieves a \c ListViewGroup object from the collection that wraps the listview group identified
/// by \c groupIdentifier.
///
/// \param[in] groupIdentifier A value that identifies the listview group to be retrieved.
/// \param[in] groupIdentifierType A value specifying the meaning of \c groupIdentifier. Any of the
/// values defined by the \c GroupIdentifierTypeConstants enumeration is valid.
/// \param[out] ppGroup Receives the group's \c IListViewGroup implementation.
///
/// \return An \c HRESULT error code.
///
/// \remarks This property is read-only.
///
/// \if UNICODE
/// \sa ListViewGroup, Add, Remove, Contains, ExLVwLibU::GroupIdentifierTypeConstants
/// \else
/// \sa ListViewGroup, Add, Remove, Contains, ExLVwLibA::GroupIdentifierTypeConstants
/// \endif
virtual HRESULT STDMETHODCALLTYPE get_Item(LONG groupIdentifier, GroupIdentifierTypeConstants groupIdentifierType = gitID, IListViewGroup** ppGroup = NULL);
/// \brief <em>Retrieves a \c VARIANT enumerator</em>
///
/// Retrieves a \c VARIANT enumerator that may be used to iterate the \c ListViewGroup objects
/// managed by this collection object. This iterator is used by Visual Basic's \c For...Each
/// construct.
///
/// \param[out] ppEnumerator Receives the iterator's \c IEnumVARIANT implementation.
///
/// \return An \c HRESULT error code.
///
/// \remarks This property is read-only and hidden.
///
/// \sa <a href="https://msdn.microsoft.com/en-us/library/ms221053.aspx">IEnumVARIANT</a>
virtual HRESULT STDMETHODCALLTYPE get__NewEnum(IUnknown** ppEnumerator);
/// \brief <em>Adds a group to the listview</em>
///
/// Adds a group with the specified properties at the specified position in the control and returns a
/// \c ListViewGroup object wrapping the inserted group.
///
/// \param[in] groupHeaderText The new group's header text. The number of characters in this text
/// is not limited.
/// \param[in] groupID The new group's ID. It must be unique and can't be set to -1.
/// \param[in] insertAt The new group's zero-based index. If set to -1, the group will be inserted
/// as the last group.
/// \param[in] virtualItemCount If the listview control is in virtual mode, this parameter specifies
/// the number of items in the new group.
/// \param[in] headerAlignment The alignment of the new group's header text. Any of the values
/// defined by the \c AlignmentConstants enumeration is valid.
/// \param[in] iconIndex The zero-based index of the new group's header icon in the control's
/// \c ilGroups imagelist. If set to -1, the group header doesn't contain an icon.
/// \param[in] collapsible If \c VARIANT_TRUE, the new group can be collapsed by the user.
/// \param[in] collapsed If \c VARIANT_TRUE, the new group is collapsed.
/// \param[in] groupFooterText The new group's footer text. The number of characters in this text
/// is not limited.
/// \param[in] footerAlignment The alignment of the new group's footer text. Any of the values
/// defined by the \c AlignmentConstants enumeration is valid.
/// \param[in] subTitleText The new group's subtitle text. The maximum number of characters in this
/// text is defined by \c MAX_GROUPSUBTITLETEXTLENGTH.
/// \param[in] taskText The new group's task link text. The maximum number of characters in this
/// text is defined by \c MAX_GROUPTASKTEXTLENGTH.
/// \param[in] subsetLinkText The text displayed as a link below the new group if not all items of the
/// group are displayed. The maximum number of characters in this text is defined by
/// \c MAX_GROUPSUBSETLINKTEXTLENGTH.
/// \param[in] subseted If \c VARIANT_TRUE, the control displays only a subset of the new group's items
/// if the control is not large enough to display all items without scrolling.
/// \param[in] showHeader If \c VARIANT_FALSE, the new group's header is not displayed.
/// \param[out] ppAddedGroup Receives the added group's \c IListViewGroup implementation.
///
/// \return An \c HRESULT error code.
///
/// \remarks The \c virtualItemCount, \c iconIndex, \c collapsible, \c collapsed, \c groupFooterText,
/// \c footerAlignment, \c subTitleText, \c taskText, \c subsetLinkText, \c subseted and
/// \c showHeader parameters are ignored if comctl32.dll is used in a version older than 6.10.\n
/// The \c virtualItemCount parameter is ignored if the control is not in virtual mode.
///
/// \if UNICODE
/// \sa Count, Remove, RemoveAll, ListViewGroup::get_Text, ListViewGroup::get_ID,
/// ListViewGroup::get_Position, ListViewGroup::get_ItemCount, ExplorerListView::get_VirtualMode,
/// ListViewGroup::get_Alignment, ExLVwLibU::AlignmentConstants, ListViewGroup::get_IconIndex,
/// ExplorerListView::get_hImageList, ExLVwLibU::ImageListConstants,
/// ListViewGroup::get_Collapsible, ListViewGroup::get_Collapsed, ListViewGroup::get_SubtitleText,
/// ListViewGroup::get_TaskText, ListViewGroup::get_SubsetLinkText, ListViewGroup::get_Subseted,
/// ListViewGroup::get_ShowHeader
/// \else
/// \sa Count, Remove, RemoveAll, ListViewGroup::get_Text, ListViewGroup::get_ID,
/// ListViewGroup::get_Position, ListViewGroup::get_ItemCount, ExplorerListView::get_VirtualMode,
/// ListViewGroup::get_Alignment, ExLVwLibA::AlignmentConstants ListViewGroup::get_IconIndex,
/// ExplorerListView::get_hImageList, ExLVwLibA::ImageListConstants,
/// ListViewGroup::get_Collapsible, ListViewGroup::get_Collapsed, ListViewGroup::get_SubtitleText,
/// ListViewGroup::get_TaskText, ListViewGroup::get_SubsetLinkText, ListViewGroup::get_Subseted,
/// ListViewGroup::get_ShowHeader
/// \endif
virtual HRESULT STDMETHODCALLTYPE Add(BSTR groupHeaderText, LONG groupID, LONG insertAt = -1, LONG virtualItemCount = 1, AlignmentConstants headerAlignment = alLeft, LONG iconIndex = -1, VARIANT_BOOL collapsible = VARIANT_FALSE, VARIANT_BOOL collapsed = VARIANT_FALSE, BSTR groupFooterText = L"", AlignmentConstants footerAlignment = alLeft, BSTR subTitleText = L"", BSTR taskText = L"", BSTR subsetLinkText = L"", VARIANT_BOOL subseted = VARIANT_FALSE, VARIANT_BOOL showHeader = VARIANT_TRUE, IListViewGroup** ppAddedGroup = NULL);
/// \brief <em>Retrieves whether the specified group is part of the group collection</em>
///
/// \param[in] groupIdentifier A value that identifies the group to be checked.
/// \param[in] groupIdentifierType A value specifying the meaning of \c groupIdentifier. Any of the
/// values defined by the \c GroupIdentifierTypeConstants enumeration is valid.
/// \param[out] pValue \c VARIANT_TRUE, if the group is part of the collection; otherwise
/// \c VARIANT_FALSE.
///
/// \return An \c HRESULT error code.
///
/// \if UNICODE
/// \sa Add, Remove, ExLVwLibU::GroupIdentifierTypeConstants
/// \else
/// \sa Add, Remove, ExLVwLibA::GroupIdentifierTypeConstants
/// \endif
virtual HRESULT STDMETHODCALLTYPE Contains(LONG groupIdentifier, GroupIdentifierTypeConstants groupIdentifierType = gitID, VARIANT_BOOL* pValue = NULL);
/// \brief <em>Counts the groups in the collection</em>
///
/// Retrieves the number of \c ListViewGroup objects in the collection.
///
/// \param[out] pValue The number of elements in the collection.
///
/// \return An \c HRESULT error code.
///
/// \sa Add, Remove, RemoveAll
virtual HRESULT STDMETHODCALLTYPE Count(LONG* pValue);
/// \brief <em>Removes the specified group in the collection from the listview</em>
///
/// \param[in] groupIdentifier A value that identifies the listview group to be removed.
/// \param[in] groupIdentifierType A value specifying the meaning of \c groupIdentifier. Any of the
/// values defined by the \c GroupIdentifierTypeConstants enumeration is valid.
///
/// \return An \c HRESULT error code.
///
/// \if UNICODE
/// \sa Add, Count, RemoveAll, Contains, ExLVwLibU::GroupIdentifierTypeConstants
/// \else
/// \sa Add, Count, RemoveAll, Contains, ExLVwLibA::GroupIdentifierTypeConstants
/// \endif
virtual HRESULT STDMETHODCALLTYPE Remove(LONG groupIdentifier, GroupIdentifierTypeConstants groupIdentifierType = gitID);
/// \brief <em>Removes all groups in the collection from the listview</em>
///
/// \return An \c HRESULT error code.
///
/// \sa Add, Count, Remove
virtual HRESULT STDMETHODCALLTYPE RemoveAll(void);
//@}
//////////////////////////////////////////////////////////////////////
/// \brief <em>Sets the owner of this collection</em>
///
/// \param[in] pOwner The owner to set.
///
/// \sa Properties::pOwnerExLvw
void SetOwner(__in_opt ExplorerListView* pOwner);
protected:
/// \brief <em>Holds the object's properties' settings</em>
struct Properties
{
/// \brief <em>The \c ExplorerListView object that owns this collection</em>
///
/// \sa SetOwner
ExplorerListView* pOwnerExLvw;
/// \brief <em>Holds the position index of the next enumerated group</em>
int nextEnumeratedGroup;
Properties()
{
pOwnerExLvw = NULL;
nextEnumeratedGroup = 0;
}
~Properties();
/// \brief <em>Retrieves the owning listview's window handle</em>
///
/// \return The window handle of the listview that contains the groups in this collection.
///
/// \sa pOwnerExLvw
HWND GetExLvwHWnd(void);
} properties;
}; // ListViewGroups
OBJECT_ENTRY_AUTO(__uuidof(ListViewGroups), ListViewGroups) | [
"tkunze71216@gmx.de"
] | tkunze71216@gmx.de |
5daa0379d5e5e0f6af70d792b79b7a7478c595c9 | c9908e7759720601dc72f76dbc7f4627b2fabb21 | /inject2.cxx | 96ee9e0664d72c1e82741146f64dcafb0b9fe7bf | [] | no_license | seanbaxter/long_demo | 78243ec90372f98b79bfe84cceb1e716ed1fee1e | 6268fa0e49a46ca14d89020043cc544e746cbbeb | refs/heads/master | 2020-09-13T13:48:33.647926 | 2020-03-01T21:49:58 | 2020-03-01T21:49:58 | 222,804,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 900 | cxx | #include <cstdio>
#include <fstream>
#include <iostream>
#include "json.hpp"
const char* inject_filename = "json_data/inject1.json";
@meta printf("Opening resource %s\n", inject_filename);
@meta std::ifstream json_file(inject_filename);
@meta nlohmann::json j;
@meta json_file>> j;
// Record the function names in this array.
@meta std::vector<std::string> function_names;
@meta for(auto& item : j.items()) {
@meta std::string name = item.value()["name"];
@meta std::string definition = item.value()["definition"];
@meta printf("Injecting function '%s' = '%s'\n",
name.c_str(), definition.c_str());
double @(name)(double x) {
return @expression(definition);
}
@meta function_names.push_back(std::move(name));
}
int main() {
double x = 15;
@meta for(const std::string& name : function_names)
printf("%s(%f) -> %f\n", @string(name), x, @(name)(x));
return 0;
}
| [
"lightborn@gmail.com"
] | lightborn@gmail.com |
032a8999f007ffe9fb2f89e437deb26c341dc2b4 | fa8a73511234afbb06469f9b38e17b65b5e6072c | /src/basic/INIT3-Cuda.cpp | 1f5409a4f72538d2e6a4ec171ff964c26fdbcf13 | [] | no_license | him-28/RAJAPerf | 5c6b3e6bb49dce22c827b7ae856b3f7c02b60e33 | a8f669c1ad01d51132a4e3d9d6aa8b2cabc9eff0 | refs/heads/master | 2020-04-01T21:39:11.737238 | 2018-09-28T16:37:07 | 2018-09-28T16:37:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,813 | cpp | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2017-18, Lawrence Livermore National Security, LLC.
//
// Produced at the Lawrence Livermore National Laboratory
//
// LLNL-CODE-738930
//
// All rights reserved.
//
// This file is part of the RAJA Performance Suite.
//
// For details about use and distribution, please read RAJAPerf/LICENSE.
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include "INIT3.hpp"
#include "RAJA/RAJA.hpp"
#if defined(RAJA_ENABLE_CUDA)
#include "common/CudaDataUtils.hpp"
#include <iostream>
namespace rajaperf
{
namespace basic
{
//
// Define thread block size for CUDA execution
//
const size_t block_size = 256;
#define INIT3_DATA_SETUP_CUDA \
Real_ptr out1; \
Real_ptr out2; \
Real_ptr out3; \
Real_ptr in1; \
Real_ptr in2; \
\
allocAndInitCudaDeviceData(out1, m_out1, iend); \
allocAndInitCudaDeviceData(out2, m_out2, iend); \
allocAndInitCudaDeviceData(out3, m_out3, iend); \
allocAndInitCudaDeviceData(in1, m_in1, iend); \
allocAndInitCudaDeviceData(in2, m_in2, iend);
#define INIT3_DATA_TEARDOWN_CUDA \
getCudaDeviceData(m_out1, out1, iend); \
getCudaDeviceData(m_out2, out2, iend); \
getCudaDeviceData(m_out3, out3, iend); \
deallocCudaDeviceData(out1); \
deallocCudaDeviceData(out2); \
deallocCudaDeviceData(out3); \
deallocCudaDeviceData(in1); \
deallocCudaDeviceData(in2);
__global__ void init3(Real_ptr out1, Real_ptr out2, Real_ptr out3,
Real_ptr in1, Real_ptr in2,
Index_type iend)
{
Index_type i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < iend) {
INIT3_BODY;
}
}
void INIT3::runCudaVariant(VariantID vid)
{
const Index_type run_reps = getRunReps();
const Index_type ibegin = 0;
const Index_type iend = getRunSize();
if ( vid == Base_CUDA ) {
INIT3_DATA_SETUP_CUDA;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
const size_t grid_size = RAJA_DIVIDE_CEILING_INT(iend, block_size);
init3<<<grid_size, block_size>>>( out1, out2, out3, in1, in2,
iend );
}
stopTimer();
INIT3_DATA_TEARDOWN_CUDA;
} else if ( vid == RAJA_CUDA ) {
INIT3_DATA_SETUP_CUDA;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
RAJA::forall< RAJA::cuda_exec<block_size, true /*async*/> >(
RAJA::RangeSegment(ibegin, iend), [=] __device__ (Index_type i) {
INIT3_BODY;
});
}
stopTimer();
INIT3_DATA_TEARDOWN_CUDA;
} else {
std::cout << "\n INIT3 : Unknown Cuda variant id = " << vid << std::endl;
}
}
} // end namespace basic
} // end namespace rajaperf
#endif // RAJA_ENABLE_CUDA
| [
"hornung1@llnl.gov"
] | hornung1@llnl.gov |
ccf7cddae0777f71ab212647d4379f1e8d383234 | e2cd39b6bff42bdfaf861e2f152af8781f2be7eb | /ShadowMultiplayer/RoboCat/Inc/ShadowFactory.hpp | d28cb3e3596fda4c65e8f2d87818b485413bd4a3 | [] | no_license | cjjb95/ConorByrneCharlieDuffCA3Multiplayer | 7cb5b797579fdd54ed57805034b7621abc05b8f0 | ec341bbbe8ccb872f2aeebf9368b68f15783a8d6 | refs/heads/master | 2022-07-14T22:09:38.009275 | 2020-05-15T20:58:17 | 2020-05-15T20:58:17 | 262,842,342 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | hpp | // Written by: Ronan
#ifndef SHADOWFACTORY_HPP
#define SHADOWFACTORY_HPP
class ShadowFactory
{
public:
static void StaticInit();
static std::unique_ptr<ShadowFactory> sInstance;
std::vector<sf::VertexArray> getShadows(sf::Vector2f playerPosition, sf::Color color, sf::FloatRect p_bounds);
bool load();
bool doesCollideWithWorld(sf::FloatRect p_bounds);
private:
std::vector<sf::FloatRect> shadowCasters;
sf::Vector2f m_worldSize;
std::vector<Line> getShadowLines();
void optimizeShadowCasters();
bool doesExitWithMapBounds(sf::FloatRect p_bounds);
};
#endif | [
"cjjb95@gmail.com"
] | cjjb95@gmail.com |
0060eea346dd4e6e79e4b87450e896fa243ccc9c | 5cef19f12d46cafa243b087fe8d8aeae07386914 | /codeforces/512/b.cpp | 40cf3935fe96e2d8733ffaada9d5f4dc2496181f | [] | no_license | lych4o/competitive-programming | aaa6e1d3f7ae052cba193c5377f27470ed16208f | c5f4b98225a934f3bd3f76cbdd2184f574fe3113 | refs/heads/master | 2020-03-28T15:48:26.134836 | 2019-05-29T13:44:39 | 2019-05-29T13:44:39 | 148,627,900 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,354 | cpp | #include<iostream>
#include<cstdio>
#include<algorithm>
#include<set>
#include<cstring>
#include<vector>
#define pii pair<int, int>
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define debug puts("???");
#define br puts("")
#define ALL(x) x.begin(),x.end()
#define sc(x) scanf("%d", &x)
#define sz(x) int((x).size())
#define sll(x) scanf("%I64d", &x)
#define pr(x) printf("%d",x)
#define sp putchar(' ');
#define ln puts("")
using namespace std;
typedef long long LL;
const LL INF64 = 0x3f3f3f3f3f3f3f3f;
const int INF = 0x3f3f3f3f;
const LL mod = 1e9+7;
const int maxn = 3e5+10;
LL a[maxn],cnt[maxn],sum[maxn],suf[maxn][2];
int n;
int main(){
sc(n);
for(int i = 1; i <= n; i++){
sll(a[i]); LL tmp = a[i];
while(tmp > 0){
cnt[i]++;
tmp -= tmp&-tmp;
}
sum[i] = sum[i-1]+cnt[i];
}
for(int i = n; i >= 1; i--){
suf[i][0]=suf[i+1][0]; suf[i][1]=suf[i+1][1];
suf[i][sum[i]%2]++;
}
LL ans = 0;
for(int l = 1, r; l <= n; l++){
LL mx = 0, all;
for(r = l; r-l+1 <= 70 && r <= n; r++){
all = sum[r]-sum[l-1];
mx = max(mx, cnt[r]);
if(all-mx*2 < 0 || all%2) continue;
ans++;
}
ans += suf[r][sum[l-1]%2];
}
cout << ans << endl;
return 0;
}
| [
"noreply@github.com"
] | lych4o.noreply@github.com |
2612c32c5f3617bd9c4909a7667b39c03395ec79 | 52bd63e7c5f1730485e80008181dde512ad1a313 | /pstade/egg/is_bind_expression.hpp | 1cd6dcfb85eba4d11eee42f78a1542830e63c78c | [
"BSL-1.0"
] | permissive | fpelliccioni/pstade | 09df122a8cada6bd809512507b1eff9543d22cb1 | ffb52f2bf187c8f001588e6c5c007a4a3aa9a5e8 | refs/heads/master | 2016-09-11T02:06:23.972758 | 2013-09-26T15:13:05 | 2013-09-26T15:13:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,481 | hpp | #ifndef PSTADE_EGG_IS_BIND_EXPRESSION_HPP
#define PSTADE_EGG_IS_BIND_EXPRESSION_HPP
#include "./detail/prefix.hpp"
// PStade.Egg
//
// Copyright Shunsuke Sogame 2007.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/mpl/bool.hpp>
#include <pstade/enable_if.hpp>
#include "./bll/functor_fwd.hpp"
namespace boost { namespace _bi {
template<class R, class F, class L>
class bind_t;
} }
namespace pstade { namespace egg {
template<class X, class EnableIf>
struct is_bind_expression_base :
boost::mpl::false_
{ };
template<class X>
struct is_bind_expression :
is_bind_expression_base<X, enabler>
{ };
template<class X>
struct is_bind_expression<X const> :
is_bind_expression<X>
{ };
template<class X>
struct is_bind_expression<X volatile> :
is_bind_expression<X>
{ };
template<class X>
struct is_bind_expression<X const volatile> :
is_bind_expression<X>
{ };
template<class T>
struct is_bind_expression< boost::lambda::lambda_functor<T> > :
boost::mpl::true_
{ };
template<class R, class F, class L>
struct is_bind_expression< boost::_bi::bind_t<R, F, L> > :
boost::mpl::true_
{ };
} } // namespace pstade::egg
#endif
| [
"fpelliccioni@gmail.com"
] | fpelliccioni@gmail.com |
8333538f0787aa08cc4aee9d32c85c4238163e96 | 202443d103d4777cc8976185233d9da587da75fc | /r_dump_basic.h | 0b0b7d621d39479610042052f493506726da2824 | [] | no_license | pts/pts-contestcc | 3e0cb2ac36924b17c2862ddc23c9a797e3c4bf57 | dde2f4bddffaf5ecddda0957140bad728431f0cd | refs/heads/master | 2021-01-01T05:47:15.028723 | 2014-04-24T21:25:30 | 2014-04-24T21:27:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 522 | h | #ifndef R_DUMP_BASIC_H
#define R_DUMP_BASIC_H 1
#ifndef __cplusplus
#error This is a C++ header.
#endif
#include <stdint.h>
#include <string.h>
#include <string>
#include "r_strpiece.h"
namespace r {
void wrdump_low(char v, std::string *out);
void wrdump_low(const StrPiece &v, std::string *out);
void wrdump_low(const std::string &v, std::string *out);
void wrdump_low(const char *v, uintptr_t size, std::string *out);
void wrdump_low(const char *v, std::string *out);
} // namespace r
#endif // R_DUMP_BASIC_H
| [
"pts@fazekas.hu"
] | pts@fazekas.hu |
ada34e001b2f4c91cafe4258d59a6436f8fceb87 | 487d3cf6209e32b0d8f8b84976a66a74910ff676 | /src/rpcmining.cpp | 82a33b9bbbc0da0e5a46b4c5e270bc2546815017 | [
"MIT"
] | permissive | eonagen/eonagenEONA | 1040e3ff4b3879ccbd122f5cfe6687286faef770 | 606898a77b43ec8c7de664987bb88ceaa3d94ffe | refs/heads/master | 2020-04-15T17:09:37.826304 | 2019-01-09T12:58:25 | 2019-01-09T12:58:25 | 162,619,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,998 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "chainparams.h"
#include "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "kernel.h"
#include <boost/assign/list_of.hpp>
using namespace json_spirit;
using namespace std;
using namespace boost::assign;
// Key used by getwork/getblocktemplate miners.
// Allocated in InitRPCMining, free'd in ShutdownRPCMining
static CReserveKey* pMiningKey = NULL;
void InitRPCMining()
{
if (!pwalletMain)
return;
// getwork/getblocktemplate mining rewards paid here:
pMiningKey = new CReserveKey(pwalletMain);
}
void ShutdownRPCMining()
{
if (!pMiningKey)
return;
delete pMiningKey; pMiningKey = NULL;
}
Value getsubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getsubsidy [nTarget]\n"
"Returns proof-of-work subsidy value for the specified value of target.");
return (uint64_t)GetProofOfWorkReward(pindexBest->nHeight, 0);
}
Value getstakesubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getstakesubsidy <hex string>\n"
"Returns proof-of-stake subsidy value for the specified coinstake.");
RPCTypeCheck(params, list_of(str_type));
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint64_t nCoinAge;
CTxDB txdb("r");
if (!tx.GetCoinAge(txdb, pindexBest, nCoinAge))
throw JSONRPCError(RPC_MISC_ERROR, "GetCoinAge failed");
return (uint64_t)GetProofOfStakeReward(pindexBest, nCoinAge, 0);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
uint64_t nWeight = 0;
if (pwalletMain)
nWeight = pwalletMain->GetStakeWeight();
Object obj, diff, weight;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(pindexBest->nHeight, 0)));
obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
weight.push_back(Pair("minimum", (uint64_t)nWeight));
weight.push_back(Pair("maximum", (uint64_t)0));
weight.push_back(Pair("combined", (uint64_t)nWeight));
obj.push_back(Pair("stakeweight", weight));
obj.push_back(Pair("testnet", TestNet()));
return obj;
}
Value getstakinginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakinginfo\n"
"Returns an object containing staking-related information.");
uint64_t nWeight = 0;
uint64_t nExpectedTime = 0;
if (pwalletMain)
nWeight = pwalletMain->GetStakeWeight();
uint64_t nNetworkWeight = GetPoSKernelPS();
bool staking = nLastCoinStakeSearchInterval && nWeight;
nExpectedTime = staking ? (TARGET_SPACING * nNetworkWeight / nWeight) : 0;
Object obj;
obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
obj.push_back(Pair("staking", staking));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("weight", (uint64_t)nWeight));
obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
obj.push_back(Pair("expectedtime", nExpectedTime));
return obj;
}
Value checkkernel(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"checkkernel [{\"txid\":txid,\"vout\":n},...] [createblocktemplate=false]\n"
"Check if one of given inputs is a kernel input at the moment.\n"
);
RPCTypeCheck(params, list_of(array_type)(bool_type));
Array inputs = params[0].get_array();
bool fCreateBlockTemplate = params.size() > 1 ? params[1].get_bool() : false;
if (vNodes.empty())
throw JSONRPCError(-9, "eonagen is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "eonagen is downloading blocks...");
COutPoint kernel;
CBlockIndex* pindexPrev = pindexBest;
unsigned int nBits = GetNextTargetRequired(pindexPrev, true);
int64_t nTime = GetAdjustedTime();
nTime &= ~STAKE_TIMESTAMP_MASK;
BOOST_FOREACH(Value& input, inputs)
{
const Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint cInput(uint256(txid), nOutput);
if (CheckKernel(pindexPrev, nBits, nTime, cInput))
{
kernel = cInput;
break;
}
}
Object result;
result.push_back(Pair("found", !kernel.IsNull()));
if (kernel.IsNull())
return result;
Object oKernel;
oKernel.push_back(Pair("txid", kernel.hash.GetHex()));
oKernel.push_back(Pair("vout", (int64_t)kernel.n));
oKernel.push_back(Pair("time", nTime));
result.push_back(Pair("kernel", oKernel));
if (!fCreateBlockTemplate)
return result;
int64_t nFees;
auto_ptr<CBlock> pblock(CreateNewBlock(*pMiningKey, true, &nFees));
pblock->nTime = pblock->vtx[0].nTime = nTime;
CDataStream ss(SER_DISK, PROTOCOL_VERSION);
ss << *pblock;
result.push_back(Pair("blocktemplate", HexStr(ss.begin(), ss.end())));
result.push_back(Pair("blocktemplatefees", nFees));
CPubKey pubkey;
if (!pMiningKey->GetReservedKey(pubkey))
throw JSONRPCError(RPC_MISC_ERROR, "GetReservedKey failed");
result.push_back(Pair("blocktemplatesignkey", HexStr(pubkey)));
return result;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(-9, "eonagen is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "eonagen is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > maEONAwBlock_t;
static maEONAwBlock_t maEONAwBlock;
static vector<CBlock*> vNewBlock;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
maEONAwBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(*pMiningKey);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
maEONAwBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!maEONAwBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = maEONAwBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = maEONAwBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
assert(pwalletMain != NULL);
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "eonagen is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "eonagen is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > maEONAwBlock_t;
static maEONAwBlock_t maEONAwBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
maEONAwBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(*pMiningKey);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlock.push_back(pblock);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
maEONAwBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!maEONAwBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = maEONAwBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = maEONAwBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
assert(pwalletMain != NULL);
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "eonagen is not connected!");
//if (IsInitialBlockDownload())
// throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "eonagen is downloading blocks...");
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
{
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(*pMiningKey);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = GetLegacySigOpCount(tx);
nSigOps += GetP2SHSigOpCount(tx, mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
ssBlock >> block;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
bool fAccepted = ProcessBlock(NULL, &block);
if (!fAccepted)
return "rejected";
return Value::null;
}
| [
"45151553+Pinecoin-Developer@users.noreply.github.com"
] | 45151553+Pinecoin-Developer@users.noreply.github.com |
6fac978491b24aa2336915bffa1b2d7b8911ea1c | 005339a7ad587359b9fbf657b61afa5364741c71 | /src/taskevad.cpp | 08a2b4d439ca6f910666af561479f9c597aa9c69 | [
"MIT"
] | permissive | taskeva/Taskeva-core | f81bb26e18b87b87ccc780ab6207d6a6941f254f | d88a5f8983617bc7a8e179e7187818be1c5e92f3 | refs/heads/master | 2020-05-07T18:56:38.113460 | 2019-04-11T12:42:33 | 2019-04-11T12:42:33 | 179,446,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,074 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX Developers
// Copyright (c) 2018-2019 The Taskeva Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "init.h"
#include "main.h"
#include "masternodeconfig.h"
#include "noui.h"
#include "rpcserver.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called Taskeva (http://www.taskeva.io),
* which enables instant payments to anyone, anywhere in the world. Taskeva uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
static bool fDaemon;
void DetectShutdownThread(boost::thread_group* threadGroup)
{
bool fShutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!fShutdown) {
MilliSleep(200);
fShutdown = ShutdownRequested();
}
if (threadGroup) {
threadGroup->interrupt_all();
threadGroup->join_all();
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
//
// Parameters
//
// If Qt is used, parameters/taskeva.conf are parsed in qt/taskeva.cpp's main()
ParseParameters(argc, argv);
// Process help and version before taking care about datadir
if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) {
std::string strUsage = _("Taskeva Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";
if (mapArgs.count("-version")) {
strUsage += LicenseInfo();
} else {
strUsage += "\n" + _("Usage:") + "\n" +
" taskevad [options] " + _("Start Taskeva Core Daemon") + "\n";
strUsage += "\n" + HelpMessage(HMM_BITCOIND);
}
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
try {
if (!boost::filesystem::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
try {
ReadConfigFile(mapArgs, mapMultiArgs);
} catch (std::exception& e) {
fprintf(stderr, "Error reading configuration file: %s\n", e.what());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
if (!SelectParamsFromCommandLine()) {
fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
return false;
}
// parse masternode.conf
std::string strErr;
if (!masternodeConfig.read(strErr)) {
fprintf(stderr, "Error reading masternode configuration file: %s\n", strErr.c_str());
return false;
}
// Command-line RPC
bool fCommandLine = false;
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "taskeva:"))
fCommandLine = true;
if (fCommandLine) {
fprintf(stderr, "Error: There is no RPC client functionality in taskevad anymore. Use the taskeva-cli utility instead.\n");
exit(1);
}
#ifndef WIN32
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon) {
fprintf(stdout, "Taskeva server starting\n");
// Daemonize
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
SoftSetBoolArg("-server", true);
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
} catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
// threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
// the startup-failure cases to make sure they don't result in a hang due to some
// thread-blocking-waiting-for-another-thread-during-startup case
}
if (detectShutdownThread) {
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect taskevad signal handlers
noui_connect();
return (AppInit(argc, argv) ? 0 : 1);
}
| [
"xnkennyh@mail.com"
] | xnkennyh@mail.com |
ab7799b0ac23261cd567425d3e9f8f01768fe963 | 4beae9d121cced388d2295d1cbc436b80b4a25f2 | /src/test/test_mocha.h | 933bb810c9db23d7f2af2502248bf3a4cd4091d4 | [
"MIT"
] | permissive | volbil/newmocha | 8e5e5e3cbb51d05a330e7ad05d3bed4a3632ded6 | 809c90fbb6bc72364af2ed0ba6f97abac9d23e22 | refs/heads/master | 2022-06-11T09:37:03.595755 | 2020-04-27T02:35:06 | 2020-04-27T02:35:06 | 260,594,664 | 0 | 0 | null | 2020-05-02T01:50:46 | 2020-05-02T01:50:45 | null | UTF-8 | C++ | false | false | 4,531 | h | // Copyright (c) 2015 The Bitcoin Core developers
// Copyright (c) 2014-2019 The Mocha Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_TEST_TEST_DASH_H
#define BITCOIN_TEST_TEST_DASH_H
#include "chainparamsbase.h"
#include "fs.h"
#include "key.h"
#include "pubkey.h"
#include "random.h"
#include "scheduler.h"
#include "txdb.h"
#include "txmempool.h"
#include <boost/thread.hpp>
extern uint256 insecure_rand_seed;
extern FastRandomContext insecure_rand_ctx;
static inline void SeedInsecureRand(bool fDeterministic = false)
{
if (fDeterministic) {
insecure_rand_seed = uint256();
} else {
insecure_rand_seed = GetRandHash();
}
insecure_rand_ctx = FastRandomContext(insecure_rand_seed);
}
static inline uint32_t InsecureRand32() { return insecure_rand_ctx.rand32(); }
static inline uint256 InsecureRand256() { return insecure_rand_ctx.rand256(); }
static inline uint64_t InsecureRandBits(int bits) { return insecure_rand_ctx.randbits(bits); }
static inline uint64_t InsecureRandRange(uint64_t range) { return insecure_rand_ctx.randrange(range); }
static inline bool InsecureRandBool() { return insecure_rand_ctx.randbool(); }
/** Basic testing setup.
* This just configures logging and chain parameters.
*/
struct BasicTestingSetup {
ECCVerifyHandle globalVerifyHandle;
BasicTestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
~BasicTestingSetup();
};
/** Testing setup that configures a complete environment.
* Included are data directory, coins database, script check threads setup.
*/
class CConnman;
class CNode;
struct CConnmanTest {
static void AddNode(CNode& node);
static void ClearNodes();
};
class PeerLogicValidation;
struct TestingSetup: public BasicTestingSetup {
CCoinsViewDB *pcoinsdbview;
fs::path pathTemp;
boost::thread_group threadGroup;
CConnman* connman;
CScheduler scheduler;
std::unique_ptr<PeerLogicValidation> peerLogic;
TestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
~TestingSetup();
};
class CBlock;
struct CMutableTransaction;
class CScript;
struct TestChainSetup : public TestingSetup
{
TestChainSetup(int blockCount);
~TestChainSetup();
// Create a new block with just given transactions, coinbase paying to
// scriptPubKey, and try to add it to the current chain.
CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
const CScript& scriptPubKey);
CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
const CKey& scriptKey);
CBlock CreateBlock(const std::vector<CMutableTransaction>& txns,
const CScript& scriptPubKey);
CBlock CreateBlock(const std::vector<CMutableTransaction>& txns,
const CKey& scriptKey);
std::vector<CTransaction> coinbaseTxns; // For convenience, coinbase transactions
CKey coinbaseKey; // private/public key needed to spend coinbase transactions
};
//
// Testing fixture that pre-creates a
// 100-block REGTEST-mode block chain
//
struct TestChain100Setup : public TestChainSetup {
TestChain100Setup() : TestChainSetup(100) {}
};
struct TestChainDIP3Setup : public TestChainSetup
{
TestChainDIP3Setup() : TestChainSetup(431) {}
};
struct TestChainDIP3BeforeActivationSetup : public TestChainSetup
{
TestChainDIP3BeforeActivationSetup() : TestChainSetup(430) {}
};
class CTxMemPoolEntry;
struct TestMemPoolEntryHelper
{
// Default values
CAmount nFee;
int64_t nTime;
unsigned int nHeight;
bool spendsCoinbase;
unsigned int sigOpCount;
LockPoints lp;
TestMemPoolEntryHelper() :
nFee(0), nTime(0), nHeight(1),
spendsCoinbase(false), sigOpCount(4) { }
CTxMemPoolEntry FromTx(const CMutableTransaction &tx);
CTxMemPoolEntry FromTx(const CTransaction &tx);
// Change the default value
TestMemPoolEntryHelper &Fee(CAmount _fee) { nFee = _fee; return *this; }
TestMemPoolEntryHelper &Time(int64_t _time) { nTime = _time; return *this; }
TestMemPoolEntryHelper &Height(unsigned int _height) { nHeight = _height; return *this; }
TestMemPoolEntryHelper &SpendsCoinbase(bool _flag) { spendsCoinbase = _flag; return *this; }
TestMemPoolEntryHelper &SigOps(unsigned int _sigops) { sigOpCount = _sigops; return *this; }
};
#endif
| [
"whoffman1031@gmail.com"
] | whoffman1031@gmail.com |
0abd8118bd63240512bc970cc21e0dc812df3880 | 1a29e3fc23318be40f27339a749bbc3bdc59c0c3 | /codeforces/gym/102021/j.cpp | 6bc53c4ff11306abd16f672095ddf0b818318398 | [] | no_license | wdzeng/cp-solutions | 6c2ac554f6d291774929bc6ad612c4c2e3966c9f | 8d39fcbda812a1db7e03988654cd20042cf4f854 | refs/heads/master | 2023-03-23T17:23:08.809526 | 2020-12-05T00:29:21 | 2020-12-05T00:29:21 | 177,706,525 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,043 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
const double PI = acos(-1);
#define x first
#define y second
#define iter(c) c.begin(), c.end()
#define ms(a) memset(a, 0, sizeof(a))
#define mss(a) memset(a, -1, sizeof(a))
#define mp(e, f) make_pair(e, f)
inline void foul() {
cout << "impossible\n";
exit(0);
}
struct puzzle {
const int index;
int top, left, bottom, right;
puzzle *nextline = NULL, *next = NULL;
puzzle(int i, int t, int l, int b, int r) : index(i), top(t), left(l), bottom(b), right(r) {}
inline void rotate() {
int tmp = top;
top = right;
right = bottom;
bottom = left;
left = tmp;
}
inline void concat_right(puzzle* pz) {
while (pz->left != right) pz->rotate();
next = pz;
}
inline void concat_bottom(puzzle* pz) {
while (pz->top != bottom) pz->rotate();
nextline = pz;
}
};
const int maxn = 3e5 + 10;
bitset<maxn> vis;
vector<puzzle*> puzzles;
vector<pii> edges;
int N, R = 0, C;
puzzle* root = NULL;
inline void add_edge(int e, int i) {
if (e == 0) return;
if (e >= edges.size()) foul();
(edges[e].x == -1 ? edges[e].x : edges[e].y) = i;
}
void set_root_if_valid(puzzle* pz) {
for (int j = 0; j < 3; j++) {
if (pz->left == 0 && pz->top == 0) {
root = pz;
vis[pz->index] = 1;
break;
}
pz->rotate();
}
}
void get_input() {
cin >> N;
edges.assign(N * 2, {-1, -1});
for (int i = 0; i < N; i++) {
int a, b, c, d;
cin >> a >> b >> c >> d;
puzzle* pz = new puzzle(i, a, b, c, d);
add_edge(a, i);
add_edge(b, i);
add_edge(c, i);
add_edge(d, i);
puzzles.push_back(pz);
if (root == NULL) set_root_if_valid(pz);
}
}
void assemble_puzzles() {
auto linkright = [&](puzzle* src) -> puzzle* {
int e = src->right;
if (!e) return NULL;
auto& e2 = edges[e];
if (vis[e2.x] && vis[e2.y]) foul();
int v = vis[e2.x] ? e2.y : e2.x;
vis[v] = 1;
src->concat_right(puzzles[v]);
return src->next;
};
auto linkbottom = [&](puzzle* src) -> puzzle* {
int e = src->bottom;
if (!e) return NULL;
auto& e2 = edges[e];
if (vis[e2.x] && vis[e2.y]) foul();
int v = vis[e2.x] ? e2.y : e2.x;
vis[v] = 1;
src->concat_bottom(puzzles[v]);
return src->nextline;
};
auto topleft = root;
while (topleft) {
if (topleft->left != 0) foul();
R++;
auto bottomright = topleft;
int counter = 1;
while (bottomright = linkright(bottomright)) {
if (topleft == root && bottomright->top != 0) foul();
counter++;
}
if (topleft == root) C = counter;
if (C != counter) foul();
topleft = linkbottom(topleft);
}
if (R * C != N) foul();
}
void check_edges() {
puzzle* upper = root;
puzzle* lower;
while (upper) {
lower = upper->nextline;
puzzle* r1 = upper;
puzzle* r2 = lower;
while (r1) {
if (r2) {
if (r1->bottom == 0) foul();
if (r1->bottom != r2->top) foul();
r2 = r2->next;
} //
else {
if (r1->bottom != 0) foul();
}
r1 = r1->next;
}
upper = lower;
}
}
void print_puzzles() {
cout << R << ' ' << C << '\n';
auto topleft = root;
while (topleft) {
auto bottomright = topleft;
while (bottomright) {
cout << bottomright->index + 1 << ' ';
bottomright = bottomright->next;
}
cout << '\n';
topleft = topleft->nextline;
}
}
int main() {
cin.tie(0), ios::sync_with_stdio(0);
get_input();
assemble_puzzles();
check_edges();
print_puzzles();
return 0;
} | [
"hyperbola.cs07@gmail.com"
] | hyperbola.cs07@gmail.com |
a2677df5fc9fca2f2154108d250d83c6b76139f0 | a91796ab826878e54d91c32249f45bb919e0c149 | /modules/gapi/src/streaming/onevpl/accelerators/utils/elastic_barrier.hpp | b91554f43575eca3451fc4446e174141ce92fbe8 | [
"Apache-2.0"
] | permissive | opencv/opencv | 8f1c8b5a16980f78de7c6e73a4340d302d1211cc | a308dfca9856574d37abe7628b965e29861fb105 | refs/heads/4.x | 2023-09-01T12:37:49.132527 | 2023-08-30T06:53:59 | 2023-08-30T06:53:59 | 5,108,051 | 68,495 | 62,910 | Apache-2.0 | 2023-09-14T17:37:48 | 2012-07-19T09:40:17 | C++ | UTF-8 | C++ | false | false | 12,134 | hpp | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2021 Intel Corporation
#ifndef GAPI_STREAMING_ONEVPL_ACCELERATORS_UTILS_ELASTIC_BARRIER_HPP
#define GAPI_STREAMING_ONEVPL_ACCELERATORS_UTILS_ELASTIC_BARRIER_HPP
#include <atomic>
namespace cv {
namespace gapi {
namespace wip {
namespace onevpl {
template<typename Impl>
class elastic_barrier {
public:
using self_t = Impl;
elastic_barrier() :
incoming_requests(),
outgoing_requests(),
pending_requests(),
reinit(false) {
}
self_t* get_self() {
return static_cast<self_t*>(this);
}
template<typename ...Args>
void visit_in (Args&& ...args) {
on_lock(std::forward<Args>(args)...);
}
template<typename ...Args>
void visit_out (Args&& ...args) {
on_unlock(std::forward<Args>(args)...);
}
protected:
~elastic_barrier() = default;
private:
std::atomic<size_t> incoming_requests;
std::atomic<size_t> outgoing_requests;
std::atomic<size_t> pending_requests;
std::atomic<bool> reinit;
template<typename ...Args>
void on_first_in(Args&& ...args) {
get_self()->on_first_in_impl(std::forward<Args>(args)...);
}
template<typename ...Args>
void on_last_out(Args&& ...args) {
get_self()->on_last_out_impl(std::forward<Args>(args)...);
}
template<typename ...Args>
void on_lock(Args&& ...args) {
// Read access is more complex
// each `incoming` request must check in before acquire resource
size_t thread_id = incoming_requests.fetch_add(1);
if (thread_id == 0) {
/*
* only one `incoming` request is allowable to init resource
* at first time
* let's filter out the first one by `thread_id`
*
* The first one `incoming` request becomes main `incoming` request
* */
if (outgoing_requests.load() == 0) {
get_self()->on_first_in(std::forward<Args>(args)...);
/*
* The main `incoming` request finished resource initialization
* and became `outgoing`
*
* Non empty `outgoing` count means that
* other further `incoming` (or busy-wait) requests
* are getting on with its job without resource initialization,
* because main `incoming` request has already initialized it at here
* */
outgoing_requests.fetch_add(1);
return;
}
return;
} else {
/*
* CASE 1)
*
* busy wait for others `incoming` requests for resource initialization
* besides main `incoming` request which are getting on
* resource initialization at this point
*
* */
// OR
/*
* CASE 2)
*
* busy wait for ALL `incoming` request for resource initialization
* including main `incoming` request. It will happen if
* new `incoming` requests had came here while resource was getting on deinit
* in `on_unlock` in another processing thread.
* In this case no actual main `incoming` request is available and
* all `incoming` requests must be in busy-wait stare
*
* */
// Each `incoming` request became `busy-wait` request
size_t busy_thread_id = pending_requests.fetch_add(1);
/*
* CASE 1)
*
* Non empty `outgoing` requests count means that other further `incoming` or
* `busy-wait` request are getting on with its job
* without resource initialization because
* main thread has already initialized it at here
* */
while (outgoing_requests.load() == 0) {
// OR
/*
* CASE 2)
*
* In case of NO master `incoming `request is available and doesn't
* provide resource initialization. All `incoming` requests must be in
* busy-wait state.
* If it is not true then CASE 1) is going on
*
* OR
*
* `on_unlock` is in deinitialization phase in another thread.
* Both cases mean busy-wait state here
* */
if (pending_requests.load() == incoming_requests.load()) {
/*
* CASE 2) ONLY
*
* It will happen if 'on_unlock` in another thread
* finishes its execution only
*
* `on_unlock` in another thread might finished with either
* deinitialization action or without deinitialization action
* (the call off deinitialization case)
*
* We must not continue at here (without reinit)
* if deinitialization happens in `on_unlock` in another thread.
* So try it on
* */
// only single `busy-wait` request must make sure about possible
// deinitialization. So first `busy-wait` request becomes
// main `busy-wait` request
if (busy_thread_id == 0) {
bool expected_reinit = true;
if (!reinit.compare_exchange_strong(expected_reinit, false)) {
/*
* deinitialization called off in `on_unlock`
* because new `incoming` request had appeared at here before
* `on_unlock` started deinit procedure in another thread.
* So no reinit required because no deinit had happened
*
* main `busy-wait` request must break busy-wait state
* and become `outgoing` request.
* Non empty `outgoing` count means that other
* further `incoming` requests or
* `busy-wait` requests are getting on with its job
* without resource initialization/reinitialization
* because no deinit happened in `on_unlock`
* in another thread
* */
break; //just quit busy loop
} else {
/* Deinitialization had happened in `on_unlock`
* in another thread right before
* new `incoming` requests appeared.
* So main `busy-wait` request must start reinit procedure
*/
get_self()->on_first_in(std::forward<Args>(args)...);
/*
* Main `busy-wait` request has finished reinit procedure
* and becomes `outgong` request.
* Non empty `outgoing` count means that other
* further `incoming` requests or
* `busy-wait` requests are getting on with its job
* without resource initialization because
* main `busy-wait` request
* has already re-initialized it at here
*/
outgoing_requests.fetch_add(1);
pending_requests.fetch_sub(1);
return;
}
}
}
}
// All non main requests became `outgoing` and look at on initialized resource
outgoing_requests++;
// Each `busy-wait` request are not busy-wait now
pending_requests.fetch_sub(1);
}
return;
}
template<typename ...Args>
void on_unlock(Args&& ...args) {
// Read unlock
/*
* Each released `outgoing` request checks out to doesn't use resource anymore.
* The last `outgoing` request becomes main `outgoing` request and
* must deinitialize resource if no `incoming` or `busy-wait` requests
* are waiting for it
*/
size_t thread_id = outgoing_requests.fetch_sub(1);
if (thread_id == 1) {
/*
* Make sure that no another `incoming` (including `busy-wait)
* exists.
* But beforehand its must make sure that no `incoming` or `pending`
* requests are exist.
*
* The main `outgoing` request is an one of `incoming` request
* (it is the oldest one in the current `incoming` bunch) and still
* holds resource in initialized state (thus we compare with 1).
* We must not deinitialize resource before decrease
* `incoming` requests counter because
* after it has got 0 value in `on_lock` another thread
* will start initialize resource procedure which will get conflict
* with current deinitialize procedure
*
* From this point, all `on_lock` request in another thread would
* become `busy-wait` without reaching main `incoming` state (CASE 2)
* */
if (incoming_requests.load() == 1) {
/*
* The main `outgoing` request is ready to deinit shared resource
* in unconflicting manner.
*
* This is a critical section for single thread for main `outgoing`
* request
*
* CASE 2 only available in `on_lock` thread
* */
get_self()->on_last_out(std::forward<Args>(args)...);
/*
* Before main `outgoinq` request become released it must notify
* subsequent `busy-wait` requests in `on_lock` in another thread
* that main `busy-wait` must start reinit resource procedure
* */
reinit.store(true);
/*
* Deinitialize procedure is finished and main `outgoing` request
* (it is the oldest one in `incoming` request) must become released
*
* Right after when we decrease `incoming` counter
* the condition for equality
* `busy-wait` and `incoming` counter will become true (CASE 2 only)
* in `on_lock` in another threads. After that
* a main `busy-wait` request would check `reinit` condition
* */
incoming_requests.fetch_sub(1);
return;
}
/*
* At this point we have guarantee that new `incoming` requests
* had became increased in `on_lock` in another thread right before
* current thread deinitialize resource.
*
* So call off deinitialization procedure here
* */
}
incoming_requests.fetch_sub(1);
}
elastic_barrier(const elastic_barrier&) = delete;
elastic_barrier(elastic_barrier&&) = delete;
elastic_barrier& operator() (const elastic_barrier&) = delete;
elastic_barrier& operator() (elastic_barrier&&) = delete;
};
} // namespace onevpl
} // namespace wip
} // namespace gapi
} // namespace cv
#endif // GAPI_STREAMING_ONEVPL_ACCELERATORS_UTILS_ELASTIC_BARRIER_HPP
| [
"noreply@github.com"
] | opencv.noreply@github.com |
12b990d0d9edece7ea1cd3c5221c83deb9ce0920 | 1b420621bceca23eb375f78d0568a5dc76549a75 | /CFMM.cpp | e6be8b2c495795662db7da16b2b1adfed00d3c02 | [] | no_license | GireeshGalande/Codechef | 6b7652b00428a510fba81f2ab662f26f95a3640e | ee68927606d497fbd5cf360939b459847e45fa7f | refs/heads/master | 2022-07-09T12:51:07.919130 | 2020-05-13T07:05:54 | 2020-05-13T07:05:54 | 263,547,535 | 0 | 0 | null | 2020-05-13T06:54:33 | 2020-05-13T06:44:05 | null | UTF-8 | C++ | false | false | 1,014 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t,n,y,z;
cin>>t;
for(int i=0;i<t;i++)
{ string x="",q;
int p=0;
cin>>n;
y=0;
int a[6]={0};
for(int j=0;j<n;j++)
{
cin>>q;
x+=q;
}
for(int k=0;k<x.length();k++)
{
if(x[k]=='c')
a[0]++;
else if(x[k]=='o')
a[1]++;
else if(x[k]=='d')
a[2]++;
else if(x[k]=='e')
a[3]++;
else if(x[k]=='h')
a[4]++;
else if(x[k]=='f')
a[5]++;
}
z=a[0];
for(int j=0;j<6;j++)
if(a[j]<z)
{
z=a[j];
p=j;
}
if(p==0||p==3)
y=z/2;
else if((a[0]>=2*z)&&(a[3]>=2*z))
y=z;
cout<<y<<"\n";
}
return 0;
}
| [
"noreply@github.com"
] | GireeshGalande.noreply@github.com |
62116b593a5ab11f4af26892e342fad6c0e42dab | 22641cf13e595060a9e1849829952a90ba4b82ea | /MushroomSpawner.h | ce1d2b9d1658054888ccc22742f38f821d00c121 | [] | no_license | nkowales/FundComp2Project | ca48f852686a225b36f11fc51d2b9da74c58cc7c | ea7d1104b4d5aa78351ed952aa51c04b095ad297 | refs/heads/master | 2020-05-16T00:37:21.429617 | 2015-04-30T02:36:13 | 2015-04-30T02:36:13 | 30,984,299 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 665 | h | /*
* MushrooomSpawner.h
*
* Created on: Apr 29, 2015
* Author: naiello
*/
#ifndef MUSHROOMSPAWNER_H_
#define MUSHROOMSPAWNER_H_
#include "WorldObject.h"
#include "HealthMushroom.h"
#define MSPAWN_SPEED 100
class MushroomSpawner : public WorldObject
{
public:
MushroomSpawner(Uint32);
void init(ContentManager*);
void update(Uint32);
bool canCollideWith(const WorldObject*);
void handleCollision(WorldObject*, const SDL_Rect&);
WorldInput resolveInput(string);
void spawn();
void enable(WorldObject* = NULL, string = "");
private:
bool enabled = false;
double timer = 0.;
double spawnInterval = 15.;
};
#endif /* MUSHROOMSPAWNER_H_ */
| [
"naiello@nd.edu"
] | naiello@nd.edu |
3e4c083a8d7faa96bfa58d8f01904634588f3841 | 2fc6ab0fdcd34c4c8516f61638bba16bf4045b0a | /player/openBookGenerator/tableGenerator/gentable.cpp | 02166f34d5389d87627c11123118ead3c92ec119 | [] | no_license | FoteiniAthina/Leiserchess---MIT-6.172-Fall16-Final-Project | 7c534f4f79a155326584b6e2dde681a4c67f609d | e32f2e9db5155f7de1a0b2b4ec7f72f4e0388f86 | refs/heads/master | 2020-08-13T02:55:08.296021 | 2016-12-22T06:42:45 | 2016-12-22T06:42:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,432 | cpp | #include <cstdlib>
#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cstring>
#include <cassert>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define SIZE(x) (int((x).size()))
#define rep(i,l,r) for (int i=(l); i<=(r); i++)
#define repd(i,r,l) for (int i=(r); i>=(l); i--)
#define rept(i,c) for (__typeof((c).begin()) i=(c).begin(); i!=(c).end(); i++)
#ifndef ONLINE_JUDGE
#define debug(x) { cerr<<#x<<" = "<<(x)<<endl; }
#else
#define debug(x) {}
#endif
char buf1[10000], buf2[10000];
struct node
{
string result;
map<string, node*> child;
node() {}
};
node *root;
void insert(string s, string val)
{
string t="";
int i=0;
node *cur=root;
while (i<s.length())
{
while (s[i]!=' ') t+=s[i], i++;
if (!cur->child.count(t))
cur->child[t]=new node();
cur=cur->child[t];
t="";
i++;
}
cur->result=val;
}
string moves[1000000], result[1000000];
int leftc[1000000], rightc[1000000];
node *q[1000000];
void lemon()
{
root=new node();
root->result="h4g5";
int cnt=0;
while (1)
{
if (!gets(buf1)) break;
if (!gets(buf2)) break;
string s1=buf1;
assert(s1[s1.length()-1]!=' ');
s1=s1+" ";
string s2=buf2;
//assert(3<=s2.length() && s2.length()<=4);
insert(s1,s2);
cnt++;
}
fprintf(stderr,"%d states processed\n",cnt);
int head=1, tail=2;
q[head]=root; moves[head]="";
while (head<tail)
{
node *cur=q[head];
leftc[head]=tail;
rept(it,cur->child)
{
q[tail]=it->second;
moves[tail]=it->first;
tail++;
}
rightc[head]=tail;
head++;
}
printf("const char* const moves[] = {\n ");
rep(i,1,tail-1)
{
printf("\"%s\"",moves[i].c_str());
if (i<tail-1) printf(",");
if (i%10==0) printf("\n ");
}
printf("\n};\n\n");
printf("const int childrange[][2] = {\n ");
int maxb=0;
rep(i,1,tail-1)
{
printf("{%d,%d}",leftc[i]-1,rightc[i]-1);
if (rightc[i]-leftc[i]>maxb) maxb=rightc[i]-leftc[i];
if (i<tail-1) printf(",");
if (i%5==0) printf("\n ");
}
printf("\n};\n\n");
printf("const char* const results[] = {\n ");
rep(i,1,tail-1)
{
printf("\"%s\"",q[i]->result.c_str());
if (i<tail-1) printf(",");
if (i%10==0) printf("\n ");
}
printf("\n};\n\n");
fprintf(stderr,"max branch = %d\n",maxb);
}
int main()
{
ios::sync_with_stdio(true);
#ifndef ONLINE_JUDGE
freopen("D.txt","r",stdin);
#endif
lemon();
return 0;
}
| [
"haoranxu510@gmail.com"
] | haoranxu510@gmail.com |
66b14cffc882ea7cc123bf57981f1ba3dc1f7b50 | 3fc56a21137af2376ff0a0f784f6ed78d8d69973 | /DLib Attacher/ResPacker.cpp | 41fb4543259e5283285730864695dd357a95ec79 | [] | no_license | asdlei99/DLib-Attacher | c524d0cdc9f3fffcc88ccd6f9037d9dba6d977d6 | bb522c6c3863caac04acec8be2feb99563ffadb8 | refs/heads/master | 2020-12-24T03:38:14.949362 | 2014-01-15T16:51:36 | 2014-01-15T16:51:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,437 | cpp | #include "stdafx.h"
#include "ResPacker.h"
// ======================= CResPacker :: PUBLIC =======================
CResPacker::CResPacker() : _guid(0)
{
}
CResPacker::~CResPacker()
{
Clear();
}
UINT CResPacker::Add(PVOID buffer, UINT size)
{
_ResFrame frame;
if (size < 1) {
return RES_INVALID_ID;
}
frame.id = GetGuid();
frame.pdata = calloc(size, 1);
frame.size = size;
if (!frame.pdata) {
return RES_INVALID_ID;
}
memcpy(frame.pdata, buffer, size);
_res.push_back(frame);
return frame.id;
}
BOOL CResPacker::Edit(UINT id, PVOID buffer, UINT size)
{
std::list<_ResFrame>::iterator frame = GetResFrame(id);
if (frame == _res.end() || size < 1) {
return false;
}
free(frame->pdata);
frame->pdata = calloc(size, 1);
frame->size = size;
if (!frame->pdata) {
return false;
}
memcpy(frame->pdata, buffer, size);
return true;
}
BOOL CResPacker::Resize(UINT id, UINT size)
{
std::list<_ResFrame>::iterator frame = GetResFrame(id);
if (frame == _res.end() || size < 1) {
return false;
}
if (size == frame->size) {
return true;
}
frame->pdata = realloc(frame->pdata, size);
frame->size = size;
return true;
}
BOOL CResPacker::Delete(UINT id)
{
std::list<_ResFrame>::iterator frame = GetResFrame(id);
if (frame == _res.end()) {
return false;
}
free(frame->pdata);
_res.erase(frame);
return true;
}
void CResPacker::Clear()
{
std::list<_ResFrame>::iterator it = _res.begin();
while (it != _res.end()) {
free(it->pdata);
it++;
}
_res.clear();
}
PVOID CResPacker::GetDataPtr(UINT id, PUINT psize)
{
std::list<_ResFrame>::iterator frame = GetResFrame(id);
if (frame == _res.end()) {
return NULL;
}
if (psize) {
*psize = frame->size;
}
return frame->pdata;
}
DWORD CResPacker::GetResOffset(UINT id)
{
std::list<_ResFrame>::iterator it = _res.begin();
UINT offset = 0;
while (it != _res.end()) {
if (it->id == id) {
return offset + sizeof(UINT) + sizeof(UINT);//offset + header(id_var + size_var)
}
offset += it->size + sizeof(UINT) + sizeof(UINT);//buffer + id_var + size_var
it++;
}
return RES_INVALID_ID;
}
UINT CResPacker::GetTotalSize()
{
std::list<_ResFrame>::iterator it = _res.begin();
UINT total_size = 0;
while (it != _res.end()) {
total_size += it->size + sizeof(UINT) + sizeof(UINT);//buffer + id_var + size_var
it++;
}
return total_size;
}
BOOL CResPacker::Compile(PVOID output, UINT buff_size, PUINT pcomp_size)
{
std::list<_ResFrame>::iterator it = _res.begin();
DWORD offset = 0;
*pcomp_size = GetTotalSize();
if (*pcomp_size > buff_size) {
return false;
}
while (it != _res.end()) {
*(UINT *)((UINT)output + offset) = it->id;
offset += sizeof(UINT);
*(UINT *)((UINT)output + offset) = it->size;
offset += sizeof(UINT);
memcpy((PVOID)((UINT)output + offset), it->pdata, it->size);
offset += it->size;
it++;
}
return true;
}
BOOL CResPacker::Decompile(PVOID input, UINT buff_size, PUINT pcount)
{
DWORD added = 0, offset = 0;
UINT guid = 0;
_ResFrame frame;
Clear();
while (true) {
if (offset + (sizeof(UINT) * 2) > buff_size) {
break;
}
frame.id = *(UINT *)((UINT)input + offset);
offset += sizeof(UINT);
frame.size = *(UINT *)((UINT)input + offset);
offset += sizeof(UINT);
if (offset + frame.size > buff_size) {
break;
}
if (!frame.id && !frame.size) {
break;
}
if (frame.id > guid) {
guid = frame.id;
}
if (GetDataPtr(frame.id, NULL)) {
Clear();
return false;
}
frame.pdata = calloc(frame.size, 1);
if (!frame.pdata) {
Clear();
return false;
}
memcpy(frame.pdata, (PVOID)((UINT)input + offset), frame.size);
_res.push_back(frame);
offset += frame.size;
added++;
if (offset == buff_size) {
break;
}
}
_guid = ++guid;
if (pcount) {
*pcount = added;
}
return true;
}
UINT CResPacker::Count()
{
return _res.size();
}
// ======================= CResPacker :: PRIVATE =======================
UINT CResPacker::GetGuid()
{
return _guid++;
}
std::list<_ResFrame>::iterator CResPacker::GetResFrame(UINT id)
{
std::list<_ResFrame>::iterator it = _res.begin();
while (it != _res.end()) {
if (it->id == id) {
return it;
}
it++;
}
return _res.end();
}
| [
"8bit.dosninja@gmail.com"
] | 8bit.dosninja@gmail.com |
a050f872e308cdf1ee33c8c7ca816320f02be07c | 90af0fa8944c9bcb677178774d4c2c7bfe2b6e79 | /Library/Include/Graphics/Graphics.cpp | f29970971e24e480f86f93bffa9a765b953b216d | [
"MIT"
] | permissive | OiC-SysDev-Game/WonderWolfGirl | 33a5db5e7bde89bb49a90fc32950d66662a6fd52 | 6118d47fea259ec7437d5b9a7c3f967fe2eb4fa0 | refs/heads/main | 2023-07-05T11:23:24.258746 | 2021-07-30T05:41:13 | 2021-07-30T05:41:13 | 381,572,812 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 4,727 | cpp | #include "Graphics.h"
#include "../Common/Common.h"
#include "../Utility/GraphicsUtilities.h"
bool u22::graphics::Graphics::Setup(void) {
if (!::glfwInit()) {
return false;
} // if
::glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
::glfwWindowHint(GLFW_SAMPLES, 0);
::glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
::glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
::glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
::glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
::glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
// font
if (::FT_Init_FreeType(&_font)) {
return false;
} // if
return true;
}
bool u22::graphics::Graphics::LoadShader(void) {
bool ret = false;
{
auto shader = std::make_shared<u22::graphics::EffectShader>();
ret = shader->Load("../Resource/shader/sprite.vert", "../Resource/shader/sprite.frag");
if (!ret) {
ret = shader->Load("Resource/shader/sprite.vert", "Resource/shader/sprite.frag");
if (!ret) {
return false;
} // if
} // if
_shader_map.emplace(u22::graphics::EffectShaderType::Sprite, shader);
}
{
auto shader = std::make_shared<u22::graphics::EffectShader>();
ret = shader->Load("../Resource/shader/circle.vert", "../Resource/shader/circle.frag");
if (!ret) {
ret = shader->Load("Resource/shader/circle.vert", "Resource/shader/circle.frag");
if (!ret) {
return false;
} // if
} // if
_shader_map.emplace(u22::graphics::EffectShaderType::Circle, shader);
}
{
auto shader = std::make_shared<u22::graphics::EffectShader>();
ret = shader->Load("../Resource/shader/rectangle.vert", "../Resource/shader/rectangle.frag");
if (!ret) {
ret = shader->Load("Resource/shader/rectangle.vert", "Resource/shader/rectangle.frag");
if (!ret) {
return false;
} // if
} // if
_shader_map.emplace(u22::graphics::EffectShaderType::Rectangle, shader);
}
u22::utility::GraphicsUtilities::Setup();
return true;
}
bool u22::graphics::Graphics::ReleaseShader(void) {
for (auto& shader : _shader_map) {
if (!shader.second->Release()) {
return false;
} // if
} // for
_shader_map.clear();
return true;
}
u22::graphics::Graphics::Graphics() :
_initialized(false),
_shader_map(),
_font() {
bool setup = this->Setup();
_ASSERT_EXPR(setup, L"グラフィックスのセットアップでエラーが起きました");
}
u22::graphics::Graphics::~Graphics() {
}
FT_Library u22::graphics::Graphics::GetFontPtr(void) const {
return this->_font;
}
std::shared_ptr<u22::graphics::EffectShader> u22::graphics::Graphics::GetEffectShader(u22::graphics::EffectShaderType type) const {
return this->_shader_map.at(type);
}
void u22::graphics::Graphics::ClearTarget(const u22::math::Vector4F& color, float depth, float stencil) {
// クリア
auto& c = color;
::glClearColor(c.r, c.g, c.b, c.a);
::glClearDepth(depth);
::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
void u22::graphics::Graphics::RenderStart(void) {
// 2d depth stencil = disable
// culling = disable
// デフォルトのフレームバッファに対しての操作
::glDisable(GL_DEPTH);
//::glEnable(GL_DEPTH);
::glDisable(GL_CULL_FACE);
//::glEnable(GL_CULL_FACE);
//::glFrontFace(GL_CCW); // default
//::glCullFace(GL_BACK); // default
::glEnable(GL_BLEND);
::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
bool u22::graphics::Graphics::Initialize(const std::shared_ptr<u22::Window>& window) {
_initialized = false;
// OpenGL拡張機能チュートリアル
// https://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/extensions.php
auto error = ::glewInit();
if (error != GLEW_OK) {
//std::cout << "error : " << reinterpret_cast<const char*>(::glewGetErrorString(error)) << "\n";
::glfwTerminate();
return false;
} // if
if (!GLEW_ARB_vertex_program) {
return false;
} // if
if (!this->LoadShader()) {
return false;
} // if
_initialized = true;
return _initialized;
}
bool u22::graphics::Graphics::Release(void) {
u22::utility::GraphicsUtilities::Cleanup();
::FT_Done_FreeType(_font);
_font = nullptr;
if (!this->ReleaseShader()) {
return false;
} // if
if (!_initialized) {
return false;
} // if
::glfwTerminate();
return true;
} | [
"towa.k100@icloud.com"
] | towa.k100@icloud.com |
0c2abfd3f1765fe99a9159ee9056367b524ad45d | 89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04 | /third_party/WebKit/Source/core/events/KeyboardEvent.cpp | d0c4eacd48da6436775c31f64985494acdbcab5b | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | bino7/chromium | 8d26f84a1b6e38a73d1b97fea6057c634eff68cb | 4666a6bb6fdcb1114afecf77bdaa239d9787b752 | refs/heads/master | 2022-12-22T14:31:53.913081 | 2016-09-06T10:05:11 | 2016-09-06T10:05:11 | 67,410,510 | 1 | 3 | BSD-3-Clause | 2022-12-17T03:08:52 | 2016-09-05T10:11:59 | null | UTF-8 | C++ | false | false | 6,875 | cpp | /**
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
* Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2003, 2005, 2006, 2007 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "core/events/KeyboardEvent.h"
#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ScriptState.h"
#include "platform/WindowsKeyboardCodes.h"
#include "public/platform/Platform.h"
#include "public/platform/WebInputEvent.h"
#include "wtf/PtrUtil.h"
namespace blink {
static inline const AtomicString& eventTypeForKeyboardEventType(WebInputEvent::Type type)
{
switch (type) {
case WebInputEvent::KeyUp:
return EventTypeNames::keyup;
case WebInputEvent::RawKeyDown:
return EventTypeNames::keydown;
case WebInputEvent::Char:
return EventTypeNames::keypress;
case WebInputEvent::KeyDown:
// The caller should disambiguate the combined event into RawKeyDown or Char events.
break;
default:
break;
}
NOTREACHED();
return EventTypeNames::keydown;
}
static inline KeyboardEvent::KeyLocationCode keyLocationCode(const WebInputEvent& key)
{
if (key.modifiers & WebInputEvent::IsKeyPad)
return KeyboardEvent::kDomKeyLocationNumpad;
if (key.modifiers & WebInputEvent::IsLeft)
return KeyboardEvent::kDomKeyLocationLeft;
if (key.modifiers & WebInputEvent::IsRight)
return KeyboardEvent::kDomKeyLocationRight;
return KeyboardEvent::kDomKeyLocationStandard;
}
KeyboardEvent* KeyboardEvent::create(ScriptState* scriptState, const AtomicString& type, const KeyboardEventInit& initializer)
{
if (scriptState->world().isIsolatedWorld())
UIEventWithKeyState::didCreateEventInIsolatedWorld(initializer.ctrlKey(), initializer.altKey(), initializer.shiftKey(), initializer.metaKey());
return new KeyboardEvent(type, initializer);
}
KeyboardEvent::KeyboardEvent()
: m_location(kDomKeyLocationStandard)
{
}
KeyboardEvent::KeyboardEvent(const WebKeyboardEvent& key, AbstractView* view)
: UIEventWithKeyState(eventTypeForKeyboardEventType(key.type), true, true, view, 0, static_cast<PlatformEvent::Modifiers>(key.modifiers), key.timeStampSeconds, InputDeviceCapabilities::doesntFireTouchEventsSourceCapabilities())
, m_keyEvent(wrapUnique(new WebKeyboardEvent(key)))
// TODO: BUG482880 Fix this initialization to lazy initialization.
, m_code(Platform::current()->domCodeStringFromEnum(key.domCode))
, m_key(Platform::current()->domKeyStringFromEnum(key.domKey))
, m_location(keyLocationCode(key))
{
initLocationModifiers(m_location);
}
KeyboardEvent::KeyboardEvent(const AtomicString& eventType, const KeyboardEventInit& initializer)
: UIEventWithKeyState(eventType, initializer)
, m_code(initializer.code())
, m_key(initializer.key())
, m_location(initializer.location())
{
if (initializer.repeat())
m_modifiers |= PlatformEvent::IsAutoRepeat;
initLocationModifiers(initializer.location());
}
KeyboardEvent::KeyboardEvent(const AtomicString& eventType, bool canBubble, bool cancelable, AbstractView* view,
const String& code, const String& key, unsigned location, PlatformEvent::Modifiers modifiers,
double plaformTimeStamp)
: UIEventWithKeyState(eventType, canBubble, cancelable, view, 0, modifiers, plaformTimeStamp, InputDeviceCapabilities::doesntFireTouchEventsSourceCapabilities())
, m_code(code)
, m_key(key)
, m_location(location)
{
initLocationModifiers(location);
}
KeyboardEvent::~KeyboardEvent()
{
}
void KeyboardEvent::initKeyboardEvent(ScriptState* scriptState, const AtomicString& type, bool canBubble, bool cancelable, AbstractView* view,
const String& keyIdentifier, unsigned location, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
{
if (isBeingDispatched())
return;
if (scriptState->world().isIsolatedWorld())
UIEventWithKeyState::didCreateEventInIsolatedWorld(ctrlKey, altKey, shiftKey, metaKey);
initUIEvent(type, canBubble, cancelable, view, 0);
m_location = location;
initModifiers(ctrlKey, altKey, shiftKey, metaKey);
initLocationModifiers(location);
}
int KeyboardEvent::keyCode() const
{
// IE: virtual key code for keyup/keydown, character code for keypress
// Firefox: virtual key code for keyup/keydown, zero for keypress
// We match IE.
if (!m_keyEvent)
return 0;
#if OS(ANDROID)
// FIXME: Check to see if this applies to other OS.
// If the key event belongs to IME composition then propagate to JS.
if (m_keyEvent->nativeKeyCode == 0xE5) // VKEY_PROCESSKEY
return m_keyEvent->nativeKeyCode;
#endif
if (type() == EventTypeNames::keydown || type() == EventTypeNames::keyup)
return m_keyEvent->windowsKeyCode;
return charCode();
}
int KeyboardEvent::charCode() const
{
// IE: not supported
// Firefox: 0 for keydown/keyup events, character code for keypress
// We match Firefox
if (!m_keyEvent || (type() != EventTypeNames::keypress))
return 0;
return m_keyEvent->text[0];
}
const AtomicString& KeyboardEvent::interfaceName() const
{
return EventNames::KeyboardEvent;
}
bool KeyboardEvent::isKeyboardEvent() const
{
return true;
}
int KeyboardEvent::which() const
{
// Netscape's "which" returns a virtual key code for keydown and keyup, and a character code for keypress.
// That's exactly what IE's "keyCode" returns. So they are the same for keyboard events.
return keyCode();
}
void KeyboardEvent::initLocationModifiers(unsigned location)
{
switch (location) {
case KeyboardEvent::kDomKeyLocationNumpad:
m_modifiers |= PlatformEvent::IsKeyPad;
break;
case KeyboardEvent::kDomKeyLocationLeft:
m_modifiers |= PlatformEvent::IsLeft;
break;
case KeyboardEvent::kDomKeyLocationRight:
m_modifiers |= PlatformEvent::IsRight;
break;
}
}
DEFINE_TRACE(KeyboardEvent)
{
UIEventWithKeyState::trace(visitor);
}
} // namespace blink
| [
"bino.zh@gmail.com"
] | bino.zh@gmail.com |
70b13cdc2d2a9e5217cea89f5f4284e0ad894fbf | 4f8bb0eaafafaf5b857824397604538e36f86915 | /课件/计算几何/计算几何_陈海丰/计算几何代码/pku_1389_矩形相交.cpp | ef0069449dd296a17ffe39e671b46587beef9713 | [] | no_license | programmingduo/ACMsteps | c61b622131132e49c0e82ad0007227d125eb5023 | 9c7036a272a5fc0ff6660a263daed8f16c5bfe84 | refs/heads/master | 2020-04-12T05:40:56.194077 | 2018-05-10T03:06:08 | 2018-05-10T03:06:08 | 63,032,134 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 2,188 | cpp | /*
大牛的思想
题目给出 n 个矩形,要求它们的面积并。具体做法是离散化。
先把 2n 个 x 坐标排序去重,然后再把所有水平线段(
要记录是矩形上边还是下边)按 y 坐标排序。
最后对于每一小段区间 (x[i], x[i + 1]) 扫描所有的水平线段,
求出这些水平线段在小区间内覆盖的面积。总的时间复杂度是 O(n^2)。
利用线段树,可以优化到 O(nlogn)。
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define up 1
#define down -1
typedef struct TSeg
{
double l, r;
double y;
int UpOrDown;
}TSeg;
TSeg seg[4000];
int segn;
double x[4000];
int xn;
int cmp1(const void *a, const void *b)
{
if(*(double *)a < *(double *)b) return -1;
else return 1;
}
int cmp2(const void *a, const void *b)
{
TSeg *c = (TSeg *)a;
TSeg *d = (TSeg *)b;
if(c->y < d->y) return -1;
else return 1;
}
void movex(int t, int &xn)
{
int i;
for(i = t;i <= xn - 1;i++){
x[i] = x[i + 1];
}
xn--;
}
int main()
{
//freopen("in.in", "r", stdin);
//freopen("out.out", "w", stdout);
int n, i, j, cnt;
double x1, y1, x2, y2, ylow, area;
while(1){
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
if(x1 == -1 && x2 == -1 && y1 == -1 && y2 == -1) break;
xn = 0;
segn = 0;
while(1){
if(xn != 0) {
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
if(x1 == -1 && x2 == -1 && y1 == -1 && y2 == -1) break;
}
x[xn++] = x1;
x[xn++] = x2;
seg[segn].l = x1;
seg[segn].r = x2;
seg[segn].y = y1;
seg[segn++].UpOrDown = down;
seg[segn].l = x1;
seg[segn].r = x2;
seg[segn].y = y2;
seg[segn++].UpOrDown = up;
}
qsort(x, xn, sizeof(x[0]), cmp1);
/*除掉重复的x*/
for(i = 1;i < xn;){
if(x[i] == x[i - 1]) movex(i, xn);
else i++;
}
qsort(seg, segn, sizeof(seg[0]), cmp2);
area = 0.0;
for(i = 0;i < xn - 1;i++){
cnt = 0;
for(j = 0;j < segn;j++){
if(seg[j].l <= x[i] && seg[j].r >= x[i + 1]){
if(cnt == 0) ylow = seg[j].y;
if(seg[j].UpOrDown == down) cnt++;
else cnt--;
if(cnt == 0) area += (x[i + 1] - x[i]) * (seg[j].y - ylow);
}
}
}
printf("%.0lf\n", area);
}
return 0;
}
| [
"wuduotju@163.com"
] | wuduotju@163.com |
97bef332a39ede576ecfb6cf6cc8382d71be668b | 69f8736d82d85b53282d9e8d750987c4fa587ed8 | /mainwindow.h | 1756b3ceb08e00123513c2189e10b3e904ec78e9 | [] | no_license | dridk/sampleIDViewer | 0673304ccf5d26f8ca82ca283fac125945a4baf8 | 46d9b173539da6c01f4984cf79d1337a2e43fcdc | refs/heads/master | 2021-01-16T21:23:27.926793 | 2015-07-10T15:00:00 | 2015-07-10T15:00:00 | 38,535,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 895 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "sampleidlistwidget.h"
#include "fsaplot.h"
#include "fsainfowidget.h"
#include "sampleidinfowidget.h"
#include "filebrowserwidget.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void open();
void setStatus(const QString& message);
protected:
void createToolBar(const QList<QAction*>& actionsList);
private:
Ui::MainWindow *ui;
SampleIDListWidget * mListWidget;
FsaPlot * mPlot;
QTabWidget * mTabWidget;
QSplitter * mSplitter;
SampleIDInfoWidget * mSampleIdInfoWidget;
FsaInfoWidget * mFsaInfoWidget;
FileBrowserWidget * mBrowserWidget;
QLabel * mAnimLabel;
};
#endif // MAINWINDOW_H
| [
"sacha@labsquare.org"
] | sacha@labsquare.org |
e0d9f27c9916c1e463b3996300d49e45d298ccea | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/67/9e06c1d7609ea2/main.cpp | d84f86a9b4fd674ca3b421d159be980bae2ca582 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 176 | cpp | #include <iostream>
int main()
{
const char * UserName = "Vasia";
printf("C String %s can be located by pointer %p", UserName, UserName);
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
15988d290412b98a7ed49573e21ef3adfd110956 | b4ba3bc2725c8ff84cd80803c8b53afbe5e95e07 | /Medusa/MedusaCore/Core/Chrono/ProfileNode.h | e22a385b9e2a1e3e99b2640814ef6ae2a52e76fb | [
"MIT"
] | permissive | xueliuxing28/Medusa | c4be1ed32c2914ff58bf02593f41cf16e42cc293 | 15b0a59d7ecc5ba839d66461f62d10d6dbafef7b | refs/heads/master | 2021-06-06T08:27:41.655517 | 2016-10-08T09:49:54 | 2016-10-08T09:49:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,892 | h | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#pragma once
#include "MedusaCorePreDeclares.h"
#include "Core/Collection/List.h"
#include "Core/String/StringRef.h"
#include "Core/Collection/List.h"
#include "Core/Chrono/StopWatch.h"
MEDUSA_BEGIN;
class ProfileNode
{
public:
ProfileNode(const StringRef& name, ProfileNode* parent, size_t count = 1, size_t logCount = 0);
ProfileNode();
~ProfileNode();
public:
void Begin();
bool End();
bool End(StopWatch::TimePoint timeStamp);
bool Count(StopWatch::Duration elapsedTime);
void Reset();
void Stop();
ProfileNode* FindOrCreateChildNode(const StringRef& name, size_t count = 1, size_t logCount = 0);
void PrintResult(const StringRef& totalPrefix, const StringRef& perPrefix)const;
public:
const StringRef& Name() const { return mName; }
ProfileNode* Parent() const { return mParent; }
StopWatch::Duration AverageTime()const { return mTotalCount!=0?mTotalTime / mTotalCount / mCount: StopWatch::Duration(0); }
StopWatch::Duration MinTime()const { return mTotalCount != 0 ? mMinTime / mCount : StopWatch::Duration(0); }
StopWatch::Duration MaxTime()const { return mTotalCount != 0 ? mMaxTime / mCount : StopWatch::Duration(0); }
StopWatch::Duration ElapsedTime()const { return mElapsedTime / mCount; }
private:
StringRef mName;
ProfileNode* mParent = nullptr;
List<ProfileNode*> mChildren;
size_t mCount = 1; //each run count
size_t mTotalCount = 0;
StopWatch::Duration mTotalTime{ 0 };
StopWatch::TimePoint mStartTime;
StopWatch::TimePoint mEndTime;
StopWatch::Duration mElapsedTime{ 0 };
int mRecursionCounter = 0;
List<int64> mTimeLogs;
size_t mMinLogIndex = 0;
size_t mMaxLogIndex = 0;
StopWatch::Duration mMinTime{ Math::UIntMaxValue };
StopWatch::Duration mMaxTime{ 0 };
};
MEDUSA_END; | [
"fjz13@live.cn"
] | fjz13@live.cn |
762ee83bd6c0f5853fbac5043ddeea83cfc9b89e | 493ac26ce835200f4844e78d8319156eae5b21f4 | /flow_simulation/ideal_flow/processor0/0.84/phi | 3ec670db9b82b335986b35d94a254dffcbcd89dc | [] | no_license | mohan-padmanabha/worm_project | 46f65090b06a2659a49b77cbde3844410c978954 | 7a39f9384034e381d5f71191122457a740de3ff0 | refs/heads/master | 2022-12-14T14:41:21.237400 | 2020-08-21T13:33:10 | 2020-08-21T13:33:10 | 289,277,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,108 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "0.84";
object phi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 3 -1 0 0 0 0];
oriented oriented;
internalField nonuniform List<scalar>
2708
(
1.47346e-05
-3.77602e-05
-3.47387e-06
2.64995e-05
-4.06131e-05
5.12189e-05
-0.00015991
0.000149304
0.00123751
0.000236172
-0.000913241
-0.000560445
-0.000326483
0.000184405
6.20447e-05
8.00338e-05
1.68696e-05
-5.33892e-06
-8.7447e-05
7.59164e-05
0.00046119
0.000353598
-0.000241238
-0.00057355
6.60065e-05
9.49117e-05
0.00060218
-0.000825671
0.00100601
-0.000782524
0.000193873
0.00031752
-0.000412831
-9.85624e-05
0.000158359
0.000257789
-0.000293086
-0.000123063
0.000255759
1.51994e-05
-2.29987e-05
-0.00024796
-5.04247e-05
0.000137895
-8.74706e-05
1.78192e-05
-3.18073e-05
-1.46289e-05
2.86171e-05
0.000850937
-0.000865457
4.14853e-05
-2.69654e-05
0.000137121
-0.000142196
6.1439e-05
-5.63634e-05
-4.85271e-07
-0.000325496
0.000325981
-0.000221132
0.000199077
0.000159176
-8.84572e-05
0.00024647
-0.000188855
3.08425e-05
-2.02751e-06
-2.08208e-05
2.28484e-05
0.000255132
4.0687e-05
-4.00601e-05
-7.69527e-05
-3.98165e-05
1.01857e-05
0.000106584
-0.000109515
-0.000159748
-4.03827e-05
7.42033e-05
0.000271907
-0.000305728
0.000821461
5.87115e-05
-2.92361e-05
0.000377336
7.71508e-05
-0.000406611
-4.7876e-05
0.000231897
-5.66054e-05
7.98405e-05
-0.000414671
0.000345383
-0.00015607
0.000225358
3.46346e-05
-1.94607e-05
-0.000880631
-0.001038
8.37648e-05
0.000958546
-4.30956e-06
-0.000222422
0.000139278
9.80594e-05
-1.49151e-05
-0.00043578
0.000976524
-0.000560009
1.92648e-05
0.000929776
0.000449679
-0.00061419
-0.000765265
0.000210795
0.00019633
-0.000407125
0.000118442
-0.00014573
2.7288e-05
0.000103338
-0.00014442
4.1082e-05
-0.000877022
0.000873935
0.000675001
-0.000671914
0.000147305
-3.02188e-05
-0.000183316
6.623e-05
-0.0011861
0.00114283
-5.22344e-05
9.54973e-05
5.99816e-05
-6.44571e-05
-0.000125672
-0.00140047
-3.51271e-05
0.000249499
-0.000358403
-0.000256935
4.23464e-05
0.000572992
0.000116616
-1.51398e-05
-0.000101476
-3.69865e-05
5.13711e-05
-0.000133331
0.000118947
-4.83981e-05
7.38424e-05
-0.000132167
0.000106723
0.00014172
-5.08336e-05
-0.000222017
0.000131131
7.44134e-05
0.000140445
-0.000100398
-0.000114461
5.36301e-05
0.000677619
-0.000375344
-0.000355905
-1.74501e-05
2.78831e-05
-0.000956102
0.000945669
-0.000655997
0.00116346
-0.000871037
0.000363577
3.00391e-05
-0.00108239
0.00110884
-5.64833e-05
0.000217864
-5.15461e-06
-0.000223854
1.1145e-05
-0.000429519
0.000271011
0.000316867
-0.000562092
0.000325439
0.000430527
-4.61221e-05
5.15679e-05
-5.39325e-05
4.84867e-05
-3.37648e-05
4.86092e-05
-8.24591e-05
6.76146e-05
-0.000970242
0.00011457
0.000953063
-9.73918e-05
-7.56019e-05
-8.61801e-05
0.000464849
-0.000303068
-0.000142136
-7.05781e-05
0.000625133
-0.000412419
-0.000568379
0.000531045
-4.59849e-05
9.76452e-05
-0.000128613
0.000331271
-0.00027702
-6.20355e-07
0.000118713
7.69112e-05
-7.55434e-05
-0.000120081
0.000460266
-0.000744843
-0.000592445
-0.000426775
0.000472266
0.00101195
-0.00105744
0.000847792
-0.000171105
-4.76096e-05
-0.000629077
-1.87217e-06
5.78964e-06
-0.000255817
0.0002519
0.000222113
-2.36429e-05
2.49744e-05
7.59142e-05
-4.69174e-05
-5.39712e-05
-0.000624492
0.0010295
-0.000734645
0.000329637
8.14552e-05
5.49403e-05
8.37808e-05
-1.244e-05
-7.94322e-05
8.0914e-06
-0.000106879
-3.68759e-06
-2.07276e-06
0.00011264
6.48971e-05
0.000145898
1.99854e-05
8.76359e-05
-0.000104407
-3.21453e-06
2.14822e-05
0.000644772
-0.000430082
0.000967444
6.29144e-05
-0.00101536
-1.50029e-05
0.000136961
-0.000265281
-6.88767e-05
0.000197197
-0.000953689
0.000926096
-0.000399182
1.36872e-05
0.000228099
-7.93863e-06
-0.000233847
-3.55603e-05
4.19344e-05
-3.42167e-05
2.78426e-05
4.8365e-05
-0.000138516
0.000187415
-9.72642e-05
-0.000277877
-6.456e-05
0.000202544
0.000139893
9.02897e-05
-0.000107345
3.65694e-05
-1.95142e-05
0.000138447
-2.00718e-06
-0.000153141
1.67011e-05
-6.68528e-05
-3.97929e-05
6.03127e-05
4.63329e-05
0.000781426
7.79435e-05
-3.79079e-05
-0.000118636
0.000139598
-0.000189204
0.000168243
0.000124519
0.000119369
-0.000112605
-0.000131283
-0.000204285
0.000182716
-4.52836e-05
0.00012292
-3.63742e-07
1.58906e-05
0.00113004
-1.74757e-05
3.02649e-05
-1.33821e-06
5.40944e-06
-0.000184581
0.00018051
-6.93097e-05
0.000124129
-0.000100804
-1.22428e-05
-9.46305e-05
-5.98723e-09
-6.6026e-05
-0.00100312
0.00103127
3.78744e-05
-0.000137717
-2.56172e-05
0.000139082
2.42528e-05
-0.000806242
-0.000285536
6.9447e-05
2.32267e-05
-6.76993e-05
3.01826e-05
-0.001087
0.00108712
-3.03018e-05
-6.25477e-05
1.80736e-05
0.000128256
-8.37816e-05
-0.000138249
7.99219e-06
-1.78843e-05
0.000148141
0.000205545
2.05139e-05
8.14998e-06
-0.000234209
4.46422e-05
-8.10236e-05
-4.56673e-05
8.20486e-05
0.00104003
-0.00146422
0.000184091
0.000240101
0.000475586
8.96064e-06
1.26046e-05
-0.000497151
8.82609e-05
8.77381e-05
-0.000957383
2.191e-05
5.98103e-05
-8.66602e-05
4.9399e-06
-6.15359e-06
0.00017066
-0.000216891
5.23843e-05
6.44355e-06
-0.000175087
0.000166771
0.000845112
-0.000579183
4.91712e-05
-0.0003151
-0.000223239
0.000141775
0.000200178
8.47656e-07
-1.52815e-06
0.000206226
1.2269e-05
-6.38915e-06
-0.000144129
-0.000148764
-5.76273e-05
0.000117934
3.47537e-05
-3.50224e-06
-4.49991e-05
1.37477e-05
0.000727278
9.92835e-05
-4.51357e-05
0.000171643
0.000166407
-0.00113878
0.00114082
9.59165e-05
-9.79535e-05
-0.000304017
-0.000400211
-0.000216007
-0.000289114
0.000772606
0.000179097
-0.000823267
-0.000128435
-0.0009932
-0.000637389
0.00105505
0.00057554
2.28591e-05
-3.0272e-05
-1.90375e-05
2.64504e-05
0.000117336
-4.4332e-05
0.000654274
-6.6373e-05
1.34013e-05
4.92841e-05
-2.3016e-05
4.76769e-05
-6.92601e-05
4.45991e-05
0.000822504
-0.00104102
0.000356532
-0.000138016
-9.33129e-05
6.31876e-05
1.95299e-05
1.05954e-05
-0.000351436
2.00863e-05
-0.000102464
-0.000755686
0.00085815
-9.31568e-05
-0.000194871
0.000225481
6.20624e-06
-1.47813e-05
0.000131495
-6.13898e-06
5.01436e-05
-0.00024829
8.85212e-05
-1.54329e-06
-3.19707e-06
-1.59633e-05
9.97323e-07
0.000174434
-0.000159468
-0.00010656
0.000131295
-1.28178e-06
-2.34529e-05
-0.000332863
-7.95064e-05
6.09334e-05
-0.000337799
4.4554e-05
0.000313039
-1.97942e-05
-0.000106587
9.14759e-06
0.000103646
0.000899133
-2.32708e-05
-0.000766298
-0.000109564
-0.00010386
0.00111226
0.000155062
-0.00110946
9.22406e-05
0.000860026
-0.00102786
-0.000262866
0.000430697
-0.000227115
-0.000988277
0.00118973
2.56572e-05
0.00015501
-1.22875e-05
-2.41249e-05
9.33661e-06
0.000103309
-0.000917849
0.000881754
-0.000275552
0.000311648
0.0012705
7.66069e-05
-0.00031579
-0.00103132
-4.97198e-05
0.000906619
-9.10744e-06
-8.83924e-05
0.000130716
-8.42161e-06
-3.39021e-05
-1.22561e-06
-3.43347e-05
6.7825e-05
9.08622e-06
-3.75749e-05
-4.10409e-05
-0.000930172
-0.00037805
0.000354532
-0.000269751
-9.69875e-05
0.000273581
0.000909223
0.000115338
-0.000179449
-0.000189075
0.000900543
-0.000885569
0.000174102
0.000249383
-2.49806e-05
2.20669e-05
-0.000159513
0.000176075
-3.45398e-05
-2.79145e-05
8.05279e-05
-1.72818e-05
7.08357e-05
-5.27063e-05
-2.59645e-05
0.000146772
-6.99333e-05
-2.19221e-05
8.57018e-05
-9.60129e-05
4.86132e-05
2.14428e-05
1.647e-06
-6.20536e-06
-0.000103568
6.88596e-05
-0.000160163
-0.000948024
0.000183233
0.000882127
-2.37973e-06
0.000216317
-0.000214423
0.000369621
-0.000583752
-0.00055437
0.000768501
1.41542e-05
0.000238265
-0.000876911
-3.3865e-05
0.000918565
1.44328e-05
8.52715e-05
4.12359e-05
-0.000126507
-2.51981e-05
1.90591e-05
0.00108402
-0.00126059
-0.000153598
0.000330175
0.000150472
6.92725e-05
-8.04666e-05
-0.000820429
-0.000351588
0.000853953
0.000318063
-8.41462e-05
0.00104642
-0.000949675
-1.26003e-05
-2.02707e-05
0.00014136
-2.71901e-05
-9.38988e-05
0.00012728
-0.000981384
0.000947272
-9.31674e-05
0.000176236
-0.000151282
-0.000248193
-0.000333613
0.000247638
0.000946002
-0.000924829
0.000913568
-0.000177814
0.000627723
-0.000604726
2.42683e-06
0.000555829
-0.000508112
-6.35351e-05
0.000176796
-0.0003329
-0.000909168
0.000311895
-3.65076e-05
-0.000157711
0.000224324
-3.01051e-05
-0.000339662
0.000350534
-9.47382e-05
8.38666e-05
0.000104298
0.00101744
-0.000892798
-0.000158504
0.000278286
-2.96794e-05
1.17397e-05
-0.000260346
-0.000153809
0.000166032
0.0011286
8.18425e-06
2.31457e-05
0.0010087
0.000127599
0.000935351
-0.00100269
-6.02652e-05
-3.72878e-05
-3.82556e-05
-2.79512e-05
2.94945e-05
-0.000210135
0.000280671
-7.05369e-05
-0.000200302
-0.000917716
0.000200168
-0.000326958
-7.50099e-05
4.35648e-05
-0.000198074
-0.00024871
4.08232e-05
-4.65463e-05
4.08783e-05
0.00102321
-8.68363e-05
-0.000977255
-1.65968e-05
0.000136463
-0.000123722
3.8552e-06
-7.52924e-05
0.00105684
-0.000650762
-0.000265307
0.000675091
-1.24875e-05
-0.000889718
0.000133064
0.000833905
-0.000194364
0.000977339
0.000149031
-0.000159369
-0.000967001
0.000174701
-3.33415e-05
-0.00022754
0.000179636
-5.19742e-05
-0.00019824
0.00020504
0.00089899
-0.000194807
0.000176802
4.32226e-05
-0.000256532
-8.12993e-05
0.00010089
5.46789e-06
-2.5059e-05
0.000369029
-9.18786e-05
0.000583821
-0.000860972
0.000353169
-0.000100841
0.000514915
0.00122785
-0.00055447
-0.000358771
0.000810525
-0.000883957
-1.84461e-05
-0.00102097
-0.000832583
0.000592958
0.000836704
-0.000903942
-0.000231544
-0.0010113
4.9539e-05
0.00100324
0.000881625
0.000105257
-1.66245e-05
-8.89958e-05
-0.000164786
0.000184987
0.000162515
0.00101257
0.000201018
-0.000531696
0.000962138
-0.00125611
-0.000416745
-0.000922963
0.000808012
-0.000616214
0.00087456
-8.19627e-05
-0.000991689
8.5374e-05
2.76304e-05
6.00614e-05
-7.29573e-05
-0.00093754
0.000664196
-5.95552e-05
-4.05918e-05
2.68041e-05
-2.46942e-05
3.8482e-05
-0.00110912
-3.60039e-05
0.00106984
-0.000188723
0.00017155
-0.000262568
-8.02808e-05
0.00013314
0.000209709
-0.000508275
0.000628879
-2.2441e-05
1.56874e-05
-3.08212e-05
-1.62938e-05
1.71831e-05
-2.33303e-05
0.000756957
0.000173544
0.000159976
-0.00100362
0.000154881
-0.000973958
-8.72059e-05
0.00117359
-0.00011243
0.000142583
-8.76306e-05
0.00014846
-0.000128407
0.00079202
0.000489867
-0.00115429
0.000197275
-0.000264499
-0.000964088
0.000987678
-2.35901e-05
9.58344e-05
-9.94908e-05
3.65637e-06
1.2863e-05
-3.76414e-06
-4.96907e-05
-0.00104851
-2.41671e-05
0.00107267
-0.00100524
0.00101654
-1.13044e-05
-0.000934049
-1.57564e-05
-0.000478542
0.000179826
-3.90822e-05
0.000244489
-0.000873191
-0.00102457
4.79104e-05
-0.000989278
0.00108519
0.000908977
-0.000232083
-0.000933644
-0.000118184
0.000942755
0.000109073
-0.000204097
2.55781e-05
0.000295579
-0.000117061
0.00100048
2.38313e-05
0.000445133
-0.000980259
5.5371e-05
-4.90705e-05
8.825e-05
-0.00101897
-3.4406e-05
-0.000899643
0.00102852
-0.00067111
-3.90429e-05
0.000143716
2.35829e-05
0.000144618
-7.18801e-05
-0.000123162
2.52653e-05
-2.77832e-05
-0.000154452
0.00015697
-0.000411563
-9.75298e-05
-7.66252e-05
-0.000640223
1.2956e-05
-1.26348e-05
2.64828e-05
1.90651e-05
-2.74991e-05
-7.28654e-05
-4.83465e-05
0.000234784
-0.000967836
-0.000411966
-0.000844191
0.000531936
0.000724221
-0.00101288
-0.0010513
-9.2658e-05
5.52922e-05
0.00108866
0.000551604
3.19651e-05
0.00115869
-1.35175e-05
-0.00117714
-0.000686135
-0.00054626
-1.36383e-05
-0.000139383
0.000243968
-9.09466e-05
0.000976888
-0.00103941
-0.000383597
0.000203631
0.00121938
-2.56521e-05
9.26499e-05
3.73004e-05
0.000192951
-0.00106827
0.0010026
1.68985e-05
8.60061e-05
-9.00415e-05
-0.000235292
0.000203676
-0.00134687
-2.25999e-05
-4.68247e-05
4.85842e-05
-2.98518e-06
0.000305453
0.00102155
-6.52497e-05
-0.00126175
0.000171015
3.83196e-05
0.00010343
-0.000124851
0.000378502
-0.000260995
-1.75585e-05
-1.60147e-05
2.21258e-05
-3.55586e-06
0.000864278
-2.0469e-05
-6.08027e-05
8.52281e-05
-3.95643e-06
5.25803e-05
-0.000143277
-3.9586e-05
-3.08957e-05
-0.000139769
0.000149859
2.82298e-05
-4.4645e-05
-0.000330883
-3.60346e-05
4.9605e-05
-5.85719e-05
3.02044e-05
-2.12375e-05
0.000304461
-0.000982935
7.37792e-05
8.2864e-05
7.08675e-05
0.000118569
-6.68737e-05
7.92745e-05
8.05657e-05
3.3759e-05
-0.000367671
0.000378466
6.31211e-05
-6.23401e-05
1.2175e-05
-4.10044e-05
3.11562e-05
5.82266e-05
-4.83785e-05
6.09886e-05
6.69688e-05
0.000405113
0.000923303
-0.000402321
-4.00983e-05
-7.02818e-05
5.94003e-05
5.09798e-05
0.00107959
4.68569e-05
-2.88267e-05
-3.43401e-05
1.63099e-05
9.02382e-06
5.31348e-05
-5.49707e-05
-7.18797e-06
1.27732e-06
-3.81777e-06
-1.00943e-05
-0.000129306
0.000171156
-0.000199561
-4.50652e-05
-0.000140106
0.00010489
-0.000167644
-1.12843e-05
0.000180575
-3.962e-05
6.06198e-05
-3.79177e-06
-0.000169007
-2.93897e-05
1.48173e-06
-1.41635e-05
4.20715e-05
0.00117793
-0.000891788
4.86541e-05
-6.10334e-05
0.000134143
0.000103831
-0.000248962
-0.000547878
0.000693009
-5.54583e-05
4.93963e-05
6.06192e-06
0.00010525
-0.00091628
-7.29277e-05
2.47269e-06
-1.09339e-05
8.46125e-06
1.51574e-05
-3.66183e-05
2.14609e-05
4.89831e-05
-6.00541e-05
1.10711e-05
-9.5697e-05
3.52472e-05
6.04498e-05
1.93173e-05
-6.49916e-06
-1.28182e-05
-4.61751e-05
-1.51661e-05
6.13411e-05
0.000107369
-0.000106195
-1.17447e-06
-2.98589e-05
4.43338e-05
-1.44749e-05
-0.000112134
1.64371e-05
3.25127e-05
-1.31953e-05
-5.36457e-05
-1.81258e-06
-9.67405e-05
0.000101222
-4.48124e-06
5.23038e-05
-5.09423e-05
-1.36148e-06
9.20426e-05
-8.33769e-06
-2.15212e-05
0.000106031
5.20289e-05
-5.89838e-05
6.95492e-06
-2.27019e-05
3.78593e-05
-1.10269e-05
1.34995e-05
-0.000102658
3.16711e-06
-2.50229e-05
4.30288e-05
-1.80059e-05
1.13599e-05
-5.76824e-05
2.45097e-05
2.18129e-05
1.29505e-05
8.22714e-05
-6.4695e-05
-0.000121697
0.000145779
-2.71811e-05
7.8979e-05
8.31595e-05
-0.000110523
0.00023958
-0.000142695
-9.18782e-05
2.03225e-05
0.000172446
4.02049e-05
-3.82473e-05
-3.07843e-05
1.72373e-05
-0.000329785
-0.000637128
-0.000338914
0.000387843
0.00106218
-0.000113508
1.67677e-05
1.39565e-05
-1.29544e-05
-1.00212e-06
2.42203e-05
2.62811e-05
-1.36624e-05
-3.33606e-05
3.37291e-06
6.1672e-05
-1.86432e-05
-9.31183e-06
-4.97279e-06
1.54106e-05
-1.44058e-05
3.47182e-06
-0.000334132
-0.000613766
0.00036142
0.000586478
0.00103928
-0.000267087
7.5666e-05
1.57966e-05
-5.40066e-05
4.96578e-05
-1.14478e-05
-3.01998e-05
3.68492e-05
0.000915091
-0.000924514
9.27077e-05
-8.32845e-05
2.07824e-05
1.59668e-05
-3.14621e-05
-5.28705e-06
4.85047e-05
3.79906e-06
-7.00691e-05
-1.52703e-05
5.09994e-05
7.03836e-06
-0.000172388
1.13611e-05
-7.54378e-05
1.83011e-05
4.57757e-05
0.00109073
-0.000294287
5.37814e-05
2.35821e-05
-2.77584e-05
0.000424062
-0.0010829
0.000964295
-7.1112e-06
-2.05519e-05
3.80343e-05
1.51211e-05
0.000156944
-0.000370142
0.000728113
-8.64103e-05
9.39329e-05
-8.23299e-05
0.000692254
0.000671239
-0.000489557
8.20452e-05
-7.92524e-05
0.00065765
-0.000361821
-0.000295829
-7.96987e-05
7.85168e-05
4.59197e-05
-4.47378e-05
-0.000398489
-0.00012845
0.000322842
-4.77096e-05
-4.52411e-05
3.22493e-05
6.07014e-05
1.53877e-05
9.3975e-06
-4.84832e-06
-2.67801e-05
4.91567e-05
-1.73194e-05
-5.05723e-06
-6.10196e-05
6.20645e-05
-3.67837e-05
3.57388e-05
6.32911e-05
-4.85518e-05
-0.000171617
0.000156878
-7.01331e-06
-1.75591e-05
-2.20766e-06
-5.6006e-05
4.83364e-05
-7.20291e-05
-0.000140771
-3.01195e-05
0.000234181
-5.17714e-05
0.000118539
-7.91629e-05
1.23953e-05
7.84856e-05
-8.96175e-05
-0.000112346
0.000108019
9.39442e-05
-0.000134223
-0.000102406
-5.10579e-07
5.43649e-05
-6.73452e-05
0.000121108
5.40578e-05
-4.21199e-05
-0.000133045
2.53488e-05
1.05315e-05
-0.000122311
-1.34194e-05
5.90969e-05
7.66338e-05
-2.92682e-05
3.68417e-05
4.15833e-05
-0.000166683
-4.02084e-05
0.00015512
-0.00012224
-0.000121356
7.19789e-05
3.24817e-05
0.000374081
-0.000340322
9.77187e-05
-0.000143294
0.000167018
-0.000109508
-1.06789e-05
4.52057e-06
6.1583e-06
6.23625e-05
1.9164e-05
-7.11394e-05
-1.03871e-05
-7.84351e-07
2.91554e-05
3.39915e-05
-8.8427e-05
-2.46579e-05
2.41376e-05
6.86677e-05
-9.28053e-05
-8.18702e-05
0.00013589
3.79045e-08
-0.000112763
-1.12269e-05
-2.71492e-05
-4.05288e-05
6.6584e-06
-6.869e-05
8.16893e-06
5.97367e-05
1.8815e-05
-2.92778e-05
7.25273e-05
-1.06552e-05
2.84542e-05
-3.51185e-05
-3.53549e-05
5.88615e-05
-4.69163e-06
4.09433e-05
-2.87593e-05
-3.93332e-05
2.82885e-05
-3.40943e-05
-3.4723e-05
-2.36895e-05
2.33511e-05
3.22021e-05
0.000271785
-0.000277402
0.000247726
-0.000242109
2.58304e-05
3.18975e-05
-5.77278e-05
-2.25877e-05
-9.3877e-06
-2.23728e-05
-0.000230825
0.000212815
1.9682e-05
5.74505e-05
8.85915e-05
-9.4593e-05
2.56835e-05
-4.7216e-05
-0.00044534
-0.000109469
0.000220678
-4.64549e-05
-5.14553e-05
7.55374e-05
1.18901e-06
3.96929e-05
0.000518438
-0.000271524
0.000276737
-0.00027799
-3.46296e-06
4.71539e-06
-4.32266e-05
1.76262e-05
0.000872799
-0.000215149
7.46e-05
-2.52789e-05
-9.5776e-05
3.01176e-05
-7.41697e-05
-0.000803209
0.00070788
0.000682492
-0.000814462
0.000579082
-0.000489417
0.000260869
-4.76204e-06
2.77844e-06
1.9836e-06
-2.24305e-05
0.000272848
1.47191e-05
-1.08296e-05
-0.000144408
0.00101721
-0.00110546
-0.00114028
9.55673e-05
-0.000106631
-8.69501e-05
-0.000167164
1.09391e-05
2.81429e-05
3.47395e-05
-2.17619e-05
-4.11206e-05
-4.90282e-05
4.63582e-05
4.23975e-05
-3.97275e-05
-3.5116e-06
2.76492e-05
1.00898e-06
4.96962e-06
2.08608e-05
-5.13365e-05
4.08619e-05
4.27239e-05
-0.000763548
0.00093945
0.000531979
7.74807e-06
1.93022e-05
0.000266134
-1.25884e-05
-0.000446715
7.90296e-05
0.000367686
0.000181872
-7.75552e-05
6.51117e-05
-0.000169429
9.50734e-05
-8.9405e-05
-0.000930182
-4.42288e-05
4.10864e-05
0.000185015
-0.000192264
-1.79117e-07
0.000522466
0.000155993
-0.000678458
-2.67438e-05
0.000136879
8.40342e-06
-4.70592e-06
-0.000162868
7.79566e-05
-0.000174162
5.71104e-05
9.77928e-05
-0.000111288
4.11439e-05
3.73845e-05
-5.86034e-05
-4.77747e-05
3.91339e-05
-5.8686e-05
3.91755e-05
4.03712e-05
0.000383848
-9.76679e-06
2.3275e-05
0.000360573
1.03748e-05
0.000166114
-6.83393e-05
5.46402e-05
4.91747e-05
-7.59632e-05
0.000498025
7.57502e-05
2.4493e-05
-5.94831e-05
-1.15278e-05
8.25077e-05
-0.000125127
-0.000145503
-1.39502e-06
0.000157978
-0.000153026
-9.50186e-06
1.24668e-05
-2.35169e-05
-0.000251226
2.70802e-05
0.000243448
-3.75083e-05
3.66943e-05
6.71588e-05
-4.75562e-05
-4.27057e-05
2.31032e-05
4.85748e-05
-5.72318e-05
-0.000154893
1.97654e-05
0.000188088
4.40412e-05
-0.00112349
-7.61188e-06
-0.000927125
-0.000327012
-0.000173814
5.10632e-05
4.61455e-05
2.85012e-05
3.79493e-05
-3.99784e-06
-8.01241e-05
8.72084e-05
-3.08644e-06
0.000198228
3.09473e-05
-5.67837e-05
7.2577e-06
-0.000252243
0.000325958
0.000430981
-0.000504696
3.59026e-06
-0.000161312
-5.14618e-06
-2.97996e-05
-0.00033946
2.97531e-05
-5.68755e-05
6.46025e-05
2.70126e-05
0.000172418
-0.000961543
-2.3304e-05
0.000993032
5.02921e-06
-3.67753e-05
4.72143e-05
3.04229e-05
3.0966e-05
-4.15036e-05
1.79041e-05
2.35994e-05
0.000985311
-0.00103755
4.28386e-05
-6.81058e-06
1.35243e-05
2.86796e-05
-7.50009e-05
-7.91428e-06
2.64035e-06
1.01632e-05
-4.88924e-06
4.15816e-05
-2.64462e-05
-0.000328798
1.75253e-05
-9.43767e-05
8.50203e-05
0.000143551
-0.000212342
0.000104283
-9.19314e-05
-2.02662e-05
0.000588249
-0.000311356
-2.32109e-05
-1.33564e-05
2.79827e-05
8.5847e-06
-3.29993e-05
5.49933e-05
-9.31333e-05
-0.000859324
6.07594e-05
0.000163391
8.74944e-05
-0.000168614
7.41448e-05
-0.000244717
1.57073e-05
-9.49399e-06
-6.21326e-06
4.80938e-05
1.40996e-05
-4.14111e-05
0.000257621
-0.000346474
-2.94621e-05
2.06804e-05
0.000273506
-4.82711e-05
7.19455e-05
6.16493e-05
-9.67531e-05
-9.54331e-05
-0.000154474
0.000187576
0.00026191
-0.0010026
0.000259246
2.05747e-05
-0.000741313
1.98706e-05
-9.357e-05
7.9278e-05
-2.0694e-05
-9.82537e-05
0.000115905
3.04263e-06
0.00020265
2.65437e-05
-3.37269e-05
-8.88303e-05
0.00110001
1.4551e-05
1.12826e-05
-0.00105406
-3.65383e-05
-8.10072e-05
0.000206396
-1.03096e-05
0.000538414
9.70277e-05
0.000250429
0.00124853
0.0011024
0.000163719
0.000200703
0.00110533
4.13707e-05
-2.33577e-05
1.35498e-05
-4.40998e-05
-0.000121832
-0.000157105
-0.000920774
0.00011682
-4.1054e-05
6.7193e-06
-0.000124435
7.3148e-05
-5.94522e-05
-0.000102526
3.95073e-05
-3.88981e-05
1.62174e-05
0.000187148
0.000149099
-3.52572e-05
-0.000147511
-1.89764e-05
4.8273e-05
1.79177e-05
-9.23789e-05
9.93724e-05
1.36869e-05
0.000835931
-0.00016632
-0.000639744
-2.98678e-05
-0.000750373
0.000693479
0.000318804
1.94935e-05
-6.54495e-05
3.55689e-05
1.7873e-05
-4.23471e-06
5.75621e-05
-8.34875e-07
-0.000242551
0.000328109
0.00015294
-0.000985464
7.8167e-05
0.00064667
-0.000645808
3.49323e-06
0.000400508
-0.000380726
-7.05958e-05
-1.12485e-06
-4.32732e-05
7.18187e-06
2.81337e-05
1.86886e-05
-3.03075e-05
-1.65148e-05
-0.000114992
8.94502e-05
0.000147822
-0.000203899
-0.000132778
-4.81495e-05
4.46774e-06
5.27056e-05
-9.80558e-05
7.7045e-05
0.000840856
3.48929e-06
-1.58408e-06
2.62285e-05
-3.46011e-05
-2.6599e-05
-2.69556e-05
4.20355e-05
2.65034e-05
-0.0010076
0.00104084
-0.000281945
1.62227e-05
-9.45019e-05
-0.000156781
1.76076e-06
0.000302842
0.000104592
-1.9321e-05
-0.00096676
-0.000199344
4.70093e-05
2.80665e-05
3.92195e-05
0.000790088
5.99113e-05
0.00104621
-0.00101183
0.000148811
-0.00015044
-0.000155151
0.000203257
1.04345e-05
0.000235409
1.6459e-05
-2.18804e-05
-0.000229988
-0.000308763
-2.03033e-05
3.2643e-05
7.15379e-06
-0.000179961
9.06878e-05
-8.3906e-07
-8.9179e-08
0.000421275
4.67461e-05
-5.27706e-06
0.000231249
-8.06779e-05
0.00010681
-2.80428e-05
-8.75995e-06
7.57658e-05
5.15631e-05
0.000198943
-0.000161883
0.000996723
-0.00124918
0.000267006
0.000155927
3.78052e-05
0.00072229
5.64622e-05
0.000945832
0.000277498
-9.96482e-05
-0.00112368
-7.60757e-05
-9.72987e-06
2.27612e-05
-3.83747e-05
-8.04527e-05
6.26985e-05
3.76965e-05
-1.99424e-05
-0.000138472
0.000213546
-0.000245433
0.000170359
-0.000198757
0.000184803
0.00133448
9.82773e-05
8.3423e-06
3.50553e-05
0.00132648
7.30058e-05
3.07305e-05
7.62254e-07
0.000124766
-4.6068e-05
-1.07689e-05
-0.00103183
8.04852e-05
-0.000140793
-3.56951e-05
2.48118e-05
3.36446e-05
-0.000976038
-0.00116342
0.000737516
-2.29382e-05
-1.29367e-05
-4.13488e-05
2.38064e-06
1.30783e-05
2.58899e-05
8.13751e-05
1.44694e-05
-5.5973e-05
8.13229e-05
6.69594e-06
-6.62267e-05
-2.92986e-05
-0.000146258
0.000109825
-4.13402e-05
7.77567e-05
-1.04274e-05
-7.23866e-05
2.70713e-06
8.80792e-05
-9.85392e-08
5.74649e-05
4.19209e-05
3.65719e-05
-8.15678e-05
7.49805e-06
-0.000158694
-3.82543e-06
-3.08402e-06
4.44867e-06
3.82601e-05
-5.41735e-05
-4.81034e-06
1.3015e-06
4.1654e-05
0.00086132
0.000132444
4.57217e-06
-0.000814299
1.37904e-06
2.53163e-05
-8.52976e-05
0.00046016
0.000408906
0.000148614
-1.40552e-05
0.00108513
-0.000495436
-2.5886e-05
0.000144655
-0.000135309
8.8713e-05
-5.75567e-05
7.83744e-06
-3.62179e-05
-3.29877e-05
8.7221e-05
2.15236e-05
-6.38382e-07
-0.000727233
0.000677778
4.94549e-05
0.000120302
-0.000123783
-4.12574e-05
-4.95689e-06
0.000276797
6.44603e-06
0.000891672
0.00014375
-0.000789296
6.20632e-05
5.12946e-05
0.00107383
-8.94641e-05
-0.000949939
0.0010161
-0.000332017
0.000565692
4.62984e-05
-0.000279973
-3.55934e-05
1.68084e-05
-1.06046e-05
5.80333e-05
0.000619744
-8.96602e-05
0.000100196
0.000106088
-0.000116623
4.70719e-05
-3.46035e-05
4.58638e-05
-5.83322e-05
-0.000200844
4.3515e-05
0.000157329
8.07583e-05
-5.9255e-05
5.89879e-05
8.34266e-05
8.04165e-05
2.41759e-05
-0.00024588
4.50363e-05
-0.000290212
0.00033631
-0.00038312
-0.000285207
-0.000892285
0.000268431
-2.41635e-05
2.92388e-05
-0.000134871
5.32821e-06
3.73945e-05
-0.000100018
0.000123015
1.3652e-06
0.000157394
-7.61357e-05
0.000392226
0.000537551
0.000184705
-4.57977e-05
-0.000158228
-0.000479685
0.000461572
1.8113e-05
8.27225e-05
-0.000872018
7.61074e-05
-0.000118954
-5.17329e-05
1.16275e-05
-0.000130122
0.000860239
-0.000335348
0.000373256
-0.000402492
-0.000222318
-7.64566e-05
-0.000156647
7.78033e-05
0.000878358
-0.000194832
0.000355758
-0.00096041
0.000657364
0.000632683
-0.00106665
-5.0151e-05
0.000580356
0.000389587
-0.000315384
-0.000635646
0.000579905
0.000523823
-0.00061386
0.000336916
0.000568947
-0.000265944
-0.000522879
2.28835e-05
0.000510935
0.000116248
3.67817e-07
-0.000636899
0.000758666
-0.000501613
2.19276e-05
-0.000136511
1.43376e-05
0.000369717
0.000555396
1.72141e-05
-3.18138e-05
-2.95001e-05
-1.97366e-05
1.68044e-05
-1.35826e-05
-2.86106e-05
-3.87346e-05
0.000448918
1.26539e-05
-0.000129096
6.20225e-06
4.24411e-05
0.000105368
-0.000169504
-3.96171e-05
-1.29459e-05
4.9052e-05
1.70287e-05
2.77689e-05
-1.56245e-05
4.53776e-05
-0.000429457
-0.000269483
8.16377e-05
2.17146e-05
6.84989e-06
-0.000536688
0.000113715
-0.000131497
1.44815e-06
-4.17907e-05
-2.90936e-05
-2.68608e-05
1.16971e-05
0.000111704
2.03146e-05
-0.000918795
0.000142344
-9.9998e-05
9.83392e-05
-0.000169492
0.00101352
-0.000961129
-4.35051e-05
-1.49078e-05
1.6593e-05
-1.3727e-06
0.000232703
0.000369884
-0.00108742
3.06876e-05
-7.21106e-05
7.03202e-05
-1.29776e-05
7.11135e-06
7.23146e-06
0.00092803
0.000135191
2.15151e-05
6.09244e-06
-1.49326e-05
-3.92409e-05
-9.19605e-05
-1.08569e-05
-0.000988305
0.000659414
6.43922e-05
-6.81101e-06
0.000248206
7.98878e-06
1.53562e-05
7.41024e-05
-1.21186e-05
0.00111706
6.98741e-05
-0.00108139
-0.000574301
0.000745584
3.57404e-06
-5.38344e-05
8.06061e-05
-0.000108051
0.000164406
0.000504232
-0.0007285
0.000224268
0.00043703
6.72024e-05
0.000448344
-1.13147e-05
-0.000309781
0.000466725
-0.000679923
-0.000603316
-0.000504754
-9.85617e-05
7.83728e-05
-4.79305e-05
0.000113845
-9.58505e-05
-0.000938301
-0.000121166
-6.81865e-05
-2.91298e-06
-1.16977e-05
1.27994e-05
5.34732e-05
-2.61295e-05
1.45342e-05
3.3392e-05
-1.00669e-05
4.24801e-05
2.20383e-05
-4.02982e-05
6.01834e-05
3.00933e-05
-2.52585e-05
-1.28458e-05
0.000437085
0.000814143
-2.84527e-05
2.87696e-05
1.97352e-05
-0.000154327
0.000180106
-9.78902e-05
-0.000227879
-0.000998318
0.000146546
-2.85931e-05
0.00021521
-0.000476986
-2.77678e-05
0.000272844
-0.000149182
-0.000613219
0.00012988
-5.80287e-05
-3.35624e-05
-4.10208e-05
-0.000163443
-0.000143928
7.50952e-05
6.00725e-05
9.81736e-05
-0.001152
0.00104031
-3.39323e-05
0.000205962
-0.000204731
-7.55541e-05
7.4323e-05
-2.231e-05
6.29846e-05
1.75903e-06
-6.18132e-05
0.00015543
-3.26857e-05
7.97762e-05
-0.0011903
1.85792e-06
0.000682656
-0.000383133
-5.37365e-05
3.33803e-06
-0.00025247
-7.68073e-05
-1.04342e-05
5.81388e-05
2.88148e-05
-1.28512e-05
-0.000116294
0.000111401
-0.000134371
5.80503e-05
-1.79441e-05
1.4825e-07
-0.000612609
-0.000374047
0.000131278
0.000172796
7.56444e-05
-0.000201923
0.000112859
1.70223e-05
3.91842e-05
-4.16723e-05
0.000995817
7.73827e-05
2.55563e-05
6.62392e-05
5.62125e-05
0.000168485
-7.54284e-05
-0.000164937
-0.000802759
0.00112273
-1.748e-05
-2.84908e-05
2.57172e-05
-0.000181274
-4.5144e-06
-8.54332e-06
-4.04704e-06
0.00103977
-4.71007e-05
-8.78732e-06
1.81278e-05
0.000202573
0.000154948
-9.27746e-05
-9.82237e-05
9.51313e-05
-0.00086058
4.14924e-05
0.000639911
8.17733e-05
-8.79448e-05
5.95219e-05
0.00108781
7.0905e-05
9.19969e-05
8.72252e-05
-0.000375885
5.18625e-05
0.000199695
-5.56644e-07
-4.34694e-05
-0.000238276
0.000203293
2.87774e-05
-0.000250207
2.30761e-05
6.59338e-06
6.78571e-05
0.000150359
-8.01504e-06
-0.000173011
0.000160724
-0.00096501
0.00103147
-0.000249251
0.000182787
-1.87474e-05
4.43506e-06
3.15139e-05
-3.35414e-05
0.000175289
-0.000247413
0.000523194
-0.000474706
-0.00017716
-3.36347e-05
1.75282e-05
1.51641e-05
-4.58564e-05
4.88314e-05
-4.98965e-05
-0.00115796
6.04064e-06
-3.74185e-05
-0.00010992
-4.23679e-06
0.000168941
-0.00107119
0.000970017
1.78563e-05
-1.80999e-05
0.000993275
-3.19186e-05
0.000558837
-0.000482319
-7.65188e-05
0.000233909
-4.31456e-05
0.000131443
2.84977e-07
1.50084e-06
-2.91067e-06
-0.000899516
0.000908896
0.000131765
-6.67113e-05
0.000299449
-0.000305129
5.67955e-06
-0.000290944
0.000267946
8.50526e-06
-0.000310133
5.00369e-06
0.000227885
0.00017128
0.000319944
-0.00106624
0.000107745
-1.19779e-05
-8.91983e-06
4.01668e-06
0.000239713
-0.000245133
2.49846e-05
-3.49582e-06
-2.14888e-05
2.31052e-05
0.00010328
7.53293e-05
2.19969e-05
-0.000326997
1.50127e-06
-0.000134855
-0.000616827
0.000449855
-5.08625e-05
1.50436e-05
5.82947e-05
4.94501e-05
-0.000279011
-1.67988e-05
1.14926e-06
0.000638345
-2.42854e-05
2.62921e-05
-4.78707e-05
3.21574e-06
1.12944e-05
-6.72242e-06
-0.00011813
9.20755e-05
-3.33974e-05
2.2825e-05
2.15964e-06
2.12739e-05
3.70209e-05
8.63411e-05
9.80634e-05
-4.87071e-05
4.33682e-05
9.48265e-06
-6.52076e-06
3.09503e-05
-5.18475e-06
-0.000112199
0.000457407
-0.000310931
2.96542e-06
-1.59884e-05
-0.000257222
8.94494e-06
1.388e-05
3.77007e-05
-0.00012857
0.00105346
-1.29497e-05
-0.00101485
-0.00014273
0.000110583
0.000678817
-0.000110143
0.000474616
-0.000217164
-3.11254e-05
0.000103297
3.48906e-07
0.000276572
9.68657e-06
-1.84739e-05
-0.000221671
0.000308012
2.82253e-05
-7.69324e-05
0.00140737
-0.00113732
-0.000129374
-0.000924925
-7.46395e-05
-4.39987e-05
2.35591e-05
0.000109548
6.47484e-06
0.000551332
-0.000722437
-0.000110134
9.57871e-05
4.80862e-06
-5.48994e-05
0.00025043
0.000224956
-8.17061e-05
-0.000887351
-4.13315e-05
-3.36476e-05
-0.000368761
0.000394249
-0.000192684
0.000589127
0.000924883
-0.000265485
-7.73574e-05
3.81033e-05
-7.2669e-05
-7.1435e-05
5.43021e-05
0.000682448
5.6232e-06
6.02097e-05
0.000160406
-1.00471e-05
6.98532e-05
0.000161005
-1.20268e-05
3.90519e-07
-0.000186146
-0.000143425
6.87112e-06
0.000152776
-4.2865e-05
5.69627e-05
-1.6847e-05
0.000222054
2.67263e-05
-1.33477e-06
9.14545e-05
0.00013985
2.91947e-05
0.000904515
-0.000915597
-1.95958e-05
1.83211e-05
3.08146e-05
-2.03218e-05
0.00022548
-0.000232941
5.08307e-06
0.000320898
7.70435e-05
0.000487933
3.65758e-05
-1.12447e-06
-8.59563e-05
9.06039e-05
-6.11541e-05
-0.000239111
0.000428704
3.44173e-05
-9.91903e-06
0.000292198
-0.000273397
-0.000910079
0.00016871
-5.99625e-05
4.88454e-05
0.000152669
2.53614e-05
-7.58462e-05
8.00855e-07
5.24391e-05
-1.09877e-05
-5.65485e-06
-7.05832e-05
-2.52523e-05
1.70745e-05
-1.41559e-05
-1.67403e-05
-0.000112528
2.08689e-05
6.53819e-05
4.43213e-05
-0.000360563
0.000717095
0.000242341
-3.70543e-05
-0.000106253
5.42246e-05
2.65337e-05
0.0011877
-0.00101327
-8.95796e-05
-2.60301e-05
0.000408639
0.000755264
0.000632399
-6.11787e-05
0.000304324
-0.00017018
0.000288703
-0.000857879
0.00089104
-0.000321864
-4.57863e-05
-0.000221394
-1.07657e-05
0.000230087
-0.0010187
-0.000615344
0.000229418
0.000184149
-0.00101477
-8.44601e-05
-0.000328526
-0.000110722
0.000107831
-0.000287708
-0.00099708
8.07629e-05
0.00097838
-0.00103341
0.000119048
6.89402e-05
3.86491e-05
-5.3069e-05
-0.000198842
0.000176482
-6.6386e-06
3.63803e-05
-0.000638274
-0.000304979
0.000938586
-0.000681216
-7.25132e-05
-2.23312e-05
5.78826e-05
0.000119512
0.000991599
0.000513367
-0.000183545
-0.000149887
-0.000327099
-6.2127e-06
-2.87225e-06
9.08494e-06
-4.75366e-06
8.59468e-06
0.000112064
-0.000933567
-7.15254e-06
-0.000479823
0.000425548
3.65039e-05
-0.000527634
-5.54216e-05
4.3303e-05
0.000278231
-0.000347108
-7.27176e-05
1.01791e-05
2.62339e-05
3.35888e-05
2.98035e-05
0.000217384
-0.000273218
-0.000159969
8.12172e-05
-2.38805e-05
-0.000142151
-0.000183532
4.48964e-05
-1.26691e-05
-0.000107702
4.24505e-05
6.24496e-06
-0.000953195
5.86362e-05
-5.46195e-05
0.000356028
-0.000303643
-4.53394e-05
4.24821e-05
-0.000162079
6.93581e-05
-3.11911e-05
5.32285e-05
2.05433e-05
0.000104876
0.000116888
0.00010634
-9.06647e-05
-0.000271835
-0.00127163
2.37702e-05
3.84155e-05
-3.03967e-05
8.67709e-06
-3.23378e-05
0.000232509
-7.35519e-05
0.000209932
0.000102829
-0.00102869
-1.63847e-05
0.00031388
-0.000358018
0.000129107
0.000283551
0.000102059
4.44863e-05
-3.55573e-06
-3.55984e-05
2.55156e-05
-0.000118067
5.64331e-05
0.00109356
0.000468695
4.96796e-05
-4.48709e-05
-3.8908e-05
-0.000155975
0.0001572
-3.04518e-05
-0.000151472
-0.000239464
-4.11484e-05
-0.000109793
0.000207856
-0.000670806
0.000890676
0.00106113
-6.33042e-05
0.000946695
5.22047e-05
-6.36369e-05
-0.000389996
-0.000620941
0.000498579
-0.000254674
-0.000474111
-0.000169663
4.44109e-05
0.000446001
0.000111048
-7.07145e-05
2.4789e-05
8.86652e-06
-0.00123375
-0.000117565
-0.000133813
-0.000215404
0.00027882
-0.000552913
0.000753941
-0.00101964
-3.00975e-05
-1.93011e-05
-5.44955e-05
-5.67467e-05
-0.000147307
0.000965991
-0.000119581
-1.04883e-05
3.31523e-05
-3.10814e-05
0.000143773
-3.59427e-05
4.86597e-05
-2.95564e-06
0.000955173
0.000163112
-0.00115245
0.0006179
-0.000891808
1.50275e-06
-1.84295e-05
4.59002e-05
1.33167e-05
-1.68624e-05
3.21228e-05
-0.000186006
-0.000739415
0.000806384
2.56409e-05
3.9734e-05
-2.72073e-05
-4.75784e-05
-0.00101371
0.00032303
-0.000961888
-0.00018313
-0.00021983
0.000173844
-2.29235e-05
1.32056e-05
-3.02248e-05
-2.00454e-05
-5.19553e-05
0.000640072
0.000352015
9.26949e-05
0.000922711
0.000634571
0.000136566
6.09227e-05
-0.00110798
-0.00024241
-0.00077999
0.0010793
2.26505e-05
-0.000102601
-0.000239202
3.59936e-05
-0.000104941
0.000867064
0.000834255
0.000192008
4.44385e-05
-0.000181872
-0.000182068
4.1448e-06
-0.000318359
0.000342184
9.33302e-05
-5.74625e-05
5.63365e-05
-8.13941e-06
-1.41038e-05
-0.000165544
7.31928e-05
1.12005e-05
-2.74419e-05
1.51901e-05
2.20784e-05
-6.31635e-05
7.89495e-05
-0.000102888
9.86904e-05
3.53199e-05
-8.31318e-05
9.54557e-05
6.18095e-05
0.000107941
1.1641e-05
-9.0719e-05
7.70142e-05
2.34562e-05
-2.73056e-05
5.70505e-05
0.000594657
-2.7481e-05
4.74419e-05
-2.4364e-05
0.000721009
5.59371e-05
-5.02053e-05
0.000260761
0.000104217
4.11212e-05
3.59451e-05
-0.000126642
-1.55931e-05
-0.000169856
-3.10755e-05
-0.000123645
3.08634e-05
3.44786e-05
-0.00115313
0.000813478
-0.000827982
5.7247e-05
2.2863e-05
-2.21571e-06
-1.25397e-05
1.72101e-05
-6.89898e-05
0.000149374
-0.000232875
-1.09188e-05
0.000448808
-3.95095e-05
0.000406121
-0.00047875
0.000875632
5.36498e-05
-8.41795e-05
4.79257e-05
-0.000132873
9.51989e-05
0.000107096
9.46743e-05
)
;
boundaryField
{
frontAndBack
{
type empty;
value nonuniform 0();
}
wallOuter
{
type calculated;
value uniform 0;
}
inlet
{
type calculated;
value nonuniform List<scalar> 9(-0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111);
}
outlet
{
type calculated;
value nonuniform 0();
}
wallInner
{
type calculated;
value uniform 0;
}
procBoundary0to1
{
type processor;
value nonuniform List<scalar>
29
(
-0.000128631
-3.22873e-05
-6.3112e-05
-8.86097e-05
-0.000101477
-0.000138626
0.000419611
0.000484833
0.0010154
0.000130147
0.000389937
-0.000490516
-0.000242593
-0.000251958
0.000781384
0.00110496
-2.78424e-05
0.000234191
1.0006e-05
2.09328e-05
0.0011893
0.00104715
0.000785605
0.000556408
0.000728234
8.12803e-05
0.000726138
0.000162237
0.000255783
)
;
}
procBoundary0to2
{
type processor;
value nonuniform List<scalar>
42
(
0.000127938
0.000141324
-0.000108539
-0.000173379
-8.78735e-05
0.000237736
-9.1434e-05
-7.22477e-05
-4.62693e-05
-2.55516e-06
-8.928e-05
-6.73631e-05
-9.29666e-05
-5.41782e-05
-2.77638e-05
0.000424748
-4.53818e-05
1.16484e-05
-2.34617e-05
4.02141e-05
5.73854e-05
3.71457e-05
2.9591e-06
9.80133e-05
6.64417e-05
6.4135e-05
0.000264151
6.3269e-05
0.000170877
7.66372e-05
7.77511e-05
5.39078e-05
3.78424e-05
2.22359e-05
4.1924e-06
5.12473e-05
5.84048e-05
-9.73263e-05
0.000517986
-0.000118809
-3.59043e-05
-3.13357e-05
)
;
}
}
// ************************************************************************* //
| [
"mohan.2611@gmail.com"
] | mohan.2611@gmail.com | |
b3d1e05ba071aaaefa502bd2e90101a6146795ed | 0897560a7ebde50481f950c9a441e2fc3c34ba04 | /10.0.15042.0/winrt/internal/Windows.Services.Maps.Guidance.2.h | 704325287847950eb264fe30588748c7c64a41f3 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | dngoins/cppwinrt | 338f01171153cbca14a723217129ed36b6ce2c9d | 0bb7a57392673f793ba99978738490100a9684ec | refs/heads/master | 2021-01-19T19:14:59.993078 | 2017-03-01T22:14:18 | 2017-03-01T22:14:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,865 | h | // C++ for the Windows Runtime v1.0.private
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Services.Maps.Guidance.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
#define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {};
#endif
#ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
#define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {};
#endif
#ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
#define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {};
#endif
#ifndef WINRT_GENERIC_81493670_e515_5c62_b34c_6e3d996cad31
#define WINRT_GENERIC_81493670_e515_5c62_b34c_6e3d996cad31
template <> struct __declspec(uuid("81493670-e515-5c62-b34c-6e3d996cad31")) __declspec(novtable) IVectorView<Windows::Services::Maps::Guidance::GuidanceLaneInfo> : impl_IVectorView<Windows::Services::Maps::Guidance::GuidanceLaneInfo> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_82b3f7df_bf13_5445_aadc_ec61b50fbb46
#define WINRT_GENERIC_82b3f7df_bf13_5445_aadc_ec61b50fbb46
template <> struct __declspec(uuid("82b3f7df-bf13-5445-aadc-ec61b50fbb46")) __declspec(novtable) TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceUpdatedEventArgs> : impl_TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceUpdatedEventArgs> {};
#endif
#ifndef WINRT_GENERIC_3f496c35_3dca_5e91_8730_6ef77e9d70bd
#define WINRT_GENERIC_3f496c35_3dca_5e91_8730_6ef77e9d70bd
template <> struct __declspec(uuid("3f496c35-3dca-5e91-8730-6ef77e9d70bd")) __declspec(novtable) TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_61b92b1b_f22f_581b_bfa0_4868c314c63a
#define WINRT_GENERIC_61b92b1b_f22f_581b_bfa0_4868c314c63a
template <> struct __declspec(uuid("61b92b1b-f22f-581b-bfa0-4868c314c63a")) __declspec(novtable) TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceReroutedEventArgs> : impl_TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceReroutedEventArgs> {};
#endif
#ifndef WINRT_GENERIC_743db36f_e9aa_557a_9fd7_304c9b0499df
#define WINRT_GENERIC_743db36f_e9aa_557a_9fd7_304c9b0499df
template <> struct __declspec(uuid("743db36f-e9aa-557a-9fd7-304c9b0499df")) __declspec(novtable) TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceAudioNotificationRequestedEventArgs> : impl_TypedEventHandler<Windows::Services::Maps::Guidance::GuidanceNavigator, Windows::Services::Maps::Guidance::GuidanceAudioNotificationRequestedEventArgs> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_875644d8_57a4_59d6_9d2c_5d450d39d2f6
#define WINRT_GENERIC_875644d8_57a4_59d6_9d2c_5d450d39d2f6
template <> struct __declspec(uuid("875644d8-57a4-59d6-9d2c-5d450d39d2f6")) __declspec(novtable) IVectorView<Windows::Services::Maps::Guidance::GuidanceManeuver> : impl_IVectorView<Windows::Services::Maps::Guidance::GuidanceManeuver> {};
#endif
#ifndef WINRT_GENERIC_f04c7cc2_4d54_5244_beb2_8f4f05c184e6
#define WINRT_GENERIC_f04c7cc2_4d54_5244_beb2_8f4f05c184e6
template <> struct __declspec(uuid("f04c7cc2-4d54-5244-beb2-8f4f05c184e6")) __declspec(novtable) IVectorView<Windows::Services::Maps::Guidance::GuidanceRoadSegment> : impl_IVectorView<Windows::Services::Maps::Guidance::GuidanceRoadSegment> {};
#endif
#ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
#define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {};
#endif
#ifndef WINRT_GENERIC_79362e99_4f6c_5b58_8080_00a868fe1574
#define WINRT_GENERIC_79362e99_4f6c_5b58_8080_00a868fe1574
template <> struct __declspec(uuid("79362e99-4f6c-5b58-8080-00a868fe1574")) __declspec(novtable) IVector<Windows::Services::Maps::Guidance::GuidanceLaneInfo> : impl_IVector<Windows::Services::Maps::Guidance::GuidanceLaneInfo> {};
#endif
#ifndef WINRT_GENERIC_4d4ce4d8_7ce0_5168_ab29_6bcf7f198a58
#define WINRT_GENERIC_4d4ce4d8_7ce0_5168_ab29_6bcf7f198a58
template <> struct __declspec(uuid("4d4ce4d8-7ce0-5168-ab29-6bcf7f198a58")) __declspec(novtable) IIterator<Windows::Services::Maps::Guidance::GuidanceLaneInfo> : impl_IIterator<Windows::Services::Maps::Guidance::GuidanceLaneInfo> {};
#endif
#ifndef WINRT_GENERIC_45960d72_1bf6_5a1d_a17f_e83f56f1ab57
#define WINRT_GENERIC_45960d72_1bf6_5a1d_a17f_e83f56f1ab57
template <> struct __declspec(uuid("45960d72-1bf6-5a1d-a17f-e83f56f1ab57")) __declspec(novtable) IIterable<Windows::Services::Maps::Guidance::GuidanceLaneInfo> : impl_IIterable<Windows::Services::Maps::Guidance::GuidanceLaneInfo> {};
#endif
#ifndef WINRT_GENERIC_9731f930_bd72_5313_9a18_113bc9bb48f5
#define WINRT_GENERIC_9731f930_bd72_5313_9a18_113bc9bb48f5
template <> struct __declspec(uuid("9731f930-bd72-5313-9a18-113bc9bb48f5")) __declspec(novtable) IVector<Windows::Services::Maps::Guidance::GuidanceManeuver> : impl_IVector<Windows::Services::Maps::Guidance::GuidanceManeuver> {};
#endif
#ifndef WINRT_GENERIC_74a37092_2641_5c3d_b3cb_689dc8aba22e
#define WINRT_GENERIC_74a37092_2641_5c3d_b3cb_689dc8aba22e
template <> struct __declspec(uuid("74a37092-2641-5c3d-b3cb-689dc8aba22e")) __declspec(novtable) IIterator<Windows::Services::Maps::Guidance::GuidanceManeuver> : impl_IIterator<Windows::Services::Maps::Guidance::GuidanceManeuver> {};
#endif
#ifndef WINRT_GENERIC_b5780d67_8a8b_558f_a4b6_c4531ef32ec8
#define WINRT_GENERIC_b5780d67_8a8b_558f_a4b6_c4531ef32ec8
template <> struct __declspec(uuid("b5780d67-8a8b-558f-a4b6-c4531ef32ec8")) __declspec(novtable) IIterable<Windows::Services::Maps::Guidance::GuidanceManeuver> : impl_IIterable<Windows::Services::Maps::Guidance::GuidanceManeuver> {};
#endif
#ifndef WINRT_GENERIC_dc3bab9d_a3ea_507f_9cd7_66cfa38a1c8f
#define WINRT_GENERIC_dc3bab9d_a3ea_507f_9cd7_66cfa38a1c8f
template <> struct __declspec(uuid("dc3bab9d-a3ea-507f-9cd7-66cfa38a1c8f")) __declspec(novtable) IVector<Windows::Services::Maps::Guidance::GuidanceRoadSegment> : impl_IVector<Windows::Services::Maps::Guidance::GuidanceRoadSegment> {};
#endif
#ifndef WINRT_GENERIC_148cb8ff_3ab9_53ab_8824_256a62047b43
#define WINRT_GENERIC_148cb8ff_3ab9_53ab_8824_256a62047b43
template <> struct __declspec(uuid("148cb8ff-3ab9-53ab-8824-256a62047b43")) __declspec(novtable) IIterator<Windows::Services::Maps::Guidance::GuidanceRoadSegment> : impl_IIterator<Windows::Services::Maps::Guidance::GuidanceRoadSegment> {};
#endif
#ifndef WINRT_GENERIC_f7c614c4_0fca_5eda_804c_85c829956334
#define WINRT_GENERIC_f7c614c4_0fca_5eda_804c_85c829956334
template <> struct __declspec(uuid("f7c614c4-0fca-5eda-804c-85c829956334")) __declspec(novtable) IIterable<Windows::Services::Maps::Guidance::GuidanceRoadSegment> : impl_IIterable<Windows::Services::Maps::Guidance::GuidanceRoadSegment> {};
#endif
}
namespace Windows::Services::Maps::Guidance {
struct IGuidanceAudioNotificationRequestedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceAudioNotificationRequestedEventArgs>
{
IGuidanceAudioNotificationRequestedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceLaneInfo :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceLaneInfo>
{
IGuidanceLaneInfo(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceManeuver :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceManeuver>
{
IGuidanceManeuver(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceMapMatchedCoordinate :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceMapMatchedCoordinate>
{
IGuidanceMapMatchedCoordinate(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceNavigator :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceNavigator>
{
IGuidanceNavigator(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceNavigator2 :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceNavigator2>
{
IGuidanceNavigator2(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceNavigatorStatics :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceNavigatorStatics>
{
IGuidanceNavigatorStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceNavigatorStatics2 :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceNavigatorStatics2>
{
IGuidanceNavigatorStatics2(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceReroutedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceReroutedEventArgs>
{
IGuidanceReroutedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceRoadSegment :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceRoadSegment>
{
IGuidanceRoadSegment(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceRoadSignpost :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceRoadSignpost>
{
IGuidanceRoadSignpost(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceRoute :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceRoute>
{
IGuidanceRoute(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceRouteStatics :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceRouteStatics>
{
IGuidanceRouteStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceTelemetryCollector :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceTelemetryCollector>
{
IGuidanceTelemetryCollector(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceTelemetryCollectorStatics :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceTelemetryCollectorStatics>
{
IGuidanceTelemetryCollectorStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IGuidanceUpdatedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IGuidanceUpdatedEventArgs>
{
IGuidanceUpdatedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
}
}
| [
"kwelton@microsoft.com"
] | kwelton@microsoft.com |
97a5dd6652370e48639bc89bf66800d45e2e3c5a | 37d905bbb10ea00eaadd47dc41989461fa213aea | /Virtual_Memory_Management/TLB.cpp | 499871fcdbcd8092866e2b6c4fbb4969269db86e | [] | no_license | cmarch314/Virtual_Memory | d36ebe6d1a8792d50805643a0c86d0afe484ad17 | 8ab078898d0cdfca21fd73869030588f6e45a93c | refs/heads/master | 2021-01-10T13:10:42.650548 | 2016-03-16T02:20:11 | 2016-03-16T02:20:11 | 53,989,228 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,162 | cpp | #include "TLB.h"
TLB::TLB()
{
table = new int*[4];
init();
}
void TLB::init()
{
for (int i = 0; i < 4; i++)
{
table[i] = new int[4];
table[i][0] = -1;
table[i][1] = -1;
table[i][2] = -1;
table[i][3] = -1;
}
}
TLB::~TLB()
{
delete[] table;
}
int TLB::find(int s, int p) // works as pop?
{
for (int i = 0; i < 4; i++)
{
if ((table[i][1] == s) && (table[i][2] == p))
{
return i;
}
}
return -1;
}
int TLB::update(int index, int s, int p, int f)
{
if (index == -1)//miss case
{
for (int i = 0; i < 4; i++)
{
if (table[i][0] == -1)//find empty spot (least latest acessed.)
{
index = i;
break;
}
}
if (index == -1)//if all occupied
{
for (int i = 0; i < 4; i++)
{
if (table[i][0] == 0)//find lowest priority (least latest acessed.)
{
index = i;
break;
}
}
}
table[index][0] = 0;//all shall fall by this index
table[index][1] = s;
table[index][2] = p;
table[index][3] = f;
}
for (int i = 0; i < 4; i++)
{
if (table[i][0] > table[index][0])
{
table[i][0]--;
}
}
table[index][0] = 3;
return index;
}
int TLB::get_f(int index)
{
return table[index][3];
} | [
"cmarch314@gmail.com"
] | cmarch314@gmail.com |
3c87077334db1cd165fcebda4119b1ab9a5cecee | 5ae928266943657b0734e377c165f82edb36a52c | /src/Config/ConfigDataParser.h | a7647ff2b7f887e60964f99f35c19bf7a698fa5b | [] | no_license | jmatta1/ORCHIDReader | 47e28de753f4cb855772481cc0000bbc9ea5adc7 | c3430439a5942dff89d49444ed60138717d3b575 | refs/heads/master | 2021-01-19T11:49:22.077658 | 2018-03-02T16:14:11 | 2018-03-02T16:14:11 | 80,251,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,050 | h | /***************************************************************************//**
********************************************************************************
**
** @file ConfigDataParser.h
** @author James Till Matta
** @date 21 Jan, 2017
** @brief
**
** @copyright Copyright (C) 2016 James Till Matta
**
** 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.
**
** @details holds the grammar necessary to parse the first level input file
**
********************************************************************************
*******************************************************************************/
#ifndef ORCHIDREADER_SRC_CONFIG_CONFIGDATAPARSER_H
#define ORCHIDREADER_SRC_CONFIG_CONFIGDATAPARSER_H
// includes for C system headers
// includes for C++ system headers
#include<iostream>
// includes from other libraries
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/phoenix/bind/bind_member_function.hpp>
// includes from ORCHIDReader
#include"ConfigData.h"
#include"UtilityParsers.h"
namespace InputParser
{
namespace Parsing
{
namespace qi = boost::spirit::qi;
// the main gammar
template <typename Iterator>
struct ConfigDataGrammar : qi::grammar<Iterator>
{
public:
ConfigDataGrammar(ConfigData* cd) : ConfigDataGrammar::base_type(startRule), ptr(cd)
{
namespace phoenix = boost::phoenix;
using qi::skip;
using qi::blank;
using qi::lexeme;
using qi::float_;
using qi::int_;
using Utility::eol_;
using Utility::boolSymbols_;
using qi::fail;
using qi::on_error;
using Utility::separator;
//define the rules to parse the parameters
listFilePath = (lexeme["ListFilePath"] >> '=' > quotedString [phoenix::bind(&ConfigData::listFilePathSet, ptr, qi::_1)] > separator);
rootFilePath = (lexeme["RootFilePath"] >> '=' > quotedString [phoenix::bind(&ConfigData::rootFilePathSet, ptr, qi::_1)] > separator);
arrayDataPath = (lexeme["ArrayDataPath"] >> '=' > quotedString [phoenix::bind(&ConfigData::arrayDataPathSet, ptr, qi::_1)] > separator);
runCsvPath = (lexeme["RunCsvPath"] >> '=' > quotedString [phoenix::bind(&ConfigData::runCsvPathSet, ptr, qi::_1)] > separator);
detMetaDataPath = (lexeme["DetMetaDataPath"] >> '=' > quotedString [phoenix::bind(&ConfigData::detMetaDataPathSet, ptr, qi::_1)] > separator);
batchMetaDataPath = (lexeme["BatchMetaDataPath"] >> '=' > quotedString [phoenix::bind(&ConfigData::batchMetaDataPathSet, ptr, qi::_1)] > separator);
histIntegrationTime = (lexeme["HistIntegrationTime"] >> '=' > float_ [phoenix::bind(&ConfigData::histIntegrationTimeSet, ptr, qi::_1)] > separator);
arrayXPos = (lexeme["ArrayXPosition"] >> '=' > float_ [phoenix::bind(&ConfigData::arrayXPosSet, ptr, qi::_1)] > separator);
arrayYPos = (lexeme["ArrayYPosition"] >> '=' > float_ [phoenix::bind(&ConfigData::arrayYPosSet, ptr, qi::_1)] > separator);
procFirstBuff = (lexeme["ProcessFirstBuffer"] >> '=' > boolSymbols_ [phoenix::bind(&ConfigData::processFirstBufferSet, ptr, qi::_1)] > separator);
genRootTree = (lexeme["GenerateRootTree"] >> '=' > boolSymbols_ [phoenix::bind(&ConfigData::generateRootTreeSet, ptr, qi::_1)] > separator);
rootTreeFilePath = (lexeme["RootTreeFilePath"] >> '=' > quotedString [phoenix::bind(&ConfigData::rootTreeFilePathSet, ptr, qi::_1)] > separator);
bufferLength = (lexeme["BufferLength"] >> '=' > '[' >> int_ [phoenix::bind(&ConfigData::bufferLengthAdd, ptr, qi::_1)] >> +(',' >> int_ [phoenix::bind(&ConfigData::bufferLengthAdd, ptr, qi::_1)]) >> ']' > separator);
// define the start rule which holds the whole monstrosity and set the rule to skip blanks
// if we skipped spaces we could not parse newlines as separators
startRule = skip(blank) [configDataRule];
configDataRule = *eol_ >> lexeme["[StartConfig]"] >> *eol_
> (
listFilePath ^ histIntegrationTime ^ arrayDataPath ^
arrayXPos ^ arrayYPos ^ rootFilePath ^ runCsvPath ^
detMetaDataPath ^ batchMetaDataPath ^ procFirstBuff ^
genRootTree ^ rootTreeFilePath ^ bufferLength
) > lexeme["[EndConfig]"];
on_error<fail>(startRule,
std::cout << phoenix::val("Error! Expecting ")
<< qi::_4 // what failed?
<< phoenix::val(" here: \n\"")
<< phoenix::construct<std::string>(qi::_3, qi::_2) // iterators to error-pos, end
<< phoenix::val("\"")
<< std::endl);
}
private:
//base rules for the file
qi::rule<Iterator> startRule;
qi::rule<Iterator, qi::blank_type> configDataRule;
// special sub grammars
Utility::QuotedString<Iterator> quotedString;
// parameters
qi::rule<Iterator, qi::blank_type> listFilePath, histIntegrationTime;
qi::rule<Iterator, qi::blank_type> arrayDataPath, arrayXPos;
qi::rule<Iterator, qi::blank_type> arrayYPos, rootFilePath;
qi::rule<Iterator, qi::blank_type> runCsvPath, detMetaDataPath;
qi::rule<Iterator, qi::blank_type> batchMetaDataPath, procFirstBuff;
qi::rule<Iterator, qi::blank_type> genRootTree, rootTreeFilePath;
qi::rule<Iterator, qi::blank_type> bufferLength;
// hold the pointer that we are going to bind to
ConfigData* ptr;
};
}
}
#endif //ORCHIDREADER_SRC_CONFIG_CONFIGDATAPARSER_H
| [
"jamesmatta@gmail.com"
] | jamesmatta@gmail.com |
744314d79dd303587a72122ae62612f697846687 | 157fd7fe5e541c8ef7559b212078eb7a6dbf51c6 | /TRiAS/Framework/LPict42/pictinlc.cpp | 4e8685221fd80c69514f92eff342b1eb42e67191 | [] | no_license | 15831944/TRiAS | d2bab6fd129a86fc2f06f2103d8bcd08237c49af | 840946b85dcefb34efc219446240e21f51d2c60d | refs/heads/master | 2020-09-05T05:56:39.624150 | 2012-11-11T02:24:49 | 2012-11-11T02:24:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | #include "stdafx.h"
#include "LPictImpl.h"
#ifdef LAFX_PICT_SEG
#pragma code_seg(LAFX_PICT_SEG)
#endif
/////////////////////////////////////////////////////////////////////////////
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
#define new DEBUG_NEW
#ifndef _AFX_ENABLE_INLINES // _DEBUG is defined
#ifdef AFX_DBG1_SEG
#pragma code_seg(AFX_DBG1_SEG)
#endif
static char BASED_CODE _szAfxInl[] = __FILE__;
#undef THIS_FILE
#define THIS_FILE _szAfxInl
#define _AFX_INLINE
#include "lpict/PictCod.inl"
#endif //!_AFX_ENABLE_INLINES
| [
"Windows Live ID\\hkaiser@cct.lsu.edu"
] | Windows Live ID\hkaiser@cct.lsu.edu |
005d81d4521c01b802e26f1be2e33d5935b155b2 | 0c44da76a30138ebaee6700e2e33df5204ef21fc | /PSME/application/include/psme/rest/security/account/account_manager.hpp | 920c45c42c1bd982a87b72d7aab79116b05fef20 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | rwleea/intelRSD | 263e4c86801792be88e528d30d5a1d3c85af3a62 | 8e404abc211211a2d49776b8e3bf07d108c4bd4b | refs/heads/master | 2023-02-20T22:26:07.222243 | 2022-08-04T22:08:00 | 2022-08-04T22:08:00 | 64,722,362 | 0 | 0 | null | 2016-08-02T03:49:59 | 2016-08-02T03:49:58 | null | UTF-8 | C++ | false | false | 3,124 | hpp | /*!
* @copyright
* Copyright (c) 2018-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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.
*
* @file account_manager.hpp
*
* @brief Declaration of AccountManager class.
* */
#pragma once
#include "agent-framework/generic/singleton.hpp"
#include "psme/rest/security/account/account.hpp"
namespace psme {
namespace rest {
namespace security {
namespace account {
/*!
* AccountManager class declaration.
*/
class AccountManager : public agent_framework::generic::Singleton<AccountManager> {
public:
/*!
* @brief Callback prototype for for_each()
*/
using AccountCallback = std::function<void(const Account&)>;
/*!
* @brief Default constructor
*/
AccountManager();
/*!
* @brief Destructor
*/
virtual ~AccountManager();
/*!
* @brief Get account by account id
*
* @param account_id Account id
* @return Account object
*/
const Account& get(uint64_t account_id) const;
/*!
* @brief Add account
*
* @param account new Account object to add
*/
uint64_t add(Account account);
/*!
* @brief Calculate hash from password
*
* @param password from which hash will be calculated
* @param salt random data used for hash generation
* @return SHA512 based PBKDF2 hash of the given password
*/
std::string calculate_hash(const std::string& password, const std::string& salt) const;
/*!
* @brief Visit all accounts kept by the manager
* @param handle Callback to be called on each account
* @warning Not allowed to use any AccountManager methods.
*/
void for_each(const AccountCallback& handle) const;
/*!
* @brief Validates credentials given as arguments.
* @param user_name name of the user
* @param password user password
* @return true if credentials are valid, false otherwise.
*/
bool validate_credentials(const std::string& user_name, const std::string& password) const;
private:
/*!
* @brief Authentication user name property name
*/
static constexpr char USER_NAME[] = "username";
/*!
* @brief Authentication password hash property name
*/
static constexpr char PASSWORD_HASH[] = "password";
using AccountMap = std::map<std::uint64_t, Account>;
/*!
* Update m_id to next available value.
*/
void update_next_id(void);
AccountMap m_accounts{};
mutable std::mutex m_mutex{};
/*! @brief Last assigned ID */
std::uint64_t m_id{0};
};
}
}
}
} | [
"noreply@github.com"
] | rwleea.noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.