hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
efb2eb3e96f6020c3d91536886f463811a9693f3
| 36
|
cpp
|
C++
|
Chapter-3-Tree/Homework/Chapter-3-Tree-Homework-1/main.cpp
|
jubgjf/DataStructuresAndAlgorithms
|
48c7fa62e618ddbefa760229ce677cdfc822b53f
|
[
"MIT"
] | 2
|
2020-10-18T07:36:25.000Z
|
2021-07-31T23:34:49.000Z
|
Chapter-3-Tree/Homework/Chapter-3-Tree-Homework-1/main.cpp
|
jubgjf/DataStructuresAndAlgorithms
|
48c7fa62e618ddbefa760229ce677cdfc822b53f
|
[
"MIT"
] | null | null | null |
Chapter-3-Tree/Homework/Chapter-3-Tree-Homework-1/main.cpp
|
jubgjf/DataStructuresAndAlgorithms
|
48c7fa62e618ddbefa760229ce677cdfc822b53f
|
[
"MIT"
] | null | null | null |
#include "header.h"
int main()
{
}
| 6
| 19
| 0.583333
|
jubgjf
|
efb31ec19a89d05b2cd8ef548b6d6278a3862f1c
| 3,163
|
cpp
|
C++
|
day05/ex05/CentralBureaucracy.cpp
|
psprawka/Cpp_Piscine
|
73fdb50d654c49587d7d3a2d475b1c57033c8dd4
|
[
"MIT"
] | 1
|
2019-09-15T08:29:00.000Z
|
2019-09-15T08:29:00.000Z
|
day05/ex05/CentralBureaucracy.cpp
|
psprawka/Cpp_Piscine
|
73fdb50d654c49587d7d3a2d475b1c57033c8dd4
|
[
"MIT"
] | 1
|
2019-09-15T08:28:48.000Z
|
2019-09-15T08:28:48.000Z
|
day05/ex05/CentralBureaucracy.cpp
|
psprawka/Cpp_Piscine
|
73fdb50d654c49587d7d3a2d475b1c57033c8dd4
|
[
"MIT"
] | 1
|
2020-03-04T16:14:40.000Z
|
2020-03-04T16:14:40.000Z
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* CentralBureaucracy.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: psprawka <psprawka@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/02 22:25:42 by psprawka #+# #+# */
/* Updated: 2018/07/03 13:24:10 by psprawka ### ########.fr */
/* */
/* ************************************************************************** */
#include "CentralBureaucracy.hpp"
#include "Bureaucrat.hpp"
#include "Intern.hpp"
#include "Form.hpp"
#include "OfficeBlock.hpp"
#include <iostream>
#define YELLOW "\x1B[33m"
#define NORMAL "\x1B[0m"
int CentralBureaucracy::_nb_targets = 0;
int CentralBureaucracy::_nb_signers = 0;
int CentralBureaucracy::_nb_executers = 0;
CentralBureaucracy::CentralBureaucracy(void)
{
Intern intern;
for (int i = 0; i < 20; i++)
this->_blocks[i].setIntern(intern);
}
CentralBureaucracy::CentralBureaucracy(CentralBureaucracy const &obj) {
*this = obj;
}
CentralBureaucracy::~CentralBureaucracy(void) {}
CentralBureaucracy &CentralBureaucracy::operator=(CentralBureaucracy const &obj)
{
for (int i = 0; i < 20; i++)
{
this->_blocks[i].setExecutor(*(obj._blocks[i].getExecutor()));
this->_blocks[i].setSigner(*(obj._blocks[i].getSigner()));
this->_target[i] = obj._target[i];
}
return (*this);
}
void CentralBureaucracy::feedSigner(Bureaucrat &obj)
{
if (this->_nb_signers < 20)
this->_blocks[this->_nb_signers++].setSigner(obj);
else
std::cout << "No more spots for Bureaucrats [feedSigner]." << std::endl;
}
void CentralBureaucracy::feedExecuter(Bureaucrat &obj)
{
if (this->_nb_executers < 20)
this->_blocks[this->_nb_executers++].setExecutor(obj);
else
std::cout << "No more spots for Bureaucrats [feedSigner]." << std::endl;
}
void CentralBureaucracy::doBureaucracy(void)
{
std::string interns[3] = {"shrubbery creation", "robotomy request", "presidential pardon"};
int random_person = rand () % 20;
if (this->_nb_targets == 0)
std::cout << "No targets in queue." << std::endl;
for (int i = 0; i < this->_nb_targets; i++)
{
if (!this->_blocks[random_person].getExecutor() || !this->_blocks[random_person].getSigner())
std::cout << "No worker in the office for \"" << this->_target[i] << "\".\n\n";
else
{
std::cout << YELLOW;
this->_blocks[random_person].doBureaucracy(interns[rand () % 3], this->_target[i]);
std::cout << NORMAL << std::endl;
}
random_person = rand () % 20;
}
}
void CentralBureaucracy::queueUp(std::string target)
{
if (this->_nb_targets < 20)
this->_target[this->_nb_targets++] = target;
else
std::cout << "No more targets allowed to queueUp." << std::endl;
}
| 30.12381
| 95
| 0.523554
|
psprawka
|
efb9f6507df42e6e4b450ae84d187d9bfc4a6c6c
| 818
|
cpp
|
C++
|
Problem Solving/Algorithms/Strings/Making Anagrams/making anagrams.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | 108
|
2021-03-29T05:04:16.000Z
|
2022-03-19T15:11:52.000Z
|
Problem Solving/Algorithms/Strings/Making Anagrams/making anagrams.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | null | null | null |
Problem Solving/Algorithms/Strings/Making Anagrams/making anagrams.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | 32
|
2021-03-30T03:56:54.000Z
|
2022-03-27T14:41:32.000Z
|
/* Author: Isaac Asante
* HackerRank URL for this exercise: https://www.hackerrank.com/challenges/making-anagrams/problem
* Original video explanation: https://www.youtube.com/watch?v=05mznZNMjvY
* Last verified on: May 19, 2021
*/
/* IMPORTANT:
* This code is meant to be used as a solution on HackerRank (link above).
* It is not meant to be executed as a standalone program.
*/
int makingAnagrams(string s1, string s2) {
int alphabet[26] = { 0 }; // All counts initialized to zero
int sum = 0;
for (int i = 0; i < s1.size(); i++)
--alphabet[s1[i] - 'a']; // Decrease for s1
for (int i = 0; i < s2.size(); i++)
++alphabet[s2[i] - 'a']; // Increase for s2
for (int i = 0; i < 26; i++)
sum += abs(alphabet[i]); // Get the sum of abs values
return sum;
}
| 31.461538
| 98
| 0.617359
|
IsaacAsante
|
efbb5ba8d03dba10a5d87893ddf82b2ff52cb452
| 1,396
|
hpp
|
C++
|
include/jules/array/math.hpp
|
verri/jules
|
5370c533a68bb670ae937967e024428c705215f8
|
[
"Zlib"
] | 8
|
2016-12-07T21:47:48.000Z
|
2019-11-25T14:26:27.000Z
|
include/jules/array/math.hpp
|
verri/jules
|
5370c533a68bb670ae937967e024428c705215f8
|
[
"Zlib"
] | 23
|
2016-12-07T21:22:24.000Z
|
2019-09-02T13:58:42.000Z
|
include/jules/array/math.hpp
|
verri/jules
|
5370c533a68bb670ae937967e024428c705215f8
|
[
"Zlib"
] | 3
|
2017-01-18T02:11:32.000Z
|
2018-04-16T01:40:36.000Z
|
// Copyright (c) 2017-2019 Filipe Verri <filipeverri@gmail.com>
#ifndef JULES_ARRAY_MATH_H
#define JULES_ARRAY_MATH_H
#include <jules/array/functional.hpp>
#include <jules/base/math.hpp>
#include <cmath>
namespace jules
{
template <typename Array>
auto normal_pdf(const common_array_base<Array>& array, typename Array::value_type mu, typename Array::value_type sigma)
{
return apply(array, [mu = std::move(mu), sigma = std::move(sigma)](const auto& x) { return normal_pdf(x, mu, sigma); });
}
template <typename Array> auto abs(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return abs(v); });
}
template <typename Array> auto sqrt(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return sqrt(v); });
}
template <typename Array> auto log(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return log(v); });
}
template <typename Array> auto sin(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return sin(v); });
}
template <typename Array> auto cos(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return cos(v); });
}
template <typename Array> auto tanh(const common_array_base<Array>& array)
{
return apply(array, [](const auto& v) { return tanh(v); });
}
} // namespace jules
#endif // JULES_ARRAY_MATH_H
| 26.339623
| 122
| 0.709169
|
verri
|
efc2ce4052624ade50273969756c0e36c8e72291
| 7,686
|
cpp
|
C++
|
src/kiwi/vesKiwiImagePlaneDataRepresentation.cpp
|
aashish24/ves
|
7a73d0d5f76fecc776950ba8ae45458df406c591
|
[
"Apache-2.0"
] | 10
|
2015-11-16T02:38:48.000Z
|
2021-11-17T11:19:25.000Z
|
src/kiwi/vesKiwiImagePlaneDataRepresentation.cpp
|
aashish24/ves
|
7a73d0d5f76fecc776950ba8ae45458df406c591
|
[
"Apache-2.0"
] | 1
|
2015-10-28T01:22:51.000Z
|
2016-09-26T09:41:34.000Z
|
src/kiwi/vesKiwiImagePlaneDataRepresentation.cpp
|
aashish24/ves
|
7a73d0d5f76fecc776950ba8ae45458df406c591
|
[
"Apache-2.0"
] | 3
|
2016-03-18T06:06:42.000Z
|
2017-05-10T09:29:54.000Z
|
/*========================================================================
VES --- VTK OpenGL ES Rendering Toolkit
http://www.kitware.com/ves
Copyright 2011 Kitware, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
========================================================================*/
#include "vesKiwiImagePlaneDataRepresentation.h"
#include "vesKiwiDataConversionTools.h"
#include "vesSetGet.h"
#include "vesTexture.h"
#include <vtkScalarsToColors.h>
#include <vtkImageData.h>
#include <vtkFloatArray.h>
#include <vtkLookupTable.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkNew.h>
#include <vtkQuad.h>
#include <cassert>
//----------------------------------------------------------------------------
class vesKiwiImagePlaneDataRepresentation::vesInternal
{
public:
vesInternal()
{
}
~vesInternal()
{
}
vtkSmartPointer<vtkScalarsToColors> ColorMap;
vtkSmartPointer<vtkUnsignedCharArray> TextureData;
vtkSmartPointer<vtkPolyData> ImagePlane;
};
//----------------------------------------------------------------------------
vesKiwiImagePlaneDataRepresentation::vesKiwiImagePlaneDataRepresentation()
{
this->Internal = new vesInternal();
}
//----------------------------------------------------------------------------
vesKiwiImagePlaneDataRepresentation::~vesKiwiImagePlaneDataRepresentation()
{
delete this->Internal;
}
//----------------------------------------------------------------------------
void vesKiwiImagePlaneDataRepresentation::setImageData(vtkImageData* imageData)
{
vtkSmartPointer<vtkPolyData> imagePlane = this->polyDataForImagePlane(imageData);
this->setPolyData(imagePlane);
this->Internal->ImagePlane = imagePlane;
vesSharedPtr<vesTexture> texture = this->texture();
if (!texture) {
this->setTexture(vesSharedPtr<vesTexture>(new vesTexture()));
}
this->setTextureFromImage(this->texture(), imageData);
}
//----------------------------------------------------------------------------
vesVector2f vesKiwiImagePlaneDataRepresentation::textureSize() const
{
assert(this->texture());
vesImage::Ptr image = this->texture()->image();
return vesVector2f(image->width(), image->height());
}
//----------------------------------------------------------------------------
vtkPolyData* vesKiwiImagePlaneDataRepresentation::imagePlanePolyData()
{
return this->Internal->ImagePlane;
}
//----------------------------------------------------------------------------
vtkScalarsToColors* vesKiwiImagePlaneDataRepresentation::colorMap()
{
return this->Internal->ColorMap;
}
//----------------------------------------------------------------------------
void vesKiwiImagePlaneDataRepresentation::setColorMap(vtkScalarsToColors* map)
{
this->Internal->ColorMap = map;
}
//----------------------------------------------------------------------------
void vesKiwiImagePlaneDataRepresentation::setGrayscaleColorMap(double scalarRange[2])
{
this->setColorMap(vesKiwiDataConversionTools::GetGrayscaleLookupTable(scalarRange));
}
//----------------------------------------------------------------------------
void vesKiwiImagePlaneDataRepresentation::setShaderProgram(
vesSharedPtr<vesShaderProgram> shaderProgram)
{
// Do nothing.
vesNotUsed(shaderProgram);
}
//----------------------------------------------------------------------------
vesSharedPtr<vesTexture>
vesKiwiImagePlaneDataRepresentation::newTextureFromImage(vtkImageData* image)
{
vesSharedPtr<vesTexture> texture (new vesTexture());
this->setTextureFromImage(texture, image);
return texture;
}
//----------------------------------------------------------------------------
void vesKiwiImagePlaneDataRepresentation::setTextureFromImage(
vesSharedPtr<vesTexture> texture, vtkImageData* image)
{
assert(image);
assert(image->GetDataDimension() == 2);
assert(image->GetPointData()->GetScalars());
vtkSmartPointer<vtkUnsignedCharArray> pixels = vtkUnsignedCharArray::SafeDownCast(image->GetPointData()->GetScalars());
if (!pixels) {
vtkScalarsToColors* map = this->colorMap();
assert(map);
pixels = vesKiwiDataConversionTools::MapScalars(image->GetPointData()->GetScalars(), map);
}
int dimensions[3];
image->GetDimensions(dimensions);
const int flatDimension = this->imageFlatDimension(image);
int width;
int height;
if (flatDimension == 2) {
// XY plane
width = image->GetDimensions()[0];
height = image->GetDimensions()[1];
}
else if (flatDimension == 1) {
// XZ plane
width = image->GetDimensions()[0];
height = image->GetDimensions()[2];
}
else {
// YZ plane
width = image->GetDimensions()[1];
height = image->GetDimensions()[2];
}
vesKiwiDataConversionTools::SetTextureData(pixels, texture, width, height);
this->Internal->TextureData = pixels;
}
//----------------------------------------------------------------------------
int vesKiwiImagePlaneDataRepresentation::imageFlatDimension(vtkImageData* image)
{
int dimensions[3];
image->GetDimensions(dimensions);
for (int i = 0; i < 3; ++i) {
if (dimensions[i] == 1) {
return i;
}
}
return -1;
}
//----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> vesKiwiImagePlaneDataRepresentation::polyDataForImagePlane(vtkImageData* image)
{
double bounds[6];
image->GetBounds(bounds);
vtkNew<vtkPoints> quadPoints;
quadPoints->SetNumberOfPoints(4);
const int flatDimension = vesKiwiImagePlaneDataRepresentation::imageFlatDimension(image);
if (flatDimension == 2) {
// XY plane
quadPoints->SetPoint(0, bounds[0],bounds[2],bounds[4]);
quadPoints->SetPoint(1, bounds[1],bounds[2],bounds[4]);
quadPoints->SetPoint(2, bounds[1],bounds[3],bounds[4]);
quadPoints->SetPoint(3, bounds[0],bounds[3],bounds[4]);
}
else if (flatDimension == 1) {
// XZ plane
quadPoints->SetPoint(0, bounds[0],bounds[2],bounds[4]);
quadPoints->SetPoint(1, bounds[1],bounds[2],bounds[4]);
quadPoints->SetPoint(2, bounds[1],bounds[2],bounds[5]);
quadPoints->SetPoint(3, bounds[0],bounds[2],bounds[5]);
}
else {
// YZ plane
quadPoints->SetPoint(0, bounds[0],bounds[2],bounds[4]);
quadPoints->SetPoint(1, bounds[0],bounds[3],bounds[4]);
quadPoints->SetPoint(2, bounds[0],bounds[3],bounds[5]);
quadPoints->SetPoint(3, bounds[0],bounds[2],bounds[5]);
}
vtkNew<vtkQuad> quad;
quad->GetPointIds()->SetId(0, 0);
quad->GetPointIds()->SetId(1, 1);
quad->GetPointIds()->SetId(2, 2);
quad->GetPointIds()->SetId(3, 3);
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
polyData->Allocate(1, 1);
polyData->InsertNextCell(quad->GetCellType(), quad->GetPointIds());
polyData->SetPoints(quadPoints.GetPointer());
// add texture coordinates
vtkNew<vtkFloatArray> tcoords;
tcoords->SetName("tcoords");
tcoords->SetNumberOfComponents(2);
tcoords->SetNumberOfTuples(4);
tcoords->SetTuple2(0, 0,0);
tcoords->SetTuple2(1, 1,0);
tcoords->SetTuple2(2, 1,1);
tcoords->SetTuple2(3, 0,1);
polyData->GetPointData()->SetScalars(tcoords.GetPointer());
return polyData;
}
| 31.5
| 121
| 0.611371
|
aashish24
|
efc35cabfe9d8082842d0bb0d67189eec5730142
| 33,561
|
cpp
|
C++
|
src/lib/safe_storage.cpp
|
imaginatho/safestorage
|
a2581a1ec4e2e52b39f1f8f7f08afa9c566ee127
|
[
"MIT"
] | 8
|
2015-07-04T04:06:15.000Z
|
2015-07-10T07:43:41.000Z
|
src/lib/safe_storage.cpp
|
imaginatho/safestorage
|
a2581a1ec4e2e52b39f1f8f7f08afa9c566ee127
|
[
"MIT"
] | null | null | null |
src/lib/safe_storage.cpp
|
imaginatho/safestorage
|
a2581a1ec4e2e52b39f1f8f7f08afa9c566ee127
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <syslog.h>
#include <iostream>
#include <sstream>
#include <string>
#include <exception>
using namespace std;
#include <log.h>
#include <safe_storage_imp.h>
#include <safe_storage_listener.h>
static const char *__safe_storage_extensions [] = {"", ".idx", ".rlg", ".st"};
#define CSTORAGE_SIGNATURE 0x51213298
#define CSTORAGE_SIGNATURE_MASK 0x00000007
#define DECLARE_STRUCT(X,Y) X Y; memset(&Y, 0, sizeof(Y));
#define DECLARE_DEFAULT_STRUCT(X,Y) X __##Y; if (!Y) { memset(&__##Y, 0, sizeof(__##Y)); Y=&__##Y; };
#define CSTORAGE_MODE_STANDARD 0
#define CSTORAGE_MODE_REBUILD 1
template <class R>
bool cmp_struct_field(R st1, R st2, const char *st1_name, const char *st2_name, const char *fieldname, int32_t pos )
{
if (st1 == st2) return true;
std::stringstream msg;
msg << "Field " << fieldname << "of structures " << st1_name;
if (pos >= 0) {
msg << "[" << pos << "]";
}
msg << "(" << st1 << ") and " << st2_name;
if (pos >= 0) {
msg << "[" << pos << "]";
}
msg << "(" << st2 << ") are different";
C_LOG_ERR(msg.str().c_str());
return false;
}
#define CMP_STRUCT_FIELD(ST1,ST2,FIELD,R)\
R |= cmp_struct_field<__typeof__(ST1.FIELD)>(ST1.FIELD,ST2.FIELD,#ST1,#ST2,#FIELD,-1);
#define CMP_STRUCT_ARRAY_FIELD(ST1,ST2,FIELD,R)\
for (int32_t __##FIELD##__index__=0; __##FIELD##__index__ < (int32_t)(sizeof(ST1.FIELD)/sizeof(ST1.FIELD[0])); ++__##FIELD##__index__ ) {\
R |= cmp_struct_field<__typeof__(ST1.FIELD[0])>(\
ST1.FIELD[__##FIELD##__index__],\
ST2.FIELD[__##FIELD##__index__],\
#ST1,#ST2,#FIELD,__##FIELD##__index__);\
}\
typedef union
{
CSafeStorageIndexReg index;
CSafeStorageDataReg data;
CSafeStorageLogReg log;
uint32_t hash_key;
} CSafeStorageHashReg;
/*
* Constructor class CSafeStorage, this method initialize structures, and create list of
* safe files managed with object. These files are added in list files.
*/
CSafeStorage::CSafeStorage ( void )
: findex(0, D_CSTORAGE_INDEX_CACHE),
flog(0, D_CSTORAGE_LOG_CACHE),
fdata(0,0, D_CSTORAGE_DATA_INIT_SIZE, D_CSTORAGE_DATA_DELTA_SIZE /*, 16*/),
fstate(0,0)
{
cursor = -1;
rdwr = false;
dirtySerials = NULL;
dirtySerialSize = 0;
dirtySerialIndex = 0;
mode = CSTORAGE_MODE_STANDARD;
memset(&state, 0, sizeof(state));
files.push_back(&fdata);
files.push_back(&findex);
files.push_back(&flog);
files.push_back(&fstate);
}
/*
* Destructor, that close all files.
*/
CSafeStorage::~CSafeStorage ()
{
close();
if (dirtySerials) free(dirtySerials);
}
/*
* Method that close all file, using list file, close each file.
*/
int32_t CSafeStorage::close ( uint32_t flags )
{
CBaseSafeFileList::iterator it = files.begin();
saveState(true);
while (it != files.end())
{
(*it)->close();
++it;
}
clearDirtySerials();
if (rdwr) sync(true);
fauto_commit = false;
return E_CSTORAGE_OK;
}
/*
* Open a new environment, a list of files in one directory.
*
* @param filename prefix, filename without extension
* @param flags flags that applies to this operation. Current, no flags defined for this operation.
*
* @return 0 if no errors, error code if error occurs.
*/
int32_t CSafeStorage::open ( const string &filename, uint32_t flags, uint32_t hash_key )
{
string _filename;
fauto_commit = false;
try
{
flags |= F_CSFILE_EXCEPTIONS;
int32_t index = 0;
// Check if all file exists
string basename = normalizeFilename(filename);
rdwr = (flags & F_CSTORAGE_WR);
int32_t count = checkFilesPresent(basename, (flags & F_CSTORAGE_WR) ? (R_OK|W_OK):R_OK);
if (count > 0) {
if (count == (int32_t)files.size() && (flags & F_CSTORAGE_CREATE)) return create(basename, flags, hash_key);
return E_CSTORAGE_OPEN_FILE_NO_ACCESS;
}
CBaseSafeFileList::iterator it = files.begin();
// for each file open file
while (it != files.end())
{
_filename = basename + __safe_storage_extensions[index++];
(*it)->open(_filename, flags);
++it;
}
loadState();
// check if hash of all files it's the same.
int32_t result = checkHashKey();
if (result != E_CSTORAGE_OK)
CEXP_CODE(result);
if (flags & F_CSTORAGE_AUTO_COMMIT) {
C_LOG_INFO("Setting autocommit on (flgs:%08X)", flags);
fauto_commit = true;
}
}
catch (const CException &e)
{
// if error found, all files must be closed
C_LOG_ERR("e.getResult()=%d", e.getResult());
close();
return e.getResult();
}
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::setFlags ( uint32_t flags )
{
string _filename;
CBaseSafeFileList::iterator it = files.begin();
for (int _loop = 0; _loop < 2; ++_loop) {
while (it != files.end())
{
_filename = (*it)->getFilename();
// _filename += __safe_storage_extensions[index++];
int result = (*it)->setFlags(flags | (_loop == 0 ? F_CSFILE_CHECK_FLAGS : 0));
if (_loop == 0 && result < 0) {
return E_CSTORAGE_ERROR;
}
++it;
}
}
return 0;
}
string CSafeStorage::normalizeFilename ( const string &filename )
{
int extlen = strlen(__safe_storage_extensions[0]);
if (filename.compare(filename.size() - extlen, extlen, __safe_storage_extensions[0]) == 0) {
return filename.substr(0, filename.size() - extlen);
}
return filename;
}
/*
* Method to create all files
*
* @param filename prefix, filename without extension
* @param flags flags that applies to this operation. Current, no flags defined for this operation.
*
* @return 0 if no errors, error code if error occurs.
*/
int32_t CSafeStorage::create ( const string &filename, uint32_t flags, uint32_t hash_key )
{
C_LOG_DEBUG("create(%s, %04X)", filename.c_str(), flags);
fauto_commit = false;
string basename = normalizeFilename(filename);
if (mode != CSTORAGE_MODE_REBUILD) {
// Check if any file is created
if (checkAnyFilePresent(basename)) {
C_LOG_ERR("FileExists");
return E_CSTORAGE_CREATE_FILE_EXISTS;
}
}
string _filename;
try
{
CBaseSafeFileList::iterator it = files.begin();
int32_t index = 0;
uint32_t nflags = flags | (F_CSFILE_EXCEPTIONS|F_CSFILE_CREATE|F_CSFILE_WR|F_CSFILE_TRUNCATE);
// list of files is created on constructor, array _safe_storage_extensions
// contains extension for each type of file
while (it != files.end())
{
_filename = basename + __safe_storage_extensions[index++];
(*it)->open(_filename, ((*it) == &fdata && (mode == CSTORAGE_MODE_REBUILD)) ? flags : nflags);
++it;
}
// to link all files and avoid that one of them was replaced, renamed, etc.. generate
// a hash key and this key is stored in all files.
if (mode == CSTORAGE_MODE_REBUILD) {
getHashKey(hash_key);
}
else if ((flags & F_CSTORAGE_SET_HASH_KEY) == 0) {
hash_key = generateHashKey();
}
writeHashKey(hash_key, flags);
if (flags & F_CSTORAGE_AUTO_COMMIT) {
C_LOG_INFO("Setting autocommit on (flgs:%08X)", flags);
fauto_commit = true;
}
}
catch (CException &e)
{
// if error found, all files must be closed
C_LOG_ERR("CException %d on %s:%d", e.getResult(), e.getFile(), e.getLine());
close();
return e.getResult();
}
return 0;
}
int32_t CSafeStorage::rebuild ( const string &filename, uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageDataReg, r_data)
// donde tenemos guardaa
C_LOG_DEBUG("rebuild(%s, %04X)", filename.c_str(), flags);
mode = CSTORAGE_MODE_REBUILD;
int32_t result = CSafeStorage::create(filename, flags);
if (result != E_CSTORAGE_OK) {
return result;
}
DECLARE_STRUCT(CSafeStorageState, _state)
DECLARE_STRUCT(CSafeStorageHashReg, h)
uint8_t *data = (uint8_t *)malloc(1024*1024);
result = fdata.read(0, h.data);
if (result < 0)
{
C_LOG_ERR("Internal error %d reading data 0", result);
return E_CSTORAGE_DATA_READ;
}
// TODO: Rebuild, gestion del rebuild
while ((result = fdata.read(C_CSFILE_CURRPOS, r_data, data, 1024*1024)) > 0)
{
printf("%08X %8d %8d %6d %02X\n", r_data.signature, r_data.serial, r_data.sequence, r_data.len, r_data.flags);
writeFiles(r_data, data, r_data.len);
}
printf("end rebuild (%d)\n", result);
mode = CSTORAGE_MODE_STANDARD;
saveState(false);
sync(true);
return result;
}
/*
* Check if any file is accessible
*
* @param filename prefix of files, name without extension
* @param mode mode for access check.
*
* @return number of files accessible. If returns 0 means files no exists.
*/
int32_t CSafeStorage::checkFilesPresent ( const string &filename, int32_t mode )
{
string _filename;
int32_t index = 0;
int32_t result = 0;
// for each file
while (index < (int32_t)files.size())
{
// generate filename of each file
_filename = filename + __safe_storage_extensions[index++];
// if file is accessible increment counter result.
if (access(_filename.c_str(), mode)!= 0)
{
C_LOG_DEBUG("checking file %s (not found)", _filename.c_str());
++result;
}
else {
C_LOG_DEBUG("checking file %s (found)", _filename.c_str());
}
}
C_LOG_DEBUG("result=%d", result);
return result;
}
int32_t CSafeStorage::checkAnyFilePresent ( const string &filename )
{
return (files.size() - checkFilesPresent(filename, R_OK));
}
/*
* Sync of all files
*/
void CSafeStorage::sync ( bool full )
{
if (mode == CSTORAGE_MODE_REBUILD) return;
fdata.sync();
if (!full) return;
findex.sync();
flog.sync();
fstate.sync();
}
/*
* Method to make a commit of all made from last commit or rollback. This method
* add commit as data (to recover), as commit as log, and updated status
*
* @return 0 means Ok, otherwise means error.
*/
int32_t CSafeStorage::commit ( void )
{
DECLARE_STRUCT(CSafeStorageDataReg,r_data)
if (fauto_commit)
{
C_LOG_DEBUG("Ignore commit because we are in auto-commit mode");
return E_CSTORAGE_OK;
}
C_LOG_DEBUG("CSafeStorage::commit()");
r_data.signature = CSTORAGE_SIGNATURE | T_CSTORAGE_COMMIT;
r_data.sequence = state.last_sequence + 1;
int32_t result = writeFiles(r_data);
// TO-DO: open transactions, make a rollback?
clearDirtySerials();
sync();
return result;
}
void CSafeStorage::clearDirtySerials ( void )
{
dirtySerialIndex = 0;
}
void CSafeStorage::addDirtySerial ( tserial_t serial )
{
if (dirtySerialIndex >= dirtySerialSize) {
dirtySerialSize += C_DIRTY_SERIAL_SIZE;
if (!dirtySerials) dirtySerials = (tserial_t *)malloc(dirtySerialSize * sizeof(tserial_t));
else dirtySerials = (tserial_t *)realloc(dirtySerials, dirtySerialSize * sizeof(tserial_t));
}
dirtySerials[dirtySerialIndex++] = serial;
}
/*
* Method to make a rollback of all write made from last commit or rollback. This method make following steps:
* 1) add rollback (begin) as data
* 2) add rollback (begin) as log
* 3) save state and synchronize all data, log, and state
* 4) update all index of rollback, setting offset -1.
* 5) synchronize index
* 6) add rollback (end) as data linked to last index updated
* 7) add rollback (end) as log linked to last index updated
* 8) save state and synchronize all data, log, and state
*
* @return 0 means Ok, otherwise means error.
*/
int32_t CSafeStorage::rollback ( void )
{
C_LOG_INFO("rollback");
DECLARE_STRUCT(CSafeStorageDataReg,r_data)
int32_t result = E_CSTORAGE_OK;
if (fauto_commit)
{
C_LOG_DEBUG("Rollback disabled in auto-commit mode");
return E_CSTORAGE_NO_ROLLBACK_IN_AUTOCOMMIT;
}
C_LOG_DEBUG("CSafeStorage::rollback()");
r_data.signature = CSTORAGE_SIGNATURE | T_CSTORAGE_ROLLBACK_BEGIN;
r_data.sequence = state.last_sequence + 1;
int32_t dlen = (dirtySerialIndex+1) * sizeof(tserial_t);
tserial_t *serials = (tserial_t *)malloc(dlen);
serials[0] = dirtySerialIndex;
for (uint32_t index = 0; index < dirtySerialIndex; ++index ) serials[index+1] = dirtySerials[index];
result = writeFiles(r_data, serials, dlen);
free(serials);
// asociated to rollback_end stored last index modified, todo a check integrity
// beetween index and data.
memset(&r_data, 0, sizeof(r_data));
r_data.sequence = state.last_sequence + 1;
r_data.signature = CSTORAGE_SIGNATURE | T_CSTORAGE_ROLLBACK_END;
result = writeFiles(r_data);
clearDirtySerials();
return result;
}
/*
* Method used to verify content of data, recalculate all information and check it with index
* state, and log files
*
* @return 0 means verify was ok, error in otherwise.
*/
int32_t CSafeStorage::verify ( uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageDataReg, r_data)
DECLARE_STRUCT(CSafeStorageState, _state)
int32_t result = fdata.read(0, r_data);
if (result > 0)
{
C_LOG_ERR("Internal error %d reading data 0", result);
return E_CSTORAGE_DATA_READ;
}
while ((result = fdata.read(C_CSFILE_CURRPOS, r_data)) > 0)
{
uint32_t type = r_data.signature & CSTORAGE_SIGNATURE_MASK;
switch(type)
{
// _state.last_offset_index;
// _state.last_offsets;
case T_CSTORAGE_COMMIT:
{
_state.last_close_sequence = r_data.sequence;
_state.last_close_offset = fdata.lastOffset();
_state.last_commit_sequence = r_data.sequence;
++_state.commit_count;
break;
}
case T_CSTORAGE_WRITE:
{
++_state.data_count;
break;
}
case T_CSTORAGE_ROLLBACK_BEGIN:
{
++_state.rollback_begin_count;
break;
}
case T_CSTORAGE_ROLLBACK_END:
{
_state.last_close_sequence = r_data.sequence;
_state.last_close_offset = fdata.lastOffset();
++_state.rollback_end_count;
break;
}
case T_CSTORAGE_STATUS:
{
break;
}
default:
{
C_LOG_ERR("Internal error: Non expected data type (0x%08X) was found", type);
return E_CSTORAGE_DATA_READ;
}
}
_state.last_sequence = r_data.sequence;
++_state.count;
}
CMP_STRUCT_FIELD(state,_state,count,result);
CMP_STRUCT_FIELD(state,_state,data_count,result);
CMP_STRUCT_FIELD(state,_state,commit_count,result);
CMP_STRUCT_FIELD(state,_state,rollback_begin_count,result);
CMP_STRUCT_FIELD(state,_state,rollback_end_count,result);
CMP_STRUCT_FIELD(state,_state,last_offset_index,result);
CMP_STRUCT_FIELD(state,_state,last_commit_sequence,result);
CMP_STRUCT_FIELD(state,_state,last_rollback_sequence,result);
CMP_STRUCT_FIELD(state,_state,last_close_sequence,result);
CMP_STRUCT_FIELD(state,_state,last_sequence,result);
CMP_STRUCT_ARRAY_FIELD(state,_state,last_offsets,result);
return result;
}
int32_t CSafeStorage::recoverDirtySerials ( void )
{
DECLARE_STRUCT(CSafeStorageDataReg ,r_data)
uint64_t offset = state.last_close_offset;
clearDirtySerials();
int32_t result = fdata.read(offset, r_data);
if (result > 0)
{
C_LOG_ERR("Internal error %d reading data on offset %lld", result, offset);
return E_CSTORAGE_DATA_READ;
}
uint32_t type = r_data.signature & CSTORAGE_SIGNATURE_MASK;
if (type != T_CSTORAGE_COMMIT && type != T_CSTORAGE_ROLLBACK_BEGIN && type != T_CSTORAGE_ROLLBACK_END)
{
C_LOG_ERR("Internal error: On offset %llld non expected data type (0x%08X) was found", offset, type);
return E_CSTORAGE_DATA_READ;
}
while ((result = fdata.read(C_CSFILE_CURRPOS, r_data)) > 0)
{
type = r_data.signature & CSTORAGE_SIGNATURE_MASK;
if (type != T_CSTORAGE_WRITE)
{
C_LOG_ERR("Internal error: Non expected data type (0x%08X) was found", offset, type);
return E_CSTORAGE_DATA_READ;
}
if ((r_data.flags & F_CSTORAGE_DF_AUTO_COMMIT) == 0)
addDirtySerial(r_data.serial);
}
return result;
}
int32_t CSafeStorage::read ( tserial_t &serial, void *data, uint32_t dlen, uint32_t flags )
{
C_LOG_DEBUG("read(%ld, %p, %d, %08X)", serial, data, dlen, flags);
DECLARE_STRUCT(CSafeStorageIndexReg ,r_index)
DECLARE_STRUCT(CSafeStorageDataReg ,r_data)
cursor = serial;
if (!rdwr) loadState();
int32_t result = findex.readIndex(serial, r_index);
if (result == E_CSFILE_EMPTY_DATA)
return E_CSTORAGE_SERIAL_NOT_FOUND;
if (result < 0)
return result;
/* verify if offset error, or offset not initialized (=0) or deleted (=-1) */
last_offset = getLastOffset(r_index, serial, flags);
if (last_offset <= 0)
return E_CSTORAGE_SERIAL_NOT_FOUND;
C_LOG_DEBUG("try to read %d bytes on offset %lld", dlen, last_offset);
result = fdata.read(last_offset, r_data, data, dlen);
if (result < 0)
return result;
if (C_LOG_DEBUG_ENABLED) {
if (result > 1024) { C_LOG_DEBUG("data(%p): %s...%s", data, c_log_data2hex(data, 0, 256), c_log_data2hex(data, result - 256, 256)); }
else { C_LOG_DEBUG("data(%p): %s", data, c_log_data2hex(data, 0, result)); };
}
result = result - sizeof(r_data);
C_LOG_DEBUG("state.last_commit_sequence:%d r_data.sequence:%d autocommit:%s", state.last_commit_sequence, r_data.sequence,
(r_data.flags & F_CSTORAGE_DF_AUTO_COMMIT)? "true":"false");
if (C_LOG_DEBUG_ENABLED) {
if (result > 1024) { C_LOG_DEBUG("data(%p): %s...%s", data, c_log_data2hex(data, 0, 256), c_log_data2hex(data, result - 256, 256)); }
else { C_LOG_DEBUG("data(%p): %s", data, c_log_data2hex(data, 0, result)); };
}
return result;
}
int32_t CSafeStorage::readLog ( tseq_t seq, void *data, uint32_t dlen, uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageLogReg ,r_log)
if (!rdwr) loadState();
int32_t result = flog.readIndex(seq, r_log);
if (result < 0) return result;
if (result == E_CSFILE_EMPTY_DATA)
return E_CSTORAGE_SEQUENCE_NOT_FOUND;
if (result < 0)
return result;
int64_t offset = r_log.offset;
if (offset < 0)
return E_CSTORAGE_SEQUENCE_NOT_FOUND;
if (dlen < sizeof(CSafeStorageDataReg))
return E_CSTORAGE_NOT_ENOUGH_DATA;
uint8_t *d_data = ((uint8_t *)data) + sizeof(CSafeStorageDataReg);
result = fdata.read(offset, *((CSafeStorageDataReg *)data), d_data, dlen - sizeof(CSafeStorageDataReg));
if (result < 0)
return result;
return result;
}
/*
* Method to access to log
*
* @param seq sequence of log to read
* @param serial out parameter, if it isn't null was stored serial number of this sequence
* @param type out parameter, if it isn't null was stored type of action of this sequence
* (write, commit, rollback-begin, rollback-end)
*
* @return 0 Ok, error in otherwise.
*/
int32_t CSafeStorage::readLogReg ( tseq_t seq, tserial_t &serial, uint8_t &type, uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageLogReg ,r_log)
int32_t result = flog.readIndex(seq, r_log);
if (result < 0) return result;
serial = r_log.serial;
type = r_log.type;
return 0;
}
/*
* Write a hash (mark) in all files, to link them, to avoid that
* one of files was replaced with another.
*/
int32_t CSafeStorage::writeHashKey ( uint32_t hash_key, uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageHashReg, h)
C_LOG_TRACE("writeHashKey %08X", hash_key);
// store hash in structure
h.hash_key = hash_key;
// write hash in files
if (mode != CSTORAGE_MODE_REBUILD) {
fdata.write(0, h.data);
}
flog.write(0, h.log);
findex.write(0, h.index);
// set hash in state structure, and save it.
state.hash_key = hash_key;
saveState(false);
sync();
return 0;
}
/*
* Check that all files are liked, when files was created an random hash of 4 bytes was generated
* and copy in all files. With this feature it's possible detect when files was replace by other
* incorrect or old file. Data hash is considered how master hash. This information about hash is
* stored in first record.
*
* @return if checks is passed return 0, if not return value that was an OR of all hash that fails.
*/
int32_t CSafeStorage::checkHashKey ( void )
{
DECLARE_STRUCT(CSafeStorageHashReg, h)
uint32_t hash_key;
int32_t result = E_CSTORAGE_OK;
fdata.read(0, h.data);
hash_key = h.hash_key;
C_LOG_DEBUG("CheckHashKey %08X", hash_key);
flog.read(0, h.log);
if (h.hash_key != hash_key) {
C_LOG_ERR("CheckHashKey Log [FAILS] (Data: %08X / Log: %08X)", hash_key, h.hash_key);
result |= E_CSTORAGE_FAIL_HK_LOG;
}
findex.read(0, h.index);
if (h.hash_key != hash_key) {
C_LOG_ERR("CheckHashKey Index [FAILS] (Data: %08X / Index: %08X)", hash_key, h.hash_key);
result |= E_CSTORAGE_FAIL_HK_INDEX;
}
if (!rdwr) loadState();
if (state.hash_key != hash_key) {
C_LOG_ERR("CheckHashKey State [FAILS] (Data: %08X / State: %08X)", hash_key, state.hash_key);
result |= E_CSTORAGE_FAIL_HK_STATE;
}
C_LOG_DEBUG("CheckHashKey [%s] result = %08X", result == E_CSTORAGE_OK ? "OK":"FAILS", result);
return result;
}
int32_t CSafeStorage::write ( tserial_t serial, const void *data, uint32_t dlen, uint32_t flags )
{
DECLARE_STRUCT(CSafeStorageDataReg ,r_data)
C_LOG_DEBUG("CSafeStorage::write(%d, %p, %d) lseq:%d", serial, data, dlen, state.last_sequence);
r_data.signature = CSTORAGE_SIGNATURE | T_CSTORAGE_WRITE;
r_data.serial = serial;
r_data.sequence = state.last_sequence + 1;
r_data.len = dlen;
if (fauto_commit)
r_data.flags |= F_CSTORAGE_DF_AUTO_COMMIT;
return writeFiles(r_data, data, dlen);
}
int32_t CSafeStorage::applyLog ( const void *data, uint32_t dlen, uint32_t flags )
{
if (dlen < sizeof(CSafeStorageDataReg))
return E_CSTORAGE_NOT_ENOUGH_DATA;
uint8_t *d_data = ((uint8_t *)data) + sizeof(CSafeStorageDataReg);
return writeFiles(*((CSafeStorageDataReg *)data), d_data, dlen - sizeof(CSafeStorageDataReg));
}
int32_t CSafeStorage::writeFiles ( CSafeStorageDataReg &r_data, const void *data, uint32_t dlen )
{
DECLARE_STRUCT(CSafeStorageIndexReg ,r_index)
DECLARE_STRUCT(CSafeStorageLogReg ,r_log)
int32_t result = E_CSTORAGE_OK;
int32_t type = r_data.signature & CSTORAGE_SIGNATURE_MASK;
++state.count;
state.last_sequence = r_data.sequence;
r_log.serial = r_data.serial;
r_log.type = type;
C_LOG_DEBUG("type:%08X dlen:%d", type, dlen);
switch (type)
{
case T_CSTORAGE_WRITE:
{
// prepare log register related to write
r_log.offset = writeData(r_data, data, dlen);
++state.data_count;
// prepare index related to write
setOldestOffset(r_index, r_data.serial, r_log.offset, r_data.sequence, r_data.flags, findex.readIndex(r_data.serial, r_index) < 0);
// if error in data write, abort this write and returns error
if (r_log.offset < 0LL) {
return -1;
}
if (!fauto_commit)
addDirtySerial(r_data.serial);
// save state with information
saveState();
flog.writeIndex(r_data.sequence, r_log);
findex.writeIndex(r_data.serial, r_index);
result = dlen;
break;
}
case T_CSTORAGE_ROLLBACK_BEGIN:
{
writeData(r_data, data, dlen);
writeSyncStateLogSync(r_log);
// mark offset of all indexes as -1
tserial_t *serials = (tserial_t *) data;
int32_t count = serials[0];
// must: dlen / sizeof(tserial_t) == serials[0]+1
int32_t index = 1;
while (index <= count)
{
findex.readIndex(serials[index], r_index);
setNewestOffset(r_index, serials[index], -1, 0, 0);
int32_t result = findex.writeIndex(serials[index], r_index);
if (result < 0)
C_LOG_ERR("CSafeStorage::rollBack Error saving index %d of rollback", serials[index]);
++index;
}
if (count > 0 && mode != CSTORAGE_MODE_REBUILD)
{
findex.sync();
}
break;
}
case T_CSTORAGE_ROLLBACK_END:
{
writeData(r_data);
writeSyncStateLogSync(r_log);
break;
}
case T_CSTORAGE_COMMIT:
{
r_log.offset = writeData(r_data);
++state.commit_count;
state.last_commit_sequence = r_data.sequence;
writeSyncStateLogSync(r_log);
break;
}
}
// check if store a status snapshot
if (state.count % C_STORAGE_STATUS_FREQ == (C_STORAGE_STATUS_FREQ - 1)) {
DECLARE_STRUCT(CSafeStorageDataReg,r_state_data)
r_state_data.signature = CSTORAGE_SIGNATURE | T_CSTORAGE_STATUS;
r_state_data.sequence = state.last_sequence + 1;
memset(&r_log, 0, sizeof(r_log));
++state.count;
state.last_sequence = r_state_data.sequence;
r_log.serial = r_state_data.serial;
r_log.type = T_CSTORAGE_STATUS;
r_log.offset = writeData(r_state_data);
flog.writeIndex(state.last_sequence, r_log);
saveState();
}
return result;
}
void CSafeStorage::writeSyncStateLogSync ( CSafeStorageLogReg &r_log )
{
flog.writeIndex(state.last_sequence, r_log);
/*
if (mode != CSTORAGE_MODE_REBUILD) fdata.sync();
saveState();
if (mode != CSTORAGE_MODE_REBUILD) flog.sync();*/
}
void CSafeStorage::saveState ( bool sync )
{
if (mode == CSTORAGE_MODE_REBUILD || !rdwr) return;
fstate.write(0, state);
/* if (sync)
fstate.sync();*/
}
void CSafeStorage::loadState ( void)
{
fstate.read(0, state);
}
uint32_t CSafeStorage::generateHashKey ( void )
{
int32_t fd;
uint32_t result = 0;
fd = ::open("/dev/random", O_RDONLY);
if (fd >= 0)
{
if (::read(fd, &result, sizeof(result)) != sizeof(result))
fd = -1;
::close(fd);
}
if (fd < 0) {
srand ( time(NULL) );
result = rand();
}
return result;
}
int32_t CSafeStorage::getInfo ( CSafeStorageInfo &info )
{
info.hash_key = state.hash_key;
info.last_updated = state.last_updated;
info.version = 0;
info.count = state.count;
info.commit_count = state.commit_count;
info.rollback_begin_count = state.rollback_begin_count;
info.rollback_end_count = state.rollback_end_count;
info.last_commit_sequence = state.last_commit_sequence;
info.last_rollback_sequence = state.last_rollback_sequence;
info.last_sequence = state.last_sequence;
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::getHashKey ( uint32_t &hash_key )
{
DECLARE_STRUCT(CSafeStorageHashReg, h)
int32_t result = fdata.read(0, h.data);
if (result == sizeof(h.data)) {
result = E_CSTORAGE_OK;
hash_key = h.hash_key;
}
return result;
}
void CSafeStorage::dumpState ( void )
{
int32_t index;
printf("[state]\n");
printf("hash_key: %08X\n", state.hash_key);
printf("last_updated: %d\n", state.last_updated);
printf("count: %d\n", state.count);
printf("commit_count: %d\n", state.commit_count);
printf("rollback_begin_count: %d\n", state.rollback_begin_count);
printf("rollback_end_count: %d\n", state.rollback_end_count);
printf("last_offset_index: %d\n", state.last_offset_index);
printf("last_commit_sequence: %u\n", state.last_commit_sequence);
printf("last_rollback_sequence: %u\n", state.last_rollback_sequence);
printf("last_close_sequence: %d\n", state.last_close_sequence);
printf("last_sequence: %d\n", state.last_sequence);
printf("last_close_offset: %lld\n", state.last_close_offset);
printf("last_offsets[%d]:", sizeof(state.last_offsets)/sizeof(state.last_offsets[0]));
for (index = 0; index < (int32_t)(sizeof(state.last_offsets)/sizeof(state.last_offsets[0])); ++index) {
printf("%s%lld", index?",":"", state.last_offsets[index]);
}
printf("\n");
}
int64_t CSafeStorage::writeData ( CSafeStorageDataReg &r_data, const void *data, uint32_t dlen )
{
if (mode != CSTORAGE_MODE_REBUILD) {
int64_t result = fdata.write(r_data, data, dlen);
if (result < 0) {
C_LOG_ERR("Error writting data (%p,%p,%d) result %d", &r_data, data, dlen, (int32_t)result);
return result;
}
}
state.last_offset_index = (state.last_offset_index + 1) % (sizeof(state.last_offsets)/sizeof(state.last_offsets[0]));
state.last_offsets[state.last_offset_index] = fdata.lastOffset();
return state.last_offsets[state.last_offset_index];
}
int32_t CSafeStorage::removeFiles ( const string &filename )
{
string _filename;
int32_t index = 0;
int32_t result = 0;
int32_t count = sizeof(__safe_storage_extensions)/sizeof(char *);
// for each file
while (index < count)
{
// generate filename of each file
_filename = filename + __safe_storage_extensions[index++];
C_LOG_DEBUG("deleting file %s", _filename.c_str());
if (unlink(_filename.c_str()))
--result;
}
return result;
}
void CSafeStorage::setOldestOffset ( CSafeStorageIndexReg &index, tserial_t serial, int64_t offset, tseq_t sequence, uint32_t flags, bool init )
{
C_LOG_TRACE("In #:%ld off:%lld seq:%d flgs:%08X init:%d 0:[%d,%lld] 1:[%d,%lld]", serial, offset, sequence, flags, init?1:0, index.sequences[0], index.offsets[0],index.sequences[1], index.offsets[1]);
if (init) {
memset(&index, 0, sizeof(index));
index.offsets[0] = offset;
index.sequences[0] = sequence;
index.flags[0] = flags;
index.offsets[1] = -1;
index.sequences[1] = 0;
index.flags[1] = 0;
}
else {
int32_t pos = (index.sequences[1] > index.sequences[0] ? 0 : 1);
index.offsets[pos] = offset;
index.sequences[pos] = sequence;
index.flags[pos] = flags;
}
C_LOG_TRACE("Out #:%ld 0:[%d,%lld] 1:[%d,%lld]", serial, index.sequences[0], index.offsets[0],index.sequences[1], index.offsets[1]);
}
void CSafeStorage::setNewestOffset ( CSafeStorageIndexReg &index, tserial_t serial, int64_t offset, tseq_t sequence, uint32_t flags )
{
C_LOG_TRACE("In #:%ld off:%lld seq:%d flgs:%08X 0:[%d,%lld] 1:[%d,%lld]", serial, offset, sequence, flags, index.sequences[0], index.offsets[0],index.sequences[1], index.offsets[1]);
int32_t pos = (index.sequences[1] > index.sequences[0] ? 1 : 0);
index.offsets[pos] = offset;
index.sequences[pos] = offset;
index.flags[pos] = flags;
C_LOG_TRACE("Out #:%ld 0:[%d,%lld] 1:[%d,%lld]", serial, index.sequences[0], index.offsets[0],index.sequences[1], index.offsets[1]);
}
int64_t CSafeStorage::getLastOffset ( CSafeStorageIndexReg &index, tserial_t serial, uint32_t flags )
{
int64_t result = -1;
tseq_t lastseq = 0;
uint32_t dirtyRead = (flags & F_CSTORAGE_READ_MODE_MASK) || rdwr;
for ( int32_t i = 0; i < 2; ++i ) {
// check if current position is autocommited if not, check that index is commited, current sequence is lower or equal
// last transaccion commited, if not, check if read in dirty read. Compare with lastseq to avoid read a old register.
if (index.sequences[i] >= lastseq && ((index.flags[i] & F_CSTORAGE_DF_AUTO_COMMIT) ||
index.sequences[i] <= state.last_commit_sequence || dirtyRead)) {
result = index.offsets[i];
lastseq = index.sequences[i];
}
}
C_LOG_INFO("0:[%02X, %d,%lld] 1:[%02X, %d,%lld] S:%u FLGS:%08X R:%lld LCS:%u RDWR:%d",
index.flags[0], index.sequences[0], index.offsets[0], index.flags[1], index.sequences[1], index.offsets[1],
serial, flags, result, state.last_commit_sequence, rdwr);
return result;
}
int64_t CSafeStorage::getLastOffset ( void )
{
return last_offset;
}
int32_t CSafeStorage::goTop ( uint32_t flags )
{
cursor = -1;
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::goPos ( tserial_t serial, uint32_t flags )
{
cursor = serial < 0 ? -1 : serial-1;
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::getParam ( const string &name )
{
if (name == "index_cache_size") return findex.getCacheSize();
else if (name == "log_cache_size") return flog.getCacheSize();
return -1;
}
int32_t CSafeStorage::setParam ( const string &name, int32_t value )
{
if (name == "index_cache_size") findex.setCacheSize(value);
else if (name == "log_cache_size") flog.setCacheSize(value);
else if (name == "c_log_level") c_log_set_level(value);
else return -1;
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::createListener ( const string ¶ms, ISafeStorageListener **ltn )
{
// syslog(LOG_ERR | LOG_USER, "createListener(%s)", params.c_str());
CSafeStorageListener *listener = new CSafeStorageListener(params);
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::createReplica ( const string ¶ms, ISafeStorageReplica **rpl )
{
// syslog(LOG_ERR | LOG_USER, "createReplica(%s)", params.c_str());
return E_CSTORAGE_OK;
}
int32_t CSafeStorage::setCallback ( tsafestorage_callback_t cb )
{
// syslog(LOG_ERR | LOG_USER, "setCallback");
cb(E_CB_REPLICA_FAIL, NULL);
return E_CSTORAGE_OK;
}
void CSafeStorage::findLastSignatureReg ( int32_t max_size )
{
fdata.findLastSignatureReg(max_size, CSTORAGE_SIGNATURE, CSTORAGE_SIGNATURE_SIGN_MASK, sizeof(uint32_t));
}
int32_t ISafeStorage::getLogReg ( const void *data, uint32_t dlen, CSafeStorageLogInfo &linfo )
{
if (sizeof(CSafeStorageDataReg) > dlen) {
return E_CSTORAGE_NOT_VALID_DATA;
}
const CSafeStorageDataReg *dreg = (const CSafeStorageDataReg *)data;
if ((dreg->signature & CSTORAGE_SIGNATURE_SIGN_MASK) != CSTORAGE_SIGNATURE) {
return E_CSTORAGE_NOT_VALID_DATA;
}
memset(&linfo, 0, sizeof(linfo));
linfo.sequence = dreg->sequence;
linfo.serial = dreg->serial;
linfo.type = (dreg->signature & CSTORAGE_SIGNATURE_TYPE_MASK);
linfo.len = dreg->len;
linfo.flags = dreg->flags;
return E_CSTORAGE_OK;
}
| 29.491213
| 201
| 0.678615
|
imaginatho
|
efc3a216bf2f72dbbbc86f4644ef0f02ab9552b3
| 2,540
|
cpp
|
C++
|
src/components/UIElement.cpp
|
KirmesBude/REGoth-bs
|
2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a
|
[
"MIT"
] | 399
|
2019-01-06T17:55:18.000Z
|
2022-03-21T17:41:18.000Z
|
src/components/UIElement.cpp
|
KirmesBude/REGoth-bs
|
2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a
|
[
"MIT"
] | 101
|
2019-04-18T21:03:53.000Z
|
2022-01-08T13:27:01.000Z
|
src/components/UIElement.cpp
|
KirmesBude/REGoth-bs
|
2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a
|
[
"MIT"
] | 56
|
2019-04-10T10:18:27.000Z
|
2022-02-08T01:23:31.000Z
|
#include "UIElement.hpp"
#include <GUI/BsCGUIWidget.h>
#include <GUI/BsGUIPanel.h>
#include <Image/BsSpriteTexture.h>
#include <RTTI/RTTI_UIElement.hpp>
#include <exception/Throw.hpp>
#include <gui/skin_gothic.hpp>
#include <log/logging.hpp>
#include <original-content/OriginalGameResources.hpp>
namespace REGoth
{
UIElement::UIElement(const bs::HSceneObject& parent, bs::HCamera camera)
: bs::Component(parent)
{
setName("UIElement");
auto guiWidget = SO()->addComponent<bs::CGUIWidget>(camera);
guiWidget->setSkin(REGoth::GUI::getGothicStyleSkin());
mGuiLayout = guiWidget->getPanel();
}
UIElement::UIElement(const bs::HSceneObject& parent, HUIElement parentUiElement,
bs::GUILayout* layout)
: bs::Component(parent)
, mParentUiElement(parentUiElement)
, mGuiLayout(layout)
{
setName("UIElement");
if (parentUiElement->SO() != parent->getParent())
{
REGOTH_THROW(InvalidParametersException, "Parent UIElement must be attached to parent SO");
}
parentLayout().addElement(mGuiLayout);
}
UIElement::~UIElement()
{
}
void UIElement::show()
{
layout().setVisible(true);
}
void UIElement::hide()
{
layout().setVisible(false);
}
bs::HSceneObject UIElement::addChildSceneObject(const bs::String& name)
{
auto so = bs::SceneObject::create(name);
so->setParent(SO());
return so;
}
bs::GUILayout& UIElement::layout() const
{
if (!mGuiLayout)
{
REGOTH_THROW(InvalidStateException, "No Layout available?");
}
return *mGuiLayout;
}
bs::GUILayout& UIElement::parentLayout() const
{
if (!mParentUiElement)
{
REGOTH_THROW(InvalidStateException, "No parent available?");
}
return mParentUiElement->layout();
}
bs::Camera& UIElement::camera() const
{
if (!layout()._getParentWidget())
{
REGOTH_THROW(InvalidStateException, "No parent widget available?");
}
auto camera = layout()._getParentWidget()->getCamera();
if (!camera)
{
REGOTH_THROW(InvalidStateException, "No camera available?");
}
return *camera;
}
bs::HSpriteTexture UIElement::loadSprite(const bs::String& texture)
{
bs::HTexture t = gOriginalGameResources().texture(texture);
if (!t)
{
REGOTH_LOG(Warning, Uncategorized, "[UIElement] Failed to load texture: {0}", texture);
return {};
}
return bs::SpriteTexture::create(t);
}
REGOTH_DEFINE_RTTI(UIElement)
} // namespace REGoth
| 21.896552
| 97
| 0.658268
|
KirmesBude
|
efc5a1c2c7fcaafaa0c019bac69c79e662831cad
| 354
|
cc
|
C++
|
poj/1/1401.cc
|
eagletmt/procon
|
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
|
[
"MIT"
] | 1
|
2015-04-17T09:54:23.000Z
|
2015-04-17T09:54:23.000Z
|
poj/1/1401.cc
|
eagletmt/procon
|
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
|
[
"MIT"
] | null | null | null |
poj/1/1401.cc
|
eagletmt/procon
|
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(void)
{
int T;
cin >> T;
while (T-- > 0) {
int N;
cin >> N;
int n2 = 0;
for (int base = 2; base <= N; base *= 2) {
n2 += N/base;
}
int n5 = 0;
for (int base = 5; base <= N; base *= 5) {
n5 += N/base;
}
cout << min(n2, n5) << endl;
}
return 0;
}
| 15.391304
| 46
| 0.440678
|
eagletmt
|
efc6f35430fffde57adff0d36b3155817d6d4ba5
| 379
|
hpp
|
C++
|
src/lib/common/Utility.hpp
|
genome/diagnose_dups
|
17f63ed3d07c63f9b55dc7431f6528707d30709f
|
[
"MIT"
] | 8
|
2015-05-13T12:40:44.000Z
|
2018-03-09T15:10:21.000Z
|
src/lib/common/Utility.hpp
|
genome/diagnose_dups
|
17f63ed3d07c63f9b55dc7431f6528707d30709f
|
[
"MIT"
] | 5
|
2015-03-22T00:58:44.000Z
|
2017-12-08T18:21:49.000Z
|
src/lib/common/Utility.hpp
|
genome/diagnose_dups
|
17f63ed3d07c63f9b55dc7431f6528707d30709f
|
[
"MIT"
] | 4
|
2015-08-04T01:11:54.000Z
|
2017-04-11T10:27:42.000Z
|
#pragma once
#include <sam.h>
#include <stdint.h>
#include <vector>
namespace cigar {
std::vector<uint32_t> parse_string_to_cigar_vector(char const* cigar_string);
int32_t calculate_right_offset(bam1_t const* record);
int32_t calculate_right_offset(char const* cigar);
int32_t calculate_left_offset(bam1_t const* record);
int32_t calculate_left_offset(char const* cigar);
}
| 22.294118
| 77
| 0.802111
|
genome
|
efcb3c623f09b27de5e5af4d73f99e82b6b7561c
| 2,181
|
cpp
|
C++
|
src/kernel/io/KPrintf.cpp
|
jameskingstonclarke/arctic
|
6fec04809d6175689477abfe21416f33e63cb177
|
[
"MIT"
] | 1
|
2021-02-01T19:28:02.000Z
|
2021-02-01T19:28:02.000Z
|
src/kernel/io/KPrintf.cpp
|
jameskingstonclarke/arctic
|
6fec04809d6175689477abfe21416f33e63cb177
|
[
"MIT"
] | 9
|
2021-02-07T15:46:11.000Z
|
2021-02-18T08:25:42.000Z
|
src/kernel/io/KPrintf.cpp
|
jameskingstonclarke/arctic
|
6fec04809d6175689477abfe21416f33e63cb177
|
[
"MIT"
] | null | null | null |
#include "KPrintf.h"
#include "../utils/Math.h"
#include "../Types.h"
#include "../driver/VGAGraphics.h"
#include "Serial.h"
namespace IO{
void kinfo(const char * info){
Driver::VGAGraphics::vga_driver.colour(Driver::VGAGraphics::vga_green);
kprintf("[INFO] ");
kprintf(info);
}
void kwarn(const char * warn){
Driver::VGAGraphics::vga_driver.colour(Driver::VGAGraphics::vga_red);
kprintf("[WARNING] ");
kprintf(warn);
}
void kerr(const char * err){
Driver::VGAGraphics::vga_driver.colour(Driver::VGAGraphics::vga_red);
kprintf("[ERROR] ");
kprintf(err);
}
void kprintf(const char * msg){
unsigned int j = 0;
/* this loop writes the string to video memory */
while(msg[j] != '\0') {
switch(msg[j]){
case '%':
{
switch(msg[j+1]){
case 'd': {
// print a decimal
}
default: {
kprint_c(msg[j]);
++j;
break;
};
}
}
default: {
kprint_c(msg[j]);
++j;
break;
}
}
}
}
void kprintf(String msg){
kprintf(msg.cstr());
}
void kprint_c(const char c){
switch(c){
default:{
Driver::VGAGraphics::vga_driver.putc(c);
}
}
}
void kprint_int(int i){
char buffer[50];
if(i==0){
buffer[0]='0';
buffer[1]='\0';
IO::kprint_str(buffer);
}
bool is_neg = i<0;
if(is_neg)i*=-1;
//!@TODO for integers larger than 10
int j =0;
while(i>0){
buffer[j]=(i%10)+'0';
i/=10;
j++;
}
if(is_neg) buffer[j++]='-';
buffer[j]='\0';
int start = 0;
int end = j-1;
while(start<end){
char a, b;
a = *(buffer+start);
b = *(buffer+end);
*(buffer+start)=b;
*(buffer+end)=a;
start++;
end--;
}
kprint_str(buffer);
}
void kprint_f(float f, int prescision){
// extract integer part
volatile s32 i_part = (s32)f;
// extraft float part
//float f_part = (float)f;
//kprint_int(i_part);
//kprint_c('.');
//kprint_int((int)(f_part*Utils::Math::pow(f_part, prescision)));
}
void kprint_str(const char * str){
for(int i = 0;str[i];i++)
kprint_c(str[i]);
}
}
| 19.300885
| 74
| 0.538285
|
jameskingstonclarke
|
efd1f73832af8201c5c3a93fc34f1c6446bfe8ce
| 752
|
hpp
|
C++
|
include/RED4ext/Types/generated/community/CommunityEntryPhaseTimePeriodData.hpp
|
Cyberpunk-Extended-Development-Team/RED4ext.SDK
|
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
|
[
"MIT"
] | 1
|
2021-02-01T23:07:50.000Z
|
2021-02-01T23:07:50.000Z
|
include/RED4ext/Types/generated/community/CommunityEntryPhaseTimePeriodData.hpp
|
Cyberpunk-Extended-Development-Team/RED4ext.SDK
|
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
|
[
"MIT"
] | null | null | null |
include/RED4ext/Types/generated/community/CommunityEntryPhaseTimePeriodData.hpp
|
Cyberpunk-Extended-Development-Team/RED4ext.SDK
|
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
|
[
"MIT"
] | null | null | null |
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/Types/generated/world/GlobalNodeID.hpp>
namespace RED4ext
{
namespace community {
struct CommunityEntryPhaseTimePeriodData
{
static constexpr const char* NAME = "communityCommunityEntryPhaseTimePeriodData";
static constexpr const char* ALIAS = NAME;
CName periodName; // 00
DynArray<world::GlobalNodeID> spotNodeIds; // 08
bool isSequence; // 18
uint8_t unk19[0x20 - 0x19]; // 19
};
RED4EXT_ASSERT_SIZE(CommunityEntryPhaseTimePeriodData, 0x20);
} // namespace community
} // namespace RED4ext
| 26.857143
| 85
| 0.757979
|
Cyberpunk-Extended-Development-Team
|
efd27baa76ce20bbacdcda74479534b6e862c749
| 2,587
|
cpp
|
C++
|
source/mdb/mdbclt/mdbclt_example/src/mdbclt_example.m.cpp
|
jan-kelemen/melinda
|
308e6262bc0cab7f6253062e8abda11452490bb4
|
[
"BSD-3-Clause"
] | 3
|
2021-03-25T08:44:38.000Z
|
2022-01-06T11:05:42.000Z
|
source/mdb/mdbclt/mdbclt_example/src/mdbclt_example.m.cpp
|
jan-kelemen/melinda
|
308e6262bc0cab7f6253062e8abda11452490bb4
|
[
"BSD-3-Clause"
] | 6
|
2019-07-13T17:11:50.000Z
|
2022-03-07T19:22:09.000Z
|
source/mdb/mdbclt/mdbclt_example/src/mdbclt_example.m.cpp
|
jan-kelemen/melinda
|
308e6262bc0cab7f6253062e8abda11452490bb4
|
[
"BSD-3-Clause"
] | null | null | null |
#include <array>
#include <chrono>
#include <iostream>
#include <thread>
#include <unistd.h>
#include <vector>
#include <mblcxx_scope_exit.h>
#include <mbltrc_trace.h>
#include <mdbnet_client.h>
#include <mdbnet_serialization.h>
int main()
{
melinda::mbltrc::trace_options trace_config(std::filesystem::path("../log"),
std::filesystem::path("example_client"));
trace_config.level = melinda::mbltrc::trace_level::info;
melinda::mbltrc::initialize_process_trace_handle(
melinda::mbltrc::create_trace_handle(trace_config));
zmq::context_t ctx;
constexpr char const* const address = "tcp://localhost:22365";
melinda::mblcxx::result<zmq::socket_t> connect_result =
melinda::mdbnet::client::connect(ctx, address);
if (!connect_result)
{
MBLTRC_TRACE_FATAL("Can't connect to {}", address);
std::terminate();
}
// TODO-JK allow taking values out of result
zmq::socket_t& socket = connect_result.ok();
MBLCXX_ON_SCOPE_EXIT(socket.disconnect(address));
std::string const identity = socket.get(zmq::sockopt::routing_id, 256);
flatbuffers::FlatBufferBuilder const query =
melinda::mdbnet::serialization::query(identity, "SELECT * FROM v$sql");
while (true)
{
melinda::mdbnet::result<zmq::send_result_t> const send_result =
melinda::mdbnet::client::send(socket,
{reinterpret_cast<std::byte*>(query.GetBufferPointer()),
query.GetSize()});
if (!send_result || !send_result.ok())
{
continue;
}
melinda::mdbnet::result<melinda::mdbnet::recv_response<zmq::message_t>>
recv_result = melinda::mdbnet::client::recv(
socket); // TODO-JK: This is blocking indefinately
if (recv_result)
{
melinda::mdbnet::recv_response<zmq::message_t> const& success =
recv_result.ok();
if (success.received)
{
melinda::mdbnet::Message const* message =
flatbuffers::GetRoot<melinda::mdbnet::root_type>(
success.message.value().data());
if (message->content_type() ==
melinda::mdbnet::MessageContent_result)
{
melinda::mdbnet::QueryResult const* query_result =
message->content_as_result();
MBLTRC_TRACE_INFO("Returned {} rows.",
query_result->length());
}
}
}
}
}
| 31.54878
| 80
| 0.591032
|
jan-kelemen
|
efd409501cd105af4876885427bae9752ac9f537
| 2,329
|
cpp
|
C++
|
src/Crane.cpp
|
ithamsteri/towerblocks
|
584c37e43dea91ffb789883e873884b9279e7dcb
|
[
"MIT"
] | null | null | null |
src/Crane.cpp
|
ithamsteri/towerblocks
|
584c37e43dea91ffb789883e873884b9279e7dcb
|
[
"MIT"
] | null | null | null |
src/Crane.cpp
|
ithamsteri/towerblocks
|
584c37e43dea91ffb789883e873884b9279e7dcb
|
[
"MIT"
] | null | null | null |
#include "Crane.h"
#include "Resource.h"
#include <cmath>
spSprite
Crane::doThrowBlock()
{
if (_state != States::Working) {
return nullptr;
}
_block->detach();
_block->setPosition(_view->getPosition());
// return crane to base
auto t = _view->addTween(TweenDummy(), 50);
t->addEventListener(TweenEvent::DONE, [this](Event*) { moveToBase(); });
return _block;
}
void
Crane::start()
{
_state = States::FromBase;
_block = getNewBlock();
_block->attachTo(_view);
// reset all parameters for pendulum
_velocity = 0.0f;
_acceleration = 0.0f;
_angle = -0.5f * pi;
// TODO: "Don't Repeat Yourself (DRY)"
float x = _basePosition.x + std::sin(_angle) * _length;
float y = std::cos(_angle) * 0.5f * _length;
auto t = _view->addTween(Actor::TweenPosition(x, y), speedAnimation);
t->addEventListener(TweenEvent::DONE, [this](Event*) { _state = States::Working; });
}
void
Crane::stop()
{
_state = States::Stopped;
auto t = _view->addTween(Actor::TweenPosition(_basePosition), speedAnimation);
}
void
Crane::_init()
{
spSprite magnit = new Sprite;
magnit->setResAnim(res::ui.getResAnim("Game_CraneMagnet"));
magnit->setAnchor(0.5f, 1.0f);
magnit->attachTo(_view);
magnit->setPriority(50);
// save base position for crane
_basePosition = _view->getPosition();
// set length rope of crane
_length = _basePosition.x - _basePosition.x * 2 * 0.20f;
start();
}
void
Crane::_update(const UpdateState& us)
{
if (_state != States::Working) {
return;
}
// TODO: Make Oxygine Tween for pendulum move
_acceleration = gravity / _length * std::sin(_angle);
_velocity += _acceleration / us.dt * _speed;
_angle += _velocity / us.dt * _speed;
float x = _basePosition.x + std::sin(_angle) * _length;
float y = std::cos(_angle) * 0.5f * _length;
_view->setPosition(x, y);
}
void
Crane::moveToBase()
{
_state = States::ToBase;
auto t = _view->addTween(Actor::TweenPosition(_basePosition), speedAnimation);
t->addEventListener(TweenEvent::DONE, [this](Event*) { this->start(); });
}
spSprite
Crane::getNewBlock() const
{
int blockNum = static_cast<int>(scalar::randFloat(0.0f, 7.0f)) + 1;
auto block = new Sprite;
block->setResAnim(res::ui.getResAnim("Block" + std::to_string(blockNum)));
block->setAnchor(0.5f, 0.25f);
return block;
}
| 22.180952
| 86
| 0.668957
|
ithamsteri
|
efd502b3ded485b3ba8eb91a2671450db283faa4
| 3,520
|
cpp
|
C++
|
tests/altium_crap/Soft Designs/C++/NB3000 C++ Tetris/Embedded/input.cpp
|
hanun2999/Altium-Schematic-Parser
|
a9bd5b1a865f92f2e3f749433fb29107af528498
|
[
"MIT"
] | 1
|
2020-06-08T11:17:46.000Z
|
2020-06-08T11:17:46.000Z
|
tests/altium_crap/Soft Designs/C++/NB3000 C++ Tetris/Embedded/input.cpp
|
hanun2999/Altium-Schematic-Parser
|
a9bd5b1a865f92f2e3f749433fb29107af528498
|
[
"MIT"
] | null | null | null |
tests/altium_crap/Soft Designs/C++/NB3000 C++ Tetris/Embedded/input.cpp
|
hanun2999/Altium-Schematic-Parser
|
a9bd5b1a865f92f2e3f749433fb29107af528498
|
[
"MIT"
] | null | null | null |
// Logger thread
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <mqueue.h>
#include "devices.h"
#include "drv_ioport.h"
#include "tetris.h"
Buttons::Buttons(const int id)
{
_port = ioport_open(BUTTONS);
for (int i = 0; i < BUTTON_COUNT; ++i)
{
_switchIsUp[i] = true;
_switchUpCount[i] = 0;
}
}
Buttons::button_kind_t Buttons::GetValue()
{
char buttons;
int i;
char button_value;
char result = 0;
buttons = ioport_get_value(_port, 0);
buttons = ~buttons & 0x1F;
for (i = 0; i < BUTTON_COUNT; i++)
{
// for each button, it registers an event when it first goes down,
// as long as it has been up DEBOUNCE times
button_value = (buttons >> i) & 0x01;
if (!button_value)
{
// button is up
_switchUpCount[i]++;
if (_switchUpCount[i] >= DEBOUNCE)
{
_switchIsUp[i] = true;
}
}
else
{
// button is down
_switchUpCount[i] = 0;
if (_switchIsUp[i])
{
result = result | (1 << i);
_switchIsUp[i] = false;
}
}
}
switch (result)
{
case 0x01: return BTN_LEFT;
case 0x02: return BTN_RIGHT;
case 0x04: return BTN_ROTATE;
case 0x08: return BTN_DROP;
case 0x10: return BTN_PAUSE;
}
return BTN_NONE;
}
InputThread::InputThread() : ThreadBase()
{
}
void InputThread::Setup()
{
struct sched_param schedparam;
// base setup function
ThreadBase::Setup();
// initialize pthread attributes
pthread_attr_init(& _attr);
pthread_attr_setinheritsched(& _attr, PTHREAD_EXPLICIT_SCHED);
// initialize scheduling priority
schedparam.sched_priority = INPUT_THREAD_PRIORITY;
pthread_attr_setschedparam(& _attr, & schedparam);
// initialize thread stack
pthread_attr_setstackaddr(& _attr, (void *) & _stack[0]);
pthread_attr_setstacksize(& _attr, sizeof(_stack));
}
void * InputThread::Execute(void * arg)
{
Buttons buttons(BUTTONS);
volatile int stop = 0;
TetrisGame * theGame;
mqd_t mq;
Buttons::button_kind_t kind;
theGame = (TetrisGame *) arg;
mq = theGame->GetSendQueue();
while (!stop)
{
kind = buttons.GetValue();
// stroke actions
if (StrokeAction(theGame, kind) == false)
{
// send exit msg to logger
#define ENDED_BY_USER "\n ended by user"
mq_send(mq, ENDED_BY_USER, sizeof(ENDED_BY_USER) - 1, MSG_EXIT);
}
}
return NULL;
}
bool InputThread::StrokeAction(TetrisGame * theGame, Buttons::button_kind_t kind)
{
switch (kind)
{
case Buttons::BTN_LEFT:
theGame->GetTetrisThread().Kill(SIGBUTTON1);
break;
case Buttons::BTN_RIGHT:
theGame->GetTetrisThread().Kill(SIGBUTTON2);
break;
case Buttons::BTN_ROTATE:
theGame->GetTetrisThread().Kill(SIGBUTTON3);
break;
case Buttons::BTN_DROP:
theGame->GetTetrisThread().Kill(SIGBUTTON4);
break;
case Buttons::BTN_PAUSE:
theGame->GetTetrisThread().Kill(SIGBUTTON5);
break;
default:
break;
}
return true;
}
| 22.709677
| 81
| 0.552841
|
hanun2999
|
efda4cdf0fedf7671b9917eebe1c9b9a769eaf95
| 3,543
|
cpp
|
C++
|
external/webkit/Source/WebKit2/UIProcess/WebPreferences.cpp
|
ghsecuritylab/android_platform_sony_nicki
|
526381be7808e5202d7865aa10303cb5d249388a
|
[
"Apache-2.0"
] | 6
|
2017-05-31T01:46:45.000Z
|
2018-06-12T10:53:30.000Z
|
WebKit/Source/WebKit2/UIProcess/WebPreferences.cpp
|
JavaScriptTesting/LJS
|
9818dbdb421036569fff93124ac2385d45d01c3a
|
[
"Apache-2.0"
] | 2
|
2017-07-25T09:37:22.000Z
|
2017-08-04T07:18:56.000Z
|
WebKit/Source/WebKit2/UIProcess/WebPreferences.cpp
|
JavaScriptTesting/LJS
|
9818dbdb421036569fff93124ac2385d45d01c3a
|
[
"Apache-2.0"
] | 2
|
2017-07-17T06:02:42.000Z
|
2018-09-19T10:08:38.000Z
|
/*
* Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebPreferences.h"
#include "WebPageGroup.h"
namespace WebKit {
WebPreferences::WebPreferences()
{
platformInitializeStore();
}
WebPreferences::WebPreferences(const String& identifier)
: m_identifier(identifier)
{
platformInitializeStore();
}
WebPreferences::~WebPreferences()
{
}
void WebPreferences::addPageGroup(WebPageGroup* pageGroup)
{
m_pageGroups.add(pageGroup);
}
void WebPreferences::removePageGroup(WebPageGroup* pageGroup)
{
m_pageGroups.remove(pageGroup);
}
void WebPreferences::update()
{
for (HashSet<WebPageGroup*>::iterator it = m_pageGroups.begin(), end = m_pageGroups.end(); it != end; ++it)
(*it)->preferencesDidChange();
}
void WebPreferences::updateStringValueForKey(const String& key, const String& value)
{
platformUpdateStringValueForKey(key, value);
update(); // FIXME: Only send over the changed key and value.
}
void WebPreferences::updateBoolValueForKey(const String& key, bool value)
{
platformUpdateBoolValueForKey(key, value);
update(); // FIXME: Only send over the changed key and value.
}
void WebPreferences::updateUInt32ValueForKey(const String& key, uint32_t value)
{
platformUpdateUInt32ValueForKey(key, value);
update(); // FIXME: Only send over the changed key and value.
}
void WebPreferences::updateDoubleValueForKey(const String& key, double value)
{
platformUpdateDoubleValueForKey(key, value);
update(); // FIXME: Only send over the changed key and value.
}
#define DEFINE_PREFERENCE_GETTER_AND_SETTERS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) \
void WebPreferences::set##KeyUpper(const Type& value) \
{ \
if (!m_store.set##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key(), value)) \
return; \
update##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key(), value); \
\
} \
\
Type WebPreferences::KeyLower() const \
{ \
return m_store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()); \
} \
FOR_EACH_WEBKIT_PREFERENCE(DEFINE_PREFERENCE_GETTER_AND_SETTERS)
#undef DEFINE_PREFERENCE_GETTER_AND_SETTERS
} // namespace WebKit
| 33.11215
| 111
| 0.740051
|
ghsecuritylab
|
efdaffa8672f649e8c82c426d322ed9fcb08f56c
| 1,359
|
hpp
|
C++
|
Seer_Sim/utils/log.hpp
|
lanl/Seer
|
9fb38d5a0fdb5e4dfcd5ee6fdafd9df6078d5f5b
|
[
"BSD-3-Clause"
] | 1
|
2020-03-19T07:01:35.000Z
|
2020-03-19T07:01:35.000Z
|
Seer_Sim/utils/log.hpp
|
lanl/Seer
|
9fb38d5a0fdb5e4dfcd5ee6fdafd9df6078d5f5b
|
[
"BSD-3-Clause"
] | null | null | null |
Seer_Sim/utils/log.hpp
|
lanl/Seer
|
9fb38d5a0fdb5e4dfcd5ee6fdafd9df6078d5f5b
|
[
"BSD-3-Clause"
] | 1
|
2020-03-19T07:01:36.000Z
|
2020-03-19T07:01:36.000Z
|
#pragma once
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
namespace Seer
{
class Log
{
std::string outputFilename;
public:
std::stringstream log;
Log(){ outputFilename = "untitled.log"; }
Log(std::string _outputFilename): outputFilename(_outputFilename){ }
~Log();
void setOutputFilename(std::string _outputFilename){ outputFilename = _outputFilename; }
void clear(){ log.str(""); }
void writeToDisk();
};
inline Log::~Log()
{
outputFilename = "";
log.str("");
}
inline void Log::writeToDisk()
{
std::ofstream outputFile( outputFilename.c_str(), std::ios::out);
outputFile << log.str();
outputFile.close();
}
///////////////////////////////////////////////////////////////////////////////////
///////////// Simple Logging
inline void writeLog(std::string filename, std::string log)
{
std::ofstream outputFile( (filename+ ".log").c_str(), std::ios::out);
outputFile << log;
outputFile.close();
}
inline void writeLogApp(std::string filename, std::string log)
{
std::ofstream outputFile( (filename+ ".log").c_str(), std::ios::out | std::ios::app);
outputFile << log;
outputFile.close();
}
inline void writeLogNew(std::string filename, std::string log)
{
std::ofstream outputFile( (filename+ ".log").c_str(), std::ios::out);
outputFile << log;
outputFile.close();
}
} // namespace Seer
| 19.414286
| 89
| 0.636497
|
lanl
|
efdcd15d96899c50a32173b6c3761e27d4a3bf75
| 8,702
|
hpp
|
C++
|
src/Providers/UNIXProviders/BlockStatisticsManifest/UNIX_BlockStatisticsManifest_AIX.hpp
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | 1
|
2020-10-12T09:00:09.000Z
|
2020-10-12T09:00:09.000Z
|
src/Providers/UNIXProviders/BlockStatisticsManifest/UNIX_BlockStatisticsManifest_ZOS.hpp
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
src/Providers/UNIXProviders/BlockStatisticsManifest/UNIX_BlockStatisticsManifest_ZOS.hpp
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
UNIX_BlockStatisticsManifest::UNIX_BlockStatisticsManifest(void)
{
}
UNIX_BlockStatisticsManifest::~UNIX_BlockStatisticsManifest(void)
{
}
Boolean UNIX_BlockStatisticsManifest::getInstanceID(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());
return true;
}
String UNIX_BlockStatisticsManifest::getInstanceID() const
{
return String ("");
}
Boolean UNIX_BlockStatisticsManifest::getCaption(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CAPTION, getCaption());
return true;
}
String UNIX_BlockStatisticsManifest::getCaption() const
{
return String ("");
}
Boolean UNIX_BlockStatisticsManifest::getDescription(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
return true;
}
String UNIX_BlockStatisticsManifest::getDescription() const
{
return String ("");
}
Boolean UNIX_BlockStatisticsManifest::getElementName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());
return true;
}
String UNIX_BlockStatisticsManifest::getElementName() const
{
return String("BlockStatisticsManifest");
}
Boolean UNIX_BlockStatisticsManifest::getElementType(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ELEMENT_TYPE, getElementType());
return true;
}
Uint16 UNIX_BlockStatisticsManifest::getElementType() const
{
return Uint16(0);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeStartStatisticTime(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_START_STATISTIC_TIME, getIncludeStartStatisticTime());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeStartStatisticTime() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeStatisticTime(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_STATISTIC_TIME, getIncludeStatisticTime());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeStatisticTime() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeTotalIOs(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_TOTAL_I_OS, getIncludeTotalIOs());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeTotalIOs() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesTransferred(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_K_BYTES_TRANSFERRED, getIncludeKBytesTransferred());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesTransferred() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeIOTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_I_O_TIME_COUNTER, getIncludeIOTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeIOTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadIOs(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_READ_I_OS, getIncludeReadIOs());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadIOs() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadHitIOs(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_READ_HIT_I_OS, getIncludeReadHitIOs());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadHitIOs() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadIOTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_READ_I_O_TIME_COUNTER, getIncludeReadIOTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadIOTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadHitIOTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_READ_HIT_I_O_TIME_COUNTER, getIncludeReadHitIOTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeReadHitIOTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesRead(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_K_BYTES_READ, getIncludeKBytesRead());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesRead() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteIOs(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_WRITE_I_OS, getIncludeWriteIOs());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteIOs() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteHitIOs(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_WRITE_HIT_I_OS, getIncludeWriteHitIOs());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteHitIOs() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteIOTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_WRITE_I_O_TIME_COUNTER, getIncludeWriteIOTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteIOTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteHitIOTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_WRITE_HIT_I_O_TIME_COUNTER, getIncludeWriteHitIOTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeWriteHitIOTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesWritten(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_K_BYTES_WRITTEN, getIncludeKBytesWritten());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeKBytesWritten() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeIdleTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_IDLE_TIME_COUNTER, getIncludeIdleTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeIdleTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeMaintOp(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_MAINT_OP, getIncludeMaintOp());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeMaintOp() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::getIncludeMaintTimeCounter(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INCLUDE_MAINT_TIME_COUNTER, getIncludeMaintTimeCounter());
return true;
}
Boolean UNIX_BlockStatisticsManifest::getIncludeMaintTimeCounter() const
{
return Boolean(false);
}
Boolean UNIX_BlockStatisticsManifest::initialize()
{
return false;
}
Boolean UNIX_BlockStatisticsManifest::load(int &pIndex)
{
return false;
}
Boolean UNIX_BlockStatisticsManifest::finalize()
{
return false;
}
Boolean UNIX_BlockStatisticsManifest::find(Array<CIMKeyBinding> &kbArray)
{
CIMKeyBinding kb;
String instanceIDKey;
for(Uint32 i = 0; i < kbArray.size(); i++)
{
kb = kbArray[i];
CIMName keyName = kb.getName();
if (keyName.equal(PROPERTY_INSTANCE_ID)) instanceIDKey = kb.getValue();
}
/* EXecute find with extracted keys */
return false;
}
| 26.29003
| 97
| 0.78729
|
brunolauze
|
efe0371b0fc4ddd4c1bde0c167444d0d3a5643d1
| 1,589
|
hpp
|
C++
|
kernel/include/Sigma/types/hash_map.hpp
|
thomtl/Sigma
|
30da9446a1f1b5cae4eff77bf9917fae1446ce85
|
[
"BSD-2-Clause"
] | 46
|
2019-09-30T18:40:06.000Z
|
2022-02-20T12:54:59.000Z
|
kernel/include/Sigma/types/hash_map.hpp
|
thomtl/Sigma
|
30da9446a1f1b5cae4eff77bf9917fae1446ce85
|
[
"BSD-2-Clause"
] | 11
|
2019-08-18T18:31:11.000Z
|
2021-09-14T22:34:16.000Z
|
kernel/include/Sigma/types/hash_map.hpp
|
thomtl/Sigma
|
30da9446a1f1b5cae4eff77bf9917fae1446ce85
|
[
"BSD-2-Clause"
] | 1
|
2020-01-20T16:55:13.000Z
|
2020-01-20T16:55:13.000Z
|
#ifndef SIGMA_TYPES_HASH_MAP_H
#define SIGMA_TYPES_HASH_MAP_H
#include <Sigma/common.h>
#include <Sigma/types/linked_list.h>
#include <klibcxx/utility.hpp>
#include <Sigma/arch/x86_64/misc/spinlock.h>
namespace types
{
template<typename T>
struct nop_hasher {
using hash_result = T;
hash_result operator()(T item){
return item;
}
};
// TODO: Seriously, this is the best hash_map you can think of, just, make something doable, not this monstrosity
template<typename Key, typename Value, typename Hasher>
class hash_map {
public:
hash_map() = default;
hash_map(hash_map&& other){
this->list = std::move(other.list);
this->hasher = std::move(other.hasher);
}
hash_map& operator=(hash_map&& other){
this->list = std::move(other.list);
this->hasher = std::move(other.hasher);
return *this;
}
void push_back(Key key, Value value){
auto hash = this->hasher(key);
this->list.push_back({hash, value});
}
Value& operator[](Key key){
auto hash = this->hasher(key);
for(auto& entry : list)
if(entry.first == hash)
return entry.second;
PANIC("Hash not in map");
while(1)
;
}
private:
using entry = std::pair<typename Hasher::hash_result, Value>;
types::linked_list<entry> list;
Hasher hasher;
};
} // namespace types
#endif
| 24.446154
| 117
| 0.56073
|
thomtl
|
efe16d7cfa75b0fb9545eab906506513fb6c1f5f
| 19,369
|
cpp
|
C++
|
src/drivers/common/driver_base.cpp
|
Dwedit/sdlretro
|
521c5558cb55d4028210529e336d8a8622037358
|
[
"MIT"
] | null | null | null |
src/drivers/common/driver_base.cpp
|
Dwedit/sdlretro
|
521c5558cb55d4028210529e336d8a8622037358
|
[
"MIT"
] | null | null | null |
src/drivers/common/driver_base.cpp
|
Dwedit/sdlretro
|
521c5558cb55d4028210529e336d8a8622037358
|
[
"MIT"
] | null | null | null |
#include "driver_base.h"
#include "logger.h"
#include "cfg.h"
#include "video_base.h"
#include "buffered_audio.h"
#include "input_base.h"
#include "throttle.h"
#include "util.h"
#include <variables.h>
#include <core.h>
#include <cstring>
#include <cmath>
#include <memory>
#include <fstream>
namespace libretro {
extern struct retro_vfs_interface vfs_interface;
}
namespace drivers {
#ifdef _WIN32
#define PATH_SEPARATOR_CHAR "\\"
#else
#define PATH_SEPARATOR_CHAR "/"
#endif
inline void lowered_string(std::string &s) {
for (char &c: s) {
if (c <= ' ' || c == '\\' || c == '/' || c == ':' || c == '*' || c == '"' || c == '<' || c == '>' || c == '|')
c = '_';
else
c = std::tolower(c);
}
}
inline std::string get_base_name(const std::string &path) {
std::string basename = path;
auto pos = basename.find_last_of("/\\");
if (pos != std::string::npos) {
basename = basename.substr(pos + 1);
}
pos = basename.find_last_of('.');
if (pos != std::string::npos)
basename.erase(pos);
return basename;
}
driver_base *current_driver = nullptr;
driver_base::driver_base() {
frame_throttle = std::make_shared<throttle>();
variables = std::make_unique<libretro::retro_variables>();
}
driver_base::~driver_base() {
deinit_internal();
if (core) {
core_unload(core);
core = nullptr;
}
current_driver = nullptr;
}
void driver_base::set_dirs(const std::string &static_root, const std::string &config_root) {
static_dir = static_root;
config_dir = config_root;
system_dir = config_root + PATH_SEPARATOR_CHAR "system";
util_mkdir(system_dir.c_str());
save_dir = config_root + PATH_SEPARATOR_CHAR "saves";
util_mkdir(save_dir.c_str());
}
void driver_base::run(std::function<void()> in_game_menu_cb) {
while (!shutdown_driver && run_frame(in_game_menu_cb, video->frame_drawn())) {
auto check = g_cfg.get_save_check();
if (check) {
if (!save_check_countdown) {
check_save_ram();
save_check_countdown = lround(check * fps);
} else {
save_check_countdown--;
}
}
core->retro_run();
video->message_frame_pass();
}
}
bool RETRO_CALLCONV retro_environment_cb(unsigned cmd, void *data) {
if (!current_driver) return false;
return current_driver->env_callback(cmd, data);
}
void RETRO_CALLCONV log_printf(enum retro_log_level level, const char *fmt, ...) {
#if defined(NDEBUG) || !defined(LIBRETRO_DEBUG_LOG)
if (level >= RETRO_LOG_DEBUG)
return;
#endif
va_list l;
va_start(l, fmt);
log_vprintf((int)level, fmt, l);
va_end(l);
}
static void RETRO_CALLCONV retro_video_refresh_cb(const void *data, unsigned width, unsigned height, size_t pitch) {
if (!data) return;
current_driver->get_video()->render(data, width, height, pitch);
}
static void RETRO_CALLCONV retro_audio_sample_cb(int16_t left, int16_t right) {
int16_t samples[2] = {left, right};
current_driver->get_audio()->write_samples(samples, 2);
}
static size_t RETRO_CALLCONV retro_audio_sample_batch_cb(const int16_t *data, size_t frames) {
current_driver->get_audio()->write_samples(data, frames * 2);
return frames;
}
static void RETRO_CALLCONV retro_input_poll_cb() {
current_driver->get_input()->input_poll();
}
static int16_t RETRO_CALLCONV retro_input_state_cb(unsigned port, unsigned device, unsigned index, unsigned id) {
return current_driver->get_input()->input_state(port, device, index, id);
}
static bool RETRO_CALLCONV retro_set_rumble_state_cb(unsigned port, enum retro_rumble_effect effect, uint16_t strength) {
return false;
}
inline bool read_file(const std::string filename, std::vector<uint8_t> &data) {
std::ifstream ifs(filename, std::ios_base::binary | std::ios_base::in);
if (!ifs.good()) return false;
ifs.seekg(0, std::ios_base::end);
size_t sz = ifs.tellg();
if (!sz) {
ifs.close();
return false;
}
data.resize(sz);
ifs.seekg(0, std::ios_base::beg);
ifs.read((char *)data.data(), sz);
ifs.close();
return true;
}
bool driver_base::load_game(const std::string &path) {
retro_game_info info = {};
info.path = path.c_str();
if (!need_fullpath) {
std::ifstream ifs(path, std::ios_base::binary | std::ios_base::in);
if (!ifs.good()) {
logger(LOG_ERROR) << "Unable to load " << path << std::endl;
return false;
}
ifs.seekg(0, std::ios_base::end);
game_data.resize(ifs.tellg());
ifs.seekg(0, std::ios_base::beg);
ifs.read(&game_data[0], game_data.size());
ifs.close();
info.data = &game_data[0];
info.size = game_data.size();
}
if (!core->retro_load_game(&info)) {
logger(LOG_ERROR) << "Unable to load " << path << std::endl;
return false;
}
game_path = path;
post_load();
return true;
}
bool driver_base::load_game_from_mem(const std::string &path, const std::string ext, const std::vector<uint8_t> &data) {
retro_game_info info = {};
if (!need_fullpath) {
game_data.assign(data.begin(), data.end());
info.path = path.c_str();
info.data = &game_data[0];
info.size = game_data.size();
} else {
std::string basename = get_base_name(path);
temp_file = config_dir + PATH_SEPARATOR_CHAR "tmp";
util_mkdir(temp_file.c_str());
temp_file = temp_file + PATH_SEPARATOR_CHAR + basename + "." + ext;
std::ofstream ofs(temp_file, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
if (!ofs.good()) return false;
ofs.write((const char*)&data[0], data.size());
if (ofs.bad()) {
ofs.close();
remove(temp_file.c_str());
return false;
}
ofs.close();
info.path = temp_file.c_str();
}
if (!core->retro_load_game(&info)) {
logger(LOG_ERROR) << "Unable to load " << path << std::endl;
return false;
}
game_path = path;
post_load();
return true;
}
void driver_base::unload_game() {
shutdown_driver = false;
check_save_ram();
game_path.clear();
game_base_name.clear();
game_save_path.clear();
game_rtc_path.clear();
save_data.clear();
rtc_data.clear();
core->retro_unload_game();
audio->stop();
unload();
if (!temp_file.empty()) {
remove(temp_file.c_str());
temp_file.clear();
}
}
void driver_base::reset() {
core->retro_reset();
}
bool driver_base::env_callback(unsigned cmd, void *data) {
switch (cmd) {
case RETRO_ENVIRONMENT_SET_ROTATION:
break;
case RETRO_ENVIRONMENT_GET_OVERSCAN:
*(bool*)data = false;
return true;
case RETRO_ENVIRONMENT_GET_CAN_DUPE:
*(bool*)data = true;
return true;
case RETRO_ENVIRONMENT_SET_MESSAGE: {
const auto *msg = (const retro_message*)data;
video->set_message(msg->msg, msg->frames);
return true;
}
case RETRO_ENVIRONMENT_SHUTDOWN:
shutdown_driver = true;
return true;
case RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL:
return true;
case RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY:
*(const char**)data = system_dir.c_str();
return true;
case RETRO_ENVIRONMENT_SET_PIXEL_FORMAT: {
auto new_format = (unsigned)*(const enum retro_pixel_format *)data;
if (new_format != pixel_format) {
pixel_format = new_format;
video->resolution_changed(base_width, base_height, pixel_format == RETRO_PIXEL_FORMAT_XRGB8888 ? 32 : 16);
}
return true;
}
case RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS: {
const auto *inp = (const retro_input_descriptor*)data;
while (inp->description != nullptr) {
input->add_button(inp->port, inp->device, inp->index, inp->id, inp->description);
++inp;
}
return true;
}
case RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK:
case RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE:
case RETRO_ENVIRONMENT_SET_HW_RENDER:
break;
case RETRO_ENVIRONMENT_GET_VARIABLE: {
variables->set_variables_updated(false);
auto *var = (retro_variable *)data;
auto *vari = variables->get_variable(var->key);
if (vari) {
var->value = vari->options[vari->curr_index].first.c_str();
return true;
}
return false;
}
case RETRO_ENVIRONMENT_SET_VARIABLES: {
const auto *vars = (const retro_variable*)data;
variables->load_variables(vars);
variables->load_variables_from_cfg(core_cfg_path);
return true;
}
case RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE:
*(bool*)data = variables->get_variables_updated();
return true;
case RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME:
support_no_game = *(bool*)data;
return true;
case RETRO_ENVIRONMENT_GET_LIBRETRO_PATH:
*(const char**)data = nullptr;
return true;
case RETRO_ENVIRONMENT_SET_FRAME_TIME_CALLBACK:
case RETRO_ENVIRONMENT_SET_AUDIO_CALLBACK:
break;
case RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE: {
auto *ri = (retro_rumble_interface*)data;
ri->set_rumble_state = retro_set_rumble_state_cb;
return true;
}
case RETRO_ENVIRONMENT_GET_INPUT_DEVICE_CAPABILITIES:
*(uint64_t*)data = (1ULL << RETRO_DEVICE_JOYPAD) | (1ULL << RETRO_DEVICE_ANALOG);
return true;
case RETRO_ENVIRONMENT_GET_SENSOR_INTERFACE:
case RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE:
break;
case RETRO_ENVIRONMENT_GET_LOG_INTERFACE: {
((retro_log_callback*)data)->log = log_printf;
return true;
}
case RETRO_ENVIRONMENT_GET_PERF_INTERFACE:
case RETRO_ENVIRONMENT_GET_LOCATION_INTERFACE:
case RETRO_ENVIRONMENT_GET_CORE_ASSETS_DIRECTORY:
break;
case RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY:
*(const char**)data = core_save_dir.empty() ? nullptr : core_save_dir.c_str();
return true;
case RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO:
case RETRO_ENVIRONMENT_SET_PROC_ADDRESS_CALLBACK:
case RETRO_ENVIRONMENT_SET_SUBSYSTEM_INFO:
break;
case RETRO_ENVIRONMENT_SET_CONTROLLER_INFO: {
const auto *info = (const retro_controller_info*)data;
return true;
}
case RETRO_ENVIRONMENT_SET_MEMORY_MAPS: {
const auto *memmap = (const retro_memory_map*)data;
for (unsigned i = 0; i < memmap->num_descriptors; ++i) {
/* TODO: store info of memory map for future use */
}
return true;
}
case RETRO_ENVIRONMENT_SET_GEOMETRY: {
const auto *geometry = (const retro_game_geometry*)data;
base_width = geometry->base_width;
base_height = geometry->base_height;
max_width = geometry->max_width;
max_height = geometry->max_height;
aspect_ratio = geometry->aspect_ratio;
video->resolution_changed(base_width, base_height, pixel_format == RETRO_PIXEL_FORMAT_XRGB8888 ? 32 : 16);
return true;
}
case RETRO_ENVIRONMENT_GET_USERNAME:
*(const char**)data = "sdlretro";
return true;
case RETRO_ENVIRONMENT_GET_LANGUAGE:
*(unsigned*)data = RETRO_LANGUAGE_ENGLISH;
return true;
case RETRO_ENVIRONMENT_GET_CURRENT_SOFTWARE_FRAMEBUFFER:
/*
{
auto *fb = (retro_framebuffer*)data;
fb->data = video->get_framebuffer(&fb->width, &fb->height, &fb->pitch, (int*)&fb->format);
if (fb->data)
return true;
}
*/
return false;
case RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE:
break;
case RETRO_ENVIRONMENT_SET_SUPPORT_ACHIEVEMENTS:
support_achivements = data ? *(bool*)data : true;
return true;
case RETRO_ENVIRONMENT_SET_HW_RENDER_CONTEXT_NEGOTIATION_INTERFACE:
case RETRO_ENVIRONMENT_SET_SERIALIZATION_QUIRKS:
case RETRO_ENVIRONMENT_SET_HW_SHARED_CONTEXT:
break;
case RETRO_ENVIRONMENT_GET_VFS_INTERFACE: {
auto *info = (struct retro_vfs_interface_info *)data;
if (info->required_interface_version > 3) return false;
info->iface = &libretro::vfs_interface;
return true;
}
case RETRO_ENVIRONMENT_GET_LED_INTERFACE:
case RETRO_ENVIRONMENT_GET_AUDIO_VIDEO_ENABLE:
case RETRO_ENVIRONMENT_GET_MIDI_INTERFACE:
case RETRO_ENVIRONMENT_GET_FASTFORWARDING:
case RETRO_ENVIRONMENT_GET_TARGET_REFRESH_RATE:
break;
case RETRO_ENVIRONMENT_GET_INPUT_BITMASKS:
if (data) *(bool*)data = true;
return true;
case RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION:
*(unsigned*)data = RETRO_API_VERSION;
return true;
case RETRO_ENVIRONMENT_SET_CORE_OPTIONS: {
variables->load_variables((const retro_core_option_definition*)data);
variables->load_variables_from_cfg(core_cfg_path);
return true;
}
case RETRO_ENVIRONMENT_SET_CORE_OPTIONS_INTL: {
variables->load_variables(((const retro_core_options_intl*)data)->us);
variables->load_variables_from_cfg(core_cfg_path);
return true;
}
case RETRO_ENVIRONMENT_SET_CORE_OPTIONS_DISPLAY: {
const auto *opt = (const retro_core_option_display*)data;
variables->set_variable_visible(opt->key, opt->visible);
return true;
}
case RETRO_ENVIRONMENT_GET_PREFERRED_HW_RENDER:
default:
break;
}
if (cmd & RETRO_ENVIRONMENT_EXPERIMENTAL) {
logger(LOG_INFO) << "Unhandled env: " << (cmd & 0xFFFFU) << "(EXPERIMENTAL)" << std::endl;
} else {
logger(LOG_INFO) << "Unhandled env: " << cmd << std::endl;
}
return false;
}
void driver_base::save_variables_to_cfg() {
variables->save_variables_to_cfg(core_cfg_path);
}
bool driver_base::load_core(const std::string &path) {
core = core_load(path.c_str());
if (!core) return false;
current_driver = this;
core_cfg_path = config_dir + PATH_SEPARATOR_CHAR + "cfg";
util_mkdir(core_cfg_path.c_str());
retro_system_info sysinfo = {};
core->retro_get_system_info(&sysinfo);
library_name = sysinfo.library_name;
library_version = sysinfo.library_version;
need_fullpath = sysinfo.need_fullpath;
std::string name = sysinfo.library_name;
lowered_string(name);
core_cfg_path = core_cfg_path + PATH_SEPARATOR_CHAR + name + ".cfg";
core_save_dir = save_dir + PATH_SEPARATOR_CHAR + name;
util_mkdir(core_save_dir.c_str());
init_internal();
return true;
}
bool driver_base::init_internal() {
if (inited) return true;
if (!init()) {
return false;
}
shutdown_driver = false;
core->retro_set_environment(retro_environment_cb);
core->retro_init();
core->retro_set_video_refresh(retro_video_refresh_cb);
core->retro_set_audio_sample(retro_audio_sample_cb);
core->retro_set_audio_sample_batch(retro_audio_sample_batch_cb);
core->retro_set_input_poll(retro_input_poll_cb);
core->retro_set_input_state(retro_input_state_cb);
inited = true;
return true;
}
void driver_base::deinit_internal() {
if (!inited) return;
core->retro_deinit();
/* reset all variables to default value */
library_name.clear();
library_version.clear();
need_fullpath = false;
pixel_format = 0;
support_no_game = false;
base_width = 0;
base_height = 0;
max_width = 0;
max_height = 0;
aspect_ratio = 0.f;
game_data.clear();
variables->reset();
inited = false;
}
void driver_base::check_save_ram() {
// TODO: use progressive check for large sram?
size_t sram_size = core->retro_get_memory_size(RETRO_MEMORY_SAVE_RAM);
if (sram_size) {
void *sram = core->retro_get_memory_data(RETRO_MEMORY_SAVE_RAM);
if (sram_size != save_data.size() || memcmp(sram, save_data.data(), sram_size) != 0) {
std::ofstream ofs(game_save_path, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
ofs.write((const char*)sram, sram_size);
ofs.close();
save_data.assign((uint8_t*)sram, (uint8_t*)sram + sram_size);
}
}
size_t rtc_size = core->retro_get_memory_size(RETRO_MEMORY_RTC);
if (rtc_size) {
void *rtc = core->retro_get_memory_data(RETRO_MEMORY_RTC);
if (rtc_size != rtc_data.size() || memcmp(rtc, rtc_data.data(), rtc_size) != 0) {
std::ofstream ofs(game_rtc_path, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
ofs.write((const char*)rtc, rtc_size);
ofs.close();
rtc_data.assign((uint8_t*)rtc, (uint8_t*)rtc + rtc_size);
}
}
}
void driver_base::post_load() {
game_base_name = get_base_name(game_path);
game_save_path = (core_save_dir.empty() ? "" : (core_save_dir + PATH_SEPARATOR_CHAR)) + game_base_name + ".sav";
game_rtc_path = (core_save_dir.empty() ? "" : (core_save_dir + PATH_SEPARATOR_CHAR)) + game_base_name + ".rtc";
read_file(game_save_path, save_data);
read_file(game_rtc_path, rtc_data);
if (!save_data.empty()) {
size_t sz = core->retro_get_memory_size(RETRO_MEMORY_SAVE_RAM);
if (sz > save_data.size()) sz = save_data.size();
if (sz) memcpy(core->retro_get_memory_data(RETRO_MEMORY_SAVE_RAM), save_data.data(), sz);
}
if (!rtc_data.empty()) {
size_t sz = core->retro_get_memory_size(RETRO_MEMORY_RTC);
if (sz > rtc_data.size()) sz = rtc_data.size();
if (sz) memcpy(core->retro_get_memory_data(RETRO_MEMORY_RTC), rtc_data.data(), sz);
}
retro_system_av_info av_info = {};
core->retro_get_system_av_info(&av_info);
base_width = av_info.geometry.base_width;
base_height = av_info.geometry.base_height;
max_width = av_info.geometry.max_width;
max_height = av_info.geometry.max_height;
aspect_ratio = av_info.geometry.aspect_ratio;
fps = av_info.timing.fps;
audio->start(g_cfg.get_mono_audio(), av_info.timing.sample_rate, g_cfg.get_sample_rate(), av_info.timing.fps);
frame_throttle->reset(fps);
core->retro_set_controller_port_device(0, RETRO_DEVICE_JOYPAD);
video->resolution_changed(base_width, base_height, pixel_format == RETRO_PIXEL_FORMAT_XRGB8888 ? 32 : 16);
char library_message[256];
snprintf(library_message, 256, "Loaded core: %s", library_name.c_str());
video->set_message(library_message, lround(fps * 5));
}
}
| 34.403197
| 122
| 0.634674
|
Dwedit
|
efe23776cdeb4c1b4199c11404b11748f3439077
| 4,835
|
cpp
|
C++
|
libs/evolvo/test/tests.cpp
|
rufus-stone/genetic-algo-cpp
|
5e31f080d30ffc204fa7891883703183302b2954
|
[
"MIT"
] | null | null | null |
libs/evolvo/test/tests.cpp
|
rufus-stone/genetic-algo-cpp
|
5e31f080d30ffc204fa7891883703183302b2954
|
[
"MIT"
] | null | null | null |
libs/evolvo/test/tests.cpp
|
rufus-stone/genetic-algo-cpp
|
5e31f080d30ffc204fa7891883703183302b2954
|
[
"MIT"
] | null | null | null |
#include "evolvo/chromosome.hpp"
#include "evolvo/crossover.hpp"
#include "evolvo/individual.hpp"
#include "evolvo/population.hpp"
#include "evolvo/selection.hpp"
#define CATCH_CONFIG_MAIN // This tells the Catch2 header to generate a main
#include "catch.hpp"
#include <random>
#include <vector>
#include <map>
#include <spdlog/spdlog.h>
#include <evolvo/ga.hpp>
////////////////////////////////////////////////////////////////
TEST_CASE("Chromosome", "[ga][chromosome]")
{
auto const chromo = ga::Chromosome{{1.1, 2.0, -3.3, 4.6}};
REQUIRE_THAT(chromo, Catch::Matchers::Approx(std::vector<double>{1.1, 2.0, -3.3, 4.6}));
REQUIRE(chromo[0] == Approx(1.1));
REQUIRE(chromo.size() == 4);
}
////////////////////////////////////////////////////////////////
TEST_CASE("Individual", "[ga][individual]")
{
// Create a Chromosome and a fitness
auto const chromo = ga::Chromosome{{1.1, 2.0, -3.3, 4.6}};
double const fitness = 1.0;
// Create a new Individual from the Chromosome
auto const individual1 = ga::Individual{chromo};
// Check that it was created correctly
REQUIRE(individual1.chromosome() == chromo);
REQUIRE_THAT(individual1.chromosome(), Catch::Matchers::Approx(std::vector<double>{1.1, 2.0, -3.3, 4.6}));
REQUIRE(individual1.fitness() == 0.0);
// Create a new Individual from the fitness
auto const individual2 = ga::Individual{fitness};
// Check that it was created correctly
REQUIRE(individual2.chromosome().empty() == true);
REQUIRE(individual2.fitness() == 1.0);
// Create a new Individual from the Chromosome and the fitness
auto const individual3 = ga::Individual{chromo, fitness};
// Check that it was created correctly
REQUIRE(individual3.chromosome() == chromo);
REQUIRE_THAT(individual3.chromosome(), Catch::Matchers::Approx(std::vector<double>{1.1, 2.0, -3.3, 4.6}));
REQUIRE(individual3.fitness() == 1.0);
}
////////////////////////////////////////////////////////////////
TEST_CASE("Selection", "[ga][individual]")
{
// Seed an mt19937 prng for a predictable "random" number to use for testing
auto prng = std::mt19937{42};
// Create a RouletteWheelSelection SelectionMethod
auto roulette_wheel = ga::RouletteWheelSelection{};
// Create a new Population from a collection of Individuals with the specified fitnesses to ride the wheel
auto const population = ga::Population{{ga::Individual{2.0}, ga::Individual{1.0}, ga::Individual{4.0}, ga::Individual{3.0}}};
// Spin the wheel 1000 times and see how many times each individual is chosen
auto results = std::map<int, int>{};
constexpr std::size_t spins = 1000;
for (std::size_t i = 0; i < spins; ++i)
{
std::size_t const choice = roulette_wheel.select(prng, population);
// Make a note of the fitness that was chosen
auto fitness = static_cast<std::size_t>(population[choice].fitness());
results[fitness] += 1;
}
for (auto const &[fitness, times_chosen] : results)
{
spdlog::info("Individual with fitness score {} chosen {} of 1000 times ({:.2f}%)", fitness, times_chosen, (static_cast<double>(times_chosen) / spins) * 100);
}
// Given the specified Population and their fitness scores, after 1000 spins of the wheel we expect the each Individual to have been selected the following number of times based on their fitness scores
auto const expected = std::map<int, int>{{1, 104}, {2, 176}, {3, 294}, {4, 426}};
// Check that the results matched what we expected
REQUIRE(results == expected);
}
////////////////////////////////////////////////////////////////
TEST_CASE("Crossover", "[ga][crossover]")
{
// Seed an mt19937 prng for a predictable "random" number to use for testing
auto prng = std::mt19937{42};
// Create a UniformCrossover CrossoverMethod
auto uniform_crossover = ga::UniformCrossover{};
// Create a pair of Chromosomes to use as parents
auto parent_a = ga::Chromosome{{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}};
auto parent_b = ga::Chromosome{{-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0, -10.0}};
// Create a child by using the UniformCrossover method
auto child = uniform_crossover.crossover(prng, parent_a, parent_b);
// A UniformCrossover has an even 50/50 chance that a gene will come from either parent
auto const expected = ga::Chromosome{{-1.0, 2.0, 3.0, -4.0, 5.0, 6.0, 7.0, 8.0, -9.0, -10.0}};
// Check that the results matched what we expected
REQUIRE(child == expected);
}
////////////////////////////////////////////////////////////////
TEST_CASE("Genetic Algorithm", "[ga][genetic_algorithm]")
{
auto selection_method = std::make_unique<ga::RouletteWheelSelection>();
auto crossover_method = std::make_unique<ga::UniformCrossover>();
auto ga = ga::GeneticAlgorithm{std::move(selection_method), std::move(crossover_method)};
REQUIRE(1 == 1);
}
| 36.908397
| 203
| 0.64757
|
rufus-stone
|
efe522521a9e3e7e53b2f14ea3e49ff2c8753433
| 2,690
|
cpp
|
C++
|
implementations/ugene/src/plugins/external_tool_support/src/trimmomatic/steps/TrailingStep.cpp
|
r-barnes/sw_comparison
|
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
|
[
"BSD-Source-Code"
] | null | null | null |
implementations/ugene/src/plugins/external_tool_support/src/trimmomatic/steps/TrailingStep.cpp
|
r-barnes/sw_comparison
|
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
|
[
"BSD-Source-Code"
] | null | null | null |
implementations/ugene/src/plugins/external_tool_support/src/trimmomatic/steps/TrailingStep.cpp
|
r-barnes/sw_comparison
|
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
|
[
"BSD-Source-Code"
] | null | null | null |
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "TrailingStep.h"
#include <U2Core/U2SafePoints.h>
#include "trimmomatic/util/QualitySettingsWidget.h"
namespace U2 {
namespace LocalWorkflow {
const QString TrailingStepFactory::ID = "TRAILING";
TrailingStep::TrailingStep()
: TrimmomaticStep(TrailingStepFactory::ID) {
name = "TRAILING";
description = tr("<html><head></head><body>"
"<h4>TRAILING</h4>"
"<p>This step removes low quality bases from the end. As long as a base has "
"a value below this threshold the base is removed and the next base "
"(i.e. the preceding one) will be investigated. This approach can be "
"used removing the special Illumina \"low quality segment\" regions "
"(which are marked with quality score of 2), but SLIDINGWINDOW or MAXINFO "
"are recommended instead.</p>"
"<p>Input the following values:</p>"
"<ul>"
"<li><b>Quality threshold</b>: the minimum quality required to keep a base.</li>"
"</ul>"
"</body></html>");
}
TrimmomaticStepSettingsWidget *TrailingStep::createWidget() const {
return new QualitySettingsWidget(tr("The minimum quality required to keep a base."));
}
QString TrailingStep::serializeState(const QVariantMap &widgetState) const {
return QualitySettingsWidget::serializeState(widgetState);
}
QVariantMap TrailingStep::parseState(const QString &command) const {
return QualitySettingsWidget::parseState(command, id);
}
TrailingStepFactory::TrailingStepFactory()
: TrimmomaticStepFactory(ID) {
}
TrailingStep *TrailingStepFactory::createStep() const {
return new TrailingStep();
}
} // namespace LocalWorkflow
} // namespace U2
| 36.849315
| 102
| 0.67026
|
r-barnes
|
efe5281be27fba8ce55da7b1321e1d3fdd27f082
| 9,860
|
hpp
|
C++
|
naos/includes/kernel/util/str.hpp
|
kadds/NaOS
|
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
|
[
"BSD-3-Clause"
] | 14
|
2020-02-12T11:07:58.000Z
|
2022-02-02T00:05:08.000Z
|
naos/includes/kernel/util/str.hpp
|
kadds/NaOS
|
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
|
[
"BSD-3-Clause"
] | null | null | null |
naos/includes/kernel/util/str.hpp
|
kadds/NaOS
|
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
|
[
"BSD-3-Clause"
] | 4
|
2020-02-27T09:53:53.000Z
|
2021-11-07T17:43:44.000Z
|
#pragma once
#include "array.hpp"
#include "assert.hpp"
#include "common.hpp"
#include "hash.hpp"
#include "iterator.hpp"
#include "kernel/mm/allocator.hpp"
#include "formatter.hpp"
#include "memory.hpp"
#include <utility>
namespace util
{
/// \brief compair two string
/// \return 0 if equal
int strcmp(const char *str1, const char *str2);
/// \brief copy src to dst (include \\0) same as 'strcopy(char *, const char *)'
i64 strcopy(char *dst, const char *src, i64 max_len);
/// \brief copy src to dst (include \\0)
/// \param dst copy to
/// \param src copy from
/// \return copy char count (not include \\0)
i64 strcopy(char *dst, const char *src);
/// \brief get string length (not include \\0)
i64 strlen(const char *str);
/// \brief find substring in str
/// \return -1 if not found
i64 strfind(const char *str, const char *pat);
class string;
template <typename CE> class base_string_view
{
private:
struct value_fn
{
CE operator()(CE val) { return val; }
};
struct prev_fn
{
CE operator()(CE val) { return val - 1; }
};
struct next_fn
{
CE operator()(CE val) { return val + 1; }
};
public:
using iterator = base_bidirectional_iterator<CE, value_fn, prev_fn, next_fn>;
base_string_view()
: ptr(nullptr)
, len(0)
{
}
base_string_view(CE ptr, u64 len)
: ptr(ptr)
, len(len)
{
}
CE data() {
return ptr;
}
string to_string(memory::IAllocator *allocator);
iterator begin() { return iterator(ptr); }
iterator end() { return iterator(ptr + len); }
bool to_int(i64 &out) const
{
const char *beg = ptr;
const char *end = ptr + len;
return formatter::str2int(beg, end, out) != beg;
}
bool to_uint(u64 &out) const {
const char *beg = ptr;
const char *end = ptr + len;
return formatter::str2uint(beg, end, out) != beg;
}
bool to_int_ext(i64 &out, base_string_view &last) const {
CE beg = ptr;
CE end = ptr + len;
beg = formatter::str2int(beg, end, out);
last = base_string_view(beg, len - (beg - ptr));
return beg != ptr;
}
bool to_uint_ext(u64 &out, base_string_view &last) const {
CE beg = ptr;
CE end = ptr + len;
beg = const_cast<CE>(formatter::str2uint(beg, end, out));
last = base_string_view(beg, len - (beg - ptr));
return beg != ptr;
}
void split2(base_string_view &v0, base_string_view &v1, iterator iter)
{
v0 = base_string_view(ptr, iter.get() - ptr);
v1 = base_string_view(iter.get() + 1, len - (iter.get() - ptr));
}
array<base_string_view<CE>> split(char c, memory::IAllocator *vec_allocator)
{
array<base_string_view<CE>> vec(vec_allocator);
CE p = ptr;
CE prev = p;
for (u64 i = 0; i < len; i++)
{
if (*p == c)
{
if (prev < p)
{
vec.push_back(base_string_view<CE>(prev, p - prev));
}
prev = p + 1;
}
p++;
}
if (prev < p)
{
vec.push_back(base_string_view<CE>(prev, p - prev));
}
return vec;
}
private:
CE ptr;
u64 len;
};
using string_view = base_string_view<char *>;
using const_string_view = base_string_view<const char *>;
/// \brief kernel string type, use it everywhere
///
class string
{
private:
template <typename N> struct value_fn
{
N operator()(N val) { return val; }
};
template <typename N> struct prev_fn
{
N operator()(N val) { return val - 1; }
};
template <typename N> struct next_fn
{
N operator()(N val) { return val + 1; }
};
using CE = const char *;
using NE = char *;
public:
using const_iterator = base_bidirectional_iterator<CE, value_fn<CE>, prev_fn<CE>, next_fn<CE>>;
using iterator = base_bidirectional_iterator<NE, value_fn<NE>, prev_fn<NE>, next_fn<NE>>;
string(const string &rhs) { copy(rhs); }
string(string &&rhs) { move(std::move(rhs)); }
///\brief init empty string ""
string(memory::IAllocator *allocator);
///\brief init from char array
/// no_shared
string(memory::IAllocator *allocator, const char *str, i64 len = -1) { init(allocator, str, len); }
///\brief init from char array lit
/// readonly & shared
string(const char *str) { init_lit(str); }
~string() { free(); }
string &operator=(const string &rhs);
string &operator=(string &&rhs);
u64 size() const { return get_count(); }
u64 capacity() const
{
if (likely(is_sso()))
{
return stack.get_cap();
}
else
{
return head.get_cap();
}
}
u64 hash() const { return murmur_hash2_64(data(), get_count(), 0); }
iterator begin() { return iterator(data()); }
iterator end() { return iterator(data() + size()); }
const_iterator begin() const { return const_iterator(data()); }
const_iterator end() const { return const_iterator(data() + size()); }
string_view view() { return string_view(data(), size()); }
const_string_view view() const { return const_string_view(data(), size()); }
bool is_shared() const
{
if (likely(is_sso()))
{
return false;
}
else
{
return head.get_allocator() == nullptr;
}
}
char *data()
{
if (likely(is_sso()))
{
return stack.get_buffer();
}
else
{
return head.get_buffer();
}
}
const char *data() const
{
if (likely(is_sso()))
{
return stack.get_buffer();
}
else
{
return head.get_buffer();
}
}
void append(const string &rhs);
void append_buffer(const char *buf, u64 length);
void push_back(char ch);
char pop_back();
void remove_at(u64 index, u64 end_index);
void remove(iterator beg, iterator end)
{
u64 index = beg.get() - data();
u64 index_end = end.get() - data();
remove_at(index, index_end);
}
char at(u64 index) const
{
cassert(index < get_count());
return data()[index];
}
string &operator+=(const string &rhs)
{
append(rhs);
return *this;
}
bool operator==(const string &rhs) const;
bool operator!=(const string &rhs) const { return !operator==(rhs); }
private:
// littel endian machine
// 0x0
// |-----------------|---------------|
// | count(63) | char(64) 8 |
// | flag_shared(1) | |
// |-----------------|---------------|
// | buffer(64) | char(64) 8 |
// |----------------|----------------|
// | cap(63) | char(56) 7 |
// | none(1) | count(5) |
// |----------------|----------------|
// | flag_type(1)0 | flag_type(1)1 |
// | allocator(63) | allocator(63) |
// |----------------|----------------|
// 0x1F
struct head_t
{
u64 count;
char *buffer;
u64 cap;
memory::IAllocator *allocator;
u64 get_count() const { return count & ((1UL << 63) - 1); }
void set_count(u64 c) { count = (c & ((1UL << 63) - 1)) | (count & (1UL << 63)); };
u64 get_cap() const { return cap & ((1UL << 63) - 1); }
void set_cap(u64 c) { cap = (c & ((1UL << 63) - 1)) | (cap & (1UL << 63)); }
char *get_buffer() { return buffer; }
const char *get_buffer() const { return buffer; }
void set_buffer(char *b) { buffer = b; }
memory::IAllocator *get_allocator() const { return allocator; }
void set_allocator(memory::IAllocator *alc)
{
cassert((reinterpret_cast<u64>(alc) & 0x1) == 0); // bit 0
allocator = alc;
}
void init()
{
count = 0;
buffer = nullptr;
cap = 0;
allocator = 0;
}
};
struct stack_t
{
byte data[24];
memory::IAllocator *allocator;
public:
u64 get_count() const { return get_cap() - static_cast<u64>(data[23]); }
void set_count(u64 c) { data[23] = static_cast<byte>(get_cap() - c); }
u64 get_cap() const { return 23; }
char *get_buffer() { return reinterpret_cast<char *>(data); }
const char *get_buffer() const { return reinterpret_cast<const char *>(data); }
memory::IAllocator *get_allocator() const
{
return reinterpret_cast<memory::IAllocator *>(reinterpret_cast<u64>(allocator) & ~0x1);
}
void set_allocator(memory::IAllocator *alc)
{
allocator = reinterpret_cast<memory::IAllocator *>(reinterpret_cast<u64>(alc) | 0x1);
}
bool is_stack() const { return reinterpret_cast<u64>(allocator) & 0x1; }
};
union
{
stack_t stack;
head_t head;
};
static_assert(sizeof(stack_t) == sizeof(head_t));
private:
u64 select_capacity(u64 capacity);
void free();
void copy(const string &rhs);
void move(string &&rhs);
void init(memory::IAllocator *allocator, const char *str, i64 len = -1);
void init_lit(const char *str);
u64 get_count() const
{
if (likely(is_sso()))
return stack.get_count();
else
return head.get_count();
}
private:
bool is_sso() const { return stack.is_stack(); }
};
template <typename CE> string base_string_view<CE>::to_string(memory::IAllocator *allocator)
{
return string(allocator, ptr, len);
}
} // namespace util
| 25.025381
| 103
| 0.535497
|
kadds
|
efe6ee13015e03dd9051e0633494633c358b2e37
| 622
|
cc
|
C++
|
code/qttoolkit/contentbrowser/code/main.cc
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 67
|
2015-03-30T19:56:16.000Z
|
2022-03-11T13:52:17.000Z
|
code/qttoolkit/contentbrowser/code/main.cc
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 5
|
2015-04-15T17:17:33.000Z
|
2016-02-11T00:40:17.000Z
|
code/qttoolkit/contentbrowser/code/main.cc
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 34
|
2015-03-30T15:08:00.000Z
|
2021-09-23T05:55:10.000Z
|
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "contentbrowserwindow.h"
#include "contentbrowserapp.h"
#include "extlibs/libqimg/qdevilplugin.h"
Q_IMPORT_PLUGIN(qdevil);
//------------------------------------------------------------------------------
/**
*/
int __cdecl
main(int argc, const char** argv)
{
Util::CommandLineArgs args(argc, argv);
ContentBrowser::ContentBrowserApp app;
app.SetCompanyName("gscept");
app.SetAppTitle("NebulaT Content Browser");
app.SetCmdLineArgs(args);
if (app.Open())
{
app.Run();
app.Close();
}
app.Exit();
}
| 23.037037
| 80
| 0.530547
|
gscept
|
efec806f461fd802325dd210f9399cbef4211775
| 503
|
hpp
|
C++
|
source/ashes/renderer/TestRenderer/Sync/TestEvent.hpp
|
DragonJoker/Ashes
|
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
|
[
"MIT"
] | 227
|
2018-09-17T16:03:35.000Z
|
2022-03-19T02:02:45.000Z
|
source/ashes/renderer/TestRenderer/Sync/TestEvent.hpp
|
DragonJoker/RendererLib
|
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
|
[
"MIT"
] | 39
|
2018-02-06T22:22:24.000Z
|
2018-08-29T07:11:06.000Z
|
source/ashes/renderer/TestRenderer/Sync/TestEvent.hpp
|
DragonJoker/Ashes
|
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
|
[
"MIT"
] | 8
|
2019-05-04T10:33:32.000Z
|
2021-04-05T13:19:27.000Z
|
/*
This file belongs to Ashes.
See LICENSE file in root folder
*/
#pragma once
#include "renderer/TestRenderer/TestRendererPrerequisites.hpp"
namespace ashes::test
{
class Event
{
public:
Event( VkDevice device );
/**
*\copydoc ashes::Event::getStatus
*/
VkResult getStatus()const;
/**
*\copydoc ashes::Event::getStatus
*/
VkResult set()const;
/**
*\copydoc ashes::Event::getStatus
*/
VkResult reset()const;
private:
mutable VkResult m_status{ VK_EVENT_RESET };
};
}
| 15.71875
| 62
| 0.683897
|
DragonJoker
|
efefffccc5b2dfe52e8eaa70f4732ce12a45df5e
| 6,280
|
cpp
|
C++
|
src/ui/radio.cpp
|
ptitSeb/freespace2
|
500ee249f7033aac9b389436b1737a404277259c
|
[
"Linux-OpenIB"
] | 1
|
2020-07-14T07:29:18.000Z
|
2020-07-14T07:29:18.000Z
|
src/ui/radio.cpp
|
ptitSeb/freespace2
|
500ee249f7033aac9b389436b1737a404277259c
|
[
"Linux-OpenIB"
] | 2
|
2019-01-01T22:35:56.000Z
|
2022-03-14T07:34:00.000Z
|
src/ui/radio.cpp
|
ptitSeb/freespace2
|
500ee249f7033aac9b389436b1737a404277259c
|
[
"Linux-OpenIB"
] | 2
|
2021-03-07T11:40:42.000Z
|
2021-12-26T21:40:39.000Z
|
/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on
* the source.
*/
/*
* $Logfile: /Freespace2/code/UI/RADIO.cpp $
* $Revision: 307 $
* $Date: 2010-02-08 09:09:13 +0100 (Mon, 08 Feb 2010) $
* $Author: taylor $
*
* Code to handle radio buttons.
*
* $Log$
* Revision 1.3 2004/09/20 01:31:45 theoddone33
* GCC 3.4 fixes.
*
* Revision 1.2 2002/06/09 04:41:29 relnev
* added copyright header
*
* Revision 1.1.1.1 2002/05/03 03:28:11 root
* Initial import.
*
*
* 4 12/02/98 5:47p Dave
* Put in interface xstr code. Converted barracks screen to new format.
*
* 3 10/13/98 9:29a Dave
* Started neatening up freespace.h. Many variables renamed and
* reorganized. Added AlphaColors.[h,cpp]
*
* 2 10/07/98 10:54a Dave
* Initial checkin.
*
* 1 10/07/98 10:51a Dave
*
* 9 3/10/98 4:19p John
* Cleaned up graphics lib. Took out most unused gr functions. Made D3D
* & Glide have popups and print screen. Took out all >8bpp software
* support. Made Fred zbuffer. Made zbuffer allocate dynamically to
* support Fred. Made zbuffering key off of functions rather than one
* global variable.
*
* 8 2/03/98 4:21p Hoffoss
* Made UI controls draw white text when disabled.
*
* 7 1/14/98 6:44p Hoffoss
* Massive changes to UI code. A lot cleaner and better now. Did all
* this to get the new UI_DOT_SLIDER to work properly, which the old code
* wasn't flexible enough to handle.
*
* 6 6/12/97 12:39p John
* made ui use freespace colors
*
* 5 6/11/97 1:13p John
* Started fixing all the text colors in the game.
*
* 4 5/26/97 10:26a Lawrance
* get slider control working 100%
*
* 3 1/01/97 6:46p Lawrance
* changed text color of radio button to green from black
*
* 2 11/15/96 11:43a John
*
* 1 11/14/96 6:55p John
*
* $NoKeywords: $
*/
#include "uidefs.h"
#include "ui.h"
#include "alphacolors.h"
void UI_RADIO::create(UI_WINDOW *wnd, const char *_text, int _x, int _y, int _state, int _group )
{
int _w, _h;
// gr_get_string_size( &_w, &_h, "X" );
_w = 18;
_h = 18;
if (_text)
text = strdup(_text);
else
text = NULL;
base_create( wnd, UI_KIND_RADIO, _x, _y, _w, _h );
position = 0;
pressed_down = 0;
flag = _state;
group = _group;
};
void UI_RADIO::destroy()
{
if (text)
free(text);
UI_GADGET::destroy();
}
void UI_RADIO::draw()
{
int offset;
if ( uses_bmaps ) {
if ( disabled_flag ) {
if ( flag ) {
if ( bmap_ids[RADIO_DISABLED_MARKED] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_DISABLED_MARKED], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
else {
if ( bmap_ids[RADIO_DISABLED_CLEAR] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_DISABLED_CLEAR], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
}
else { // not disabled
if ( position == 0 ) { // up
if ( flag ) { // marked
if ( bmap_ids[RADIO_UP_MARKED] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_UP_MARKED], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
else { // not marked
if ( bmap_ids[RADIO_UP_CLEAR] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_UP_CLEAR], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
}
else { // down
if ( flag ) { // marked
if ( bmap_ids[RADIO_DOWN_MARKED] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_DOWN_MARKED], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
else { // not marked
if ( bmap_ids[RADIO_DOWN_CLEAR] != -1 ) {
gr_set_bitmap(bmap_ids[RADIO_DOWN_CLEAR], GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
gr_bitmap(x,y);
}
}
}
}
}
else {
gr_set_font(my_wnd->f_id);
gr_set_clip( x, y, w, h );
if (position == 0 ) {
ui_draw_box_out( 0, 0, w-1, h-1 );
offset = 0;
} else {
ui_draw_box_in( 0, 0, w-1, h-1 );
offset = 1;
}
if (disabled_flag)
gr_set_color_fast(&CDARK_GRAY);
else if (my_wnd->selected_gadget == this)
gr_set_color_fast(&CBRIGHT_GREEN);
else
gr_set_color_fast(&CGREEN);
// if (flag)
// ui_string_centered( Middle(w)+offset, Middle(h)+offset, "*" );
// else
// ui_string_centered( Middle(w)+offset, Middle(h)+offset, "o" );
if (flag) {
gr_circle( Middle(w)+offset, Middle(h)+offset, 8 );
} else {
gr_circle( Middle(w)+offset, Middle(h)+offset, 8 );
gr_set_color_fast( &CWHITE );
gr_circle( Middle(w)+offset, Middle(h)+offset, 4 );
}
if (disabled_flag)
gr_set_color_fast(&CDARK_GRAY);
else if (my_wnd->selected_gadget == this)
gr_set_color_fast(&CBRIGHT_GREEN);
else
gr_set_color_fast(&CGREEN);
if ( text ) {
gr_reset_clip();
gr_string( x+w+4, y+2, text );
}
}
}
void UI_RADIO::process(int focus)
{
int OnMe, oldposition;
if (disabled_flag) {
position = 0;
return;
}
if (my_wnd->selected_gadget == this)
focus = 1;
OnMe = is_mouse_on();
oldposition = position;
if (B1_PRESSED && OnMe) {
position = 1;
} else {
position = 0;
}
if (my_wnd->keypress == hotkey) {
position = 2;
my_wnd->last_keypress = 0;
}
if ( focus && ((my_wnd->keypress == KEY_SPACEBAR) || (my_wnd->keypress == KEY_ENTER)) )
position = 2;
if (focus)
if ( (oldposition == 2) && (keyd_pressed[KEY_SPACEBAR] || keyd_pressed[KEY_ENTER]) )
position = 2;
pressed_down = 0;
if (position) {
if ( (oldposition == 1) && OnMe )
pressed_down = 1;
if ( (oldposition == 2) && focus )
pressed_down = 1;
}
if (pressed_down && user_function) {
user_function();
}
if (pressed_down && (flag == 0)) {
UI_GADGET *tmp = (UI_GADGET *) next;
UI_RADIO *tmpr;
while (tmp != this) {
if (tmp->kind == UI_KIND_RADIO) {
tmpr = (UI_RADIO *) tmp;
if ((tmpr->group == group) && tmpr->flag) {
tmpr->flag = 0;
tmpr->pressed_down = 0;
}
}
tmp = tmp->next;
}
flag = 1;
}
}
int UI_RADIO::changed()
{
return pressed_down;
}
int UI_RADIO::checked()
{
return flag;
}
| 22.269504
| 109
| 0.62086
|
ptitSeb
|
eff0238aa7ff1bec34896371a361d58922c057d1
| 2,097
|
cpp
|
C++
|
nori-base-2019/src/lightDepthArea.cpp
|
TamerMograbi/ShadowNet
|
99a9fb4522546e58817bbdd373f63d6996685e21
|
[
"BSD-3-Clause"
] | null | null | null |
nori-base-2019/src/lightDepthArea.cpp
|
TamerMograbi/ShadowNet
|
99a9fb4522546e58817bbdd373f63d6996685e21
|
[
"BSD-3-Clause"
] | null | null | null |
nori-base-2019/src/lightDepthArea.cpp
|
TamerMograbi/ShadowNet
|
99a9fb4522546e58817bbdd373f63d6996685e21
|
[
"BSD-3-Clause"
] | 1
|
2020-01-22T11:55:43.000Z
|
2020-01-22T11:55:43.000Z
|
#include <nori/integrator.h>
#include <nori/scene.h>
#include <nori/bsdf.h>
NORI_NAMESPACE_BEGIN
class lightDepthAreaIntegrator : public Integrator {
public:
lightDepthAreaIntegrator(const PropertyList &props)
{
}
void preprocess(const Scene *scene)
{
emitterMeshes = scene->getEmitterMeshes();
const MatrixXf vertices = emitterMeshes[0]->getVertexPositions();
for (int colIdx = 0; colIdx < vertices.cols(); colIdx++)
{
meshCenter += vertices.col(colIdx);
}
meshCenter /= vertices.cols();
}
//point x will be visible only if light reaches it
//bool visiblity(const Scene *scene, Point3f x) const
//{
// Vector3f dir = position - x;//direction from point to light source
// dir.normalize();
// Ray3f ray(x, dir);
// return !scene->rayIntersect(ray);//if ray intersects, then it means that it hit another point in the mesh
// //while on it's way to the light source. so x won't recieve light
//}
//scale value x from range [-1,1] to [a,b]
float scaleToAB(float x, float a, float b) const
{
return (b - a)*(x + 1) / 2 + a;
}
Color3f Li(const Scene *scene, Sampler *sampler, const Ray3f &ray) const
{
Intersection its;
if (!scene->rayIntersect(ray, its))
{
return Color3f(0.f);
}
Point3f x = its.p; //where the ray hits the mesh
Vector3f intersectionToLight = (meshCenter - x).normalized();
float scaledX = scaleToAB(intersectionToLight[0], 0, 1);
float scaledY = scaleToAB(intersectionToLight[1], 0, 1);
float scaledZ = scaleToAB(intersectionToLight[2], 0, 1);
//we scale from -1 to 1 (which is the range that the coordinates of a normalized direction can be in) to 0 2
return Color3f(scaledX, scaledY, scaledZ);
}
std::string toString() const {
return "lightDepthAreaIntegrator[]";
}
EIntegratorType getIntegratorType() const
{
return EIntegratorType::ELightDepthArea;
}
std::vector<Mesh *> emitterMeshes;
Point3f meshCenter;
};
NORI_REGISTER_CLASS(lightDepthAreaIntegrator, "lightDepthArea");
NORI_NAMESPACE_END
| 29.957143
| 116
| 0.674297
|
TamerMograbi
|
eff15b2b488eacb70224936cb68fa4bf82be018a
| 14,983
|
cc
|
C++
|
MemoryBlock.cc
|
DrItanium/syn
|
bee289392e9e84a12d98a4b19f2a0ada9d7ae14a
|
[
"BSD-2-Clause"
] | 1
|
2017-04-17T14:46:28.000Z
|
2017-04-17T14:46:28.000Z
|
MemoryBlock.cc
|
DrItanium/syn
|
bee289392e9e84a12d98a4b19f2a0ada9d7ae14a
|
[
"BSD-2-Clause"
] | 4
|
2017-03-15T23:28:14.000Z
|
2017-10-29T22:48:28.000Z
|
MemoryBlock.cc
|
DrItanium/syn
|
bee289392e9e84a12d98a4b19f2a0ada9d7ae14a
|
[
"BSD-2-Clause"
] | null | null | null |
/**
* @file
* implementation of methods described in ClipsExtensions.h
* @copyright
* syn
* Copyright (c) 2013-2017, Joshua Scoggins and Contributors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "BaseTypes.h"
#include "ClipsExtensions.h"
#include "Base.h"
#include "ExternalAddressWrapper.h"
#include "MemoryBlock.h"
#include <cstdint>
#include <climits>
#include <sstream>
#include <memory>
#include <map>
#include <iostream>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
extern "C" {
#include "clips.h"
}
namespace syn {
template<typename T>
using Block = T[];
//bool Arg2IsInteger(Environment* env, UDFValue* storage, const std::string& funcStr) noexcept {
// return tryGetArgumentAsInteger(env, funcStr, 2, storage);
//}
//bool Arg2IsSymbol(Environment* env, UDFValue* storage, const std::string& funcStr) noexcept {
// return tryGetArgumentAsSymbol(env, funcStr, 2, storage);
//}
void handleProblem(Environment* env, UDFValue* ret, const syn::Problem& p, const std::string funcErrorPrefix) noexcept {
setBoolean(env, ret, false);
std::stringstream s;
s << "an exception was thrown: " << p.what();
auto str = s.str();
errorMessage(env, "CALL", 2, funcErrorPrefix, str);
}
template<typename Word>
class ManagedMemoryBlock : public ExternalAddressWrapper<Block<Word>> {
public:
static_assert(std::is_integral<Word>::value, "Expected an integral type to be for type Word");
using Address = int64_t;
using WordBlock = Block<Word>;
using Parent = ExternalAddressWrapper<WordBlock>;
using Self = ManagedMemoryBlock;
using Self_Ptr = Self*;
static ManagedMemoryBlock* make(int64_t capacity) noexcept {
return new ManagedMemoryBlock(capacity);
}
using ManagedMemoryBlock_Ptr = ManagedMemoryBlock*;
static void newFunction(UDFContext* context, UDFValue* ret) {
auto* env = context->environment;
try {
UDFValue capacity;
if (!UDFNextArgument(context, MayaType::INTEGER_BIT, &capacity)) {
setBoolean(env, ret, false);
errorMessage(env, "NEW", 1, getFunctionErrorPrefixNew<WordBlock>(), " expected an integer for capacity!");
}
auto cap = getInteger(capacity);
auto idIndex = Self::getAssociatedEnvironmentId(env);
setExternalAddress(env, ret, Self::make(cap), idIndex);
} catch(const syn::Problem& p) {
handleProblem(env, ret, p, getFunctionErrorPrefixNew<WordBlock>());
}
}
enum class MemoryBlockOp {
Populate,
Size,
Type,
Set,
Move,
Swap,
Decrement,
Increment,
Get,
MapWrite,
Count,
};
static std::tuple<MemoryBlockOp, int> getParameters(const std::string& op) noexcept {
static std::map<std::string, std::tuple<MemoryBlockOp, int>> opTranslation = {
{ "populate", std::make_tuple(MemoryBlockOp:: Populate , 1) },
{ "size", std::make_tuple(MemoryBlockOp:: Size , 0) },
{ "type", std::make_tuple(MemoryBlockOp:: Type , 0) },
{ "write", std::make_tuple(MemoryBlockOp:: Set , 2) },
{ "move", std::make_tuple(MemoryBlockOp:: Move , 2) },
{ "swap", std::make_tuple(MemoryBlockOp:: Swap , 2) },
{ "decrement", std::make_tuple(MemoryBlockOp:: Decrement , 1) },
{ "increment", std::make_tuple(MemoryBlockOp:: Increment , 1) },
{ "read", std::make_tuple(MemoryBlockOp:: Get , 1) },
{ "map-write", std::make_tuple(MemoryBlockOp::MapWrite, 2) },
};
static std::tuple<MemoryBlockOp, int> bad;
static bool init = false;
if (!init) {
init = true;
bad = std::make_tuple(syn::defaultErrorState<MemoryBlockOp>, -1);
}
auto result = opTranslation.find(op);
if (result == opTranslation.end()) {
return bad;
} else {
return result->second;
}
}
static bool callFunction(UDFContext* context, UDFValue* theValue, UDFValue* ret) {
UDFValue operation;
if (!UDFNextArgument(context, MayaType::SYMBOL_BIT, &operation)) {
//TODO: put error messages in here
return false;
}
std::string str(getLexeme(&operation));
// translate the op to an enumeration
auto* env = context->environment;
auto result = getParameters(str);
if (syn::isErrorState(std::get<0>(result))) {
setBoolean(context, ret, false);
return false;
//return Parent::callErrorMessageCode3(env, ret, str, " <- unknown operation requested!");
}
MemoryBlockOp op;
int aCount;
setBoolean(env, ret, true);
auto ptr = static_cast<Self_Ptr>(getExternalAddress(theValue));
std::tie(op, aCount) = result;
switch(op) {
case MemoryBlockOp::Type:
Self::setType(context, ret);
break;
case MemoryBlockOp::Size:
setInteger(context, ret, ptr->size());
break;
case MemoryBlockOp::Get:
return ptr->load(env, context, ret);
case MemoryBlockOp::Populate:
return ptr->populate(env, context, ret);
case MemoryBlockOp::Increment:
return ptr->increment(env, context, ret);
case MemoryBlockOp::Decrement:
return ptr->decrement(env, context, ret);
case MemoryBlockOp::Swap:
return ptr->swap(env, context, ret);
case MemoryBlockOp::Move:
return ptr->move(env, context, ret);
case MemoryBlockOp::Set:
return ptr->store(env, context, ret);
case MemoryBlockOp::MapWrite:
return ptr->mapWrite(env, context, ret);
default:
setBoolean(context, ret, false);
//return Parent::callErrorMessageCode3(env, ret, str, "<- legal but unimplemented operation!");
//TODO: add error message
return false;
}
return true;
}
static void registerWithEnvironment(Environment* env, const char* title) {
Parent::registerWithEnvironment(env, title, callFunction, newFunction);
}
static void registerWithEnvironment(Environment* env) {
registerWithEnvironment(env, Parent::getType().c_str());
}
public:
ManagedMemoryBlock(Address capacity) : Parent(std::move(std::make_unique<WordBlock>(capacity))), _capacity(capacity) { }
inline Address size() const noexcept { return _capacity; }
inline bool legalAddress(Address idx) const noexcept { return addressInRange<Address>(_capacity, idx); }
inline Word getMemoryCellValue(Address addr) noexcept { return this->_value.get()[addr]; }
inline void setMemoryCell(Address addr0, Word value) noexcept { this->_value.get()[addr0] = value; }
inline void swapMemoryCells(Address addr0, Address addr1) noexcept { syn::swap<Word>(this->_value.get()[addr0], this->_value.get()[addr1]); }
inline void decrementMemoryCell(Address address) noexcept { --this->_value.get()[address]; }
inline void incrementMemoryCell(Address address) noexcept { ++this->_value.get()[address]; }
inline void copyMemoryCell(Address from, Address to) noexcept {
auto ptr = this->_value.get();
ptr[to] = ptr[from];
}
inline void setMemoryToSingleValue(Word value) noexcept {
auto ptr = this->_value.get();
for (Address i = 0; i < _capacity; ++i) {
ptr[i] = value;
}
}
private:
bool extractInteger(UDFContext* context, UDFValue& storage) noexcept {
if (!UDFNextArgument(context, MayaType::INTEGER_BIT, &storage)) {
// TODO: put error message here
return false;
}
return true;
}
bool defaultSingleOperationBody(Environment* env, UDFContext* context, UDFValue* ret, std::function<bool(Environment*, UDFContext*, UDFValue*, Address)> body) noexcept {
UDFValue address;
if (!extractInteger(context, address)) {
setBoolean(env, ret, false);
return false;
}
auto value = static_cast<Address>(getInteger(address));
if (!legalAddress(value)) {
// TODO: insert error message here about illegal address
setBoolean(env, ret, false);
return false;
}
return body(env, context, ret, value);
}
bool defaultTwoOperationBody(Environment* env, UDFContext* context, UDFValue* ret, std::function<bool(Environment*, UDFContext*, UDFValue*, Address, Address)> body) noexcept {
UDFValue address, address2;
if (!extractInteger(context, address)) {
setBoolean(env, ret, false);
return false;
}
if (!extractInteger(context, address2)) {
setBoolean(env, ret, false);
return false;
}
auto addr0 = static_cast<Address>(getInteger(address));
auto addr1 = static_cast<Address>(getInteger(address2));
if (!legalAddress(addr0) || !legalAddress(addr1)) {
setBoolean(env, ret, false);
return false;
}
return body(env, context, ret, addr0, addr1);
}
public:
bool populate(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
UDFValue value;
if (!extractInteger(context, value)) {
setBoolean(env, ret, false);
return false;
}
auto population = static_cast<Word>(getInteger(value));
setMemoryToSingleValue(population);
setBoolean(env, ret, true);
return true;
}
bool load(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
return defaultSingleOperationBody(env, context, ret, [this](auto* env, auto* context, auto* ret, auto address) noexcept {
setInteger(env, ret, this->getMemoryCellValue(address));
return true;
});
}
bool increment(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
return defaultSingleOperationBody(env, context, ret, [this](auto* env, auto* context, auto* ret, auto address) noexcept {
this->incrementMemoryCell(address);
setBoolean(env, ret, true);
return true;
});
}
bool decrement(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
return defaultSingleOperationBody(env, context, ret, [this](auto* env, auto* context, auto* ret, auto address) noexcept {
this->decrementMemoryCell(address);
setBoolean(env, ret, true);
return true;
});
}
bool swap(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
return defaultTwoOperationBody(env, context, ret, [this](auto* env, auto* context, auto* ret, auto addr0, auto addr1) noexcept {
this->swapMemoryCells(addr0, addr1);
setBoolean(env, ret, true);
return true;
});
}
bool move(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
return defaultTwoOperationBody(env, context, ret, [this](auto* env, auto* context, auto* ret, auto from, auto to) noexcept {
this->copyMemoryCell(from, to);
setBoolean(env, ret, true);
return true;
});
}
bool store(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
UDFValue address, value;
if (!extractInteger(context, address)) {
setBoolean(env, ret, false);
return false;
}
if (!extractInteger(context, value)) {
setBoolean(env, ret, false);
return false;
}
auto addr = static_cast<Address>(getInteger(address));
if (!legalAddress(addr)) {
setBoolean(env, ret, false);
return false;
}
auto data = static_cast<Word>(getInteger(value));
this->setMemoryCell(addr, data);
setBoolean(env, ret, true);
return true;
}
bool mapWrite(Environment* env, UDFContext* context, UDFValue* ret) noexcept {
UDFValue startingAddress;
if (!extractInteger(context, startingAddress)) {
setBoolean(env, ret, false);
return false;
}
auto addr = static_cast<Address>(getInteger(startingAddress));
while(UDFHasNextArgument(context)) {
if (!legalAddress(addr)) {
setBoolean(env, ret, false);
return false;
}
UDFValue currentItem;
if (!extractInteger(context, currentItem)) {
setBoolean(env, ret, false);
return false;
}
auto data = static_cast<Word>(getInteger(currentItem));
this->setMemoryCell(addr, data);
++addr;
}
setBoolean(env, ret, true);
return true;
}
private:
Address _capacity;
};
DefWrapperSymbolicName(Block<int64_t>, "memory-block");
using StandardManagedMemoryBlock = ManagedMemoryBlock<int64_t>;
#ifndef ENABLE_EXTENDED_MEMORY_BLOCKS
#define ENABLE_EXTENDED_MEMORY_BLOCKS 0
#endif // end ENABLE_EXTENDED_MEMORY_BLOCKS
#if ENABLE_EXTENDED_MEMORY_BLOCKS
#define DefMemoryBlock(name, type, alias) \
DefWrapperSymbolicName(Block< type > , name ); \
using alias = ManagedMemoryBlock< type >
DefMemoryBlock("memory-block:uint8", uint8, ManagedMemoryBlock_uint8);
DefMemoryBlock("memory-block:uint16", uint16, ManagedMemoryBlock_uint16);
DefMemoryBlock("memory-block:uint32", uint32, ManagedMemoryBlock_uint32);
DefMemoryBlock("memory-block:int32", int32, ManagedMemoryBlock_int32);
DefMemoryBlock("memory-block:int16", int16, ManagedMemoryBlock_int16);
DefMemoryBlock("memory-block:int8", int8, ManagedMemoryBlock_int8);
#undef DefMemoryBlock
#endif // end ENABLE_EXTENDED_MEMORY_BLOCKS
void installMemoryBlockTypes(Environment* theEnv) {
StandardManagedMemoryBlock::registerWithEnvironment(theEnv);
#if ENABLE_EXTENDED_MEMORY_BLOCKS
ManagedMemoryBlock_uint8::registerWithEnvironment(theEnv);
ManagedMemoryBlock_uint16::registerWithEnvironment(theEnv);
ManagedMemoryBlock_uint32::registerWithEnvironment(theEnv);
ManagedMemoryBlock_int8::registerWithEnvironment(theEnv);
ManagedMemoryBlock_int16::registerWithEnvironment(theEnv);
ManagedMemoryBlock_int32::registerWithEnvironment(theEnv);
#endif // end ENABLE_EXTENDED_MEMORY_BLOCKS
}
}
| 38.319693
| 178
| 0.680705
|
DrItanium
|
eff414eb37b93f36a5e9cd4a7a03fea2fdf00899
| 4,837
|
hpp
|
C++
|
libs/Core/include/argos-Core/Syntax/SyntaxParenthesizedExpression.hpp
|
henrikfroehling/interlinck
|
d9d947b890d9286c6596c687fcfcf016ef820d6b
|
[
"MIT"
] | null | null | null |
libs/Core/include/argos-Core/Syntax/SyntaxParenthesizedExpression.hpp
|
henrikfroehling/interlinck
|
d9d947b890d9286c6596c687fcfcf016ef820d6b
|
[
"MIT"
] | 19
|
2021-12-01T20:37:23.000Z
|
2022-02-14T21:05:43.000Z
|
libs/Core/include/argos-Core/Syntax/SyntaxParenthesizedExpression.hpp
|
henrikfroehling/interlinck
|
d9d947b890d9286c6596c687fcfcf016ef820d6b
|
[
"MIT"
] | null | null | null |
#ifndef ARGOS_CORE_SYNTAX_SYNTAXPARENTHESIZEDEXPRESSION_H
#define ARGOS_CORE_SYNTAX_SYNTAXPARENTHESIZEDEXPRESSION_H
#include <string>
#include "argos-Core/argos_global.hpp"
#include "argos-Core/Syntax/ExpressionKinds.hpp"
#include "argos-Core/Syntax/ISyntaxParenthesizedExpression.hpp"
#include "argos-Core/Syntax/SyntaxExpression.hpp"
#include "argos-Core/Syntax/SyntaxVariant.hpp"
#include "argos-Core/Types.hpp"
namespace argos::Core::Syntax
{
class ISyntaxExpression;
class ISyntaxToken;
/**
* @brief Base class implementation for <code>ISyntaxParenthesizedExpression</code>.
*/
class ARGOS_CORE_API SyntaxParenthesizedExpression : public virtual ISyntaxParenthesizedExpression,
public SyntaxExpression
{
public:
SyntaxParenthesizedExpression() = delete;
/**
* @brief Creates a <code>SyntaxParenthesizedExpression</code> instance.
* @param expressionKind The <code>ExpressionKind</code> of the <code>SyntaxParenthesizedExpression</code>.
* @param openParenthesisToken The left sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
* @param expression The <code>ISyntaxExpression</code> in the parenthesized expression.
* @param closeParenthesisToken The right sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
*/
explicit SyntaxParenthesizedExpression(ExpressionKind expressionKind,
const ISyntaxToken* openParenthesisToken,
const ISyntaxExpression* expression,
const ISyntaxToken* closeParenthesisToken) noexcept;
~SyntaxParenthesizedExpression() noexcept override = default;
/**
* @brief Returns the children count of the parenthesized expression.
* @return The children count of the parenthesized expression.
*/
argos_size childCount() const noexcept override;
/**
* @brief Returns the child item of the parenthesized expression at the given <code>index</code>.
* @param index The index for which a child item will be returned.
* @return The child item of the parenthesized expression at the given <code>index</code>.
*/
SyntaxVariant child(argos_size index) const noexcept final;
/**
* @brief Returns the first child item of the parenthesized expression.
* @return The first child item of the parenthesized expression.
*/
SyntaxVariant first() const noexcept override;
/**
* @brief Returns the last child item of the parenthesized expression.
* @return The last child item of the parenthesized expression.
*/
SyntaxVariant last() const noexcept override;
/**
* @brief Returns a string representation of theparenthesized expression with basic data.
* @return A string representation of the parenthesized expression with basic data.
*/
std::string toString() const noexcept override;
/**
* @brief Returns a short string representation of the parenthesized expression with basic data.
* @return A short string representation of the parenthesized expression with basic data.
*/
std::string toShortString() const noexcept override;
/**
* @brief Returns the type name (e.g. the specific class name) of the parenthesized expression.
* @return The type name (e.g. the specific class name) of the parenthesized expression.
*/
std::string typeName() const noexcept override;
/**
* @brief Returns whether the expression is a parenthesized expression.
* @return Returns true.
*/
bool isParenthesizedExpression() const noexcept final;
/**
* @brief Returns the left sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
* @return The left sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
*/
const ISyntaxToken* openParenthesisToken() const noexcept final;
/**
* @brief Returns the <code>ISyntaxExpression</code> in the parenthesized expression.
* @return The <code>ISyntaxExpression</code> in the parenthesized expression.
*/
const ISyntaxExpression* expression() const noexcept final;
/**
* @brief Returns the right sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
* @return The right sided open parenthesis <code>ISyntaxToken</code> of the parenthesized expression.
*/
const ISyntaxToken* closeParenthesisToken() const noexcept final;
protected:
const ISyntaxToken* _openParenthesisToken;
const ISyntaxExpression* _expression;
const ISyntaxToken* _closeParenthesisToken;
};
} // end namespace argos::Core::Syntax
#endif // ARGOS_CORE_SYNTAX_SYNTAXBINARYEXPRESSION_H
| 40.991525
| 127
| 0.716767
|
henrikfroehling
|
56028334e37554e54761bca0249086aeb90bb51b
| 2,091
|
cc
|
C++
|
services/ui/ws/window_server_test_impl.cc
|
zipated/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 2,151
|
2020-04-18T07:31:17.000Z
|
2022-03-31T08:39:18.000Z
|
services/ui/ws/window_server_test_impl.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 395
|
2020-04-18T08:22:18.000Z
|
2021-12-08T13:04:49.000Z
|
services/ui/ws/window_server_test_impl.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 338
|
2020-04-18T08:03:10.000Z
|
2022-03-29T12:33:22.000Z
|
// Copyright 2016 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 "services/ui/ws/window_server_test_impl.h"
#include "services/ui/public/interfaces/window_tree.mojom.h"
#include "services/ui/ws/server_window.h"
#include "services/ui/ws/window_server.h"
#include "services/ui/ws/window_tree.h"
namespace ui {
namespace ws {
WindowServerTestImpl::WindowServerTestImpl(WindowServer* window_server)
: window_server_(window_server) {}
WindowServerTestImpl::~WindowServerTestImpl() {}
void WindowServerTestImpl::OnSurfaceActivated(
const std::string& name,
EnsureClientHasDrawnWindowCallback cb,
ServerWindow* window) {
// This api is used to detect when a client has painted once, which is
// dictated by whether there is a CompositorFrameSink.
WindowTree* tree = window_server_->GetTreeWithClientName(name);
if (tree && tree->HasRoot(window) &&
window->has_created_compositor_frame_sink()) {
std::move(cb).Run(true);
} else {
// No tree with the given name, or it hasn't painted yet. Install a callback
// for the next time a client creates a CompositorFramesink.
InstallCallback(name, std::move(cb));
}
}
void WindowServerTestImpl::InstallCallback(
const std::string& client_name,
EnsureClientHasDrawnWindowCallback cb) {
window_server_->SetSurfaceActivationCallback(
base::BindOnce(&WindowServerTestImpl::OnSurfaceActivated,
base::Unretained(this), client_name, std::move(cb)));
}
void WindowServerTestImpl::EnsureClientHasDrawnWindow(
const std::string& client_name,
EnsureClientHasDrawnWindowCallback callback) {
WindowTree* tree = window_server_->GetTreeWithClientName(client_name);
if (tree) {
for (const ServerWindow* window : tree->roots()) {
if (window->has_created_compositor_frame_sink()) {
std::move(callback).Run(true);
return;
}
}
}
InstallCallback(client_name, std::move(callback));
}
} // namespace ws
} // namespace ui
| 33.725806
| 80
| 0.730751
|
zipated
|
56043e77013eda58e4eb07859c1cba7299bfe06d
| 11,642
|
cpp
|
C++
|
tries/TST/lib/TST.cpp
|
hpaucar/datastructures-ii-repo
|
203dbafcd4bb82a4214f93e21f15b3be89cea76c
|
[
"MIT"
] | null | null | null |
tries/TST/lib/TST.cpp
|
hpaucar/datastructures-ii-repo
|
203dbafcd4bb82a4214f93e21f15b3be89cea76c
|
[
"MIT"
] | null | null | null |
tries/TST/lib/TST.cpp
|
hpaucar/datastructures-ii-repo
|
203dbafcd4bb82a4214f93e21f15b3be89cea76c
|
[
"MIT"
] | null | null | null |
// Copyright 2015 Maitesin
#include <string>
#include <vector>
#include <iostream>
#include "./TST.h"
template <class T> const T &TST::tst<T>::find(const std::string &key) {
node_ptr node(find(root, key, 0));
if (node != nullptr) {
aux_ret = node->value;
node.release();
return aux_ret;
} else {
return def;
}
}
template <class T>
typename TST::tst<T>::node_ptr
TST::tst<T>::find(TST::tst<T>::node_ptr &n, const std::string &key, size_t d) {
if (key.size() == d + 1) {
if (n == nullptr)
return nullptr;
else {
if (n->c > key[d] && n->left != nullptr) {
return find(n->left, key, d);
}
if (n->c == key[d]) {
if (n->value != def)
return node_ptr(n.get());
else
return nullptr;
}
if (n->c < key[d] && n->right != nullptr) {
return find(n->right, key, d);
}
}
} else {
if (n != nullptr) {
if (n->c > key[d] && n->left != nullptr) {
return find(n->left, key, d);
}
if (n->c == key[d])
return find(n->middle, key, d + 1);
if (n->c < key[d] && n->right != nullptr) {
return find(n->right, key, d);
}
}
}
return nullptr;
}
template <class T>
void TST::tst<T>::insert(const std::string &key, const T &value) {
if (key == "")
return;
if (root == nullptr)
root = node_ptr(new node(key[0]));
bool created = false;
root = insert(std::move(root), key, value, 0, created);
if (created)
++s;
}
template <class T>
typename TST::tst<T>::node_ptr
TST::tst<T>::insert(TST::tst<T>::node_ptr n, const std::string &key,
const T &value, size_t d, bool &created) {
if (key.size() == d + 1) {
if (n->c > key[d]) {
if (n->left == nullptr)
n->left = node_ptr(new node(key[d]));
n->left = insert(std::move(n->left), key, value, d, created);
}
if (n->c == key[d]) {
if (n->value == def)
created = true;
n->value = value;
}
if (n->c < key[d]) {
if (n->right == nullptr)
n->right = node_ptr(new node(key[d]));
n->right = insert(std::move(n->right), key, value, d, created);
}
return n;
} else {
if (n->c > key[d]) {
if (n->left == nullptr)
n->left = node_ptr(new node(key[d]));
n->left = insert(std::move(n->left), key, value, d, created);
}
if (n->c == key[d]) {
if (n->middle == nullptr)
n->middle = node_ptr(new node(key[d + 1]));
n->middle = insert(std::move(n->middle), key, value, d + 1, created);
}
if (n->c < key[d]) {
if (n->right == nullptr)
n->right = node_ptr(new node(key[d]));
n->right = insert(std::move(n->right), key, value, d, created);
}
return n;
}
}
template <class T> void TST::tst<T>::clear(TST::tst<T>::node_ptr n) {
if (n->left != nullptr)
clear(std::move(n->left));
if (n->middle != nullptr)
clear(std::move(n->middle));
if (n->right != nullptr)
clear(std::move(n->right));
n.reset();
}
template <class T> bool TST::tst<T>::contains(const std::string &key) {
return root != nullptr ? contains(root, key, 0) : false;
}
template <class T>
bool TST::tst<T>::contains(TST::tst<T>::node_ptr &n, const std::string &key,
size_t d) {
if (key.size() == d + 1) {
if (n == nullptr)
return false;
if (n->c > key[d] && n->left != nullptr) {
return contains(n->left, key, d);
}
if (n->c == key[d]) {
return n->value != def;
}
if (n->c < key[d] && n->right != nullptr) {
return contains(n->right, key, d);
}
} else {
if (n->c > key[d] && n->left != nullptr) {
return contains(n->left, key, d);
}
if (n->c == key[d]) {
if (n->middle != nullptr)
return contains(n->middle, key, d + 1);
return false;
}
if (n->c < key[d] && n->right != nullptr) {
return contains(n->right, key, d);
}
}
return false;
}
template <class T> void TST::tst<T>::erase(const std::string &key) {
bool decrease = false;
if (root != nullptr) {
erase(root, key, 0, decrease);
}
if (decrease)
--s;
}
template <class T>
bool TST::tst<T>::erase(TST::tst<T>::node_ptr &n, const std::string &key,
size_t d, bool &decrease) {
if (key.size() == d + 1 && n != nullptr) {
if (n->left != nullptr && n->c > key[d]) {
if (n->left->c == key[d]) {
bool deleted = erase(n->left, key, d, decrease);
if (deleted) {
n->left.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
} else {
return erase(n->left, key, d, decrease);
}
}
if (n->c == key[d]) {
if (n->value != def)
decrease = true;
n->value = T();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr)
return true;
}
if (n->right != nullptr && n->c < key[d]) {
if (n->right->c == key[d]) {
bool deleted = erase(n->right, key, d, decrease);
if (deleted) {
n->right.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
} else {
return erase(n->right, key, d, decrease);
}
}
} else {
if (n->left != nullptr && n->c > key[d]) {
if (n->left->c == key[d]) {
bool deleted = erase(n->left, key, d, decrease);
if (deleted) {
n->left.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
} else {
return erase(n->left, key, d, decrease);
}
}
if (n->middle != nullptr && n->c == key[d]) {
bool deleted = erase(n->middle, key, d + 1, decrease);
if (deleted) {
n->middle.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
}
if (n->right != nullptr && n->c < key[d]) {
if (n->right->c == key[d]) {
bool deleted = erase(n->right, key, d, decrease);
if (deleted) {
n->middle.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
}
if (n->right != nullptr && n->c < key[d]) {
if (n->right->c == key[d]) {
bool deleted = erase(n->right, key, d, decrease);
if (deleted) {
n->right.reset();
if (n->left == nullptr
&& n->middle == nullptr
&& n->right == nullptr
&& n->value == def)
return true;
}
return false;
} else {
return erase(n->right, key, d, decrease);
}
} else {
return erase(n->right, key, d, decrease);
}
}
}
return false;
}
template <class T>
std::vector<std::string> TST::tst<T>::keys(const std::string &prefix) {
vec_ptr vec;
vec = vec_ptr(new std::vector<std::string>());
keys(root, prefix, 0, vec);
return *vec;
}
template <class T>
void TST::tst<T>::keys(TST::tst<T>::node_ptr &n, std::string prefix, size_t d,
TST::tst<T>::vec_ptr &v) {
if (prefix.size() <= d + 1) {
if (prefix.size() == d + 1) {
if (n->c > prefix[d] && n->left != nullptr)
keys(n->left, prefix, d, v);
if (n->c == prefix[d]) {
if (n->value != def)
v->push_back(prefix);
gather_keys(n->middle, prefix, v);
}
if (n->c < prefix[d] && n->right != nullptr)
keys(n->right, prefix, d, v);
} else
gather_keys(n, prefix, v);
} else {
if (n->c > prefix[d] && n->left != nullptr) {
keys(n->left, prefix, d, v);
}
if (n->c == prefix[d] && n->middle != nullptr)
keys(n->middle, prefix, d + 1, v);
if (n->c < prefix[d] && n->right != nullptr) {
keys(n->right, prefix, d, v);
}
}
}
template <class T>
void TST::tst<T>::gather_keys(TST::tst<T>::node_ptr &n, std::string prefix,
TST::tst<T>::vec_ptr &v) {
if (n == nullptr)
return;
if (n->value != def) {
v->push_back(prefix + n->c);
}
gather_keys(n->left, prefix, v);
gather_keys(n->middle, prefix + n->c, v);
gather_keys(n->right, prefix, v);
}
template <class T> void TST::tst<T>::show() {
std::cout << "digraph graphName{" << std::endl;
std::cout << "node [shape=record];" << std::endl;
// Node labels
size_t label = 0;
std::cout << label << " [shape=record,label=\"{ <data> " << root->c
<< " | {<left> l | <middle> m | <right> r}}\"];" << std::endl;
if (root->left != nullptr) {
++label;
show_label(root->left, label);
}
if (root->middle != nullptr) {
++label;
show_label(root->middle, label);
}
if (root->right != nullptr) {
++label;
show_label(root->right, label);
}
// Node hierarchy
label = 0;
if (root->left != nullptr) {
std::cout << "0:left"
<< "->";
++label;
show(root->left, label);
}
if (root->middle != nullptr) {
std::cout << "0:middle"
<< "->";
++label;
show(root->middle, label);
}
if (root->right != nullptr) {
std::cout << "0:right"
<< "->";
++label;
show(root->right, label);
}
std::cout << "}" << std::endl;
}
template <class T>
void TST::tst<T>::show_label(TST::tst<T>::node_ptr &n, size_t &label) {
std::cout << label << " [shape=record,label=\"{<data> " << n->c;
if (n->value != T())
std::cout << " | <value> " << n->value;
std::cout << " | {<left> l | <middle> m | <right> r}}\"";
if (n->value != T())
std::cout << "color=\"blue\"";
std::cout << "];" << std::endl;
if (n->left != nullptr) {
++label;
show_label(n->left, label);
}
if (n->middle != nullptr) {
++label;
show_label(n->middle, label);
}
if (n->right != nullptr) {
++label;
show_label(n->right, label);
}
}
template <class T>
void TST::tst<T>::show(TST::tst<T>::node_ptr &n, size_t &label) {
std::cout << label << ":data" << std::endl;
size_t copy_label = label;
if (n->left != nullptr) {
std::cout << copy_label << ":left"
<< "->";
++label;
show(n->left, label);
}
if (n->middle != nullptr) {
std::cout << copy_label << ":middle"
<< "->";
++label;
show(n->middle, label);
}
if (n->right != nullptr) {
std::cout << copy_label << ":right"
<< "->";
++label;
show(n->right, label);
}
}
template <class T> std::string TST::tst<T>::lcp() {
return lcp_clean_before(root);
}
template <class T>
std::string TST::tst<T>::lcp_clean_before(TST::tst<T>::node_ptr &n) {
if (n == nullptr) {
return "";
}
if (n->middle == nullptr) {
if (n->left == nullptr && n->right != nullptr) {
return lcp_clean_before(n->right);
} else if (n->left != nullptr && n->right == nullptr) {
return lcp_clean_before(n->left);
} else if (n->left == nullptr && n->right == nullptr) {
return "";
}
} else {
return lcp(n, "");
}
return "";
}
template <class T>
std::string TST::tst<T>::lcp(TST::tst<T>::node_ptr &n, std::string s) {
if (n != nullptr
&& n->left == nullptr
&& n->right == nullptr) {
return lcp(n->middle, s + n->c);
}
return s;
}
| 26.459091
| 79
| 0.49038
|
hpaucar
|
5605cbbccd04885598aebbc1699203f68164d32b
| 20,333
|
cpp
|
C++
|
net/ias/mmc/nap/iasstringattributeeditor.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
net/ias/mmc/nap/iasstringattributeeditor.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
net/ias/mmc/nap/iasstringattributeeditor.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
//////////////////////////////////////////////////////////////////////////////
/*++
Copyright (C) Microsoft Corporation, 1998 - 1999
Module Name:
IASStringAttributeEditor.cpp
Abstract:
Implementation file for the CIASStringAttributeEditor class.
Revision History:
mmaguire 06/25/98 - created
--*/
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// BEGIN INCLUDES
//
// standard includes:
//
#include "Precompiled.h"
//
// where we can find declaration for main class in this file:
//
#include "IASStringAttributeEditor.h"
//
// where we can find declarations needed in this file:
//
#include "IASStringEditorPage.h"
#include "iashelper.h"
//
// END INCLUDES
//////////////////////////////////////////////////////////////////////////////
BYTE PREFIX___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD[] = {0,0,0,0};
UINT PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 4;
UINT PREFIX_OFFSET_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 3; // 0 based index -- the fourth byte
UINT PREFIX_LEN_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 1; // one byte
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::ShowEditor
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::ShowEditor( /*[in, out]*/ BSTR *pReserved )
{
TRACE(_T("CIASStringAttributeEditor::ShowEditor\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
HRESULT hr = S_OK;
try
{
// Load page title.
// ::CString strPageTitle;
// strPageTitle.LoadString(IDS_IAS_IP_EDITOR_TITLE);
//
// CPropertySheet propSheet( (LPCTSTR)strPageTitle );
//
// IP Address Editor
//
CIASPgSingleAttr cppPage;
// Initialize the page's data exchange fields with info from IAttributeInfo
CComBSTR bstrName;
CComBSTR bstrSyntax;
ATTRIBUTESYNTAX asSyntax = IAS_SYNTAX_OCTETSTRING;
ATTRIBUTEID Id = ATTRIBUTE_UNDEFINED;
if( m_spIASAttributeInfo )
{
hr = m_spIASAttributeInfo->get_AttributeName( &bstrName );
if( FAILED(hr) ) throw hr;
hr = m_spIASAttributeInfo->get_SyntaxString( &bstrSyntax );
if( FAILED(hr) ) throw hr;
hr = m_spIASAttributeInfo->get_AttributeSyntax( &asSyntax );
if( FAILED(hr) ) throw hr;
hr = m_spIASAttributeInfo->get_AttributeID( &Id );
if( FAILED(hr) ) throw hr;
}
cppPage.m_strAttrName = bstrName;
cppPage.m_AttrSyntax = asSyntax;
cppPage.m_nAttrId = Id;
cppPage.m_strAttrFormat = bstrSyntax;
// Attribute type is actually attribute ID in string format
WCHAR szTempId[MAX_PATH];
wsprintf(szTempId, _T("%ld"), Id);
cppPage.m_strAttrType = szTempId;
// Initialize the page's data exchange fields with info from VARIANT value passed in.
if ( V_VT(m_pvarValue) != VT_EMPTY )
{
EStringType sp;
CComBSTR bstrTemp;
get_ValueAsStringEx( &bstrTemp, &sp );
cppPage.m_strAttrValue = bstrTemp;
cppPage.m_OctetStringType = sp;
}
// propSheet.AddPage(&cppPage);
// int iResult = propSheet.DoModal();
int iResult = cppPage.DoModal();
if (IDOK == iResult)
{
CComBSTR bstrTemp = (LPCTSTR)cppPage.m_strAttrValue;
put_ValueAsStringEx( bstrTemp, cppPage.m_OctetStringType);
}
else
{
hr = S_FALSE;
}
//
// delete the property page pointer
//
// propSheet.RemovePage(&cppPage);
}
catch( HRESULT & hr )
{
return hr;
}
catch(...)
{
return hr = E_FAIL;
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::SetAttributeValue
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::SetAttributeValue(VARIANT * pValue)
{
TRACE(_T("CIASStringAttributeEditor::SetAttributeValue\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
// Check for preconditions.
if( ! pValue )
{
return E_INVALIDARG;
}
// From Baogang's old code, it appears that this editor should accept
// either VT_BSTR, VT_BOOL, VT_I4 or VT_EMPTY.
if( V_VT(pValue) != VT_BSTR
&& V_VT(pValue) != VT_BOOL
&& V_VT(pValue) != VT_I4
&& V_VT(pValue) != VT_EMPTY
&& V_VT(pValue) != (VT_ARRAY | VT_UI1))
{
return E_INVALIDARG;
}
m_pvarValue = pValue;
return S_OK;
}
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::get_ValueAsString
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::get_ValueAsString(BSTR * pbstrDisplayText )
{
TRACE(_T("CIASStringAttributeEditor::get_ValueAsString\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
// Check for preconditions.
if( ! pbstrDisplayText )
{
return E_INVALIDARG;
}
if( ! m_spIASAttributeInfo || ! m_pvarValue )
{
// We are not initialized properly.
return OLE_E_BLANK;
}
HRESULT hr = S_OK;
try
{
CComBSTR bstrDisplay;
VARTYPE vType = V_VT(m_pvarValue);
switch( vType )
{
case VT_BOOL:
{
if( V_BOOL(m_pvarValue) )
{
// ISSUE: This is not localizable!!!
// Should it be? Ask Ashwin about this as some of
// Baogang's error checking code was specifically looking
// for either hardcoded "TRUE" or "FALSE".
// ISSUE: I think that for Boolean syntax attributes,
// we should be popping up the same type of attribute
// editor as for the enumerables only with TRUE and FALSE in it.
bstrDisplay = L"TRUE";
}
else
{
bstrDisplay = L"FALSE";
}
}
break;
case VT_I4:
{
// The variant is some type which must be coerced to a bstr.
CComVariant varValue;
// Make sure you pass a VT_EMPTY variant to VariantChangeType
// or it will assert.
// So don't do: V_VT(&varValue) = VT_BSTR;
hr = VariantChangeType(&varValue, m_pvarValue, VARIANT_NOVALUEPROP, VT_BSTR);
if( FAILED( hr ) ) throw hr;
bstrDisplay = V_BSTR(&varValue);
}
break;
case VT_BSTR:
bstrDisplay = V_BSTR(m_pvarValue);
break;
case VT_UI1 | VT_ARRAY: // Treat as Octet string
{
EStringType t;
return get_ValueAsStringEx(pbstrDisplayText, &t);
}
break;
default:
// need to check what is happening here,
ASSERT(0);
break;
case VT_EMPTY:
// do nothing -- we will fall through and return a blank string.
break;
}
*pbstrDisplayText = bstrDisplay.Copy();
}
catch( HRESULT &hr )
{
return hr;
}
catch(...)
{
return E_FAIL;
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::put_ValueAsString
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::put_ValueAsString(BSTR newVal)
{
TRACE(_T("CIASStringAttributeEditor::put_ValueAsString\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
if( ! m_pvarValue )
{
// We are not initialized properly.
return OLE_E_BLANK;
}
if( m_spIASAttributeInfo == NULL )
{
// We are not initialized properly.
return OLE_E_BLANK;
}
HRESULT hr = S_OK;
try
{
CComBSTR bstrTemp = newVal;
CComVariant varValue;
V_VT(&varValue) = VT_BSTR;
V_BSTR(&varValue) = bstrTemp.Copy();
VARTYPE vType = V_VT(m_pvarValue);
// Initialize the variant that was passed in.
VariantClear(m_pvarValue);
{
ATTRIBUTESYNTAX asSyntax;
hr = m_spIASAttributeInfo->get_AttributeSyntax( &asSyntax );
if( FAILED(hr) ) throw hr;
// if this Octet string, this should be BSTR, no matter what it was before.
if(asSyntax == IAS_SYNTAX_OCTETSTRING)
vType = VT_BSTR;
if ( VT_EMPTY == vType)
{
// decide the value type:
switch (asSyntax)
{
case IAS_SYNTAX_BOOLEAN:
vType = VT_BOOL;
break;
case IAS_SYNTAX_INTEGER:
case IAS_SYNTAX_UNSIGNEDINTEGER:
case IAS_SYNTAX_ENUMERATOR:
case IAS_SYNTAX_INETADDR:
vType = VT_I4;
break;
case IAS_SYNTAX_STRING:
case IAS_SYNTAX_UTCTIME:
case IAS_SYNTAX_PROVIDERSPECIFIC:
case IAS_SYNTAX_OCTETSTRING:
vType = VT_BSTR;
break;
default:
_ASSERTE(FALSE);
vType = VT_BSTR;
break;
}
}
}
hr = VariantChangeType(m_pvarValue, &varValue, VARIANT_NOVALUEPROP, vType);
if( FAILED( hr ) ) throw hr;
}
catch( HRESULT &hr )
{
return hr;
}
catch(...)
{
return E_FAIL;
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::get_ValueAsStringEx
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::get_ValueAsStringEx(BSTR * pbstrDisplayText, EStringType* pType )
{
TRACE(_T("CIASStringAttributeEditor::get_ValueAsString\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
ATTRIBUTESYNTAX asSyntax;
m_spIASAttributeInfo->get_AttributeSyntax( &asSyntax );
if(asSyntax != IAS_SYNTAX_OCTETSTRING)
{
if(pType)
*pType = STRING_TYPE_NORMAL;
return get_ValueAsString(pbstrDisplayText);
}
// only care about IAS_SYNTAX_OCTETSTRING
ASSERT(pType);
VARTYPE vType = V_VT(m_pvarValue);
SAFEARRAY* psa = NULL;
HRESULT hr = S_OK;
switch(vType)
{
case VT_ARRAY | VT_UI1:
psa = V_ARRAY(m_pvarValue);
break;
case VT_EMPTY:
if(pType)
*pType = STRING_TYPE_NULL;
return get_ValueAsString(pbstrDisplayText);
break;
case VT_BSTR:
if(pType)
*pType = STRING_TYPE_NORMAL;
return get_ValueAsString(pbstrDisplayText);
break;
default:
ASSERT(0); // should not happen, should correct some code
if(pType)
*pType = STRING_TYPE_NORMAL;
return get_ValueAsString(pbstrDisplayText);
break;
};
// no data is available , or the safe array is not valid, don't intepret the string
if(psa == NULL || psa->cDims != 1 || psa->cbElements != 1)
{
*pType = STRING_TYPE_NULL;
return hr;
}
// need to figure out how to convert the binary to text
char* pData = NULL;
int nBytes = 0;
WCHAR* pWStr = NULL;
int nWStr = 0;
DWORD dwErr = 0;
BOOL bStringConverted = FALSE;
CComBSTR bstrDisplay;
EStringType sType = STRING_TYPE_NULL;
hr = ::SafeArrayAccessData( psa, (void**)&pData);
if(hr != S_OK)
return hr;
nBytes = psa->rgsabound[0].cElements;
ASSERT(pData);
if(!pData) goto Error;
#ifdef __WE_WANT_TO_USE_UTF8_FOR_NORMAL_STRING_AS_WELL_
// UTF8 requires the flag to be 0
nWStr = MultiByteToWideChar(CP_UTF8, 0, pData, nBytes, NULL, 0);
if(nWStr == 0)
dwErr = GetLastError();
#endif
try{
#ifdef __WE_WANT_TO_USE_UTF8_FOR_NORMAL_STRING_AS_WELL_
if(nWStr != 0) // succ
{
pWStr = new WCHAR[nWStr + 2]; // for the 2 "s
int i = 0;
nWStr == MultiByteToWideChar(CP_UTF8, 0, pData, nBytes, pWStr , nWStr);
// if every char is printable
for(i = 0; i < nWStr -1; i++)
{
if(iswprint(pWStr[i]) == 0)
break;
}
if(0 == nWStr || i != nWStr - 1 || pWStr[i] != L'\0')
{
delete[] pWStr;
pWStr = NULL;
}
else
{
// added quotes
memmove(pWStr + 1, pWStr, nWStr * sizeof(WCHAR));
pWStr[0] = L'"';
pWStr[nWStr] = L'"';
pWStr[nWStr + 1 ] = 0; // new end of string
bStringConverted = TRUE; // to prevent from furthe convertion to HEX
sType = STRING_TYPE_UNICODE;
}
}
#endif // __WE_WANT_TO_USE_UTF8_FOR_NORMAL_STRING_AS_WELL_
// check if the attriabute is RADIUS_ATTRIBUTE_TUNNEL_PASSWORD,
// this attribute has special format --- remove 0's from the binary and
// try to conver to text
{
ATTRIBUTEID Id;
hr = m_spIASAttributeInfo->get_AttributeID( &Id );
if( FAILED(hr) ) goto Error;
if ( Id == RADIUS_ATTRIBUTE_TUNNEL_PASSWORD)
{
//BYTE PREFIX___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD[] = {0,0,0,0};
//UINT PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 4;
//UINT PREFIX_OFFSET_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 3; // 0 based index -- the fourth byte
//UINT PREFIX_LEN_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 1
if(PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD <=nBytes &&
memcmp(pData,
PREFIX___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD,
PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD - PREFIX_LEN_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD) == 0)
{
// correct prefix,
// remove the prefix
pData += PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD;
nBytes -= PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD;
// try to convert to UNICODE TEXT using CP_ACP -- get length
nWStr = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, pData, nBytes, NULL, 0);
if(nWStr != 0) // which means, we can not convert
{
pWStr = new WCHAR[nWStr + 1];
// try to convert to UNICODE TEXT using CP_ACP
nWStr = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, pData, nBytes, pWStr, nWStr);
if(nWStr != 0)
{
int i = 0;
for(i = 0; i < nWStr; i++)
{
if(iswprint(pWStr[i]) == 0)
break;
}
if( i == nWStr) // all printable
{
bStringConverted = TRUE;
pWStr[nWStr] = 0; // NULL terminator
}
}
if (!bStringConverted) // undo the thing
{
// release the buffer
delete[] pWStr;
pWStr = NULL;
nWStr = 0;
}
}
}
}
}
if(!bStringConverted) // not converted above, convert to HEX string
{
nWStr = BinaryToHexString(pData, nBytes, NULL, 0); // find out the size of the buffer
pWStr = new WCHAR[nWStr];
ASSERT(pWStr); // should have thrown if there is not enough memory
BinaryToHexString(pData, nBytes, pWStr, nWStr);
bStringConverted = TRUE; // to prevent from furthe convertion to HEX
sType = STRING_TYPE_HEX_FROM_BINARY;
}
if(bStringConverted)
{
bstrDisplay = pWStr;
// fill in the output parameters
*pbstrDisplayText = bstrDisplay.Copy();
*pType = sType;
delete[] pWStr;
pWStr = NULL;
}
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
Error:
if(pWStr)
delete[] pWStr;
if(psa)
::SafeArrayUnaccessData(psa);
return hr;
}
//////////////////////////////////////////////////////////////////////////////
/*++
*/
//////////////////////////////////////////////////////////////////////////////
/*++
CIASStringAttributeEditor::put_ValueAsStringEx
--*/
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CIASStringAttributeEditor::put_ValueAsStringEx(BSTR newVal, EStringType type)
{
TRACE(_T("CIASStringAttributeEditor::put_ValueAsStringEx\n"));
AFX_MANAGE_STATE(AfxGetStaticModuleState())
ATTRIBUTESYNTAX asSyntax;
m_spIASAttributeInfo->get_AttributeSyntax( &asSyntax );
if(asSyntax != IAS_SYNTAX_OCTETSTRING)
return put_ValueAsString(newVal);
// only care about IAS_SYNTAX_OCTETSTRING
HRESULT hr = S_OK;
char* pData = NULL;
int nLen = 0;
switch(type)
{
case STRING_TYPE_NULL:
// remove the data
break;
case STRING_TYPE_NORMAL:
case STRING_TYPE_UNICODE:
#ifdef __WE_WANT_TO_USE_UTF8_FOR_NORMAL_STRING_AS_WELL_
// need to convert UTF8 before passing into SafeArray
nLen = WideCharToMultiByte(CP_UTF8, 0, newVal, -1, NULL, 0, NULL, NULL);
if(nLen != 0) // when == 0 , need not to do anything
{
try{
pData = new char[nLen];
nLen = WideCharToMultiByte(CP_UTF8, 0, newVal, -1, pData, nLen, NULL, NULL);
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
}
break;
#else
// check if the attriabute is RADIUS_ATTRIBUTE_TUNNEL_PASSWORD,
// this attribute has special format --- remove 0's from the binary and
// try to conver to text
{
ATTRIBUTEID Id;
hr = m_spIASAttributeInfo->get_AttributeID( &Id );
if( FAILED(hr) ) goto Error;
if ( Id == RADIUS_ATTRIBUTE_TUNNEL_PASSWORD)
{
BOOL bUsedDefault = FALSE;
UINT nStrLen = wcslen(newVal);
// try to convert to UNICODE TEXT using CP_ACP -- get length
nLen = ::WideCharToMultiByte(CP_ACP, 0, newVal, nStrLen, NULL, 0, NULL, &bUsedDefault);
if(nLen != 0) // which means, we can not convert
{
try{
pData = new char[nLen];
ASSERT(pData);
// try to convert to UNICODE TEXT using CP_ACP
nLen = ::WideCharToMultiByte(CP_ACP, 0, newVal, nStrLen, pData, nLen, NULL, &bUsedDefault);
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
}
if(nLen == 0 || bUsedDefault) // failed to convert, then error message
{
// ANSI code page is allowed
hr = E_INVALIDARG;
AfxMessageBox(IDS_IAS_ERR_INVALIDCHARINPASSWORD);
goto Error;
}
}
else
return put_ValueAsString(newVal);
}
break;
#endif
case STRING_TYPE_HEX_FROM_BINARY:
// need to convert to binary before passing into SafeArray
if(wcslen(newVal) != 0)
{
newVal = GetValidVSAHexString(newVal);
if(newVal == NULL)
{
hr = E_INVALIDARG;
goto Error;
}
nLen = HexStringToBinary(newVal, NULL, 0); // find out the size of the buffer
}
else
nLen = 0;
// get the binary
try{
pData = new char[nLen];
ASSERT(pData);
HexStringToBinary(newVal, pData, nLen);
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
break;
default:
ASSERT(0); // this should not happen
break;
}
// check if the attriabute is RADIUS_ATTRIBUTE_TUNNEL_PASSWORD,
// this attribute has special format --- remove 0's from the binary and
// try to conver to text
{
ATTRIBUTEID Id;
hr = m_spIASAttributeInfo->get_AttributeID( &Id );
if( FAILED(hr) ) goto Error;
if ( Id == RADIUS_ATTRIBUTE_TUNNEL_PASSWORD)
{
char* pData1 = NULL;
// get the binary
//BYTE PREFIX___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD[] = {0,0,0,0};
//UINT PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 4;
//UINT PREFIX_OFFSET_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 3; // 0 based index -- the fourth byte
//UINT PREFIX_LEN_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD = 1
try{
pData1 = new char[nLen + PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD];
ASSERT(pData1);
memcpy(pData1, PREFIX___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD, PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD);
unsigned char lenByte = (unsigned char)nLen;
memcpy(pData1 + PREFIX_OFFSET_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD, &lenByte, PREFIX_LEN_DATALENBYTE___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD);
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
if(pData)
{
memcpy(pData1 + PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD, pData, nLen);
delete [] pData;
pData = pData1;
nLen += PREFIX_LEN___RADIUS_ATTRIBUTE_TUNNEL_PASSWORD;
}
}
}
// put the data into the safe array
VariantClear(m_pvarValue);
if(pData) // need to put data to safe array
{
SAFEARRAY* psa = NULL;
SAFEARRAYBOUND sab[1];
sab[0].cElements = nLen;
sab[0].lLbound = 0;
try{
psa = SafeArrayCreate(VT_UI1, 1, sab);
char* pByte = NULL;
if(S_OK == SafeArrayAccessData(psa, (void**)&pByte))
{
ASSERT(pByte);
memcpy(pByte, pData, nLen);
SafeArrayUnaccessData(psa);
V_VT(m_pvarValue) = VT_ARRAY | VT_UI1;
V_ARRAY(m_pvarValue) = psa;
}
else
SafeArrayDestroy(psa);
}
catch(...)
{
hr = E_OUTOFMEMORY;
goto Error;
}
psa = NULL;
};
Error:
if(pData)
{
delete [] pData;
pData = NULL;
}
return hr;
}
| 23.105682
| 152
| 0.602321
|
npocmaka
|
56068b094935639c12ba5efca575ca59056eb0b4
| 8,551
|
hpp
|
C++
|
Unidad 4/src/biblioteca/funciones/strings.hpp
|
Franeiro/AyED
|
a53142ac0c92fb74e62064e26fb4a4f86bace388
|
[
"Xnet",
"X11"
] | null | null | null |
Unidad 4/src/biblioteca/funciones/strings.hpp
|
Franeiro/AyED
|
a53142ac0c92fb74e62064e26fb4a4f86bace388
|
[
"Xnet",
"X11"
] | null | null | null |
Unidad 4/src/biblioteca/funciones/strings.hpp
|
Franeiro/AyED
|
a53142ac0c92fb74e62064e26fb4a4f86bace388
|
[
"Xnet",
"X11"
] | null | null | null |
#ifndef _TSTRINGS_T_
#define _TSTRINGS_T_
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
int length(string s)
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
}
return i;
}
int charCount(string s, char c)
{
int i, veces;
veces = 0;
for (i = 0; i < length(s); i++)
{
if (s[i] == c)
{
veces++;
}
}
return veces;
}
string substring(string s, int d, int h)
{
int i = 0;
string aux;
for (i = d; i < h; i++)
{
aux += s[i];
}
return aux;
}
string substring(string s, int d) // ok
{
int i = 0;
string aux;
for (i = d; i < length(s); i++)
{
aux += s[i];
}
return aux;
return "";
}
int indexOf(string s, char c) // ok
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
if (s[i] == c)
{
return i;
}
}
return -1;
}
int indexOf(string s, char c, int offSet) // ok
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
if (i > offSet && s[i] == c)
{
return i;
}
}
return 0;
}
int indexOf(string s, string toSearch)
{
int a, j = 0;
for (int i = 0; i <= length(s); i++)
{
if (s[i] == toSearch[0])
{
a = i;
while (s[i] == toSearch[j] && j < length(toSearch))
{
i++;
j++;
if (j == length(toSearch))
{
return a;
break;
}
}
i = a;
}
}
return -1;
}
int indexOf(string s, string toSearch, int offset) // ok
{
int i, a, j = 0;
for (i = 0; i <= length(s); i++)
{
if (i > offset && s[i] == toSearch[0])
{
a = i;
while (s[i] == toSearch[j] && j < length(toSearch))
{
i++;
j++;
if (j == length(toSearch))
{
return a;
break;
}
}
i = a;
}
}
return 0;
}
int lastIndexOf(string s, char c)
{
int i;
for (i = length(s); i >= 0; i--)
{
if (s[i] == c)
{
return i;
break;
}
}
return -1;
}
int indexOfN(string s, char c, int n)
{
int i, veces = 0;
for (i = 0; i <= length(s); i++)
{
if (s[i] == c)
{
veces++;
if (veces == n)
{
return i;
break;
}
}
}
return -1;
}
int charToInt(char c)
{
/*
int numero;
numero = c - 48;
return numero;
*/
int i = '0';
int n = c;
int resultado = n - i;
return resultado;
}
char intToChar(int i)
{
char caracter;
caracter = (i + 48);
return caracter;
}
int potencia(int x, int y) // CREO FUNCION PARA CALCULAR POTENCIAS
{
if (y == 0)
{
return 1;
}
else
{
if (int(y % 2) == 0)
{
return (potencia(x, int(y / 2)) * potencia(x, int(y / 2)));
}
else
{
return (x * potencia(x, int(y / 2)) * potencia(x, int(y / 2)));
}
}
}
int getDigit(int n, int i)
{
int p = potencia(10, i);
int q = n / p;
return q % 10;
}
int digitCount(int n)
{
int a = 0, t;
for (t = 0; n / (long)potencia(10, t) >= 1; t++)
{
a++;
}
return a;
}
string intToString(int i)
{
int n = digitCount(i);
string parse = "";
for (int j = 0; j < n; j++)
{
int f = (n - j) - 1;
int digito = getDigit(i, f);
char c = digito + 48;
parse += c;
}
return parse;
}
int stringToInt(string s, int b) // ok
{
int parseInt, j;
int longitud = length(s) - 1;
char i = 0;
for (j = longitud; j >= 0; j--)
{
int x;
if (s[j] >= '0' and s[j] <= '9')
{
x = '0';
}
else
{
x = 'A' - 10;
}
parseInt = parseInt + (s[j] - x) * potencia(b, i);
i++;
}
return parseInt;
}
int stringToInt(string s) // ok
{
int parseInt = 0, j = 0;
int longitud = length(s) - 1;
int i = 0;
for (j = longitud; j >= 0; j--)
{
parseInt = parseInt + (charToInt(s[j]) * potencia(10, i));
i++;
}
return parseInt;
}
string charToString(char c)
{
string a;
a += c;
return a;
}
char stringToChar(string s)
{
char a;
a = s[0];
return a;
}
string stringToString(string s)
{
string a;
a = s;
return a;
}
string doubleToString(double d) // saltear
{
char x[100];
sprintf(x, "%f", d); // esto es de lenguaje C, no se usa
string ret = x;
return ret;
}
double stringToDouble(string s) // No se hace
{
return 1.1;
}
bool isEmpty(string s)
{
bool a;
string verdad;
a = s == "";
if (a == 0)
{
verdad = "false";
}
else
{
verdad = "true";
}
return a;
}
bool startsWith(string s, string x)
{
int coincidencia;
for (int i = 0; i <= length(x); i++)
{
if (x[i] == s[i])
{
coincidencia++;
}
}
if (coincidencia == length(x))
{
return true;
}
else
{
return false;
}
}
bool endsWith(string s, string x)
{
int coincidencia;
int posX = length(x);
for (int i = length(s); posX >= 0; i--)
{
if (x[posX] == s[i])
{
coincidencia++;
}
posX--;
}
if (coincidencia - 1 == length(x))
{
return true;
}
else
{
return false;
}
}
bool contains(string s, char c)
{
int coincidencia;
for (int i = 0; i <= length(s); i++)
{
if (s[i] == c)
{
coincidencia = 1;
}
}
if (coincidencia == 1)
{
return true;
}
else
{
return false;
}
}
string replace(string s, char oldChar, char newChar)
{
for (int i = 0; i <= length(s); i++)
{
if (s[i] == oldChar)
{
s[i] = newChar;
}
}
return s;
}
string insertAt(string s, int pos, char c)
{
string r = substring(s, 0, pos) + c + substring(s, pos);
return r;
}
string removeAt(string s, int pos)
{
string r = substring(s, 0, pos) + substring(s, pos + 1);
return r;
}
string ltrim(string s)
{
int largo = length(s);
int i = 0;
while (s[i] == ' ')
{
i++;
}
return substring(s, i, largo);
}
string rtrim(string s)
{
int largo = length(s) - 1;
while (s[largo] == ' ')
{
largo--;
}
return substring(s, 0, largo + 1);
}
string trim(string s)
{
return rtrim(ltrim(s));
}
string replicate(char c, int n)
{
string a;
for (int i = 0; i <= n; i++)
{
a += c;
}
return a;
}
string spaces(int n)
{
string a;
for (int i = 0; i <= n; i++)
{
a += ' ';
}
return a;
}
string lpad(string s, int n, char c)
{
string a;
for (int i = 0; i <= n; i++)
{
a += c;
}
a += s;
return a;
}
string rpad(string s, int n, char c)
{
string a;
a += s;
for (int i = 0; i <= n; i++)
{
a += c;
}
return a;
}
string cpad(string s, int n, char c)
{
string a;
int espacio = (n - length(s));
for (int i = 0; i <= espacio; i++)
{
if (i < (espacio / 2))
{
a += c;
}
if (i == (espacio / 2))
{
a += s;
}
if (i > (espacio / 2))
{
a += c;
}
}
return a;
}
bool isDigit(char c)
{
if (c >= 48 && c <= 57)
{
return true;
}
else
{
return false;
}
}
bool isLetter(char c)
{
if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122))
{
return true;
}
else
{
return false;
}
}
bool isUpperCase(char c)
{
if ((c >= 65 && c <= 90))
{
return true;
}
else
{
return false;
}
}
bool isLowerCase(char c)
{
if ((c >= 97 && c <= 122))
{
return true;
}
else
{
return false;
}
}
char toUpperCase(char c)
{
if (c >= 97 && c <= 122)
{
c -= 32;
}
else
{
return c;
}
return c;
}
char toLowerCase(char c)
{
if (c >= 65 && c <= 90)
{
c += 32;
}
else
{
return c;
}
return c;
}
string toUpperCase(string s)
{
for (int i = 0; i <= length(s); i++)
{
if (s[i] >= 97 && s[i] <= 122)
{
s[i] -= 32;
}
else
{
s[i] = s[i];
}
}
return s;
}
string toLowerCase(string s)
{
for (int i = 0; i <= length(s); i++)
{
if (s[i] >= 65 && s[i] <= 90)
{
s[i] += 32;
}
else
{
s[i] = s[i];
}
}
return s;
}
#endif
| 12.303597
| 72
| 0.422758
|
Franeiro
|
5608f4ab3eee3af228771b5bf8b4f6f59e63929b
| 432
|
hpp
|
C++
|
inc/OptionParser.hpp
|
Aracthor/paranoidRM
|
1d7200090f18db7f152461f47afd63b0e4f7f02f
|
[
"MIT"
] | null | null | null |
inc/OptionParser.hpp
|
Aracthor/paranoidRM
|
1d7200090f18db7f152461f47afd63b0e4f7f02f
|
[
"MIT"
] | null | null | null |
inc/OptionParser.hpp
|
Aracthor/paranoidRM
|
1d7200090f18db7f152461f47afd63b0e4f7f02f
|
[
"MIT"
] | null | null | null |
//
// OptionParser.hpp for paranoidRM in /home/aracthor/programs/projects/paranoidRM
//
// Made by Aracthor
// Login <aracthor@epitech.net>
//
// Started on Mon Jun 8 20:05:10 2015 Aracthor
// Last Update Mon Jun 8 20:10:50 2015 Aracthor
//
char
OptionParser::getFlag() const
{
return (mFlag);
}
const char*
OptionParser::getName() const
{
return (mName);
}
bool
OptionParser::needArg() const
{
return (mNeedArg);
}
| 15.428571
| 81
| 0.69213
|
Aracthor
|
560acde3772fa021d6bf2942daf2b52dcf32eda5
| 563
|
cpp
|
C++
|
PhotonBox/src/component/SpotLight.cpp
|
strager/PhotonBox
|
aba8ad303012dd1ca75b7c00ab6b8d5fff2e4128
|
[
"MIT"
] | 118
|
2018-01-20T04:41:50.000Z
|
2022-03-27T12:52:19.000Z
|
PhotonBox/src/component/SpotLight.cpp
|
strager/PhotonBox
|
aba8ad303012dd1ca75b7c00ab6b8d5fff2e4128
|
[
"MIT"
] | 18
|
2017-12-03T02:13:08.000Z
|
2020-11-12T00:09:41.000Z
|
PhotonBox/src/component/SpotLight.cpp
|
strager/PhotonBox
|
aba8ad303012dd1ca75b7c00ab6b8d5fff2e4128
|
[
"MIT"
] | 13
|
2018-03-05T23:23:38.000Z
|
2021-07-19T22:33:04.000Z
|
#include "PhotonBox/component/SpotLight.h"
#include "PhotonBox/core/system/Lighting.h"
#include "PhotonBox/resource/shader/ForwardSpotLightShader.h"
#ifdef PB_MEM_DEBUG
#include "PhotonBox/util/MEMDebug.h"
#define new DEBUG_NEW
#endif
void SpotLight::init()
{
Lighting::addLight(this);
}
void SpotLight::destroy()
{
Lighting::removeLight(this);
}
Shader * SpotLight::getLightShader()
{
return ForwardSpotLightShader::getInstance();
}
void SpotLight::OnEnable()
{
Lighting::addLight(this);
}
void SpotLight::OnDisable()
{
Lighting::removeLight(this);
}
| 16.558824
| 61
| 0.756661
|
strager
|
560b1872dd11349dd3aa06f59fc9efe930c89299
| 3,079
|
cxx
|
C++
|
src/test/testMcClasses.cxx
|
fermi-lat/mcRootData
|
1529a12d481fe1db38bfa7bc02780303232eb15d
|
[
"BSD-3-Clause"
] | null | null | null |
src/test/testMcClasses.cxx
|
fermi-lat/mcRootData
|
1529a12d481fe1db38bfa7bc02780303232eb15d
|
[
"BSD-3-Clause"
] | null | null | null |
src/test/testMcClasses.cxx
|
fermi-lat/mcRootData
|
1529a12d481fe1db38bfa7bc02780303232eb15d
|
[
"BSD-3-Clause"
] | null | null | null |
#include <mcRootData/McEvent.h>
#include <commonRootData/RootDataUtil.h>
#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TTree.h"
#include "TRandom.h"
/** @file testMcClasses.cxx
* @brief This defines a test routine for the Monte Carlo ROOT classes.
*
* This program create a new Monte Carlo ROOT file, and the opens it up again
* for reading. The contents are checked against the values known to be stored
* during the original writing of the file.
* The contents of the file are printed to the screen.
* The program returns 0 if the test passed.
* If failure, the program returns -1.
*
* $Header$
*/
const UInt_t RUN_NUM = 1 ;
Float_t RAND_NUM ;
int read( char * fileName, unsigned int numEvents) {
// Purpose and Method: Read in the ROOT file just generated via the
// write method
TFile *f = new TFile(fileName, "READ");
TTree *t = (TTree*)f->Get("Mc");
McEvent *evt = 0;
t->SetBranchAddress("McEvent", &evt);
std::cout << "Opened the ROOT file for reading" << std::endl;
UInt_t iEvent ;
for ( iEvent = 0 ; iEvent < numEvents ; ++iEvent ) {
t->GetEvent(iEvent);
std::cout << "McEvent iEvent = " << iEvent << std::endl;
evt->Print() ;
// DC: I CANNOT MAKE A McEvent::Fake() and
// a McEvent::CompareInRange(), because McEvent
// is designed as a singleton.
if (!evt->CompareToFake(iEvent,RUN_NUM,RAND_NUM)) {
return -1 ;
}
}
f->Close();
delete f;
return(0);
}
/// Create a new ROOT file
int write( char * fileName, UInt_t numEvents ) {
Int_t buffer = 64000;
Int_t splitLevel = 1;
TFile *f = new TFile(fileName, "RECREATE");
TTree *t = new TTree("Mc", "Mc");
McEvent * evt = new McEvent() ;
t->Branch("McEvent", "McEvent", &evt, buffer, splitLevel);
std::cout << "Created new ROOT file" << std::endl;
UInt_t iEvent ;
for (iEvent = 0; iEvent < numEvents; iEvent++) {
evt->Fake(iEvent,RUN_NUM,RAND_NUM) ;
t->Fill() ;
}
std::cout << "Filled ROOT file with " << numEvents << " events" << std::endl;
delete evt ;
f->Write();
f->Close();
delete f;
return(0);
}
/// Main program
/// Return 0 for success.
/// Returns -1 for failure.
int main(int argc, char **argv) {
char *fileName = "mc.root";
int n =1 ;
unsigned int numEvents =10 ;
if (argc > 1) {
fileName = argv[n++];
}
if (argc > 2) {
numEvents = atoi(argv[n++]);
}
TRandom randGen ;
RAND_NUM = randGen.Rndm() ;
int sc = 0;
try
{
sc = write(fileName, numEvents);
sc = read(fileName, numEvents);
}
catch (...)
{
std::cout<<"AN UNKNOWN EXCEPTION HAS BEEN RAISED"<<std::endl ;
sc = 1 ;
}
if (sc == 0) {
std::cout << "MC ROOT file writing and reading suceeded!" << std::endl;
} else {
std::cout << "FAILED" << std::endl;
}
return(sc);
}
| 23.868217
| 81
| 0.566418
|
fermi-lat
|
560c318ccb48481b339258f541ef6ee72900450d
| 387
|
cpp
|
C++
|
src/server/src/ca_check.cpp
|
Eothred/hpsim
|
526a00a9d1affcb83b642ea2aef939925a76cad9
|
[
"Unlicense"
] | 6
|
2018-04-30T08:03:24.000Z
|
2021-11-10T00:17:34.000Z
|
src/server/src/ca_check.cpp
|
Eothred/hpsim
|
526a00a9d1affcb83b642ea2aef939925a76cad9
|
[
"Unlicense"
] | 1
|
2018-09-26T17:04:27.000Z
|
2018-09-26T17:35:04.000Z
|
src/server/src/ca_check.cpp
|
Eothred/hpsim
|
526a00a9d1affcb83b642ea2aef939925a76cad9
|
[
"Unlicense"
] | 4
|
2017-11-14T14:36:48.000Z
|
2020-01-14T13:51:16.000Z
|
#include <string>
#include <iostream>
#include "cadef.h"
bool CACheck(int r_status, std::string r_op, std::string r_pv)
{
if(r_status != ECA_NORMAL)
{
std::cerr << "CA Error: ";
if(r_pv.compare("") != 0)
std::cerr << r_op << " failure for PV: " << r_pv << std::endl;
else
std::cerr << r_op << " failure" << std::endl;
return false;
}
return true;
}
| 21.5
| 68
| 0.571059
|
Eothred
|
560d337df5e08c9730025627181dfee90cc5575b
| 5,309
|
cpp
|
C++
|
sandbox/src/main.cpp
|
backwardspy/leviathan
|
0b53656a5cca0b80d1ac0ae3f176f37948d0675f
|
[
"MIT"
] | null | null | null |
sandbox/src/main.cpp
|
backwardspy/leviathan
|
0b53656a5cca0b80d1ac0ae3f176f37948d0675f
|
[
"MIT"
] | null | null | null |
sandbox/src/main.cpp
|
backwardspy/leviathan
|
0b53656a5cca0b80d1ac0ae3f176f37948d0675f
|
[
"MIT"
] | null | null | null |
#include <leviathan/leviathan.h>
class CustomLayer : public lv::Layer {
public:
explicit CustomLayer(lv::Application& app) :
Layer("Custom"),
app(app),
window(app.get_window()),
ctx(app.get_render_context()),
ent_registry(app.get_ent_registry()),
camera(ent_registry.create()),
duck(ent_registry.create()) {
init_camera();
init_ducks();
}
private:
bool handle(lv::Event const& event) override {
switch (event.type) {
case lv::Event::Type::WindowResized:
ent_registry.get<lv::Camera>(camera).aspect_ratio = window.get_aspect_ratio();
break;
case lv::Event::Type::KeyPressed:
if (event.key.code == lv::KeyCode::Space) {
zoom_level = 0;
auto& [cam, transform] = ent_registry.get<lv::Camera, lv::Transform>(camera);
cam.ortho_size = 1.0f;
transform.position = glm::vec3(0);
}
break;
case lv::Event::Type::ButtonPressed:
if (event.button.code == lv::ButtonCode::Right) dragging = true;
break;
case lv::Event::Type::ButtonReleased:
if (event.button.code == lv::ButtonCode::Right) dragging = false;
break;
case lv::Event::Type::MouseMoved:
if (dragging) drag_camera(event.mouse.delta);
break;
case lv::Event::Type::MouseScrolled:
zoom_camera(static_cast<int>(event.mouse.delta.y));
break;
}
return false;
}
void gui() override {
auto const dt = lv::time::render_delta_time();
ImGui::Begin("Sandbox");
ImGui::Text("Performance: %.3f ms/frame (%.f fps)", lv::time::to_milliseconds(dt).count(), 1.0f / lv::time::to_seconds(dt).count());
ImGui::Text("Simulation Time: %.3f", lv::time::to_seconds(lv::time::elapsed()).count());
ImGui::End();
ImGui::Begin("Shader");
if (ImGui::ColorPicker4("Tint", glm::value_ptr(tint))) {
ent_registry.get<lv::MeshRenderer>(duck).material->set_parameter("Tint", tint);
}
ImGui::End();
}
void drag_camera(glm::vec2 mouse_delta) {
auto motion_ndc = 2.0f * mouse_delta / static_cast<glm::vec2>(window.get_size());
// usually we'd flip the Y, but since we're subtracting this motion anyway we flip the x instead
motion_ndc.x = -motion_ndc.x;
auto& [cam, transform] = ent_registry.get<lv::Camera, lv::Transform>(camera);
auto world_motion = cam.unproject(motion_ndc);
transform.position += glm::vec3(world_motion, 0);
}
void zoom_camera(int zoom) {
zoom_level += zoom;
auto mouse_pos = lv::remap(
lv::Input::get_mouse_position(),
glm::vec2(0),
static_cast<glm::vec2>(window.get_size()),
glm::vec2(-1),
glm::vec2(1)
);
mouse_pos.y = -mouse_pos.y;
auto& [cam, transform] = ent_registry.get<lv::Camera, lv::Transform>(camera);
auto pos_before = cam.unproject(mouse_pos);
cam.ortho_size = pow(1.1f, -zoom_level);
auto diff = pos_before - cam.unproject(mouse_pos);
transform.position += glm::vec3(diff, 0);
}
void init_camera() {
ent_registry.emplace<lv::Transform>(camera);
ent_registry.emplace<lv::Camera>(camera, lv::Camera::make_orthographic(1.0f, window.get_aspect_ratio()));
}
void init_ducks() {
auto shader = ctx.make_shader("assets/shaders/unlit_generic.glsl", { lv::Shader::Type::Vertex, lv::Shader::Type::Pixel });
shader->set_alpha_blend(true);
auto material = ctx.make_material(shader);
material->set_texture("MainTex", 0, ctx.make_texture("assets/textures/duck.png"));
material->set_parameter("Tint", tint);
auto vertex_array = [&ctx = ctx] {
return ctx.make_vertex_array(
{
lv::Vertex{ glm::vec3(-0.5f, 0.5f, 0), glm::vec4(1), glm::vec2(0) },
lv::Vertex{ glm::vec3(0.5f, 0.5f, 0), glm::vec4(1), glm::vec2(1, 0) },
lv::Vertex{ glm::vec3(-0.5f, -0.5f, 0), glm::vec4(1), glm::vec2(0, 1) },
lv::Vertex{ glm::vec3(0.5f, -0.5f, 0), glm::vec4(1), glm::vec2(1) },
}, {
0, 1, 2,
1, 3, 2
});
}();
ent_registry.emplace<lv::Transform>(duck);
ent_registry.emplace<lv::MeshRenderer>(duck, material, vertex_array);
}
private:
lv::Application& app;
lv::Window& window;
lv::Context& ctx;
entt::registry& ent_registry;
entt::entity camera, duck;
int zoom_level = 0;
bool dragging = false;
glm::vec2 drag_start {};
// shader params
glm::vec4 tint = glm::vec4(1.0f);
};
class Sandbox : public lv::Application {
protected:
virtual lv::LayerVector get_layers() override {
lv::LayerVector layers;
layers.push_back(lv::make_scope<CustomLayer>(*this));
return layers;
}
};
lv::scope<lv::Application> lv::CreateApplication() {
return lv::make_scope<Sandbox>();
}
| 35.15894
| 140
| 0.559427
|
backwardspy
|
560df1042a482b6fc705bf40aaae20c8924c6231
| 8,066
|
cpp
|
C++
|
test/math.t.cpp
|
ltjax/replay
|
33680beae225c9c388f33e3f7ffd7e8bae4643e9
|
[
"MIT"
] | 1
|
2015-09-15T19:52:50.000Z
|
2015-09-15T19:52:50.000Z
|
test/math.t.cpp
|
ltjax/replay
|
33680beae225c9c388f33e3f7ffd7e8bae4643e9
|
[
"MIT"
] | 3
|
2017-12-03T21:53:09.000Z
|
2019-11-23T02:11:50.000Z
|
test/math.t.cpp
|
ltjax/replay
|
33680beae225c9c388f33e3f7ffd7e8bae4643e9
|
[
"MIT"
] | null | null | null |
#include <catch2/catch.hpp>
#include <replay/math.hpp>
#include <replay/matrix2.hpp>
#include <replay/minimal_sphere.hpp>
#include <replay/vector_math.hpp>
#include <boost/math/constants/constants.hpp>
#include <random>
namespace
{
// FIXME: this is somewhat generically useful - lift it to a visible namespace?
replay::vector3f polar_to_model(float latitude, float longitude)
{
latitude = replay::math::convert_to_radians(latitude);
longitude = replay::math::convert_to_radians(longitude);
float cw = std::cos(latitude);
float sw = std::sin(latitude);
float ch = std::cos(longitude);
float sh = std::sin(longitude);
return {cw * ch, sw * ch, sh};
}
template <class IteratorType>
float distance_to_sphere(const IteratorType point_begin,
const IteratorType point_end,
const replay::vector3f& center,
const float square_radius)
{
float max_sqr_distance = 0.f;
for (IteratorType i = point_begin; i != point_end; ++i)
{
const float sqr_distance = (center - (*i)).squared();
max_sqr_distance = std::max(max_sqr_distance, sqr_distance);
}
float radius = std::sqrt(square_radius);
return std::max(0.f, std::sqrt(max_sqr_distance) - radius);
}
} // namespace
TEST_CASE("matrix2_operations")
{
using namespace replay;
matrix2 Rotation = matrix2::make_rotation(boost::math::constants::pi<float>() * 0.25f); // 45deg rotation
matrix2 Inv = Rotation;
REQUIRE(Inv.invert());
using math::fuzzy_equals;
using math::fuzzy_zero;
matrix2 I = Rotation * Inv;
// This should be identity
REQUIRE(fuzzy_equals(I[0], 1.f));
REQUIRE(fuzzy_zero(I[1]));
REQUIRE(fuzzy_zero(I[2]));
REQUIRE(fuzzy_equals(I[3], 1.f));
I = Inv * Rotation;
// This should be identity
REQUIRE(fuzzy_equals(I[0], 1.f));
REQUIRE(fuzzy_zero(I[1]));
REQUIRE(fuzzy_zero(I[2]));
REQUIRE(fuzzy_equals(I[3], 1.f));
}
// This test verifies integer arithmetic with a vector3.
// Hopefully, floating-point math will behave correct if this does.
TEST_CASE("vector3_integer_operations")
{
using namespace replay;
typedef vector3<int> vec3;
const vec3 a(-1, -67, 32);
const vec3 b(7777, 0, -111);
const vec3 c(a - b);
REQUIRE(c - a == -b);
const vec3 all_one(1, 1, 1);
REQUIRE(all_one.sum() == 3);
REQUIRE(all_one.squared() == 3);
int checksum = dot(a, all_one);
REQUIRE(checksum == a.sum());
checksum = dot(b, all_one);
REQUIRE(checksum == b.sum());
REQUIRE(a.sum() - b.sum() == c.sum());
REQUIRE((a * 42).sum()== a.sum() * 42);
const vec3 all_two(2, 2, 2);
REQUIRE(all_one * 2== all_two);
REQUIRE(all_one + all_one== all_two);
}
TEST_CASE("quadratic_equation_solver")
{
using namespace replay;
using range_type = std::uniform_real_distribution<float>;
// Attempt to solve a few equations of the form (x-b)(x-a)=0 <=> x^2+(-a-b)*x+b*a=0
std::mt19937 rng;
range_type range(-100.f, 300.f);
auto die = [&] { return range(rng); };
for (std::size_t i = 0; i < 32; ++i)
{
float a = die();
float b = die();
if (replay::math::fuzzy_equals(a, b))
continue;
interval<> r;
// FIXME: use a relative epsilon
math::solve_quadratic_eq(1.f, -a - b, a * b, r, 0.001f);
if (a > b)
std::swap(a, b);
REQUIRE(r[0] == Approx(a).margin(0.01f));
REQUIRE(r[1] == Approx(b).margin(0.01f));
}
}
TEST_CASE("matrix4_determinant_simple")
{
using namespace replay;
matrix4 M(0.f, 0.f, 3.f, 0.f, 4.f, 0.f, 0.f, 0.f, 0.f, 2.f, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f);
float d = M.determinant();
REQUIRE(d == Approx(24.f).margin(0.0001f));
matrix4 N(2.f, 1.f, 0.f, 0.f, 1.f, 2.f, 1.f, 0.f, 0.f, 1.f, 2.f, 1.f, 0.f, 0.f, 1.f, 2.f);
float e = N.determinant();
REQUIRE(e == Approx(5.f).margin(0.0001f));
}
TEST_CASE("circumcircle")
{
using namespace replay;
// Construct a rotational matrix
vector3f x = polar_to_model(177.f, -34.f);
vector3f y = normalized(math::construct_perpendicular(x));
matrix3 M(x, y, cross(x, y));
// Construct three points on a circle and rotate them
const float radius = 14.f;
float angle = math::convert_to_radians(34.f);
vector3f a = M * (vector3f(std::cos(angle), std::sin(angle), 0.f) * radius);
angle = math::convert_to_radians(134.f);
vector3f b = M * (vector3f(std::cos(angle), std::sin(angle), 0.f) * radius);
angle = math::convert_to_radians(270.f);
vector3f c = M * (vector3f(std::cos(angle), std::sin(angle), 0.f) * radius);
// Move the circle
const vector3f center(45.f, 32.f, -37.f);
a += center;
b += center;
c += center;
// Reconstruct it
equisphere<float, 3> s(1e-16f);
REQUIRE(s.push(a.ptr()));
REQUIRE(s.push(b.ptr()));
REQUIRE(s.push(c.ptr()));
vector3f equisphere_center(vector3f::cast(s.get_center()));
vector3f center_delta = center - equisphere_center;
REQUIRE(center_delta.squared() < 0.001f);
REQUIRE(std::sqrt(s.get_squared_radius()) == Approx(radius).margin(0.001f));
}
// Simple test case directly testing the minimal ball solver in 3D
TEST_CASE("minimal_ball")
{
using namespace replay;
typedef vector3f vec3;
using range_type = std::uniform_real_distribution<float>;
// setup random number generators
std::mt19937 rng;
auto random_latitude = [&] { return range_type(-180.f, 180.f)(rng); };
auto random_longitude = [&] { return range_type(-90.f, 90.f)(rng); };
auto random_scale = [&] { return range_type(0.f, 1.0f)(rng); };
// setup a simple point set
std::list<vec3> points{ vec3(1.f, 0.f, 0.f), vec3(0.f, 1.f, 0.f), vec3(0.f, 0.f, 1.f), vec3(0.f, -1.f, 0.f) };
for (std::size_t i = 0; i < 32; ++i)
{
vector3f t = polar_to_model(random_latitude(), random_longitude());
float s = random_scale();
points.push_back(t * s);
}
// run the solver
replay::minimal_ball<float, replay::vector3f, 3> ball(points, 1e-15f);
// check correctness
REQUIRE(ball.square_radius() == Approx(1.f).margin(0.001f));
REQUIRE(ball.center().squared() < 0.001f);
REQUIRE(distance_to_sphere(points.begin(), points.end(), ball.center(), ball.square_radius()) < 0.001f);
}
// Slightly more sophisticated test for the minimal ball routines using
// the wrapper from vector_math.hpp and an std::vector
TEST_CASE("minimal_sphere")
{
using namespace replay;
using range_type = std::uniform_real_distribution<float>;
std::mt19937 rng;
auto random_coord = [&] { return range_type(-100.f, 100.f)(rng); };
auto random_radius = [&] { return range_type(1.f, 3.f)(rng); };
auto random_latitude = [&] { return range_type(-180.f, 180.f)(rng); };
auto random_longitude = [&] { return range_type(-90.f, 90.f)(rng); };
auto random_scale = [&] { return range_type(0.0f, 1.0f)(rng); };
std::vector<vector3f> p(64);
for (std::size_t i = 0; i < 16; ++i)
{
const vector3f center(random_coord(), random_coord(), random_coord());
const float radius = random_radius();
std::size_t boundary_n = 2 + rng() % 3;
for (std::size_t j = 0; j < boundary_n; ++j)
p[j] = center + polar_to_model(random_latitude(), random_longitude()) * radius;
for (std::size_t j = boundary_n; j < 64; ++j)
p[j] = center + polar_to_model(random_latitude(), random_longitude()) * (random_scale() * radius);
std::shuffle(p.begin(), p.end(), rng);
auto const [result_center, result_square_radius] = math::minimal_sphere(p);
float square_radius = radius * radius;
// The generated boundary doesn't necessarily define the minimal ball, but it's an upper bound
REQUIRE(result_square_radius <= Approx(square_radius).margin(0.0001));
REQUIRE(distance_to_sphere(p.begin(), p.end(), result_center, result_square_radius) < 0.001f);
}
}
| 31.263566
| 114
| 0.621994
|
ltjax
|
56139a49800d5032c797beff52bcc9559e664d2b
| 4,059
|
cpp
|
C++
|
WebKit/Source/WebCore/platform/graphics/skia/BitLockerSkia.cpp
|
JavaScriptTesting/LJS
|
9818dbdb421036569fff93124ac2385d45d01c3a
|
[
"Apache-2.0"
] | 1
|
2019-06-18T06:52:54.000Z
|
2019-06-18T06:52:54.000Z
|
WebKit/Source/WebCore/platform/graphics/skia/BitLockerSkia.cpp
|
JavaScriptTesting/LJS
|
9818dbdb421036569fff93124ac2385d45d01c3a
|
[
"Apache-2.0"
] | null | null | null |
WebKit/Source/WebCore/platform/graphics/skia/BitLockerSkia.cpp
|
JavaScriptTesting/LJS
|
9818dbdb421036569fff93124ac2385d45d01c3a
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "BitLockerSkia.h"
#include "IntRect.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkRegion.h"
#include <CoreGraphics/CoreGraphics.h>
namespace WebCore {
static CGAffineTransform SkMatrixToCGAffineTransform(const SkMatrix& matrix)
{
// CGAffineTransforms don't support perspective transforms, so make sure
// we don't get those.
ASSERT(!matrix[SkMatrix::kMPersp0]);
ASSERT(!matrix[SkMatrix::kMPersp1]);
ASSERT(matrix[SkMatrix::kMPersp2] == 1.0f);
return CGAffineTransformMake(
matrix[SkMatrix::kMScaleX],
matrix[SkMatrix::kMSkewY],
matrix[SkMatrix::kMSkewX],
matrix[SkMatrix::kMScaleY],
matrix[SkMatrix::kMTransX],
matrix[SkMatrix::kMTransY]);
}
BitLockerSkia::BitLockerSkia(SkCanvas* canvas)
: m_canvas(canvas)
, m_cgContext(0)
{
}
BitLockerSkia::~BitLockerSkia()
{
releaseIfNeeded();
}
void BitLockerSkia::releaseIfNeeded()
{
if (!m_cgContext)
return;
m_canvas->getDevice()->accessBitmap(true).unlockPixels();
CGContextRelease(m_cgContext);
m_cgContext = 0;
}
CGContextRef BitLockerSkia::cgContext()
{
SkDevice* device = m_canvas->getDevice();
ASSERT(device);
if (!device)
return 0;
releaseIfNeeded();
const SkBitmap& bitmap = device->accessBitmap(true);
bitmap.lockPixels();
void* pixels = bitmap.getPixels();
m_cgContext = CGBitmapContextCreate(pixels, device->width(),
device->height(), 8, bitmap.rowBytes(), CGColorSpaceCreateDeviceRGB(),
kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst);
// Apply device matrix.
CGAffineTransform contentsTransform = CGAffineTransformMakeScale(1, -1);
contentsTransform = CGAffineTransformTranslate(contentsTransform, 0, -device->height());
CGContextConcatCTM(m_cgContext, contentsTransform);
// Apply clip in device coordinates.
CGMutablePathRef clipPath = CGPathCreateMutable();
SkRegion::Iterator iter(m_canvas->getTotalClip());
for (; !iter.done(); iter.next()) {
IntRect rect = iter.rect();
CGPathAddRect(clipPath, 0, rect);
}
CGContextAddPath(m_cgContext, clipPath);
CGContextClip(m_cgContext);
CGPathRelease(clipPath);
// Apply content matrix.
const SkMatrix& skMatrix = m_canvas->getTotalMatrix();
CGAffineTransform affine = SkMatrixToCGAffineTransform(skMatrix);
CGContextConcatCTM(m_cgContext, affine);
return m_cgContext;
}
}
| 33.825
| 92
| 0.725055
|
JavaScriptTesting
|
5618e356badef6dedb972f4a7c2ea09ff7dbfcd2
| 275
|
hpp
|
C++
|
src/modules/osg/generated_code/vector_less__bool__greater_.pypp.hpp
|
JaneliaSciComp/osgpyplusplus
|
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
|
[
"BSD-3-Clause"
] | 17
|
2015-06-01T12:19:46.000Z
|
2022-02-12T02:37:48.000Z
|
src/modules/osg/generated_code/vector_less__bool__greater_.pypp.hpp
|
cmbruns/osgpyplusplus
|
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
|
[
"BSD-3-Clause"
] | 7
|
2015-07-04T14:36:49.000Z
|
2015-07-23T18:09:49.000Z
|
src/modules/osg/generated_code/vector_less__bool__greater_.pypp.hpp
|
cmbruns/osgpyplusplus
|
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
|
[
"BSD-3-Clause"
] | 7
|
2015-11-28T17:00:31.000Z
|
2020-01-08T07:00:59.000Z
|
// This file has been generated by Py++.
#ifndef vector_less__bool__greater__hpp__pyplusplus_wrapper
#define vector_less__bool__greater__hpp__pyplusplus_wrapper
void register_vector_less__bool__greater__class();
#endif//vector_less__bool__greater__hpp__pyplusplus_wrapper
| 30.555556
| 59
| 0.887273
|
JaneliaSciComp
|
562072287f24126f19d8fae38014768b89bbfb53
| 6,232
|
cpp
|
C++
|
EndGame/EndGame/Src/SubSystems/RenderSubSystem/Renderer2D.cpp
|
siddharthgarg4/EndGame
|
ba608714b3eacb5dc05d0c852db573231c867d8b
|
[
"MIT"
] | null | null | null |
EndGame/EndGame/Src/SubSystems/RenderSubSystem/Renderer2D.cpp
|
siddharthgarg4/EndGame
|
ba608714b3eacb5dc05d0c852db573231c867d8b
|
[
"MIT"
] | null | null | null |
EndGame/EndGame/Src/SubSystems/RenderSubSystem/Renderer2D.cpp
|
siddharthgarg4/EndGame
|
ba608714b3eacb5dc05d0c852db573231c867d8b
|
[
"MIT"
] | null | null | null |
//
// Renderer2D.cpp
//
//
// Created by Siddharth on 09/07/20.
//
#include "Renderer2D.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <EndGame/Src/SubSystems/RenderSubSystem/RenderCommand.h>
#include <EndGame/Src/SubSystems/RenderSubSystem/RenderApiFactory.hpp>
namespace EndGame {
Renderer2DStorage *Renderer2D::storage = nullptr;
void Renderer2D::init() {
//init storage
storage = new Renderer2DStorage();
storage->quadVertexArray = RenderApiFactory::createVertexArray();
//vertex buffer
storage->quadVertexBuffer = RenderApiFactory::createVertexBuffer(storage->maxQuadVerticesPerDraw * sizeof(QuadVertexData));
storage->quadVertexBuffer->setLayout({
{ShaderDataType::Float3, "attrPosition"},
{ShaderDataType::Float4, "attrColor"},
{ShaderDataType::Float2, "attrTextureCoord"},
{ShaderDataType::Float, "attrTextureIndex"},
{ShaderDataType::Float, "attrTilingFactor"}
});
storage->quadVertexArray->addVertexBuffer(storage->quadVertexBuffer);
//index buffer
uint32_t *quadIndices = new uint32_t[storage->maxQuadIndicesPerDraw];
for (uint32_t offset=0, i=0; i<storage->maxQuadIndicesPerDraw; i+=6) {
quadIndices[i+0] = offset+0;
quadIndices[i+1] = offset+1;
quadIndices[i+2] = offset+2;
quadIndices[i+3] = offset+2;
quadIndices[i+4] = offset+3;
quadIndices[i+5] = offset+0;
offset+=4;
}
std::shared_ptr<IndexBuffer> quadIndexBuffer = RenderApiFactory::createIndexBuffer(storage->maxQuadIndicesPerDraw * sizeof(uint32_t), quadIndices);
storage->quadVertexArray->setIndexBuffer(quadIndexBuffer);
delete[] quadIndices;
//shader
storage->quadShader = RenderApiFactory::createShader("Sandbox/Quad.glsl");
storage->quadShader->bind();
//setting sampler slots
std::shared_ptr<int32_t> samplers(new int32_t[storage->maxFragmentTextureSlots], std::default_delete<int[]>());
for (int32_t i=0; i<storage->maxFragmentTextureSlots; i++) {
samplers.get()[i] = i;
}
storage->quadShader->uploadUniform("u_textures", samplers, storage->maxFragmentTextureSlots);
}
void Renderer2D::shutdown() {
delete storage;
}
void Renderer2D::beginScene(const OrthographicCamera &camera) {
storage->quadShader->bind();
storage->quadShader->uploadUniform("u_viewProjection", camera.getViewProjectionMatrix());
beginNewBatch();
}
void Renderer2D::endScene() {
flushVertexBuffer();
}
void Renderer2D::flushVertexBuffer() {
//sort quadVertexBufferData by z-index to render textures with lower z index first
std::sort(storage->quadVertexBufferData.begin(), storage->quadVertexBufferData.begin() + storage->quadVertexBufferDataSize, [](const QuadVertexData &first, const QuadVertexData &second){
return first.position.z < second.position.z;
});
storage->quadShader->bind();
storage->quadVertexBuffer->setData(storage->quadVertexBufferDataSize * sizeof(QuadVertexData), storage->quadVertexBufferData.data());
storage->quadVertexArray->bind();
//bind all texture slots
for (uint32_t i=0; i<storage->textureSlotsDataSize; i++) {
storage->textureSlots[i]->bind(i);
}
//each quad is 6 indices (2 triangles)
uint32_t numberOfQuads = storage->quadVertexBufferDataSize/4;
RenderCommand::drawIndexed(storage->quadVertexArray, numberOfQuads*6);
}
void Renderer2D::drawQuad(QuadRendererData data, bool shouldRotate) {
//pushing to local buffer until data can be accomodated
if (storage->quadVertexBufferDataSize >= storage->maxQuadVerticesPerDraw ||
storage->textureSlotsDataSize >= storage->maxFragmentTextureSlots) {
//flush if we reach max quads or max textures
flushVertexBuffer();
beginNewBatch();
}
//transforms
glm::mat4 transform = glm::translate(glm::mat4(1.0f), data.position);
if (shouldRotate) {
transform *= glm::rotate(glm::mat4(1.0f), glm::radians(data.rotation), {0, 0, 1});
}
transform *= glm::scale(glm::mat4(1.0f), {data.size.x, data.size.y, 1.0f});
//textures - switch in shader defaults to no texture
float textureIndex = -1.0f;
if (data.texture != nullptr) {
//if quad has texture
for (uint32_t i=0; i<storage->textureSlotsDataSize; i++) {
if (*storage->textureSlots[i].get() == *data.texture.get()) {
textureIndex = (float)i;
break;
}
}
//texture hasn't been used before
if (textureIndex == -1.0f) {
textureIndex = (float)storage->textureSlotsDataSize;
addTextureSlot(data.texture);
}
}
addQuadVertexData(QuadVertexData(transform * storage->quadVertexDefaultPositions[0], data.color, {0.0f, 0.0f}, textureIndex, data.tilingFactor));
addQuadVertexData(QuadVertexData(transform * storage->quadVertexDefaultPositions[1], data.color, {1.0f, 0.0f}, textureIndex, data.tilingFactor));
addQuadVertexData(QuadVertexData(transform * storage->quadVertexDefaultPositions[2], data.color, {1.0f, 1.0f}, textureIndex, data.tilingFactor));
addQuadVertexData(QuadVertexData(transform * storage->quadVertexDefaultPositions[3], data.color, {0.0f, 1.0f}, textureIndex, data.tilingFactor));
}
void Renderer2D::beginNewBatch() {
storage->quadVertexBufferDataSize = 0;
storage->textureSlotsDataSize = 0;
}
void Renderer2D::addQuadVertexData(const QuadVertexData &data) {
storage->quadVertexBufferData[storage->quadVertexBufferDataSize] = data;
storage->quadVertexBufferDataSize++;
}
void Renderer2D::addTextureSlot(std::shared_ptr<Texture2D> texture) {
storage->textureSlots[storage->textureSlotsDataSize] = texture;
storage->textureSlotsDataSize++;
}
}
| 45.823529
| 194
| 0.648748
|
siddharthgarg4
|
56223febd33a024d24f2bee3f67e5889466d8b60
| 1,923
|
cpp
|
C++
|
intro/knight_scape.cpp
|
eder-matheus/programming_challenges
|
9d318bf5b8df18f732c07e60aa72b302ea887419
|
[
"BSD-3-Clause"
] | null | null | null |
intro/knight_scape.cpp
|
eder-matheus/programming_challenges
|
9d318bf5b8df18f732c07e60aa72b302ea887419
|
[
"BSD-3-Clause"
] | null | null | null |
intro/knight_scape.cpp
|
eder-matheus/programming_challenges
|
9d318bf5b8df18f732c07e60aa72b302ea887419
|
[
"BSD-3-Clause"
] | 1
|
2021-08-24T17:18:54.000Z
|
2021-08-24T17:18:54.000Z
|
// knight scape
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
const int dimension = 8;
const int num_pieces = 9;
void findKnightMoviments(int row, int col, std::vector<std::pair<int, int> >& movements) {
for (int r = -2; r <= 2; r++) {
for (int c = -2; c <= 2; c++) {
if ((abs(r) == 2 && abs(c) == 1) ||
(abs(r) == 1 && abs(c) == 2)) {
if (((row + r) >= 0 && (row + r) < dimension) &&
((col + c) >= 0 && (col + c) < dimension)) {
movements.push_back(std::pair<int, int>(row+r, col+c));
}
}
}
}
}
void findPawnsAttacks(int row, int col, std::vector<std::pair<int, int> >& movements) {
int attack_row = row - 1;
int attack_col1 = col + 1;
int attack_col2 = col - 1;
if (attack_row < dimension) {
if (attack_col1 < dimension) {
movements.erase(
std::remove(
movements.begin(),
movements.end(),
std::pair<int, int>(attack_row, attack_col1)),
movements.end());
}
if (attack_col2 >= 0) {
movements.erase(
std::remove(
movements.begin(),
movements.end(),
std::pair<int, int>(attack_row, attack_col2)),
movements.end());
}
}
}
int main() {
int row = -1;
char column;
std::vector<std::pair<int, int> > movements;
int cnt = 0;
int test = 1;
while (row != 0) {
scanf("%d%c", &row, &column);
int col = (int)column - 96;
// first row of input --> knight position
if (cnt == 0) {
findKnightMoviments(row-1, col-1, movements);
} else { // other rows --> pawns position
findPawnsAttacks(row-1, col-1, movements);
}
cnt++;
if (cnt == num_pieces) {
std::cout << "Caso de Teste #" << test << ": " << movements.size() << " movimento(s).\n";
cnt = 0;
test++;
movements.clear();
}
}
return 0;
}
| 24.341772
| 95
| 0.514301
|
eder-matheus
|
5622aa0f33e74cba4f4bb881ff2fc714394f2d5d
| 4,264
|
cpp
|
C++
|
wnd/block_info_dlg.cpp
|
HyperBlockChain/Hyperchain-Core-YH
|
2a7c4ac23f27c2034a678e61c2474e0008f5135e
|
[
"MIT"
] | 1
|
2019-08-30T07:36:33.000Z
|
2019-08-30T07:36:33.000Z
|
wnd/block_info_dlg.cpp
|
HyperBlockChain/Hyperchain-Core-YH
|
2a7c4ac23f27c2034a678e61c2474e0008f5135e
|
[
"MIT"
] | null | null | null |
wnd/block_info_dlg.cpp
|
HyperBlockChain/Hyperchain-Core-YH
|
2a7c4ac23f27c2034a678e61c2474e0008f5135e
|
[
"MIT"
] | 2
|
2019-11-01T03:39:57.000Z
|
2020-03-26T06:21:22.000Z
|
/*Copyright 2016-2018 hyperchain.net (Hyperchain)
Distributed under the MIT software license, see the accompanying
file COPYING or https://opensource.org/licenses/MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "block_info_dlg.h"
#include "customui/base_frameless_wnd.h"
#include "channel/block_info_channel.h"
#include <QTextCodec>
#include <QtWebEngineWidgets/QWebEngineSettings>
#include <QtWebEngineWidgets/QWebEngineView>
#include <QtWebChannel/QWebChannel>
#include <QApplication>
#include <QVariantMap>
#include <QDebug>
block_info_dlg::block_info_dlg(QObject *parent) : QObject(parent)
{
QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8"));
init();
}
void block_info_dlg::show(bool bShow)
{
dlg_->setHidden(!bShow);
}
void block_info_dlg::setGeometry(QRect rect)
{
dlg_->setGeometry(rect);
}
void block_info_dlg::refreshNodeInfo(QSharedPointer<TBLOCKINFO> pNodeInfo)
{
static int64 MAX_TIME_S = 9999999999;
QVariantMap m;
m["blockNum"] = (qint64)(pNodeInfo->iBlockNo);
m["fileName"] = QString::fromStdString(pNodeInfo->tPoeRecordInfo.cFileName);
m["customInfo"] = QString::fromStdString(pNodeInfo->tPoeRecordInfo.cCustomInfo);
m["rightOwner"] = QString::fromStdString(pNodeInfo->tPoeRecordInfo.cRightOwner);
m["fileHash"] = QString::fromStdString(pNodeInfo->tPoeRecordInfo.cFileHash);
m["regTime"] = (qint64)(pNodeInfo->tPoeRecordInfo.tRegisTime);
m["fileSize"] = (qint64)(pNodeInfo->tPoeRecordInfo.iFileSize);
m["fileState"] = pNodeInfo->tPoeRecordInfo.iFileState;
emit reg_->sigNewBlockInfo(m);
}
bool block_info_dlg::hasFcous()
{
return dlg_->hasFocus();
}
void block_info_dlg::setFocus()
{
dlg_->setFocus();
}
void block_info_dlg::setLanguage(int lang)
{
reg_->sigChangeLang(lang);
}
void block_info_dlg::onMouseEnter(QEvent *event)
{
mouseEnter_ = true;
}
void block_info_dlg::onMouseLeave(QEvent *event)
{
mouseEnter_ = false;
dlg_->hide();
}
void block_info_dlg::init()
{
dlg_ = QSharedPointer<base_frameless_wnd>(new base_frameless_wnd());
dlg_->setScale(false);
dlg_->showTitleBar(false);
dlg_->setGeometry(QRect(0,0,200,300));
dlg_->hide();
connect(dlg_.data(), &base_frameless_wnd::sigEnter, this, &block_info_dlg::onMouseEnter);
connect(dlg_.data(), &base_frameless_wnd::sigLeave, this, &block_info_dlg::onMouseLeave);
Qt::WindowFlags flags = dlg_->windowFlags();
flags |= Qt::ToolTip;
dlg_->setWindowFlags(flags);
view_ = new QWebEngineView((QWidget*)dlg_.data()->content_);
view_->setAcceptDrops(false);
dlg_->addWidget(view_);
QWebChannel *channel = new QWebChannel(this);
reg_ = new block_info_channel(this);
channel->registerObject(QString("qBlockInfo"), reg_);
view_->page()->setWebChannel(channel);
#ifdef QT_DEBUG
#if defined (Q_OS_WIN)
QString str = QString("file:///%1/%2").arg(QApplication::applicationDirPath()).arg("../../ui/view/blockinfo.html");
#else
QString str = QString("file:///%1/%2").arg(QApplication::applicationDirPath()).arg("../ui/view/blockinfo.html");
#endif
#else
QString str = QString("file:///%1/%2").arg(QApplication::applicationDirPath()).arg("ui/view/blockinfo.html");
#endif
view_->page()->load(QUrl(str));
}
| 30.457143
| 123
| 0.739212
|
HyperBlockChain
|
56275bb9eac3f7c05bcc5aaabc4a9261e55c7d7f
| 26,432
|
cpp
|
C++
|
code_reading/oceanbase-master/unittest/sql/engine/sort/ob_sort_test.cpp
|
wangcy6/weekly_read
|
3a8837ee9cd957787ee1785e4066dd623e02e13a
|
[
"Apache-2.0"
] | null | null | null |
code_reading/oceanbase-master/unittest/sql/engine/sort/ob_sort_test.cpp
|
wangcy6/weekly_read
|
3a8837ee9cd957787ee1785e4066dd623e02e13a
|
[
"Apache-2.0"
] | null | null | null |
code_reading/oceanbase-master/unittest/sql/engine/sort/ob_sort_test.cpp
|
wangcy6/weekly_read
|
3a8837ee9cd957787ee1785e4066dd623e02e13a
|
[
"Apache-2.0"
] | 1
|
2020-10-18T12:59:31.000Z
|
2020-10-18T12:59:31.000Z
|
/**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include "sql/engine/sort/ob_sort.h"
#include "sql/session/ob_sql_session_info.h"
#include "sql/engine/ob_physical_plan.h"
#include "lib/utility/ob_test_util.h"
#include "lib/utility/ob_tracepoint.h"
#include "lib/container/ob_se_array.h"
#include <gtest/gtest.h>
#include "ob_fake_table.h"
#include "sql/engine/ob_exec_context.h"
#include "share/ob_worker.h"
#include "observer/ob_signal_handle.h"
#include "storage/blocksstable/ob_data_file_prepare.h"
#include "observer/omt/ob_tenant_config_mgr.h"
#include <thread>
#include <vector>
#include <gtest/gtest.h>
using namespace oceanbase;
using namespace oceanbase::sql;
using namespace oceanbase::omt;
using namespace oceanbase::common;
using oceanbase::sql::test::ObFakeTable;
#define TEST_SORT_DUMP_GET_HASH_AREA_SIZE() (get_sort_area_size())
#define TEST_SORT_DUMP_SET_HASH_AREA_SIZE(size) (set_sort_area_size(size))
class ObSortTest : public blocksstable::TestDataFilePrepare {
public:
ObSortTest();
virtual ~ObSortTest();
private:
// disallow copy
ObSortTest(const ObSortTest& other);
ObSortTest& operator=(const ObSortTest& other);
protected:
virtual void SetUp() override
{
GCONF.enable_sql_operator_dump.set_value("True");
ASSERT_EQ(OB_SUCCESS, init_tenant_mgr());
blocksstable::TestDataFilePrepare::SetUp();
}
virtual void TearDown() override
{
blocksstable::TestDataFilePrepare::TearDown();
destroy_tenant_mgr();
}
int init_tenant_mgr();
int64_t get_sort_area_size()
{
int64_t sort_area_size = 0;
int ret = OB_SUCCESS;
ret = ObSqlWorkareaUtil::get_workarea_size(SORT_WORK_AREA, OB_SYS_TENANT_ID, sort_area_size);
if (OB_FAIL(ret)) {
SQL_ENG_LOG(WARN, "failed to get hash area size", K(ret), K(sort_area_size));
}
return sort_area_size;
}
void set_sort_area_size(int64_t size)
{
int ret = OB_SUCCESS;
int64_t tenant_id = OB_SYS_TENANT_ID;
ObTenantConfigGuard tenant_config(TENANT_CONF(tenant_id));
if (tenant_config.is_valid()) {
tenant_config->_sort_area_size = size;
} else {
ret = OB_ERR_UNEXPECTED;
SQL_ENG_LOG(WARN, "unexpected status: config is invalid", K(tenant_id));
}
// ASSERT_EQ(OB_SUCCESS, ret);
}
void destroy_tenant_mgr()
{
ObTenantManager::get_instance().destroy();
}
template <typename SortInit>
void sort_test(int64_t row_count, int64_t mem_limit, SortInit sort_init, int64_t verify_row_cnt = -1,
bool local_merge_sort = false);
void sort_test(int64_t row_count, int64_t mem_limit, int64_t sort_col1, ObCollationType cs_type1, int64_t sort_col2,
ObCollationType cs_type2);
void local_merge_sort_test(int64_t row_count, int64_t mem_limit, int64_t sort_col1, ObCollationType cs_type1,
int64_t sort_col2, ObCollationType cs_type2);
void serialize_test();
void sort_exception_test(int expect_ret);
private:
static void copy_cell_varchar(ObObj& cell, char* buf, int64_t buf_size)
{
ObString str;
ASSERT_EQ(OB_SUCCESS, cell.get_varchar(str));
ASSERT_TRUE(str.length() < buf_size);
memcpy(buf, str.ptr(), str.length());
str.assign_ptr(buf, str.length());
cell.set_varchar(str);
return;
}
void cons_op_schema_objs(const ObIArray<ObSortColumn>& sort_columns, ObIArray<ObOpSchemaObj>& op_schema_objs)
{
for (int64_t i = 0; i < sort_columns.count(); i++) {
ObOpSchemaObj op_schema_obj;
if (0 == sort_columns.at(i).index_) {
op_schema_obj.obj_type_ = common::ObVarcharType;
} else {
op_schema_obj.obj_type_ = common::ObIntType;
}
op_schema_objs.push_back(op_schema_obj);
}
return;
}
};
class ObSortPlan {
public:
static ObSort& get_instance()
{
return *sort_;
}
template <typename SortInit>
static int init(int64_t row_count, int64_t mem_limit, SortInit sort_init)
{
if (mem_limit <= 0) {
mem_limit = 1 << 20;
}
int ret = OB_SUCCESS;
sort_->set_id(0);
input_table_->set_id(1);
sort_->set_column_count(input_table_->get_column_count());
sort_->set_mem_limit(mem_limit);
int64_t tenant_id = OB_SYS_TENANT_ID;
ObTenantConfigGuard tenant_config(TENANT_CONF(tenant_id));
if (tenant_config.is_valid()) {
tenant_config->_sort_area_size = mem_limit;
} else {
ret = OB_ERR_UNEXPECTED;
SQL_ENG_LOG(WARN, "unexpected status: config is invalid", K(tenant_id));
}
cons_run_filename(*filename_);
input_table_->set_row_count(row_count);
input_table_->set_phy_plan(physical_plan_);
sort_->set_phy_plan(physical_plan_);
row_count_ = row_count;
if (OB_FAIL(sort_->set_child(0, *input_table_))) {
} else if (OB_FAIL(sort_init(*sort_))) {
}
return ret;
}
static void set_local_merge_sort()
{
sort_->set_local_merge_sort(true);
}
static int init(int64_t row_count, int64_t mem_limit, int64_t sort_col1, ObCollationType cs_type1, int64_t sort_col2,
ObCollationType cs_type2)
{
return init(row_count, mem_limit, [&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col1, cs_type1, false, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col2, cs_type2, true, ObMaxType, default_asc_direction()))) {
}
return ret;
});
}
static void reset()
{
sort_->reset();
input_table_->reset();
row_count_ = -1;
}
static void reuse()
{
sort_->reuse();
input_table_->reuse();
row_count_ = -1;
}
private:
ObSortPlan();
static void cons_run_filename(ObString& filename)
{
char* filename_buf = (char*)"ob_sort_test.run";
filename.assign_ptr(filename_buf, (int32_t)strlen(filename_buf));
return;
}
public:
private:
static ObPhysicalPlan* physical_plan_;
static ObFakeTable* input_table_;
static ObSort* sort_;
static int64_t row_count_;
static ObString* filename_;
};
ObSortTest::ObSortTest() : blocksstable::TestDataFilePrepare("TestDiskIR", 2 << 20, 2000)
{}
ObSortTest::~ObSortTest()
{}
int ObSortTest::init_tenant_mgr()
{
int ret = OB_SUCCESS;
ObTenantManager& tm = ObTenantManager::get_instance();
ObAddr self;
oceanbase::rpc::frame::ObReqTransport req_transport(NULL, NULL);
oceanbase::obrpc::ObSrvRpcProxy rpc_proxy;
oceanbase::obrpc::ObCommonRpcProxy rs_rpc_proxy;
oceanbase::share::ObRsMgr rs_mgr;
int64_t tenant_id = 1;
self.set_ip_addr("127.0.0.1", 8086);
ret = ObTenantConfigMgr::get_instance().add_tenant_config(tenant_id);
EXPECT_EQ(OB_SUCCESS, ret);
ret = tm.init(self, rpc_proxy, rs_rpc_proxy, rs_mgr, &req_transport, &ObServerConfig::get_instance());
EXPECT_EQ(OB_SUCCESS, ret);
ret = tm.add_tenant(tenant_id);
EXPECT_EQ(OB_SUCCESS, ret);
ret = tm.set_tenant_mem_limit(tenant_id, 2L * 1024L * 1024L * 1024L, 4L * 1024L * 1024L * 1024L);
EXPECT_EQ(OB_SUCCESS, ret);
ret = tm.add_tenant(OB_SYS_TENANT_ID);
EXPECT_EQ(OB_SUCCESS, ret);
ret = tm.add_tenant(OB_SERVER_TENANT_ID);
EXPECT_EQ(OB_SUCCESS, ret);
const int64_t ulmt = 128LL << 30;
const int64_t llmt = 128LL << 30;
ret = tm.set_tenant_mem_limit(OB_SYS_TENANT_ID, ulmt, llmt);
EXPECT_EQ(OB_SUCCESS, ret);
oceanbase::lib::set_memory_limit(128LL << 32);
return ret;
}
#define BEGIN_THREAD_CODE_V2(num) \
{ \
std::vector<std::thread*> _threads; \
for (int _i = 0; _i < (num); _i++) _threads.push_back(new std::thread([&]
#define END_THREAD_CODE_V2() )); \
for (auto t : _threads) \
t->join(); \
}
template <typename SortInit>
void ObSortTest::sort_test(
int64_t row_count, int64_t mem_limit, SortInit sort_init, int64_t verify_row_cnt, bool local_merge_sort)
{
ASSERT_EQ(OB_SUCCESS, ObSortPlan::init(row_count, mem_limit, sort_init));
if (local_merge_sort) {
ObSortPlan::set_local_merge_sort();
}
BEGIN_THREAD_CODE_V2(2)
{
ObExecContext exec_ctx;
ASSERT_EQ(OB_SUCCESS, exec_ctx.init_phy_op(2));
ASSERT_EQ(OB_SUCCESS, exec_ctx.create_physical_plan_ctx());
ObSQLSessionInfo my_session;
my_session.test_init(0, 0, 0, NULL);
my_session.init_tenant("sys", 1);
exec_ctx.set_my_session(&my_session);
THIS_WORKER.set_timeout_ts(ObTimeUtility::current_time() + 600000000);
// do sort.
ObSort& sort = ObSortPlan::get_instance();
ASSERT_EQ(OB_SUCCESS, sort.open(exec_ctx));
auto& sort_columns = sort.get_sort_columns();
ObSEArray<ObOpSchemaObj, 8> op_schema_objs;
cons_op_schema_objs(sort_columns, op_schema_objs);
sort.get_op_schema_objs_for_update().assign(op_schema_objs);
ObObj pre[sort_columns.count()];
char varchar_buf[1024];
const ObNewRow* row = NULL;
int64_t cnt = verify_row_cnt > 0 ? verify_row_cnt : row_count;
for (int64_t i = 0; i < cnt; ++i) {
ASSERT_EQ(OB_SUCCESS, sort.get_next_row(exec_ctx, row)) << i;
// check order
for (int64_t j = 0; i > 0 && j < sort_columns.count(); j++) {
auto& col = sort_columns.at(j);
int cmp = pre[j].compare(row->cells_[col.index_], col.cs_type_);
if (cmp != 0) {
ASSERT_TRUE(col.is_ascending() ? cmp < 0 : cmp > 0);
break;
}
}
// save previous row
int64_t pos = 0;
for (int64_t j = 0; j < sort_columns.count(); j++) {
pre[j] = row->cells_[sort_columns.at(j).index_];
auto& c = pre[j];
if (c.is_string_type()) {
auto len = std::min((uint64_t)c.val_len_, sizeof(varchar_buf) - pos);
MEMCPY(varchar_buf + pos, c.v_.string_, len);
c.v_.string_ = varchar_buf + pos;
pos += len;
}
}
} // end for
ASSERT_EQ(OB_ITER_END, sort.get_next_row(exec_ctx, row));
ASSERT_EQ(OB_SUCCESS, sort.close(exec_ctx));
int64_t sort_row_count = 0;
ASSERT_EQ(OB_SUCCESS, sort.get_sort_row_count(exec_ctx, sort_row_count));
ASSERT_EQ(row_count, sort_row_count);
ob_print_mod_memory_usage();
ObTenantManager::get_instance().print_tenant_usage();
}
END_THREAD_CODE_V2();
ObSortPlan::reset();
}
void ObSortTest::sort_test(int64_t row_count, int64_t mem_limit, int64_t sort_col1, ObCollationType cs_type1,
int64_t sort_col2, ObCollationType cs_type2)
{
sort_test(row_count, mem_limit, [&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col1, cs_type1, false, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col2, cs_type2, true, ObMaxType, default_asc_direction()))) {
}
return ret;
});
}
void ObSortTest::local_merge_sort_test(int64_t row_count, int64_t mem_limit, int64_t sort_col1,
ObCollationType cs_type1, int64_t sort_col2, ObCollationType cs_type2)
{
sort_test(
row_count,
mem_limit,
[&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col1, cs_type1, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(sort_col2, cs_type2, true, ObMaxType, default_asc_direction()))) {
}
return ret;
},
-1,
true);
}
void ObSortTest::serialize_test()
{
ObSort& sort_1 = ObSortPlan::get_instance();
ObArenaAllocator alloc;
ObSort sort_2(alloc);
const int64_t MAX_SERIALIZE_BUF_LEN = 1024;
char buf[MAX_SERIALIZE_BUF_LEN] = {'\0'};
ASSERT_EQ(OB_SUCCESS, ObSortPlan::init(1024, 1024, 0, CS_TYPE_INVALID, 1, CS_TYPE_INVALID));
int64_t pos = 0;
ASSERT_EQ(OB_SUCCESS, sort_1.serialize(buf, MAX_SERIALIZE_BUF_LEN, pos));
ASSERT_EQ(pos, sort_1.get_serialize_size());
int64_t data_len = pos;
sort_2.set_phy_plan(const_cast<ObPhysicalPlan*>(sort_1.get_phy_plan()));
pos = 0;
ASSERT_EQ(OB_SUCCESS, sort_2.deserialize(buf, data_len, pos));
ASSERT_EQ(pos, data_len);
const char* str_1 = to_cstring(sort_1);
const char* str_2 = to_cstring(sort_2);
ASSERT_EQ(0, strcmp(str_1, str_2)) << "sort_1: " << to_cstring(sort_1) << std::endl
<< "sort_2: " << to_cstring(sort_2);
ObSortPlan::reuse();
}
void ObSortTest::sort_exception_test(int expect_ret)
{
int ret = OB_SUCCESS;
ObExecContext exec_ctx;
const ObNewRow* row = NULL;
ObSQLSessionInfo my_session;
my_session.test_init(0, 0, 0, NULL);
my_session.init_tenant("sys", 1);
exec_ctx.set_my_session(&my_session);
ASSERT_EQ(OB_SUCCESS, exec_ctx.init_phy_op(2));
ASSERT_EQ(OB_SUCCESS, exec_ctx.create_physical_plan_ctx());
ObSort& sort = ObSortPlan::get_instance();
ObSortPlan::reset();
int64_t row_count = 16 * 1024;
if (OB_FAIL(ObSortPlan::init(row_count, 0, 0, CS_TYPE_UTF8MB4_BIN, 1, CS_TYPE_UTF8MB4_BIN))) {
} else if (OB_FAIL(sort.open(exec_ctx))) {
} else {
ObSEArray<ObOpSchemaObj, 8> op_schema_objs;
cons_op_schema_objs(sort.get_sort_columns(), op_schema_objs);
sort.get_op_schema_objs_for_update().assign(op_schema_objs);
while (OB_SUCC(ret)) {
ret = sort.get_next_row(exec_ctx, row);
}
if (OB_ITER_END == ret) {
int64_t sort_row_count = 0;
if (OB_FAIL(sort.close(exec_ctx))) {
} else if (OB_FAIL(sort.get_sort_row_count(exec_ctx, sort_row_count))) {
} else {
ASSERT_EQ(row_count, sort_row_count);
}
}
}
sort.close(exec_ctx);
ObSortPlan::reuse();
if (OB_FAIL(ret)) {
ASSERT_EQ(expect_ret, ret);
}
}
TEST_F(ObSortTest, varchar_int_item_in_mem_test)
{
int64_t sort_col1 = 0;
int64_t sort_col2 = 1;
ObCollationType cs_type1 = CS_TYPE_UTF8MB4_BIN;
ObCollationType cs_type2 = CS_TYPE_UTF8MB4_BIN;
sort_test(16 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(64 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
cs_type2 = CS_TYPE_UTF8MB4_GENERAL_CI;
sort_test(16 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(64 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
}
TEST_F(ObSortTest, varchar_int_item_merge_sort_test)
{
int64_t sort_col1 = 0;
int64_t sort_col2 = 1;
ObCollationType cs_type1 = CS_TYPE_UTF8MB4_BIN;
ObCollationType cs_type2 = CS_TYPE_UTF8MB4_BIN;
sort_test(128 * 1024, 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 4 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
// recursive merge needed.
sort_test(256 * 1024, 512 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
cs_type2 = CS_TYPE_UTF8MB4_GENERAL_CI;
sort_test(128 * 1024, 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 4 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
}
TEST_F(ObSortTest, int_int_item_in_mem_test)
{
int64_t sort_col1 = 1;
int64_t sort_col2 = 2;
ObCollationType cs_type1 = CS_TYPE_UTF8MB4_BIN;
ObCollationType cs_type2 = CS_TYPE_UTF8MB4_BIN;
sort_test(16 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(64 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
}
TEST_F(ObSortTest, int_int_item_merge_sort_test)
{
int64_t sort_col1 = 1;
int64_t sort_col2 = 2;
ObCollationType cs_type1 = CS_TYPE_UTF8MB4_BIN;
ObCollationType cs_type2 = CS_TYPE_UTF8MB4_BIN;
// sort_test(64 * 1024, 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
sort_test(256 * 1024, 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
}
TEST_F(ObSortTest, test_conf)
{
TEST_SORT_DUMP_SET_HASH_AREA_SIZE(128 * 1024 * 1024);
int64_t sort_mem = 0;
sort_mem = TEST_SORT_DUMP_GET_HASH_AREA_SIZE();
ASSERT_EQ((128 * 1024 * 1024), sort_mem);
TEST_SORT_DUMP_SET_HASH_AREA_SIZE(1 * 1024 * 1024 * 1024);
sort_mem = TEST_SORT_DUMP_GET_HASH_AREA_SIZE();
ASSERT_EQ((1024 * 1024 * 1024), sort_mem);
TEST_SORT_DUMP_SET_HASH_AREA_SIZE(128 * 1024 * 1024);
}
TEST_F(ObSortTest, prefix_sort_test1)
{
sort_test(1024 * 1024, 1024 * 1024, [](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(3))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_BINARY, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_prefix_pos(1);
}
return ret;
});
}
TEST_F(ObSortTest, prefix_sort_test3)
{
sort_test(256 * 1024, 1024 * 1024, [](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(3))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL5_ROW_ID_DIV_3, CS_TYPE_BINARY, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_prefix_pos(1);
}
return ret;
});
}
TEST_F(ObSortTest, prefix_merge_sort_test)
{
sort_test(256 * 1024, 1024 * 1024, [](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(3))) {
} else if (OB_FAIL(sort.add_sort_column(ObFakeTable::COL11_ROW_ID_MULTIPLY_3_DIV_COUNT,
CS_TYPE_BINARY,
true,
ObMaxType,
default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_prefix_pos(1);
}
return ret;
});
}
class MockExpr : public ObSqlExpression {
public:
MockExpr(ObIAllocator& alloc, int64_t cnt) : ObSqlExpression(alloc)
{
set_item_count(1);
start_gen_infix_exr();
ObPostExprItem item;
item.set_int(cnt);
item.set_item_type(T_INT);
add_expr_item(item);
}
int calc(common::ObExprCtx&, const common::ObNewRow&, common::ObObj& result) const
{
result.set_int(get_expr_items().at(0).get_obj().get_int());
return OB_SUCCESS;
}
};
TEST_F(ObSortTest, topn_sort_test)
{
ObArenaAllocator alloc;
MockExpr expr(alloc, 4);
sort_test(
20,
10 << 20,
[&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_topn_expr(&expr);
}
return ret;
},
4);
}
TEST_F(ObSortTest, topn_disk_sort_test)
{
ObArenaAllocator alloc;
MockExpr expr(alloc, 4);
sort_test(
20,
0,
[&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_topn_expr(&expr);
}
return ret;
},
4);
}
TEST_F(ObSortTest, local_merge_sort_test)
{
int64_t sort_col1 = 1;
int64_t sort_col2 = 2;
ObCollationType cs_type1 = CS_TYPE_UTF8MB4_BIN;
ObCollationType cs_type2 = CS_TYPE_UTF8MB4_BIN;
local_merge_sort_test(0, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(16, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(256, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(16, 0, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(256, 0, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(64 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
local_merge_sort_test(256 * 1024, 256 * 1024 * 1024, sort_col1, cs_type1, sort_col2, cs_type2);
}
TEST_F(ObSortTest, local_merge_sort_disk_test)
{
ObArenaAllocator alloc;
MockExpr expr(alloc, 4);
sort_test(
256 * 1024,
1 << 20,
[&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_topn_expr(&expr);
}
return ret;
},
4,
true);
}
TEST_F(ObSortTest, local_merge_sort_topn_test)
{
ObArenaAllocator alloc;
MockExpr expr(alloc, 4);
sort_test(
1024,
10 << 20,
[&](ObSort& sort) {
int ret = OB_SUCCESS;
if (OB_FAIL(sort.init_sort_columns(2))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL0_RAND_STR, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else if (OB_FAIL(sort.add_sort_column(
ObFakeTable::COL1_ROW_ID, CS_TYPE_UTF8MB4_BIN, true, ObMaxType, default_asc_direction()))) {
} else {
sort.set_topn_expr(&expr);
}
return ret;
},
4,
true);
}
TEST_F(ObSortTest, ser)
{
serialize_test();
}
#define SORT_EXCEPTION_TEST(file, func, key, err, expect_ret) \
do { \
TP_SET_ERROR("engine/sort/" file, func, key, err); \
sort_exception_test(expect_ret); \
TP_SET_ERROR("engine/sort/" file, func, key, NULL); \
ASSERT_FALSE(HasFatalFailure()); \
} while (0)
TEST_F(ObSortTest, sort_exception)
{
THIS_WORKER.set_timeout_ts(ObTimeUtility::current_time() + 600000000);
SORT_EXCEPTION_TEST("ob_sort.cpp", "add_sort_column", "t1", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "open", "t1", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "open", "t3", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "open", "t5", 1, OB_ERR_UNEXPECTED);
SORT_EXCEPTION_TEST("ob_sort.cpp", "open", "t7", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "open", "t9", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "close", "t1", 1, OB_ERR_UNEXPECTED);
SORT_EXCEPTION_TEST("ob_sort.cpp", "close", "t3", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t1", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t3", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t5", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t7", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t9", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t11", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "do_sort", "t13", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "inner_get_next_row", "t1", 1, OB_ERR_UNEXPECTED);
SORT_EXCEPTION_TEST("ob_sort.cpp", "inner_get_next_row", "t3", 1, OB_TIMEOUT);
// see comments for tracepoint t5 in inner_get_next_row() of ob_sort.cpp.
// SORT_EXCEPTION_TEST("ob_sort.cpp", "inner_get_next_row", "t5", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "inner_get_next_row", "t7", 1, OB_ERR_UNEXPECTED);
SORT_EXCEPTION_TEST("ob_sort.cpp", "inner_get_next_row", "t9", OB_ERROR, OB_ERROR);
SORT_EXCEPTION_TEST("ob_sort.cpp", "get_sort_row_count", "t1", 1, OB_ERR_UNEXPECTED);
}
ObPhysicalPlan* ObSortPlan::physical_plan_ = nullptr;
ObSort* ObSortPlan::sort_ = nullptr;
ObFakeTable* ObSortPlan::input_table_ = nullptr;
int64_t ObSortPlan::row_count_ = -1;
ObString* ObSortPlan::filename_ = nullptr;
int main(int argc, char** argv)
{
ObClockGenerator::init();
system("rm -f test_sort.log*");
OB_LOGGER.set_file_name("test_sort.log", true, true);
OB_LOGGER.set_log_level("INFO");
oceanbase::observer::ObSignalHandle signal_handle;
oceanbase::observer::ObSignalHandle::change_signal_mask();
signal_handle.start();
void* buf = nullptr;
ObArenaAllocator allocator;
buf = allocator.alloc(sizeof(ObPhysicalPlan));
ObSortPlan::physical_plan_ = new (buf) ObPhysicalPlan();
buf = allocator.alloc(sizeof(ObSort));
ObSortPlan::sort_ = new (buf) ObSort(ObSortPlan::physical_plan_->get_allocator());
buf = allocator.alloc(sizeof(ObFakeTable));
ObSortPlan::input_table_ = new (buf) ObFakeTable();
ObSortPlan::row_count_ = -1;
buf = allocator.alloc(sizeof(ObString));
ObSortPlan::filename_ = new (buf) ObString();
::testing::InitGoogleTest(&argc, argv);
oceanbase::common::ObLogger::get_logger().set_log_level("INFO");
return RUN_ALL_TESTS();
}
| 35.055703
| 119
| 0.687311
|
wangcy6
|
562dd6271c974c01c0876e325eb533931807e451
| 159
|
cpp
|
C++
|
CPP_Projects/Studying/ConsoleApplication1/ConsoleApplication1/pr1.cpp
|
GUNU-GO/SNUPI
|
a73137699d9fc6ae8fa3d1522f341c04d8d43052
|
[
"MIT"
] | null | null | null |
CPP_Projects/Studying/ConsoleApplication1/ConsoleApplication1/pr1.cpp
|
GUNU-GO/SNUPI
|
a73137699d9fc6ae8fa3d1522f341c04d8d43052
|
[
"MIT"
] | null | null | null |
CPP_Projects/Studying/ConsoleApplication1/ConsoleApplication1/pr1.cpp
|
GUNU-GO/SNUPI
|
a73137699d9fc6ae8fa3d1522f341c04d8d43052
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
int main() {
int num;
scanf_s("%d", &num);
for(int i = 1; i <= num; i++) {
if (num % i == 0) {
printf("%d, ",i);
}
}
}W
| 9.9375
| 32
| 0.415094
|
GUNU-GO
|
562f2b292e7b632be0821c80de2481a80dc30153
| 3,701
|
hpp
|
C++
|
include/haz/Tools/EnumFlag.hpp
|
Hazurl/Framework-haz
|
370348801cd969ce8521264653069923a255e0b0
|
[
"MIT"
] | null | null | null |
include/haz/Tools/EnumFlag.hpp
|
Hazurl/Framework-haz
|
370348801cd969ce8521264653069923a255e0b0
|
[
"MIT"
] | null | null | null |
include/haz/Tools/EnumFlag.hpp
|
Hazurl/Framework-haz
|
370348801cd969ce8521264653069923a255e0b0
|
[
"MIT"
] | null | null | null |
#ifndef __HAZ_ENUM_FLAG
#define __HAZ_ENUM_FLAG
#include <haz/Tools/Macro.hpp>
#include <type_traits>
#define ENUM_FLAG(name, bloc_enum...)\
BEG_NAMESPACE_HAZ_HIDDEN namespace enumFlagNamespace { \
enum class UNIQUE_NAME(name) \
bloc_enum; \
} END_NAMESPACE_HAZ_HIDDEN \
typedef haz::__hide::enumFlagNamespace::UNIQUE_NAME(name) name
#define ENUM_FLAG_NESTED(beg_ns, end_ns, name, bloc_enum...)\
BEG_NAMESPACE_HAZ_HIDDEN namespace enumFlagNamespace { \
enum class UNIQUE_NAME(name) \
bloc_enum; \
} END_NAMESPACE_HAZ_HIDDEN \
beg_ns typedef haz::__hide::enumFlagNamespace::UNIQUE_NAME(name) name; end_ns
BEG_NAMESPACE_HAZ_HIDDEN
namespace enumFlagNamespace {
#define TEMPLATE_RESTRICTIONS(T) typename = typename std::enable_if<std::is_enum<T>::value, T>::type
#define CAST_UNDER_TYPE(T) static_cast<typename std::underlying_type<T>::type>
template<typename T, TEMPLATE_RESTRICTIONS(T)>
class auto_bool
{
T value;
public:
constexpr auto_bool(T value) : value(value) {}
constexpr operator T() const { return value; }
constexpr operator bool() const
{
return CAST_UNDER_TYPE(T)(value) != 0;
}
};
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr auto_bool<T> operator&(T lhs, T rhs) {
return static_cast<T>(CAST_UNDER_TYPE(T)(lhs) & CAST_UNDER_TYPE(T)(rhs));
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T operator|(T lhs, T rhs) {
return static_cast<T>(CAST_UNDER_TYPE(T)(lhs) | CAST_UNDER_TYPE(T)(rhs));
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T operator^(T lhs, T rhs) {
return static_cast<T>(CAST_UNDER_TYPE(T)(lhs) ^ CAST_UNDER_TYPE(T)(rhs));
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T& operator|=(T& lhs, T rhs) {
return lhs = (lhs | rhs);
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T& operator&=(T& lhs, T rhs) {
return lhs = (lhs & rhs);
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T& operator^=(T& lhs, T rhs) {
return lhs = (lhs ^ rhs);
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T operator~(T t) {
return static_cast<T>(~ CAST_UNDER_TYPE(T)(t));
}
}
#define IMPLM_ENUM_FLAP_OP(name) \
inline constexpr ::haz::__hide::enumFlagNamespace::auto_bool<name> operator & (name lhs, name rhs) { \
return static_cast<name>( \
static_cast<typename std::underlying_type<name>::type>(lhs) \
& static_cast<typename std::underlying_type<name>::type>(rhs) \
); \
} \
inline constexpr name operator | (name lhs, name rhs) { \
return static_cast<name>( \
static_cast<typename std::underlying_type<name>::type>(lhs) \
| static_cast<typename std::underlying_type<name>::type>(rhs) \
); \
} \
inline constexpr name operator ^ (name lhs, name rhs) { \
return static_cast<name>( \
static_cast<typename std::underlying_type<name>::type>(lhs) \
^ static_cast<typename std::underlying_type<name>::type>(rhs) \
); \
} \
inline constexpr name& operator &= (name& lhs, name rhs) { \
return lhs = (lhs & rhs); \
} \
inline constexpr name& operator |= (name& lhs, name rhs) { \
return lhs = (lhs | rhs); \
} \
inline constexpr name& operator ^= (name& lhs, name rhs) { \
return lhs = (lhs ^ rhs); \
} \
inline constexpr name operator ~ (name lhs) { \
return static_cast<name>( \
~ static_cast<typename std::underlying_type<name>::type>(lhs) \
); \
}
#undef TEMPLATE_RESTRICTIONS
#undef CAST_UNDER_TYPE
END_NAMESPACE_HAZ_HIDDEN
#endif
| 31.905172
| 102
| 0.663334
|
Hazurl
|
5631846960b9848c74957911364c8b9b629890bf
| 13,072
|
cc
|
C++
|
google/cloud/apigateway/api_gateway_client.cc
|
jmouradi-google/google-cloud-cpp
|
7bd738251a80e9520d7a7de4cc14558f161c8edc
|
[
"Apache-2.0"
] | null | null | null |
google/cloud/apigateway/api_gateway_client.cc
|
jmouradi-google/google-cloud-cpp
|
7bd738251a80e9520d7a7de4cc14558f161c8edc
|
[
"Apache-2.0"
] | null | null | null |
google/cloud/apigateway/api_gateway_client.cc
|
jmouradi-google/google-cloud-cpp
|
7bd738251a80e9520d7a7de4cc14558f161c8edc
|
[
"Apache-2.0"
] | null | null | null |
// 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/apigateway/v1/apigateway_service.proto
#include "google/cloud/apigateway/api_gateway_client.h"
#include "google/cloud/apigateway/internal/api_gateway_option_defaults.h"
#include <memory>
namespace google {
namespace cloud {
namespace apigateway {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
ApiGatewayServiceClient::ApiGatewayServiceClient(
std::shared_ptr<ApiGatewayServiceConnection> connection, Options options)
: connection_(std::move(connection)),
options_(internal::MergeOptions(
std::move(options),
apigateway_internal::ApiGatewayServiceDefaultOptions(
connection_->options()))) {}
ApiGatewayServiceClient::~ApiGatewayServiceClient() = default;
StreamRange<google::cloud::apigateway::v1::Gateway>
ApiGatewayServiceClient::ListGateways(std::string const& parent,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::ListGatewaysRequest request;
request.set_parent(parent);
return connection_->ListGateways(request);
}
StreamRange<google::cloud::apigateway::v1::Gateway>
ApiGatewayServiceClient::ListGateways(
google::cloud::apigateway::v1::ListGatewaysRequest request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->ListGateways(std::move(request));
}
StatusOr<google::cloud::apigateway::v1::Gateway>
ApiGatewayServiceClient::GetGateway(std::string const& name, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::GetGatewayRequest request;
request.set_name(name);
return connection_->GetGateway(request);
}
StatusOr<google::cloud::apigateway::v1::Gateway>
ApiGatewayServiceClient::GetGateway(
google::cloud::apigateway::v1::GetGatewayRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->GetGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::Gateway>>
ApiGatewayServiceClient::CreateGateway(
std::string const& parent,
google::cloud::apigateway::v1::Gateway const& gateway,
std::string const& gateway_id, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::CreateGatewayRequest request;
request.set_parent(parent);
*request.mutable_gateway() = gateway;
request.set_gateway_id(gateway_id);
return connection_->CreateGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::Gateway>>
ApiGatewayServiceClient::CreateGateway(
google::cloud::apigateway::v1::CreateGatewayRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->CreateGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::Gateway>>
ApiGatewayServiceClient::UpdateGateway(
google::cloud::apigateway::v1::Gateway const& gateway,
google::protobuf::FieldMask const& update_mask, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::UpdateGatewayRequest request;
*request.mutable_gateway() = gateway;
*request.mutable_update_mask() = update_mask;
return connection_->UpdateGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::Gateway>>
ApiGatewayServiceClient::UpdateGateway(
google::cloud::apigateway::v1::UpdateGatewayRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->UpdateGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteGateway(std::string const& name,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::DeleteGatewayRequest request;
request.set_name(name);
return connection_->DeleteGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteGateway(
google::cloud::apigateway::v1::DeleteGatewayRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->DeleteGateway(request);
}
StreamRange<google::cloud::apigateway::v1::Api>
ApiGatewayServiceClient::ListApis(std::string const& parent, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::ListApisRequest request;
request.set_parent(parent);
return connection_->ListApis(request);
}
StreamRange<google::cloud::apigateway::v1::Api>
ApiGatewayServiceClient::ListApis(
google::cloud::apigateway::v1::ListApisRequest request, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->ListApis(std::move(request));
}
StatusOr<google::cloud::apigateway::v1::Api> ApiGatewayServiceClient::GetApi(
std::string const& name, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::GetApiRequest request;
request.set_name(name);
return connection_->GetApi(request);
}
StatusOr<google::cloud::apigateway::v1::Api> ApiGatewayServiceClient::GetApi(
google::cloud::apigateway::v1::GetApiRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->GetApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::Api>>
ApiGatewayServiceClient::CreateApi(
std::string const& parent, google::cloud::apigateway::v1::Api const& api,
std::string const& api_id, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::CreateApiRequest request;
request.set_parent(parent);
*request.mutable_api() = api;
request.set_api_id(api_id);
return connection_->CreateApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::Api>>
ApiGatewayServiceClient::CreateApi(
google::cloud::apigateway::v1::CreateApiRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->CreateApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::Api>>
ApiGatewayServiceClient::UpdateApi(
google::cloud::apigateway::v1::Api const& api,
google::protobuf::FieldMask const& update_mask, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::UpdateApiRequest request;
*request.mutable_api() = api;
*request.mutable_update_mask() = update_mask;
return connection_->UpdateApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::Api>>
ApiGatewayServiceClient::UpdateApi(
google::cloud::apigateway::v1::UpdateApiRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->UpdateApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteApi(std::string const& name, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::DeleteApiRequest request;
request.set_name(name);
return connection_->DeleteApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteApi(
google::cloud::apigateway::v1::DeleteApiRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->DeleteApi(request);
}
StreamRange<google::cloud::apigateway::v1::ApiConfig>
ApiGatewayServiceClient::ListApiConfigs(std::string const& parent,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::ListApiConfigsRequest request;
request.set_parent(parent);
return connection_->ListApiConfigs(request);
}
StreamRange<google::cloud::apigateway::v1::ApiConfig>
ApiGatewayServiceClient::ListApiConfigs(
google::cloud::apigateway::v1::ListApiConfigsRequest request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->ListApiConfigs(std::move(request));
}
StatusOr<google::cloud::apigateway::v1::ApiConfig>
ApiGatewayServiceClient::GetApiConfig(std::string const& name,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::GetApiConfigRequest request;
request.set_name(name);
return connection_->GetApiConfig(request);
}
StatusOr<google::cloud::apigateway::v1::ApiConfig>
ApiGatewayServiceClient::GetApiConfig(
google::cloud::apigateway::v1::GetApiConfigRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->GetApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::ApiConfig>>
ApiGatewayServiceClient::CreateApiConfig(
std::string const& parent,
google::cloud::apigateway::v1::ApiConfig const& api_config,
std::string const& api_config_id, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::CreateApiConfigRequest request;
request.set_parent(parent);
*request.mutable_api_config() = api_config;
request.set_api_config_id(api_config_id);
return connection_->CreateApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::ApiConfig>>
ApiGatewayServiceClient::CreateApiConfig(
google::cloud::apigateway::v1::CreateApiConfigRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->CreateApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::ApiConfig>>
ApiGatewayServiceClient::UpdateApiConfig(
google::cloud::apigateway::v1::ApiConfig const& api_config,
google::protobuf::FieldMask const& update_mask, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::UpdateApiConfigRequest request;
*request.mutable_api_config() = api_config;
*request.mutable_update_mask() = update_mask;
return connection_->UpdateApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::ApiConfig>>
ApiGatewayServiceClient::UpdateApiConfig(
google::cloud::apigateway::v1::UpdateApiConfigRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->UpdateApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteApiConfig(std::string const& name,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::DeleteApiConfigRequest request;
request.set_name(name);
return connection_->DeleteApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteApiConfig(
google::cloud::apigateway::v1::DeleteApiConfigRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->DeleteApiConfig(request);
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace apigateway
} // namespace cloud
} // namespace google
| 38.789318
| 79
| 0.746558
|
jmouradi-google
|
56323b24a47b69b41fa0fd4d8431e279aaebc438
| 6,614
|
hpp
|
C++
|
OcularCore/include/Math/Bounds/BoundsOBB.hpp
|
ssell/OcularEngine
|
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
|
[
"Apache-2.0"
] | 8
|
2017-01-27T01:06:06.000Z
|
2020-11-05T20:23:19.000Z
|
OcularCore/include/Math/Bounds/BoundsOBB.hpp
|
ssell/OcularEngine
|
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
|
[
"Apache-2.0"
] | 39
|
2016-06-03T02:00:36.000Z
|
2017-03-19T17:47:39.000Z
|
OcularCore/include/Math/Bounds/BoundsOBB.hpp
|
ssell/OcularEngine
|
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
|
[
"Apache-2.0"
] | 4
|
2019-05-22T09:13:36.000Z
|
2020-12-01T03:17:45.000Z
|
/**
* Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef __H__OCULAR_MATH_BOUNDS_OBB__H__
#define __H__OCULAR_MATH_BOUNDS_OBB__H__
#include "Math/Bounds/Bounds.hpp"
#include "Math/Vector3.hpp"
//------------------------------------------------------------------------------------------
/**
* \addtogroup Ocular
* @{
*/
namespace Ocular
{
/**
* \addtogroup Math
* @{
*/
namespace Math
{
class Ray;
class BoundsSphere;
class BoundsAABB;
class Plane;
/**
* \class BoundsOBB
*
* Implementation of an Oriented Bounding Box.
*
* Essentially an OBB is an AABB that can be arbitrarily rotated.
* They are more expensive to create and their intersection tests
* are more complicated, but have the benefit of not needing to
* be recalculated every time their contents are rotated.
*
* Additionally, in most cases an OBB will also provide a tighter
* fit than an AABB.
*/
class BoundsOBB : public Bounds
{
public:
BoundsOBB(Vector3f const& center, Vector3f const& extents, Vector3f const& xDir, Vector3f const& yDir, Vector3f const& zDir);
BoundsOBB();
~BoundsOBB();
/**
* Returns the center of the bounding box.
*/
Vector3f const& getCenter() const;
/**
* /param[in] center
*/
void setCenter(Vector3f const& center);
/**
* Returns the positive half-lengths of the box.
* These are the distances along each local axis to the box edge.
*/
Vector3f const& getExtents() const;
/**
* /param[in] extents
*/
void setExtents(Vector3f const& extents);
/**
* Returns the normalized direction of the x-axis of the bounding box.
*/
Vector3f const& getDirectionX() const;
/**
* /param[in] dirX
*/
void setDirectionX(Vector3f const& dirX);
/**
* Returns the normalized direction of the y-axis of the bounding box.
*/
Vector3f const& getDirectionY() const;
/**
* /param[in] dirY
*/
void setDirectionY(Vector3f const& dirY);
/**
* Returns the normalized direction of the z-axis of the bounding box.
*/
Vector3f const& getDirectionZ() const;
/**
* /param[in] dirZ
*/
void setDirectionZ(Vector3f const& dirZ);
//------------------------------------------------------------------------------
// Intersection and Containment Testing
//------------------------------------------------------------------------------
/**
* Performs an intersection test on a ray and OBB.
*
* \param[in] ray
* \return TRUE if the ray and OBB intersect.
*/
bool intersects(Ray const& ray) const;
/**
* Performs an intersection test on a bounding sphere and OBB.
*
* \param[in] bounds
* \return TRUE if the bounding sphere and OBB intersect.
*/
bool intersects(BoundsSphere const& bounds) const;
/**
* Performs an intersection test on a AABB and OBB.
*
* \param[in] bounds
* \return TRUE if the AABB and OBB intersect.
*/
bool intersects(BoundsAABB const& bounds) const;
/**
* Performs an intersection test on two OBBs.
*
* \param[in] bounds
* \return TRUE if the two OBBs intersect.
*/
bool intersects(BoundsOBB const& bounds) const;
/**
* Performs an intersection test on a plane and OBB.
*
* If the result is Inside, then the OBB is located entirely within the plane's positive half space. <br/>
* If the result is Outside, then the OBB is located entirely outside the plane's positive half space.
*
* The positive half space of the plane is the direction that the plane is facing, as described by it's normal.
*
* As an example, say we have the plane defined as:
*
* Point: (0.0, 0.0, 0.0)
* Normal: (0.0, 1.0, 0.0)
*
* The plane is 'facing up' along the world origin.
*
* If the intersection test returns Outside, then the AABB is entirely in the +y world space. <br/>
* If the intersection test returns Inside, then the AABB is entirely in the -y world space.
*
* \param[in] plane
* \param[out] result Detailed intersection result.
*
* \return TRUE if the plane and OBB intersects, otherwise FALSE.
*/
bool intersects(Plane const& plane, IntersectionType* result = nullptr) const;
protected:
private:
Vector3f m_Center; ///< Center point of the box
Vector3f m_Extents; ///< Positive half-lengths
Vector3f m_DirectionX; ///< Normalized direction of the X side direction
Vector3f m_DirectionY; ///< Normalized direction of the Y side direction
Vector3f m_DirectionZ; ///< Normalized direction of the Z side direction
};
}
/**
* @} End of Doxygen Groups
*/
}
/**
* @} End of Doxygen Groups
*/
//------------------------------------------------------------------------------------------
#endif
| 33.40404
| 137
| 0.508164
|
ssell
|
563304c25502d7cd748cd4959b1f93f90fe0b31d
| 2,867
|
cpp
|
C++
|
src/common/file-lock.cpp
|
Samsung/security-manager
|
10b062f317d5d5a7b88ed13242540e9034fd019f
|
[
"Apache-2.0"
] | 14
|
2015-09-17T19:30:34.000Z
|
2021-11-11T14:10:43.000Z
|
src/common/file-lock.cpp
|
Samsung/security-manager
|
10b062f317d5d5a7b88ed13242540e9034fd019f
|
[
"Apache-2.0"
] | 5
|
2015-09-17T13:33:39.000Z
|
2015-11-12T21:37:09.000Z
|
src/common/file-lock.cpp
|
Samsung/security-manager
|
10b062f317d5d5a7b88ed13242540e9034fd019f
|
[
"Apache-2.0"
] | 14
|
2015-06-08T07:40:24.000Z
|
2020-01-20T18:58:13.000Z
|
/*
* Copyright (c) 2000 - 2017 Samsung Electronics Co., Ltd All Rights Reserved
*
* Contact: Rafal Krypa <r.krypa@samsung.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
/*
* @file file-lock.cpp
* @author Sebastian Grabowski (s.grabowski@samsung.com)
* @version 1.0
* @brief Implementation of simple file locking for a service
*/
/* vim: set ts=4 et sw=4 tw=78 : */
#include <fstream>
#include "dpl/log/log.h"
#include "tzplatform-config.h"
#include "file-lock.h"
namespace SecurityManager {
const std::string SERVICE_LOCK_FILE = TizenPlatformConfig::makePath(
TZ_SYS_RUN, "lock", "security-manager.lock");
FileLocker::FileLocker(const std::string &lockFile, bool blocking)
{
if (lockFile.empty()) {
LogError("File name can not be empty.");
ThrowMsg(FileLocker::Exception::LockFailed,
"File name can not be empty.");
}
m_locked = false;
m_blocking = blocking;
m_lockFile = lockFile;
Lock();
}
FileLocker::~FileLocker()
{
try {
Unlock();
} catch (...) {
LogError("~FileLocker() threw an exception");
}
}
bool FileLocker::Locked()
{
return m_locked;
}
void FileLocker::Lock()
{
if (m_locked)
return;
try {
std::ofstream tmpf(m_lockFile);
tmpf.close();
m_flock = boost::interprocess::file_lock(m_lockFile.c_str());
if (m_blocking) {
m_flock.lock();
m_locked = true;
} else
m_locked = m_flock.try_lock();
} catch (const std::exception &e) {
LogError("Error while locking a file: " << e.what());
ThrowMsg(FileLocker::Exception::LockFailed,
"Error while locking a file: " << e.what());
}
if (m_locked)
LogDebug("We have a lock on " << m_lockFile << " file.");
else
LogDebug("Impossible to lock a file now.");
}
void FileLocker::Unlock()
{
if (m_locked) {
try {
m_flock.unlock();
} catch (const std::exception &e) {
LogError("Error while unlocking a file: " << e.what());
ThrowMsg(FileLocker::Exception::UnlockFailed,
"Error while unlocking a file: " << e.what());
}
m_locked = false;
LogDebug("Lock released.");
}
}
} // namespace SecurityManager
| 26.063636
| 78
| 0.611789
|
Samsung
|
5635d1b5960254c4c718c1bc639529e28924c81b
| 4,878
|
cpp
|
C++
|
system/apps/test45_simcom/main.cpp
|
tomwei7/LA104
|
fdf04061f37693d37e2812ed6074348e65d7e5f9
|
[
"MIT"
] | 336
|
2018-11-23T23:54:15.000Z
|
2022-03-21T03:47:05.000Z
|
system/apps/test45_simcom/main.cpp
|
203Null/LA104
|
b8ae9413d01ea24eafb9fdb420c97511287cbd99
|
[
"MIT"
] | 56
|
2019-02-01T05:01:07.000Z
|
2022-03-26T16:00:24.000Z
|
system/apps/test45_simcom/main.cpp
|
203Null/LA104
|
b8ae9413d01ea24eafb9fdb420c97511287cbd99
|
[
"MIT"
] | 52
|
2019-02-06T17:05:04.000Z
|
2022-03-04T12:30:53.000Z
|
#include <library.h>
#include "../../os_host/source/framework/Console.h"
using namespace BIOS;
#include "simcom.h"
// https://dweet.io/follow/la104simcom900
// https://dweet.io/dweet/for/la104simcom900?counter=10123
// https://dweet.io/get/latest/dweet/for/la104simcom900
int gReset = 0;
class CMyHttpReceiver : public CHttpResponse
{
bool mFirstLine{true};
public:
virtual void OnHttpCode(int code) override
{
if (code != 200)
{
CONSOLE::Color(RGB565(ff00ff));
CONSOLE::Print("HTTP Error: %d\n", code);
}
}
virtual void OnBody(char* body, int length) override
{
if (!mFirstLine)
return;
mFirstLine = false;
if (length > 31)
strcpy(body+31-3, "...");
CONSOLE::Color(RGB565(b0b0b0));
CONSOLE::Print("Resp: ");
CONSOLE::Color(RGB565(ffffff));
CONSOLE::Print(body);
CONSOLE::Print("\n");
}
virtual void OnFinished() override
{
mFirstLine = true;
}
};
class CMyHttpRequest : public CHttpRequest
{
char mArguments[RequestArgumentsLength];
public:
CMyHttpRequest(const char* host, const char* path)
{
mProtocol = "TCP";
mHost = host;
mPath = path;
mPort = 80;
strcpy(mArguments, "");
}
virtual CAtStream& Request(CAtStream& s)
{
CAtStreamCounter counter;
GetArguments(counter);
s << "POST " << mPath << " HTTP/1.0\r\n"
<< "Host: " << mHost << "\r\n"
<< "User-Agent: sim800L on LA104 by valky.eu\r\n"
<< "content-type: application/x-www-form-urlencoded\r\n"
<< "content-length: " << counter.Count() << "\r\n"
<< "\r\n";
GetArguments(s);
s << "\r\n";
return s;
}
void SetArguments(char *args)
{
_ASSERT(strlen(args) < sizeof(mArguments)-1);
strcpy(mArguments, args);
}
virtual void GetArguments(CAtStream& s)
{
s << mArguments;
}
};
class CClientApp
{
static CClientApp* pInstance;
CGprs mGprs;
CHttpRequestPost mRequest{"dweet.io", "/dweet/for/la104simcom"};
CMyHttpReceiver mResponse;
bool shouldProcess{false};
int mCounter{0};
public:
void Init()
{
BIOS::GPIO::PinMode(BIOS::GPIO::P3, BIOS::GPIO::Output);
// io pins before special io
BIOS::GPIO::PinMode(BIOS::GPIO::P1, BIOS::GPIO::Uart);
BIOS::GPIO::PinMode(BIOS::GPIO::P2, BIOS::GPIO::Uart);
GPIO::UART::Setup(115200, GPIO::UART::EConfig::length8);
//gprs.SetApn("o2internet"); //O2
mGprs.SetApn("internet"); // 4ka
mGprs.SetReceiver(&mResponse);
mGprs.AttachPrint([](char c){ GPIO::UART::Write(c); });
mGprs.AttachPower([](bool value){ gReset++;
BIOS::GPIO::DigitalWrite(BIOS::GPIO::P3, 1-value); });
}
void comm_yield()
{
while (GPIO::UART::Available())
{
char c = GPIO::UART::Read();
mGprs << c;
if (c == '\n')
shouldProcess = true;
}
}
void gprs_yield()
{
static long last = 0;
long now = millis();
if (shouldProcess || now > last + 500)
{
shouldProcess = false;
last = now;
mGprs();
}
}
void Do()
{
comm_yield();
gprs_yield();
if (mGprs.isReady())
{
mResponse.Reset();
char request[128];
sprintf(request, "time=%d&reset=%d&counter=%d", BIOS::SYS::GetTick(), gReset, mCounter++);
mRequest.SetArguments(request);
mGprs.request(mRequest);
}
}
CClientApp()
{
pInstance = this;
}
};
CClientApp* CClientApp::pInstance = nullptr;
CClientApp app;
#ifdef _ARM
__attribute__((__section__(".entry")))
#endif
int _main(void)
{
CRect rcClient(0, 0, LCD::Width, LCD::Height);
LCD::Bar(rcClient, RGB565(0000b0));
CRect rc1(rcClient);
rc1.bottom = 14;
GUI::Background(rc1, RGB565(4040b0), RGB565(404040));
BIOS::LCD::Print(8, rc1.top, RGB565(ffffff), RGBTRANS, "SIMCOM web client & dweet.io");
CRect rc2(rcClient);
rc2.top = rc2.bottom-14;
GUI::Background(rc2, RGB565(404040), RGB565(202020));
BIOS::LCD::Print(8, rc2.top, RGB565(808080), RGBTRANS, "https://dweet.io/follow/la104simcom");
app.Init();
BIOS::KEY::EKey key;
while ((key = KEY::GetKey()) != KEY::EKey::Escape)
{
app.Do();
}
return 0;
}
void _HandleAssertion(const char* file, int line, const char* cond)
{
CONSOLE::Color(RGB565(ffff00));
CONSOLE::Print("Assertion failed in ");
CONSOLE::Print(file);
CONSOLE::Print(" [%d]: %s\n", line, cond);
#ifdef __APPLE__
//kill(getpid(), SIGSTOP);
#endif
while (1);
}
| 23.118483
| 102
| 0.555351
|
tomwei7
|
563b8cea31f72e9688e73cb8ae99652284e35afc
| 8,870
|
hpp
|
C++
|
roller_eye/test/bist/BistNode.hpp
|
lorenzo-bianchi/Scout-open-source
|
ca20d3112388f47a36a245de5de1a35673afd260
|
[
"MIT"
] | 35
|
2022-03-12T01:36:17.000Z
|
2022-03-28T14:56:13.000Z
|
roller_eye/test/bist/BistNode.hpp
|
lorenzo-bianchi/Scout-open-source
|
ca20d3112388f47a36a245de5de1a35673afd260
|
[
"MIT"
] | null | null | null |
roller_eye/test/bist/BistNode.hpp
|
lorenzo-bianchi/Scout-open-source
|
ca20d3112388f47a36a245de5de1a35673afd260
|
[
"MIT"
] | 9
|
2022-03-12T01:39:43.000Z
|
2022-03-31T20:54:19.000Z
|
#include <iostream>
#include <cstdlib>
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/select.h>
#include <linux/input.h>
#include "zlog.h"
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "roller_eye/ros_tools.h"
#include "roller_eye/motor.h"
#include "roller_eye/plt_assert.h"
#include <iostream>
#include <fstream>
#include "roller_eye/camera_handle.hpp"
#include "roller_eye/algo_utils.h"
#include "roller_eye/status_publisher.h"
#include "roller_eye/cv_img_stream.h"
#include "roller_eye/SensorBase.h"
#include "roller_eye/plt_tools.h"
#include "roller_eye/plt_config.h"
#include "roller_eye/wifi_ops.h"
#include "sensor_msgs/Illuminance.h"
#include "roller_eye/cv_img_stream.h"
#include "std_msgs/Int32.h"
#include "roller_eye/track_trace.h"
#include "roller_eye/recorder_mgr.h"
#include <roller_eye/wifi_ops.h>
#include "roller_eye/sound_effects_mgr.h"
#include "roller_eye/start_bist.h"
#include "roller_eye/get_bist_result.h"
#include <opencv2/opencv.hpp>
#include <opencv2/core/eigen.hpp>
#include <opencv2/core/core.hpp>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
#include <cv_bridge/cv_bridge.h>
using namespace roller_eye;
#define DETECT_ROLL_SPEED (1.5)
#define BIST_BOOT_ERROR 1
#define BIST_WFI_ERROR 2
#define BIST_KEY_PRESSING_ERROR 3
#define BIST_LIGHT_SENSOR_ERROR 4
#define BIST_SOUND_ERROR 5
#define BIST_TOF_ERROR 6
#define BIST_IMU_ERROR 7
#define BIST_MOTOR_WHEELS_ERROR 8
#define BIST_CAMERA_RESOLUTION_ERROR 9
#define BIST_CAMERA_DISTORTION_ERROR 10
#define BIST_BATTERY_ERROR 11
#define BIST_IRLIGHT_ERROR 12
#define BIST_BATTERY_WIFIANTENNA_ERROR 13
#define BIST_MEMERY_ERROR 14
#define BIST_DISK_ERROR 15
#define RESET_KEY_LONG_PRESS_TIME (500)
#define WIFI_KEY_LONG_PRESS_TIME (500)
#define POWER_KEY_LONGPRESS_TIME (500)
#define BIST_DETECT_W 640
#define BIST_DETECT_H 480
#define BIST_DETECT "/var/roller_eye/devAudio/got_new_instruction/got_new_instrction.wav"
#define NAV_OUT_SPEED 0.4
#define BIST_MOVE_DIST 0.5
#define CHESSBAORD_ROW 5
#define CHESSBAORD_COL 5
#define CHESSBAORD_SIZE 0.0065
#define CAM_K_FX 720.5631606
#define CAM_K_FY 723.6323653
#define CAM_K_CX 659.39411452
#define CAM_K_CY 369.00731648
#define DISTRO_K1 -0.36906219
#define DISTRO_K2 0.16914887
#define DISTRO_P1 -0.00147033
#define DISTRO_P2 -0.00345135
#define CAR_LENGTH (0.1)
#define ALIGN_DISTANCE 0.16
#define MEM_SIZE 900000
#define DISK_SIZE 7.0 //GB
class CompGreater
{
public:
bool operator ()(const WiFiInFo& info1, const WiFiInFo& info2)
{
return info1.signal > info2.signal;
}
};
class BistNode{
public:
BistNode();
~BistNode();
private:
void MotorWheelCB(const detectConstPtr& obj);
void tofDataCB(const sensor_msgs::RangeConstPtr &r);
void odomRelativeCB(const nav_msgs::Odometry::ConstPtr& msg);
void BatteryStatusCB(const statusConstPtr &s);
void IlluminanceCB(const sensor_msgs::IlluminanceConstPtr& ptr);
void IRLightCB(const sensor_msgs::IlluminanceConstPtr& ptr);
void imuCB(const sensor_msgs::Imu::ConstPtr& msg);
void VideoDataCB(roller_eye::frameConstPtr frame);
void calDistanceAndAngle(Eigen::Quaterniond& q,Eigen::Vector3d& pos,Eigen::Vector3d &goal,double &angle,double &distance);
void LEDControl(int id,int flag)
{
static const char* ids[]={"gpio02_","gpio03_","gpio04_","gpio05_"};
static const char* flags[]={"0", "1"};
char buff[16];
//PLOG_INFO("bist","LEDControl %d",id);
snprintf(buff,sizeof(buff),"%s%s\n",ids[id],flags[flag]);
ofstream of(LED_PATH);
if(!of){
PLOG_ERROR("bist","can't not open %s\n",LED_PATH.c_str());
return;
}
of<<buff<<std::flush;
}
void logInit(){
log_t arg = {
confpath: "/var/roller_eye/config/log/bist.cfg",
levelpath: "/var/roller_eye/config/log/bist.level",
logpath: "/var/log/node/bistNode.log",
cname: "bist"
};
int ret = dzlogInit(&arg,2);
system("echo 20 > /var/roller_eye/config/log/bist.level");
printf("dzlogInit:%d\r\n",ret);
zlog_category_t *zc = zlog_get_category("bist");
zlog_level_switch(zc,20);
}
void LEDProcess(int flag);
void LEDStatus(int flag);
void LEDAllON();
void LEDAllOFF();
void IrLightOn();
void IrLightOff();
void PCMAnalysis(int type = 0);
void PCMgeneration();
float ImagArticulation(const cv::Mat &image);
int pcm2wave(const char *pcmpath, int channels, int sample_rate, const char *wavepath);
void BistSaveImage();
void JpgCallback(roller_eye::frameConstPtr frame);
void getPose(float &lastX,float &lastY,float &angle);
//void GreyImagCallback(const sensor_msgs::ImageConstPtr& msg);
void BistVideoDetect();
void BistTofDetect();
void BistSpeakerMicrophoneDetect();
void BistKeyDetect();
void BistWIFIDetect();
void BistBatteryDetect();
void BistLightDetect();
void BistIMUDetect();
void BistMotorWheelsDetect();
void BistIRLightDetect();
void BistWIFIAntennaDetect();
void BistMemDetect();
void BistDiskDetect();
void BistDriveMotor();
void BistPCBIMUDetect();
void BistPCBTofDetect();
void BistMicrophoneDetect();
void BistPCBVideoDetect();
AlgoUtils mAlgo;
float mRange = 0.0;
float mPCBRange = 0.0;
double mDistance = 0.0;
double mAngle = 0.0;
int mCharging = -1;
double mArticulation = 0.0;
//mutex mBistMutex;
std::mutex mtx;
std::condition_variable cv;
const string LED_PATH="/proc/driver/gpioctl";
const string LOG_CFG="/var/roller_eye/config/log.conf";
const string LOG_LEVEL="/var/roller_eye/config/log.level";
const string PCMFILE="/tmp/test.pcm";
const string PCM2WAVFILE="/tmp/pcm2wav.wav";
const string WAVFILE="/tmp/test.wav";
const string BistImage="/userdata/Bist.jpg";
int mPcmHzs[3] = {0};
bool mIllumMin = false;
bool mIllumMax = false;
//ir light off
int mIRLightOffValu = 0;
int mIRLightOffCount = 0;
bool mIrLightOff = false;
//ir light on
int mIRLightOnValu = 0;
int mIRLightOnCount = 0;
bool mIrLightOn = false;
//key
int mWiFiFD;
int mResetFD;
int mPowerFD;
int IllumCount;
const string WIFI_KEY_TYPE="rk29-keypad";
const string RESET_KEY_TYPE = "adc-keys";
const string POWER_KEY_TYPE = "rk8xx_pwrkey";
struct timeval mLastResetTime;
struct timeval mLastWifiTime;
struct timeval mLastPowerTime;
bool mWiFiKey = false;
bool mResetKey = false;
bool mPowerKey = false;
void processResetKey();
void processWiFiKey();
void processPowerKey();
void KeyStatusLoop();
void BistLoop();
void BistReset();
void BistStatus();
void scanWiFilist(vector<WiFiInFo>& wifis );
void scanWiFiQuality(vector<WiFiInFo>& wifis );
void BistGreyImage();
void BistMatImage();
void JpgMatCb(roller_eye::frameConstPtr frame);
bool start(roller_eye::start_bistRequest &req, roller_eye::start_bistResponse &resp);
bool getResult(roller_eye::get_bist_resultRequest &req, roller_eye::get_bist_resultResponse &resp);
int mBistType;
bool mBistStartDetct = false;
bool mBistAllPassed = false;
bool mBistVideoRes = false;
bool mBistVideoDis = false;
bool mBistVideoJpg = false;
bool mBistTof = false;
bool mSpeakerMicrophone = false;
bool mKey = false;
bool mWifi = false;
bool mWIFIAntenna = false;
bool mBattery = false;
bool mLight = false;
bool mIRLight = false;
bool mIMU = false;
bool mMotorWheel = false;
bool mMemery = false;
bool mDisk = false;
bool mDetectRunning = false;
Eigen::Quaterniond mCurPose;
Eigen::Vector3d mCurPostion;
//CVGreyImageStream mGreyStream;
ros::Subscriber m_subJPG;
ros::Subscriber m_BistJPG;
ros::Subscriber m_subGrey;
cv::Mat m_BistGrey;
vector<uint8_t> mGreyData;
ros::Subscriber mTof;
ros::Subscriber mVideo;
ros::Subscriber mOdomRelative;
ros::Subscriber mBatteryStatus;
ros::Subscriber mScrLight;
ros::Subscriber mScrIMU;
ros::ServiceClient mImuClient;
shared_ptr<ros::NodeHandle> mGlobal;
ros::Publisher mSysEvtPub;
ros::Publisher mPub;
ros::Publisher mCmdVel;
ros::NodeHandle mGlobal2;
ros::Subscriber mSwitch;
ros::Publisher mCmdVel3;
ros::ServiceServer mStartBistSrv;
ros::ServiceServer mGetBistResSrv;
//ros::NodeHandle mGlobal1;
};
| 29.177632
| 123
| 0.700225
|
lorenzo-bianchi
|
563bce5a28baa6518a4d23f7c19f34b17e37eea5
| 1,843
|
cpp
|
C++
|
src/arduino_signalbox.cpp
|
dniklaus/arduino-signalbox
|
8c4a2be46b69cb1d74278f8c76690a531fec4776
|
[
"MIT"
] | null | null | null |
src/arduino_signalbox.cpp
|
dniklaus/arduino-signalbox
|
8c4a2be46b69cb1d74278f8c76690a531fec4776
|
[
"MIT"
] | null | null | null |
src/arduino_signalbox.cpp
|
dniklaus/arduino-signalbox
|
8c4a2be46b69cb1d74278f8c76690a531fec4776
|
[
"MIT"
] | null | null | null |
// Do not remove the include below
#include "arduino_signalbox.h"
#include "Timer.h" // https://github.com/dniklaus/arduino-utils-timer
#include "ToggleButton.h" // https://github.com/dniklaus/arduino-toggle-button
#include "Blanking.h" // https://github.com/dniklaus/arduino-utils-blanking
#include "Point.h"
const int cPt05BtnDev = 32;
const int cPt05BtnStr = 33;
const int cPt05IndDev = 34;
const int cPt05IndStr = 35;
const int cPt20BtnDev = 44;
const int cPt20BtnStr = 45;
const int cPt20IndDev = 46;
const int cPt20IndStr = 47;
const int cPt21BtnDev = 40;
const int cPt21BtnStr = 41;
const int cPt21IndDev = 42;
const int cPt21IndStr = 43;
const int cPt22BtnDev = 36;
const int cPt22BtnStr = 37;
const int cPt22IndDev = 38;
const int cPt22IndStr = 39;
const int cPt23BtnDev = 22;
const int cPt23BtnStr = 23;
const int cPt23Ind1 = 27;
const int cPt23Ind2 = 26;
const int cPt23Ind3 = 24;
const int cPt23Ind4 = 25;
const int cPt24BtnDev = 28;
const int cPt24BtnStr = 29;
const int cPt24IndDev = 30;
const int cPt24IndStr = 31;
class Point* pt05;
class Point* pt20;
class Point* pt21;
class Point* pt22;
class Point* pt23;
class Point* pt24;
//-----------------------------------------------------------------------------
void setup()
{
Serial.begin(115200);
Serial.println(F("Hello from Signal Box Arduino Application!\n"));
pt05 = new Point(cPt05BtnDev, cPt05BtnStr, cPt05IndDev, cPt05IndStr);
pt20 = new Point(cPt20BtnDev, cPt20BtnStr, cPt20IndDev, cPt20IndStr);
pt21 = new Point(cPt21BtnDev, cPt21BtnStr, cPt21IndDev, cPt21IndStr);
pt22 = new Point(cPt22BtnDev, cPt22BtnStr, cPt22IndDev, cPt22IndStr);
pt23 = new Crossing(cPt23BtnDev, cPt23BtnStr, cPt23Ind1, cPt23Ind2, cPt23Ind3, cPt23Ind4);
pt24 = new Point(cPt24BtnDev, cPt24BtnStr, cPt24IndDev, cPt24IndStr);
}
void loop()
{
yield();
}
| 27.507463
| 92
| 0.705372
|
dniklaus
|
563fb5522362017893114feea9c10dd8d3558c7b
| 999
|
hpp
|
C++
|
src/image.hpp
|
robotjandal/image_processor
|
02eb861082212249e958acf0dbd2ac0144cac458
|
[
"BSD-3-Clause"
] | null | null | null |
src/image.hpp
|
robotjandal/image_processor
|
02eb861082212249e958acf0dbd2ac0144cac458
|
[
"BSD-3-Clause"
] | null | null | null |
src/image.hpp
|
robotjandal/image_processor
|
02eb861082212249e958acf0dbd2ac0144cac458
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef CMAKE_IMAGE_H
#define CMAKE_IMAGE_H
#include <string>
#include <opencv4/opencv2/opencv.hpp>
#include <boost/filesystem.hpp>
namespace ImageProcessor {
struct Image {
Image(){};
Image(cv::Mat const image, std::string const filename,
std::string const output_folder)
: image_{image}, filename_{boost::filesystem::path{filename}},
output_folder_{output_folder} {};
Image(cv::Mat const image, boost::filesystem::path const filename,
std::string const output_folder)
: image_{image}, filename_{filename}, output_folder_{output_folder} {};
bool operator==(const Image &other) const;
bool image_exists() const;
std::string get_filename() const { return filename_.filename().string(); };
std::string get_stem() const { return filename_.stem().string(); };
std::string get_extension() const { return filename_.extension().string(); };
cv::Mat image_;
boost::filesystem::path filename_;
std::string output_folder_{"output"};
};
}
#endif
| 30.272727
| 79
| 0.707708
|
robotjandal
|
5641c03f6019abd5d472656ac044d16f49b21347
| 252
|
cpp
|
C++
|
tests/main.cpp
|
mincardona/cppscratch
|
159e3757bc373245defc77c34930c0d7b1d925de
|
[
"MIT"
] | null | null | null |
tests/main.cpp
|
mincardona/cppscratch
|
159e3757bc373245defc77c34930c0d7b1d925de
|
[
"MIT"
] | null | null | null |
tests/main.cpp
|
mincardona/cppscratch
|
159e3757bc373245defc77c34930c0d7b1d925de
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <mji/algorithm.hpp>
#include <mji/math.hpp>
#include <mji/memory.hpp>
#include <mji/xplat.hpp>
int main(int argc, char** argv) {
(void)argc;
(void)argv;
std::cout << "tests passed!" << '\n';
return 0;
}
| 15.75
| 41
| 0.615079
|
mincardona
|
5641da34fc830fd337d475424076c9acdb665662
| 708
|
cpp
|
C++
|
main.cpp
|
Qanora/mstack-cpp
|
a1b6de6983404558e46b87d0e81da715fcdccd55
|
[
"MIT"
] | 15
|
2020-07-20T12:32:38.000Z
|
2022-03-24T19:24:02.000Z
|
main.cpp
|
Qanora/mstack-cpp
|
a1b6de6983404558e46b87d0e81da715fcdccd55
|
[
"MIT"
] | null | null | null |
main.cpp
|
Qanora/mstack-cpp
|
a1b6de6983404558e46b87d0e81da715fcdccd55
|
[
"MIT"
] | 5
|
2020-07-20T12:42:58.000Z
|
2021-01-16T10:13:39.000Z
|
#include <future>
#include <iostream>
#include "api.hpp"
int main(int argc, char* argv[]) {
auto stack = std::async(std::launch::async, mstack::init_stack, argc, argv);
int fd = mstack::socket(0x06, mstack::ipv4_addr_t("192.168.1.1"), 30000);
mstack::listen(fd);
char buf[2000];
int size = 2000;
int cfd = mstack::accept(fd);
while (true) {
size = 2000;
mstack::read(cfd, buf, size);
std::cout << "read size: " << size << std::endl;
for (int i = 0; i < size; i++) {
std::cout << buf[i];
}
std::cout << std::endl;
}
}
| 33.714286
| 85
| 0.461864
|
Qanora
|
564274f3fdb5851743ed4756bdc8bf7224735d77
| 63
|
cpp
|
C++
|
src/Utility_Test.cpp
|
AlbertoLeonardi/Open_SXD_Absorption
|
3d0353676dada2e6826de583355c5e35a93fa791
|
[
"BSD-3-Clause"
] | null | null | null |
src/Utility_Test.cpp
|
AlbertoLeonardi/Open_SXD_Absorption
|
3d0353676dada2e6826de583355c5e35a93fa791
|
[
"BSD-3-Clause"
] | null | null | null |
src/Utility_Test.cpp
|
AlbertoLeonardi/Open_SXD_Absorption
|
3d0353676dada2e6826de583355c5e35a93fa791
|
[
"BSD-3-Clause"
] | null | null | null |
// Utility Functions :: Test
//
#include "Utility_Test.h"
| 12.6
| 29
| 0.634921
|
AlbertoLeonardi
|
5643c15740cf50743bd304baf9cba340d7f98edd
| 3,656
|
cpp
|
C++
|
beerocks/bwl/dummy/base_wlan_hal_dummy.cpp
|
prplfoundation/prplMesh-common
|
96574a27695d2b6d3d610e680d8faaa52f0635d7
|
[
"BSD-2-Clause-Patent"
] | 1
|
2019-05-01T14:45:31.000Z
|
2019-05-01T14:45:31.000Z
|
beerocks/bwl/dummy/base_wlan_hal_dummy.cpp
|
prplfoundation/prplMesh-common
|
96574a27695d2b6d3d610e680d8faaa52f0635d7
|
[
"BSD-2-Clause-Patent"
] | 2
|
2019-05-22T15:32:59.000Z
|
2019-05-27T14:15:55.000Z
|
beerocks/bwl/dummy/base_wlan_hal_dummy.cpp
|
prplfoundation/prplMesh-common
|
96574a27695d2b6d3d610e680d8faaa52f0635d7
|
[
"BSD-2-Clause-Patent"
] | 1
|
2019-05-13T09:51:20.000Z
|
2019-05-13T09:51:20.000Z
|
/* SPDX-License-Identifier: BSD-2-Clause-Patent
*
* Copyright (c) 2016-2019 Intel Corporation
*
* This code is subject to the terms of the BSD+Patent license.
* See LICENSE file for more details.
*/
#include "base_wlan_hal_dummy.h"
#include <beerocks/bcl/beerocks_string_utils.h>
#include <beerocks/bcl/beerocks_utils.h>
#include <beerocks/bcl/network/network_utils.h>
#include <beerocks/bcl/son/son_wireless_utils.h>
#include <easylogging++.h>
#include <sys/eventfd.h>
#define UNHANDLED_EVENTS_LOGS 20
namespace bwl {
namespace dummy {
//////////////////////////////////////////////////////////////////////////////
////////////////////////// Local Module Functions ////////////////////////////
//////////////////////////////////////////////////////////////////////////////
std::ostream &operator<<(std::ostream &out, const dummy_fsm_state &value)
{
switch (value) {
case dummy_fsm_state::Delay:
out << "Delay";
break;
case dummy_fsm_state::Init:
out << "Init";
break;
case dummy_fsm_state::GetRadioInfo:
out << "GetRadioInfo";
break;
case dummy_fsm_state::Attach:
out << "Attach";
break;
case dummy_fsm_state::Operational:
out << "Operational";
break;
case dummy_fsm_state::Detach:
out << "Detach";
break;
}
return out;
}
std::ostream &operator<<(std::ostream &out, const dummy_fsm_event &value)
{
switch (value) {
case dummy_fsm_event::Attach:
out << "Attach";
break;
case dummy_fsm_event::Detach:
out << "Detach";
break;
}
return out;
}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Implementation ///////////////////////////////
//////////////////////////////////////////////////////////////////////////////
base_wlan_hal_dummy::base_wlan_hal_dummy(HALType type, std::string iface_name, bool acs_enabled,
hal_event_cb_t callback, int wpa_ctrl_buffer_size)
: base_wlan_hal(type, iface_name, IfaceType::Intel, acs_enabled, callback),
beerocks::beerocks_fsm<dummy_fsm_state, dummy_fsm_event>(dummy_fsm_state::Delay),
m_wpa_ctrl_buffer_size(wpa_ctrl_buffer_size)
{
// Allocate wpa_ctrl buffer
if (m_wpa_ctrl_buffer_size) {
m_wpa_ctrl_buffer = std::shared_ptr<char>(new char[m_wpa_ctrl_buffer_size], [](char *obj) {
if (obj)
delete[] obj;
});
}
// Set up dummy external events fd
if ((m_fd_ext_events = eventfd(0, EFD_SEMAPHORE)) < 0) {
LOG(FATAL) << "Failed creating eventfd: " << strerror(errno);
}
// Initialize the FSM
fsm_setup();
}
base_wlan_hal_dummy::~base_wlan_hal_dummy() { detach(); }
bool base_wlan_hal_dummy::fsm_setup() { return true; }
HALState base_wlan_hal_dummy::attach(bool block) { return (m_hal_state = HALState::Operational); }
bool base_wlan_hal_dummy::detach() { return true; }
bool base_wlan_hal_dummy::ping() { return true; }
bool base_wlan_hal_dummy::dummy_send_cmd(const std::string &cmd) { return false; }
bool base_wlan_hal_dummy::dummy_send_cmd(const std::string &cmd, char **reply) { return false; }
bool base_wlan_hal_dummy::refresh_radio_info() { return true; }
bool base_wlan_hal_dummy::refresh_vap_info(int vap_id) { return true; }
bool base_wlan_hal_dummy::refresh_vaps_info(int id) { return true; }
bool base_wlan_hal_dummy::process_ext_events() { return true; }
std::string base_wlan_hal_dummy::get_radio_mac() { return std::string("DE:AD:BE:EF:DE:AD"); }
} // namespace dummy
} // namespace bwl
| 30.466667
| 99
| 0.596827
|
prplfoundation
|
56462c507604830c90548b7dd8baeb644686fd66
| 6,490
|
cpp
|
C++
|
Core/STL/OS/Posix/PosixSyncPrimitives.cpp
|
azhirnov/GraphicsGenFramework-modular
|
348be601f1991f102defa0c99250529f5e44c4d3
|
[
"BSD-2-Clause"
] | 12
|
2017-12-23T14:24:57.000Z
|
2020-10-02T19:52:12.000Z
|
Core/STL/OS/Posix/PosixSyncPrimitives.cpp
|
azhirnov/ModularGraphicsFramework
|
348be601f1991f102defa0c99250529f5e44c4d3
|
[
"BSD-2-Clause"
] | null | null | null |
Core/STL/OS/Posix/PosixSyncPrimitives.cpp
|
azhirnov/ModularGraphicsFramework
|
348be601f1991f102defa0c99250529f5e44c4d3
|
[
"BSD-2-Clause"
] | null | null | null |
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt'
#include "Core/STL/Common/Platforms.h"
#if defined( PLATFORM_BASE_POSIX ) and defined( GX_USE_NATIVE_API )
#include "Core/STL/OS/Posix/SyncPrimitives.h"
namespace GX_STL
{
namespace OS
{
/*
=================================================
constructor
=================================================
*/
Mutex::Mutex ()
{
static const pthread_mutex_t tmp = PTHREAD_MUTEX_INITIALIZER;
_mutex = tmp;
# if 1
::pthread_mutex_init( OUT &_mutex, null ) == 0;
# else
pthread_mutexattr_t attr;
::pthread_mutexattr_init( &attr );
::pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
::pthread_mutex_init( &_mutex, &attr ) == 0;
# endif
}
/*
=================================================
destructor
=================================================
*/
Mutex::~Mutex ()
{
::pthread_mutex_destroy( &_mutex );
}
/*
=================================================
Lock
=================================================
*/
void Mutex::Lock ()
{
bool res = ::pthread_mutex_lock( &_mutex ) == 0;
ASSERT( res );
}
/*
=================================================
TryLock
=================================================
*/
bool Mutex::TryLock ()
{
return ::pthread_mutex_trylock( &_mutex ) == 0;
}
/*
=================================================
Unlock
=================================================
*/
void Mutex::Unlock ()
{
bool res = ::pthread_mutex_unlock( &_mutex ) == 0;
ASSERT( res );
}
//-----------------------------------------------------------------------------
/*
=================================================
constructor
=================================================
*/
ReadWriteSync::ReadWriteSync ()
{
::pthread_rwlock_init( OUT &_rwlock, null );
}
/*
=================================================
destructor
=================================================
*/
ReadWriteSync::~ReadWriteSync ()
{
::pthread_rwlock_destroy( &_rwlock );
}
/*
=================================================
LockWrite
=================================================
*/
void ReadWriteSync::LockWrite ()
{
bool res = ::pthread_rwlock_wrlock( &_rwlock ) == 0;
ASSERT( res );
}
/*
=================================================
TryLockWrite
=================================================
*/
bool ReadWriteSync::TryLockWrite ()
{
return ::pthread_rwlock_trywrlock( &_rwlock ) == 0;
}
/*
=================================================
UnlockWrite
=================================================
*/
void ReadWriteSync::UnlockWrite ()
{
bool res = ::pthread_rwlock_unlock( &_rwlock ) == 0;
ASSERT( res );
}
/*
=================================================
LockRead
=================================================
*/
void ReadWriteSync::LockRead ()
{
bool res = ::pthread_rwlock_rdlock( &_rwlock ) == 0;
ASSERT( res );
}
/*
=================================================
TryLockRead
=================================================
*/
bool ReadWriteSync::TryLockRead ()
{
return ::pthread_rwlock_tryrdlock( &_rwlock ) == 0;
}
/*
=================================================
UnlockRead
=================================================
*/
void ReadWriteSync::UnlockRead ()
{
bool res = ::pthread_rwlock_unlock( &_rwlock ) == 0;
ASSERT( res );
}
//-----------------------------------------------------------------------------
/*
=================================================
constructor
=================================================
*/
ConditionVariable::ConditionVariable ()
{
::pthread_cond_init( OUT &_cv, null );
}
/*
=================================================
destructor
=================================================
*/
ConditionVariable::~ConditionVariable ()
{
::pthread_cond_destroy( &_cv );
}
/*
=================================================
Signal
=================================================
*/
void ConditionVariable::Signal ()
{
bool res = ::pthread_cond_signal( &_cv ) == 0;
ASSERT( res );
}
/*
=================================================
Broadcast
=================================================
*/
void ConditionVariable::Broadcast ()
{
bool res = ::pthread_cond_broadcast( &_cv ) == 0;
ASSERT( res );
}
/*
=================================================
Wait
=================================================
*/
bool ConditionVariable::Wait (Mutex &cs)
{
return ::pthread_cond_wait( &_cv, &cs._mutex ) == 0;
}
/*
=================================================
Wait
=================================================
*/
bool ConditionVariable::Wait (Mutex &cs, TimeL time)
{
struct timespec currTime;
::clock_gettime( CLOCK_REALTIME, OUT &currTime );
// TODO: check
currTime.tv_nsec += time.MilliSeconds() * 1000;
currTime.tv_sec += currTime.tv_nsec / 1000000000;
return ::pthread_cond_timedwait( &_cv, &cs._mutex, &currTime );
}
//-----------------------------------------------------------------------------
/*
=================================================
constructor
=================================================
*/
Semaphore::Semaphore (GXTypes::uint initialValue)
{
::sem_init( OUT &_sem, 0, initialValue );
}
/*
=================================================
destructor
=================================================
*/
Semaphore::~Semaphore ()
{
::sem_destroy( &_sem );
}
/*
=================================================
Lock
=================================================
*/
void Semaphore::Lock ()
{
int result = ::sem_wait( &_sem );
ASSERT( result == 0 );
}
/*
=================================================
TryLock
=================================================
*/
bool Semaphore::TryLock ()
{
int result = ::sem_trywait( &_sem );
return result == 0;
}
/*
=================================================
Unlock
=================================================
*/
void Semaphore::Unlock ()
{
int result = ::sem_post( &_sem );
ASSERT( result == 0 );
}
/*
=================================================
GetValue
=================================================
*/
GXTypes::uint Semaphore::GetValue ()
{
int value = 0;
int result = ::sem_getvalue( &_sem, &value );
ASSERT( result == 0 );
return value;
}
} // OS
} // GX_STL
#endif // PLATFORM_BASE_POSIX and GX_USE_NATIVE_API
| 20.868167
| 79
| 0.362096
|
azhirnov
|
5646b3b326d2c2b9566bf4b7824be6668dd58e77
| 1,078
|
cpp
|
C++
|
examples/tutorial/hello_job_world.cpp
|
saga-project/saga-cpp
|
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
|
[
"BSL-1.0"
] | 5
|
2015-09-15T16:24:14.000Z
|
2021-08-12T11:05:55.000Z
|
examples/tutorial/hello_job_world.cpp
|
saga-project/saga-cpp
|
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
|
[
"BSL-1.0"
] | null | null | null |
examples/tutorial/hello_job_world.cpp
|
saga-project/saga-cpp
|
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
|
[
"BSL-1.0"
] | 3
|
2016-11-17T04:38:38.000Z
|
2021-04-10T17:23:52.000Z
|
// Copyright (c) 2011 Ole Weidner, Louisiana State University
//
// This is part of the code examples on the SAGA website:
// http://saga-project.org/documentation/tutorials/job-api
#include <saga/saga.hpp>
int main(int argc, char* argv[])
{
try
{
// create an "echo 'hello, world' job"
saga::job::description jd;
jd.set_attribute("Interactive", "True");
jd.set_attribute("Executable", "/bin/echo");
std::vector<std::string> args;
args.push_back("Hello, World!");
jd.set_vector_attribute("Arguments", args);
// connect to the local job service
saga::job::service js("fork://localhost");
// submit the job
saga::job::job job = js.create_job(jd);
job.run();
//wait for the job to complete
job.wait(-1);
// print the job's output
saga::job::istream output = job.get_stdout();
std::string line;
while ( ! std::getline (output, line).eof () )
{
std::cout << line << std::endl;
}
}
catch(saga::exception const & e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
| 24.5
| 62
| 0.611317
|
saga-project
|
56498b71024b3b090fb1cdb71ccf3e66e649ba7a
| 19,728
|
cpp
|
C++
|
src/mongo/db/query/cursor_response_test.cpp
|
benety/mongo
|
203430ac9559f82ca01e3cbb3b0e09149fec0835
|
[
"Apache-2.0"
] | null | null | null |
src/mongo/db/query/cursor_response_test.cpp
|
benety/mongo
|
203430ac9559f82ca01e3cbb3b0e09149fec0835
|
[
"Apache-2.0"
] | null | null | null |
src/mongo/db/query/cursor_response_test.cpp
|
benety/mongo
|
203430ac9559f82ca01e3cbb3b0e09149fec0835
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/query/cursor_response.h"
#include "mongo/rpc/op_msg_rpc_impls.h"
#include "mongo/db/pipeline/resume_token.h"
#include "mongo/unittest/unittest.h"
namespace mongo {
namespace {
TEST(CursorResponseTest, parseFromBSONFirstBatch) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
}
TEST(CursorResponseTest, parseFromBSONNextBatch) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
}
TEST(CursorResponseTest, parseFromBSONCursorIdZero) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(0) << "ns"
<< "db.coll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(0));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
}
TEST(CursorResponseTest, parseFromBSONEmptyBatch) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "nextBatch" << BSONArrayBuilder().arr())
<< "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 0U);
}
TEST(CursorResponseTest, parseFromBSONMissingCursorField) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON("ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONCursorFieldWrongType) {
StatusWith<CursorResponse> result =
CursorResponse::parseFromBSON(BSON("cursor" << 3 << "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONNsFieldMissing) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("id" << CursorId(123) << "firstBatch"
<< BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONNsFieldWrongType) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("id" << CursorId(123) << "ns" << 456 << "firstBatch"
<< BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONIdFieldMissing) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("ns"
<< "db.coll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONIdFieldWrongType) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("id"
<< "123"
<< "ns"
<< "db.coll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONBatchFieldMissing) {
StatusWith<CursorResponse> result =
CursorResponse::parseFromBSON(BSON("cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll")
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONFirstBatchFieldWrongType) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON("_id" << 1))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONNextBatchFieldWrongType) {
StatusWith<CursorResponse> result =
CursorResponse::parseFromBSON(BSON("cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "nextBatch" << BSON("_id" << 1))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONOkFieldMissing) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONPartialResultsReturnedField) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2))
<< "partialResultsReturned" << true)
<< "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
ASSERT_EQ(response.getPartialResultsReturned(), true);
}
TEST(CursorResponseTest, parseFromBSONPartialResultsReturnedFieldWrongType) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2))
<< "partialResultsReturned" << 1)
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONVarsFieldCorrect) {
BSONObj varsContents = BSON("randomVar" << 7);
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "vars" << varsContents << "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
ASSERT_TRUE(response.getVarsField());
ASSERT_BSONOBJ_EQ(response.getVarsField().get(), varsContents);
}
TEST(CursorResponseTest, parseFromBSONVarsFieldWrongType) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "vars" << 2 << "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONMultipleVars) {
BSONObj varsContents = BSON("randomVar" << 7 << "otherVar" << BSON("nested" << 2));
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "vars" << varsContents << "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
ASSERT_TRUE(response.getVarsField());
ASSERT_BSONOBJ_EQ(response.getVarsField().get(), varsContents);
}
TEST(CursorResponseTest, roundTripThroughCursorResponseBuilderWithPartialResultsReturned) {
CursorResponseBuilder::Options options;
options.isInitialResponse = true;
rpc::OpMsgReplyBuilder builder;
BSONObj okStatus = BSON("ok" << 1);
BSONObj testDoc = BSON("_id" << 1);
BSONObj expectedBody =
BSON("cursor" << BSON("firstBatch" << BSON_ARRAY(testDoc) << "partialResultsReturned"
<< true << "id" << CursorId(123) << "ns"
<< "db.coll"));
// Use CursorResponseBuilder to serialize the cursor response to OpMsgReplyBuilder.
CursorResponseBuilder crb(&builder, options);
crb.append(testDoc);
crb.setPartialResultsReturned(true);
crb.done(CursorId(123), "db.coll");
// Confirm that the resulting BSONObj response matches the expected body.
auto msg = builder.done();
auto opMsg = OpMsg::parse(msg);
ASSERT_BSONOBJ_EQ(expectedBody, opMsg.body);
// Append {"ok": 1} to the opMsg body so that it can be parsed by CursorResponse.
auto swCursorResponse = CursorResponse::parseFromBSON(opMsg.body.addField(okStatus["ok"]));
ASSERT_OK(swCursorResponse.getStatus());
// Confirm the CursorReponse parsed from CursorResponseBuilder output has the correct content.
CursorResponse response = std::move(swCursorResponse.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 1U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], testDoc);
ASSERT_EQ(response.getPartialResultsReturned(), true);
// Re-serialize a BSONObj response from the CursorResponse.
auto cursorResBSON = response.toBSONAsInitialResponse();
// Confirm that the BSON serialized by the CursorResponse is the same as that serialized by the
// CursorResponseBuilder. Field ordering differs between the two, so compare per-element.
BSONObjIteratorSorted cursorResIt(cursorResBSON["cursor"].Obj());
BSONObjIteratorSorted cursorBuilderIt(opMsg.body["cursor"].Obj());
while (cursorResIt.more()) {
ASSERT(cursorBuilderIt.more());
ASSERT_EQ(cursorResIt.next().woCompare(cursorBuilderIt.next()), 0);
}
ASSERT(!cursorBuilderIt.more());
}
TEST(CursorResponseTest, parseFromBSONHandleErrorResponse) {
StatusWith<CursorResponse> result =
CursorResponse::parseFromBSON(BSON("ok" << 0 << "code" << 123 << "errmsg"
<< "does not work"));
ASSERT_NOT_OK(result.getStatus());
ASSERT_EQ(result.getStatus().code(), 123);
ASSERT_EQ(result.getStatus().reason(), "does not work");
}
TEST(CursorResponseTest, toBSONInitialResponse) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
CursorResponse response(NamespaceString("testdb.testcoll"), CursorId(123), batch);
BSONObj responseObj = response.toBSON(CursorResponse::ResponseType::InitialResponse);
BSONObj expectedResponse = BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "testdb.testcoll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1.0);
ASSERT_BSONOBJ_EQ(responseObj, expectedResponse);
}
TEST(CursorResponseTest, toBSONSubsequentResponse) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
CursorResponse response(NamespaceString("testdb.testcoll"), CursorId(123), batch);
BSONObj responseObj = response.toBSON(CursorResponse::ResponseType::SubsequentResponse);
BSONObj expectedResponse = BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "testdb.testcoll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1.0);
ASSERT_BSONOBJ_EQ(responseObj, expectedResponse);
}
TEST(CursorResponseTest, toBSONPartialResultsReturned) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
CursorResponse response(NamespaceString("testdb.testcoll"),
CursorId(123),
batch,
boost::none,
boost::none,
boost::none,
boost::none,
boost::none,
true);
BSONObj responseObj = response.toBSON(CursorResponse::ResponseType::InitialResponse);
BSONObj expectedResponse = BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "testdb.testcoll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2))
<< "partialResultsReturned" << true)
<< "ok" << 1.0);
ASSERT_BSONOBJ_EQ(responseObj, expectedResponse);
}
TEST(CursorResponseTest, addToBSONInitialResponse) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
CursorResponse response(NamespaceString("testdb.testcoll"), CursorId(123), batch);
BSONObjBuilder builder;
response.addToBSON(CursorResponse::ResponseType::InitialResponse, &builder);
BSONObj responseObj = builder.obj();
BSONObj expectedResponse = BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "testdb.testcoll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1.0);
ASSERT_BSONOBJ_EQ(responseObj, expectedResponse);
}
TEST(CursorResponseTest, addToBSONSubsequentResponse) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
CursorResponse response(NamespaceString("testdb.testcoll"), CursorId(123), batch);
BSONObjBuilder builder;
response.addToBSON(CursorResponse::ResponseType::SubsequentResponse, &builder);
BSONObj responseObj = builder.obj();
BSONObj expectedResponse = BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "testdb.testcoll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1.0);
ASSERT_BSONOBJ_EQ(responseObj, expectedResponse);
}
TEST(CursorResponseTest, serializePostBatchResumeToken) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
auto postBatchResumeToken =
ResumeToken::makeHighWaterMarkToken(Timestamp(1, 2), ResumeTokenData::kDefaultTokenVersion)
.toDocument()
.toBson();
CursorResponse response(
NamespaceString("db.coll"), CursorId(123), batch, boost::none, postBatchResumeToken);
auto serialized = response.toBSON(CursorResponse::ResponseType::SubsequentResponse);
ASSERT_BSONOBJ_EQ(serialized,
BSON("cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "nextBatch"
<< BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2))
<< "postBatchResumeToken" << postBatchResumeToken)
<< "ok" << 1));
auto reparsed = CursorResponse::parseFromBSON(serialized);
ASSERT_OK(reparsed.getStatus());
CursorResponse reparsedResponse = std::move(reparsed.getValue());
ASSERT_EQ(reparsedResponse.getCursorId(), CursorId(123));
ASSERT_EQ(reparsedResponse.getNSS().ns(), "db.coll");
ASSERT_EQ(reparsedResponse.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(*reparsedResponse.getPostBatchResumeToken(), postBatchResumeToken);
}
} // namespace
} // namespace mongo
| 46.748815
| 100
| 0.589822
|
benety
|
5649ef306425c4e66478968eedf4b5296864a7e2
| 8,692
|
cpp
|
C++
|
src/lock_free_set.cpp
|
cconklin/nonblocking-tables
|
82acacbb16342ad36156931b9969674d85114d21
|
[
"MIT"
] | null | null | null |
src/lock_free_set.cpp
|
cconklin/nonblocking-tables
|
82acacbb16342ad36156931b9969674d85114d21
|
[
"MIT"
] | null | null | null |
src/lock_free_set.cpp
|
cconklin/nonblocking-tables
|
82acacbb16342ad36156931b9969674d85114d21
|
[
"MIT"
] | null | null | null |
#include <lock_free_set.hpp>
namespace nonblocking
{
template<> versioned<lock_free_set::bucket_state>::versioned(unsigned int version, lock_free_set::bucket_state value) : _version{version}
{
switch (value)
{
case lock_free_set::bucket_state::empty: _value = 0; break;
case lock_free_set::bucket_state::busy: _value = 1; break;
case lock_free_set::bucket_state::collided: _value = 2; break;
case lock_free_set::bucket_state::visible: _value = 3; break;
case lock_free_set::bucket_state::inserting: _value = 4; break;
case lock_free_set::bucket_state::member: _value = 5; break;
}
}
template<> versioned<lock_free_set::bucket_state>::versioned() noexcept : _version{0}, _value{0} {}
template<> bool versioned<lock_free_set::bucket_state>::operator==(versioned<lock_free_set::bucket_state> other)
{
return (_version == other._version) && (_value == other._value);
}
template<> lock_free_set::bucket_state versioned<lock_free_set::bucket_state>::value()
{
switch (_value)
{
case 0: return lock_free_set::bucket_state::empty;
case 1: return lock_free_set::bucket_state::busy;
case 2: return lock_free_set::bucket_state::collided;
case 3: return lock_free_set::bucket_state::visible;
case 4: return lock_free_set::bucket_state::inserting;
case 5: return lock_free_set::bucket_state::member;
default: return lock_free_set::bucket_state::busy;
}
}
template<> unsigned int versioned<lock_free_set::bucket_state>::version()
{
return _version;
}
lock_free_set::bucket::bucket(unsigned int key, unsigned int version, lock_free_set::bucket_state state) : key{key}, vs(versioned<lock_free_set::bucket_state>(version, state)) {}
lock_free_set::bucket::bucket() : key{0}, vs(versioned<lock_free_set::bucket_state>()) {}
lock_free_set::bucket* lock_free_set::bucket_at(unsigned int h, int index)
{
return &buckets[(h+index*(index+1)/2)%size];
}
bool lock_free_set::does_bucket_contain_collision(unsigned int h, int index)
{
auto state = bucket_at(h, index)->vs.load(std::memory_order_acquire);
if ((state.value() == visible) || (state.value() == inserting) || (state.value() == member))
{
if (hash(bucket_at(h, index)->key.load(std::memory_order_acquire)) == h)
{
auto state2 = bucket_at(h, index)->vs.load(std::memory_order_relaxed);
if ((state2.value() == visible) || (state2.value() == inserting) || (state2.value() == member))
{
if (state2.version() == state.version())
{
return true;
}
}
}
}
return false;
}
lock_free_set::lock_free_set(unsigned int size) : base(size)
{
buckets = new bucket[size];
std::atomic_thread_fence(std::memory_order_release);
}
bool lock_free_set::lookup(unsigned int key)
{
unsigned int h = hash(key);
auto max = get_probe_bound(h);
for (unsigned int i = 0; i <= max; ++i)
{
auto state = bucket_at(h, i)->vs.load(std::memory_order_acquire);
if ((state.value() == member) && (bucket_at(h, i)->key.load(std::memory_order_acquire) == key))
{
auto state2 = bucket_at(h, i)->vs.load(std::memory_order_relaxed);
if (state == state2)
{
return true;
}
}
}
return false;
}
bool lock_free_set::erase(unsigned int key)
{
unsigned int h = hash(key);
auto max = get_probe_bound(h);
for (unsigned int i = 0; i <= max; ++i)
{
auto* bucket = bucket_at(h, i);
auto state = bucket->vs.load(std::memory_order_acquire);
if ((state.value() == member) && (bucket->key.load(std::memory_order_acquire) == key))
{
if (std::atomic_compare_exchange_strong_explicit(&bucket->vs, &state, versioned<bucket_state>(state.version(), busy), std::memory_order_release, std::memory_order_relaxed))
{
conditionally_lower_bound(h, i);
bucket->vs.store(versioned<bucket_state>(state.version() + 1, empty), std::memory_order_release);
return true;
}
}
}
return false;
}
bool lock_free_set::insert(unsigned int key)
{
unsigned int h = hash(key);
int i = -1;
unsigned int version;
versioned<bucket_state> old_vs;
versioned<bucket_state> new_vs;
do
{
if (++i >= size)
{
throw "Table full";
}
version = bucket_at(h, i)->vs.load(std::memory_order_acquire).version();
old_vs = versioned<bucket_state>(version, empty);
new_vs = versioned<bucket_state>(version, busy);
}
while (!std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->vs, &old_vs, new_vs, std::memory_order_release, std::memory_order_relaxed));
bucket_at(h, i)->key.store(key, std::memory_order_relaxed);
while (true)
{
bucket_at(h, i)->vs.store(versioned<bucket_state>(version, visible), std::memory_order_release);
conditionally_raise_bound(h, i);
bucket_at(h, i)->vs.store(versioned<bucket_state>(version, inserting), std::memory_order_release);
auto r = assist(key, h, i, version);
if (!(bucket_at(h, i)->vs.load(std::memory_order_acquire) == versioned<bucket_state>(version, collided)))
{
return true;
}
if (!r)
{
conditionally_lower_bound(h, i);
bucket_at(h, i)->vs.store(versioned<bucket_state>(version+1, empty), std::memory_order_release);
return false;
}
version++;
}
}
bool lock_free_set::assist(unsigned int key, unsigned int h, int i, unsigned int ver_i)
{
auto max = get_probe_bound(h);
versioned<bucket_state> old_vs(ver_i, inserting);
for (unsigned int j = 0; j <= max; j++)
{
if (i != j)
{
auto* bkt_at = bucket_at(h, j);
auto state = bkt_at->vs.load(std::memory_order_acquire);
if ((state.value() == inserting) && (bkt_at->key.load(std::memory_order_acquire) == key))
{
if (j < i)
{
auto j_state = bkt_at->vs.load(std::memory_order_relaxed);
if (j_state == state)
{
std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->vs, &old_vs, versioned<bucket_state>(ver_i, collided), std::memory_order_relaxed, std::memory_order_relaxed);
return assist(key, h, j, state.version());
}
}
else
{
auto i_state = bucket_at(h, i)->vs.load(std::memory_order_acquire);
if (i_state == versioned<bucket_state>(ver_i, inserting))
{
std::atomic_compare_exchange_strong_explicit(&bkt_at->vs, &state, versioned<bucket_state>(state.version(), collided), std::memory_order_relaxed, std::memory_order_relaxed);
}
}
}
auto new_state = bkt_at->vs.load(std::memory_order_acquire);
if ((new_state.value() == member) && (bkt_at->key.load(std::memory_order_acquire) == key))
{
if (bkt_at->vs.load(std::memory_order_relaxed) == new_state)
{
std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->vs, &old_vs, versioned<bucket_state>(ver_i, collided), std::memory_order_relaxed, std::memory_order_relaxed);
return false;
}
}
}
}
std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->vs, &old_vs, versioned<bucket_state>(ver_i, member), std::memory_order_release, std::memory_order_relaxed);
return true;
}
lock_free_set::~lock_free_set()
{
delete buckets;
}
}
| 41.788462
| 200
| 0.554648
|
cconklin
|
5649f39794bcb8d696576f12970d330136ab6d9e
| 955
|
cpp
|
C++
|
src/CaseCreator/UIComponents/CharacterTab/CharacterDialogSpritesPage.cpp
|
Thisisderpys/my-little-investigations
|
0689f2ca3e808ba39864f024280abd2e77f8ad20
|
[
"MIT"
] | 41
|
2015-01-24T17:33:16.000Z
|
2022-01-08T19:36:40.000Z
|
src/CaseCreator/UIComponents/CharacterTab/CharacterDialogSpritesPage.cpp
|
Thisisderpys/my-little-investigations
|
0689f2ca3e808ba39864f024280abd2e77f8ad20
|
[
"MIT"
] | 15
|
2015-01-05T21:00:41.000Z
|
2016-10-18T14:37:03.000Z
|
src/CaseCreator/UIComponents/CharacterTab/CharacterDialogSpritesPage.cpp
|
Thisisderpys/my-little-investigations
|
0689f2ca3e808ba39864f024280abd2e77f8ad20
|
[
"MIT"
] | 6
|
2016-01-14T21:07:22.000Z
|
2020-11-28T09:51:15.000Z
|
#include "CharacterDialogSpritesPage.h"
#include <QVBoxLayout>
CharacterDialogSpritesPage::CharacterDialogSpritesPage(QWidget *parent) :
Page<Character>(parent)
{
isActive = false;
QVBoxLayout *pMainLayout = new QVBoxLayout();
pEmotionManipulator = new ListManipulator<Character::DialogEmotion>();
pMainLayout->addWidget(pEmotionManipulator);
setLayout(pMainLayout);
}
void CharacterDialogSpritesPage::Init(Character *pObject)
{
if (pObject == NULL)
{
return;
}
Page<Character>::Init(pObject);
pEmotionManipulator->SetParentObject(pObject);
}
void CharacterDialogSpritesPage::Reset()
{
pEmotionManipulator->Reset();
}
bool CharacterDialogSpritesPage::GetIsActive()
{
return isActive;
}
void CharacterDialogSpritesPage::SetIsActive(bool isActive)
{
if (this->isActive != isActive)
{
this->isActive = isActive;
pEmotionManipulator->SetIsActive(isActive);
}
}
| 20.319149
| 74
| 0.71623
|
Thisisderpys
|
871cfb6e6280a3cc476906643eb4d3e0a1ce5d5a
| 36,782
|
cxx
|
C++
|
libbuild2/cc/module.cxx
|
build2/build2
|
af662849b756ef2ff0f3d5148a6771acab78fd80
|
[
"MIT"
] | 422
|
2018-05-30T12:00:00.000Z
|
2022-03-29T07:29:56.000Z
|
libbuild2/cc/module.cxx
|
build2/build2
|
af662849b756ef2ff0f3d5148a6771acab78fd80
|
[
"MIT"
] | 183
|
2018-07-02T20:38:30.000Z
|
2022-03-31T09:54:35.000Z
|
libbuild2/cc/module.cxx
|
build2/build2
|
af662849b756ef2ff0f3d5148a6771acab78fd80
|
[
"MIT"
] | 14
|
2019-01-09T12:34:02.000Z
|
2021-03-16T09:10:53.000Z
|
// file : libbuild2/cc/module.cxx -*- C++ -*-
// license : MIT; see accompanying LICENSE file
#include <libbuild2/cc/module.hxx>
#include <iomanip> // left, setw()
#include <libbuild2/scope.hxx>
#include <libbuild2/function.hxx>
#include <libbuild2/diagnostics.hxx>
#include <libbuild2/bin/target.hxx>
#include <libbuild2/cc/target.hxx> // pc*
#include <libbuild2/config/utility.hxx>
#include <libbuild2/install/utility.hxx>
#include <libbuild2/cc/guess.hxx>
using namespace std;
using namespace butl;
namespace build2
{
namespace cc
{
void config_module::
guess (scope& rs, const location& loc, const variable_map&)
{
tracer trace (x, "guess_init");
bool cc_loaded (cast_false<bool> (rs["cc.core.guess.loaded"]));
// Adjust module priority (compiler). Also order cc module before us
// (we don't want to use priorities for that in case someone manages
// to slot in-between).
//
if (!cc_loaded)
config::save_module (rs, "cc", 250);
config::save_module (rs, x, 250);
auto& vp (rs.var_pool ());
// Must already exist.
//
const variable& config_c_poptions (vp["config.cc.poptions"]);
const variable& config_c_coptions (vp["config.cc.coptions"]);
const variable& config_c_loptions (vp["config.cc.loptions"]);
// Configuration.
//
using config::lookup_config;
// config.x
//
strings mode;
{
// Normally we will have a persistent configuration and computing the
// default value every time will be a waste. So try without a default
// first.
//
lookup l (lookup_config (new_config, rs, config_x));
if (!l)
{
// If there is a config.x value for one of the modules that can hint
// us the toolchain, load it's .guess module. This makes sure that
// the order in which we load the modules is unimportant and that
// the user can specify the toolchain using any of the config.x
// values.
//
if (!cc_loaded)
{
for (const char* const* pm (x_hinters); *pm != nullptr; ++pm)
{
string m (*pm);
// Must be the same as in module's init().
//
const variable& v (vp.insert<strings> ("config." + m));
if (rs[v].defined ())
{
init_module (rs, rs, m + ".guess", loc);
cc_loaded = true;
break;
}
}
}
// If cc.core.guess is already loaded then use its toolchain id,
// (optional) pattern, and mode to guess an appropriate default
// (e.g., for {gcc, *-4.9 -m64} we will get g++-4.9 -m64).
//
strings d;
if (cc_loaded)
d = guess_default (x_lang,
cast<string> (rs["cc.id"]),
cast<string> (rs["cc.pattern"]),
cast<strings> (rs["cc.mode"]));
else
{
// Note that we don't have the default mode: it doesn't feel
// correct to default to, say, -m64 simply because that's how
// build2 was built.
//
d.push_back (x_default);
if (d.front ().empty ())
fail << "not built with default " << x_lang << " compiler" <<
info << "use " << config_x << " to specify";
}
// If this value was hinted, save it as commented out so that if the
// user changes the source of the pattern/mode, this one will get
// updated as well.
//
l = lookup_config (new_config,
rs,
config_x,
move (d),
cc_loaded ? config::save_default_commented : 0);
}
// Split the value into the compiler path and mode.
//
const strings& v (cast<strings> (l));
path xc;
{
const string& s (v.empty () ? empty_string : v.front ());
try { xc = path (s); } catch (const invalid_path&) {}
if (xc.empty ())
fail << "invalid path '" << s << "' in " << config_x;
}
mode.assign (++v.begin (), v.end ());
// Save original path/mode in *.config.path/mode.
//
rs.assign (x_c_path) = xc;
rs.assign (x_c_mode) = mode;
// Figure out which compiler we are dealing with, its target, etc.
//
// Note that we could allow guess() to modify mode to support
// imaginary options (such as /MACHINE for cl.exe). Though it's not
// clear what cc.mode would contain (original or modified). Note that
// we are now folding *.std options into mode options.
//
x_info = &build2::cc::guess (
x, x_lang,
rs.root_extra->environment_checksum,
move (xc),
cast_null<string> (lookup_config (rs, config_x_id)),
cast_null<string> (lookup_config (rs, config_x_version)),
cast_null<string> (lookup_config (rs, config_x_target)),
mode,
cast_null<strings> (rs[config_c_poptions]),
cast_null<strings> (rs[config_x_poptions]),
cast_null<strings> (rs[config_c_coptions]),
cast_null<strings> (rs[config_x_coptions]),
cast_null<strings> (rs[config_c_loptions]),
cast_null<strings> (rs[config_x_loptions]));
}
const compiler_info& xi (*x_info);
// Split/canonicalize the target. First see if the user asked us to use
// config.sub.
//
target_triplet tt;
{
string ct;
if (config_sub)
{
ct = run<string> (3,
*config_sub,
xi.target.c_str (),
[] (string& l, bool) {return move (l);});
l5 ([&]{trace << "config.sub target: '" << ct << "'";});
}
try
{
tt = target_triplet (ct.empty () ? xi.target : ct);
l5 ([&]{trace << "canonical target: '" << tt.string () << "'; "
<< "class: " << tt.class_;});
}
catch (const invalid_argument& e)
{
// This is where we suggest that the user specifies --config-sub to
// help us out.
//
fail << "unable to parse " << x_lang << " compiler target '"
<< xi.target << "': " << e <<
info << "consider using the --config-sub option";
}
}
// Hash the environment (used for change detection).
//
// Note that for simplicity we use the combined checksum for both
// compilation and linking (which may compile, think LTO).
//
{
sha256 cs;
hash_environment (cs, xi.compiler_environment);
hash_environment (cs, xi.platform_environment);
env_checksum = cs.string ();
}
// Assign values to variables that describe the compiler.
//
rs.assign (x_path) = process_path_ex (
xi.path, x_name, xi.checksum, env_checksum);
const strings& xm (cast<strings> (rs.assign (x_mode) = move (mode)));
rs.assign (x_id) = xi.id.string ();
rs.assign (x_id_type) = to_string (xi.id.type);
rs.assign (x_id_variant) = xi.id.variant;
rs.assign (x_class) = to_string (xi.class_);
auto assign_version = [&rs] (const variable** vars,
const compiler_version* v)
{
rs.assign (vars[0]) = v != nullptr ? value (v->string) : value ();
rs.assign (vars[1]) = v != nullptr ? value (v->major) : value ();
rs.assign (vars[2]) = v != nullptr ? value (v->minor) : value ();
rs.assign (vars[3]) = v != nullptr ? value (v->patch) : value ();
rs.assign (vars[4]) = v != nullptr ? value (v->build) : value ();
};
assign_version (&x_version, &xi.version);
assign_version (&x_variant_version,
xi.variant_version ? &*xi.variant_version : nullptr);
rs.assign (x_signature) = xi.signature;
rs.assign (x_checksum) = xi.checksum;
// Also enter as x.target.{cpu,vendor,system,version,class} for
// convenience of access.
//
rs.assign (x_target_cpu) = tt.cpu;
rs.assign (x_target_vendor) = tt.vendor;
rs.assign (x_target_system) = tt.system;
rs.assign (x_target_version) = tt.version;
rs.assign (x_target_class) = tt.class_;
rs.assign (x_target) = move (tt);
rs.assign (x_pattern) = xi.pattern;
if (!x_stdlib.alias (c_stdlib))
rs.assign (x_stdlib) = xi.x_stdlib;
// Load cc.core.guess.
//
if (!cc_loaded)
{
// Prepare configuration hints.
//
variable_map h (rs.ctx);
// Note that all these variables have already been registered.
//
h.assign ("config.cc.id") = cast<string> (rs[x_id]);
h.assign ("config.cc.hinter") = string (x);
h.assign ("config.cc.target") = cast<target_triplet> (rs[x_target]);
if (!xi.pattern.empty ())
h.assign ("config.cc.pattern") = xi.pattern;
if (!xm.empty ())
h.assign ("config.cc.mode") = xm;
h.assign (c_runtime) = xi.runtime;
h.assign (c_stdlib) = xi.c_stdlib;
init_module (rs, rs, "cc.core.guess", loc, false, h);
}
else
{
// If cc.core.guess is already loaded, verify its configuration
// matched ours since it could have been loaded by another c-family
// module.
//
const auto& h (cast<string> (rs["cc.hinter"]));
auto check = [&loc, &h, this] (const auto& cv,
const auto& xv,
const char* what,
bool error = true)
{
if (cv != xv)
{
diag_record dr (error ? fail (loc) : warn (loc));
dr << h << " and " << x << " module " << what << " mismatch" <<
info << h << " is '" << cv << "'" <<
info << x << " is '" << xv << "'" <<
info << "consider explicitly specifying config." << h
<< " and config." << x;
}
};
check (cast<string> (rs["cc.id"]),
cast<string> (rs[x_id]),
"toolchain");
// We used to not require that patterns match assuming that if the
// toolchain id and target are the same, then where exactly the tools
// come from doesn't really matter. But in most cases it will be the
// g++-7 vs gcc kind of mistakes. So now we warn since even if
// intentional, it is still probably a bad idea.
//
// Note also that it feels right to allow different modes (think
// -fexceptions for C or -fno-rtti for C++).
//
check (cast<string> (rs["cc.pattern"]),
cast<string> (rs[x_pattern]),
"toolchain pattern",
false);
check (cast<target_triplet> (rs["cc.target"]),
cast<target_triplet> (rs[x_target]),
"target");
check (cast<string> (rs["cc.runtime"]),
xi.runtime,
"runtime");
check (cast<string> (rs["cc.stdlib"]),
xi.c_stdlib,
"c standard library");
}
}
#ifndef _WIN32
static const dir_path usr_inc ("/usr/include");
static const dir_path usr_loc_lib ("/usr/local/lib");
static const dir_path usr_loc_inc ("/usr/local/include");
# ifdef __APPLE__
static const dir_path a_usr_inc (
"/Library/Developer/CommandLineTools/SDKs/MacOSX*.sdk/usr/include");
# endif
#endif
// Extracting search dirs can be expensive (we may need to run the
// compiler several times) so we cache the result.
//
struct search_dirs
{
pair<dir_paths, size_t> lib;
pair<dir_paths, size_t> hdr;
};
static global_cache<search_dirs> dirs_cache;
void config_module::
init (scope& rs, const location& loc, const variable_map&)
{
tracer trace (x, "config_init");
const compiler_info& xi (*x_info);
const target_triplet& tt (cast<target_triplet> (rs[x_target]));
// Load cc.core.config.
//
if (!cast_false<bool> (rs["cc.core.config.loaded"]))
{
variable_map h (rs.ctx);
if (!xi.bin_pattern.empty ())
h.assign ("config.bin.pattern") = xi.bin_pattern;
init_module (rs, rs, "cc.core.config", loc, false, h);
}
// Configuration.
//
using config::lookup_config;
// config.x.{p,c,l}options
// config.x.libs
//
// These are optional. We also merge them into the corresponding
// x.* variables.
//
// The merging part gets a bit tricky if this module has already
// been loaded in one of the outer scopes. By doing the straight
// append we would just be repeating the same options over and
// over. So what we are going to do is only append to a value if
// it came from this scope. Then the usage for merging becomes:
//
// @@ There are actually two cases to this issue:
//
// 1. The module is loaded in the outer project (e.g., tests inside a
// project). It feels like this should be handled with project
// variable visibility. And now it is with the project being the
// default. Note that this is the reason we don't need any of this
// for the project configuration: there the config.* variables are
// always set on the project root.
//
// 2. The module is loaded in the outer scope within the same
// project. We are currently thinking whether we should even
// support loading of modules in non-root scopes.
//
// x.coptions = <overridable options> # Note: '='.
// using x
// x.coptions += <overriding options> # Note: '+='.
//
rs.assign (x_poptions) += cast_null<strings> (
lookup_config (rs, config_x_poptions, nullptr));
rs.assign (x_coptions) += cast_null<strings> (
lookup_config (rs, config_x_coptions, nullptr));
rs.assign (x_loptions) += cast_null<strings> (
lookup_config (rs, config_x_loptions, nullptr));
rs.assign (x_aoptions) += cast_null<strings> (
lookup_config (rs, config_x_aoptions, nullptr));
rs.assign (x_libs) += cast_null<strings> (
lookup_config (rs, config_x_libs, nullptr));
// config.x.std overrides x.std
//
strings& mode (cast<strings> (rs.assign (x_mode))); // Set by guess.
{
lookup l (lookup_config (rs, config_x_std));
const string* v;
if (l.defined ())
{
v = cast_null<string> (l);
rs.assign (x_std) = v;
}
else
v = cast_null<string> (rs[x_std]);
// Translate x_std value (if any) to the compiler option(s) (if any)
// and fold them into the compiler mode.
//
translate_std (xi, tt, rs, mode, v);
}
// config.x.internal.scope
//
// Note: save omitted.
//
// The effective internal_scope value is chosen based on the following
// priority list:
//
// 1. config.x.internal.scope
//
// 2. config.cc.internal.scope
//
// 3. effective value from bundle amalgamation
//
// 4. x.internal.scope
//
// 5. cc.internal.scope
//
// Note also that we only update x.internal.scope (and not cc.*) to
// reflect the effective value.
//
const string* iscope_str (nullptr);
{
if (lookup l = lookup_config (rs, config_x_internal_scope)) // 1
{
iscope_str = &cast<string> (l);
if (*iscope_str == "current")
fail << "'current' value in " << config_x_internal_scope;
}
else if (lookup l = rs["config.cc.internal.scope"]) // 2
{
iscope_str = &cast<string> (l);
}
else // 3
{
const scope& as (*rs.bundle_scope ());
if (as != rs)
{
// Only use the value if the corresponding module is loaded.
//
bool xl (cast_false<bool> (as[string (x) + ".config.loaded"]));
if (xl)
iscope_str = cast_null<string> (as[x_internal_scope]);
if (iscope_str == nullptr)
{
if (xl || cast_false<bool> (as["cc.core.config.loaded"]))
iscope_str = cast_null<string> (as["cc.internal.scope"]);
}
if (iscope_str != nullptr && *iscope_str == "current")
iscope_current = &as;
}
}
lookup l;
if (iscope_str == nullptr)
{
iscope_str = cast_null<string> (l = rs[x_internal_scope]); // 4
if (iscope_str == nullptr)
iscope_str = cast_null<string> (rs["cc.internal.scope"]); // 5
}
if (iscope_str != nullptr)
{
const string& s (*iscope_str);
// Assign effective.
//
if (!l)
rs.assign (x_internal_scope) = s;
if (s == "current")
{
iscope = internal_scope::current;
if (iscope_current == nullptr)
iscope_current = &rs;
}
else if (s == "base") iscope = internal_scope::base;
else if (s == "root") iscope = internal_scope::root;
else if (s == "bundle") iscope = internal_scope::bundle;
else if (s == "strong") iscope = internal_scope::strong;
else if (s == "weak") iscope = internal_scope::weak;
else if (s == "global")
; // Nothing to translate;
else
fail << "invalid " << x_internal_scope << " value '" << s << "'";
}
}
// config.x.translate_include
//
// It's still fuzzy whether specifying (or maybe tweaking) this list in
// the configuration will be a common thing to do so for now we use
// omitted.
//
if (x_translate_include != nullptr)
{
if (lookup l = lookup_config (rs, *config_x_translate_include))
{
// @@ MODHDR: if(modules) ? Yes.
//
rs.assign (x_translate_include).prepend (
cast<translatable_headers> (l));
}
}
// Extract system header/library search paths from the compiler and
// determine if we need any additional search paths.
//
// Note that for now module search paths only come from compiler_info.
//
pair<dir_paths, size_t> lib_dirs;
pair<dir_paths, size_t> hdr_dirs;
const optional<pair<dir_paths, size_t>>& mod_dirs (xi.sys_mod_dirs);
if (xi.sys_lib_dirs && xi.sys_hdr_dirs)
{
lib_dirs = *xi.sys_lib_dirs;
hdr_dirs = *xi.sys_hdr_dirs;
}
else
{
string key;
{
sha256 cs;
cs.append (static_cast<size_t> (x_lang));
cs.append (xi.path.effect_string ());
append_options (cs, mode);
key = cs.string ();
}
// Because the compiler info (xi) is also cached, we can assume that
// if dirs come from there, then they do so consistently.
//
const search_dirs* sd (dirs_cache.find (key));
if (xi.sys_lib_dirs)
lib_dirs = *xi.sys_lib_dirs;
else if (sd != nullptr)
lib_dirs = sd->lib;
else
{
switch (xi.class_)
{
case compiler_class::gcc:
lib_dirs = gcc_library_search_dirs (xi.path, rs);
break;
case compiler_class::msvc:
lib_dirs = msvc_library_search_dirs (xi.path, rs);
break;
}
}
if (xi.sys_hdr_dirs)
hdr_dirs = *xi.sys_hdr_dirs;
else if (sd != nullptr)
hdr_dirs = sd->hdr;
else
{
switch (xi.class_)
{
case compiler_class::gcc:
hdr_dirs = gcc_header_search_dirs (xi.path, rs);
break;
case compiler_class::msvc:
hdr_dirs = msvc_header_search_dirs (xi.path, rs);
break;
}
}
if (sd == nullptr)
{
search_dirs sd;
if (!xi.sys_lib_dirs) sd.lib = lib_dirs;
if (!xi.sys_hdr_dirs) sd.hdr = hdr_dirs;
dirs_cache.insert (move (key), move (sd));
}
}
sys_lib_dirs_mode = lib_dirs.second;
sys_hdr_dirs_mode = hdr_dirs.second;
sys_mod_dirs_mode = mod_dirs ? mod_dirs->second : 0;
sys_lib_dirs_extra = lib_dirs.first.size ();
sys_hdr_dirs_extra = hdr_dirs.first.size ();
#ifndef _WIN32
// Add /usr/local/{include,lib}. We definitely shouldn't do this if we
// are cross-compiling. But even if the build and target are the same,
// it's possible the compiler uses some carefully crafted sysroot and by
// adding /usr/local/* we will just mess things up. So the heuristics
// that we will use is this: if the compiler's system include directories
// contain /usr[/local]/include then we add /usr/local/*.
//
// Note that similar to GCC we also check for the directory existence.
// Failed that, we can end up with some bizarre yo-yo'ing cases where
// uninstall removes the directories which in turn triggers a rebuild
// on the next invocation.
//
{
auto& is (hdr_dirs.first);
auto& ls (lib_dirs.first);
bool ui (find (is.begin (), is.end (), usr_inc) != is.end ());
bool uli (find (is.begin (), is.end (), usr_loc_inc) != is.end ());
#ifdef __APPLE__
// On Mac OS starting from 10.14 there is no longer /usr/include.
// Instead we get the following:
//
// Homebrew GCC 9:
//
// /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include
//
// Apple Clang 10.0.1:
//
// /Library/Developer/CommandLineTools/usr/include
// /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include
//
// What exactly all this means is anyone's guess, of course (see
// homebrew-core issue #46393 for some background). So for now we
// will assume that anything that matches this pattern:
//
// /Library/Developer/CommandLineTools/SDKs/MacOSX*.sdk/usr/include
//
// Is Apple's /usr/include.
//
if (!ui && !uli)
{
for (const dir_path& d: is)
{
if (path_match (d, a_usr_inc))
{
ui = true;
break;
}
}
}
#endif
if (ui || uli)
{
bool ull (find (ls.begin (), ls.end (), usr_loc_lib) != ls.end ());
// Many platforms don't search in /usr/local/lib by default (but do
// for headers in /usr/local/include). So add it as the last option.
//
if (!ull && exists (usr_loc_lib, true /* ignore_error */))
ls.push_back (usr_loc_lib);
// FreeBSD is at least consistent: it searches in neither. Quoting
// its wiki: "FreeBSD can't even find libraries that it installed."
// So let's help it a bit.
//
if (!uli && exists (usr_loc_inc, true /* ignore_error */))
is.push_back (usr_loc_inc);
}
}
#endif
// If this is a configuration with new values, then print the report
// at verbosity level 2 and up (-v).
//
if (verb >= (new_config ? 2 : 3))
{
diag_record dr (text);
{
dr << x << ' ' << project (rs) << '@' << rs << '\n'
<< " " << left << setw (11) << x << xi.path << '\n';
}
if (!mode.empty ())
{
dr << " mode "; // One space short.
for (const string& o: mode)
dr << ' ' << o;
dr << '\n';
}
{
dr << " id " << xi.id << '\n'
<< " version " << xi.version.string << '\n'
<< " major " << xi.version.major << '\n'
<< " minor " << xi.version.minor << '\n'
<< " patch " << xi.version.patch << '\n';
}
if (!xi.version.build.empty ())
{
dr << " build " << xi.version.build << '\n';
}
if (xi.variant_version)
{
dr << " variant:" << '\n'
<< " version " << xi.variant_version->string << '\n'
<< " major " << xi.variant_version->major << '\n'
<< " minor " << xi.variant_version->minor << '\n'
<< " patch " << xi.variant_version->patch << '\n';
}
if (xi.variant_version && !xi.variant_version->build.empty ())
{
dr << " build " << xi.variant_version->build << '\n';
}
{
const string& ct (tt.string ()); // Canonical target.
dr << " signature " << xi.signature << '\n'
<< " checksum " << xi.checksum << '\n'
<< " target " << ct;
if (ct != xi.original_target)
dr << " (" << xi.original_target << ")";
dr << "\n runtime " << xi.runtime
<< "\n stdlib " << xi.x_stdlib;
if (!x_stdlib.alias (c_stdlib))
dr << "\n c stdlib " << xi.c_stdlib;
}
if (!xi.pattern.empty ()) // Note: bin_pattern printed by bin
{
dr << "\n pattern " << xi.pattern;
}
auto& mods (mod_dirs ? mod_dirs->first : dir_paths ());
auto& incs (hdr_dirs.first);
auto& libs (lib_dirs.first);
if (verb >= 3 && iscope)
{
dr << "\n int scope ";
if (*iscope == internal_scope::current)
dr << iscope_current->out_path ();
else
dr << *iscope_str;
}
if (verb >= 3 && !mods.empty ())
{
dr << "\n mod dirs";
for (const dir_path& d: mods)
{
dr << "\n " << d;
}
}
if (verb >= 3 && !incs.empty ())
{
dr << "\n hdr dirs";
for (size_t i (0); i != incs.size (); ++i)
{
if (i == sys_hdr_dirs_extra)
dr << "\n --";
dr << "\n " << incs[i];
}
}
if (verb >= 3 && !libs.empty ())
{
dr << "\n lib dirs";
for (size_t i (0); i != libs.size (); ++i)
{
if (i == sys_lib_dirs_extra)
dr << "\n --";
dr << "\n " << libs[i];
}
}
}
rs.assign (x_sys_lib_dirs) = move (lib_dirs.first);
rs.assign (x_sys_hdr_dirs) = move (hdr_dirs.first);
config::save_environment (rs, xi.compiler_environment);
config::save_environment (rs, xi.platform_environment);
}
// Global cache of ad hoc importable headers.
//
// The key is a hash of the system header search directories
// (sys_hdr_dirs) where we search for the headers.
//
static map<string, importable_headers> importable_headers_cache;
static mutex importable_headers_mutex;
void module::
init (scope& rs,
const location& loc,
const variable_map&,
const compiler_info& xi)
{
tracer trace (x, "init");
context& ctx (rs.ctx);
// Register the module function family if this is the first instance of
// this modules.
//
if (!function_family::defined (ctx.functions, x))
{
function_family f (ctx.functions, x);
compile_rule::functions (f, x);
link_rule::functions (f, x);
}
// Load cc.core. Besides other things, this will load bin (core) plus
// extra bin.* modules we may need.
//
load_module (rs, rs, "cc.core", loc);
// Search include translation headers and groups.
//
if (modules)
{
{
sha256 k;
for (const dir_path& d: sys_hdr_dirs)
k.append (d.string ());
mlock l (importable_headers_mutex);
importable_headers = &importable_headers_cache[k.string ()];
}
auto& hs (*importable_headers);
ulock ul (hs.mutex);
if (hs.group_map.find (header_group_std) == hs.group_map.end ())
guess_std_importable_headers (xi, sys_hdr_dirs, hs);
// Process x.translate_include.
//
const variable& var (*x_translate_include);
if (auto* v = cast_null<translatable_headers> (rs[var]))
{
for (const auto& p: *v)
{
const string& k (p.first);
if (k.front () == '<' && k.back () == '>')
{
if (path_pattern (k))
{
size_t n (hs.insert_angle_pattern (sys_hdr_dirs, k));
l5 ([&]{trace << "pattern " << k << " searched to " << n
<< " headers";});
}
else
{
// What should we do if not found? While we can fail, this
// could be too drastic if, for example, the header is
// "optional" and may or may not be present/used. So for now
// let's ignore (we could have also removed it from the map as
// an indication).
//
const auto* r (hs.insert_angle (sys_hdr_dirs, k));
l5 ([&]{trace << "header " << k << " searched to "
<< (r ? r->first.string ().c_str () : "<none>");});
}
}
else if (path_traits::find_separator (k) == string::npos)
{
// Group name.
//
if (k != header_group_all_importable &&
k != header_group_std_importable &&
k != header_group_all &&
k != header_group_std)
fail (loc) << "unknown header group '" << k << "' in " << var;
}
else
{
// Absolute and normalized header path.
//
if (!path_traits::absolute (k))
fail (loc) << "relative header path '" << k << "' in " << var;
}
}
}
}
// Register target types and configure their "installability".
//
bool install_loaded (cast_false<bool> (rs["install.loaded"]));
{
using namespace install;
rs.insert_target_type (x_src);
auto insert_hdr = [&rs, install_loaded] (const target_type& tt)
{
rs.insert_target_type (tt);
// Install headers into install.include.
//
if (install_loaded)
install_path (rs, tt, dir_path ("include"));
};
// Note: module (x_mod) is in x_hdr.
//
for (const target_type* const* ht (x_hdr); *ht != nullptr; ++ht)
insert_hdr (**ht);
// Also register the C header for C-derived languages.
//
if (*x_hdr != &h::static_type)
insert_hdr (h::static_type);
rs.insert_target_type<pc> ();
rs.insert_target_type<pca> ();
rs.insert_target_type<pcs> ();
if (install_loaded)
install_path<pc> (rs, dir_path ("pkgconfig"));
}
// Register rules.
//
{
using namespace bin;
// If the target doesn't support shared libraries, then don't register
// the corresponding rules.
//
bool s (tsys != "emscripten");
auto& r (rs.rules);
const compile_rule& cr (*this);
const link_rule& lr (*this);
// We register for configure so that we detect unresolved imports
// during configuration rather that later, e.g., during update.
//
r.insert<obje> (perform_update_id, x_compile, cr);
r.insert<obje> (perform_clean_id, x_compile, cr);
r.insert<obje> (configure_update_id, x_compile, cr);
r.insert<obja> (perform_update_id, x_compile, cr);
r.insert<obja> (perform_clean_id, x_compile, cr);
r.insert<obja> (configure_update_id, x_compile, cr);
if (s)
{
r.insert<objs> (perform_update_id, x_compile, cr);
r.insert<objs> (perform_clean_id, x_compile, cr);
r.insert<objs> (configure_update_id, x_compile, cr);
}
if (modules)
{
r.insert<bmie> (perform_update_id, x_compile, cr);
r.insert<bmie> (perform_clean_id, x_compile, cr);
r.insert<bmie> (configure_update_id, x_compile, cr);
r.insert<hbmie> (perform_update_id, x_compile, cr);
r.insert<hbmie> (perform_clean_id, x_compile, cr);
r.insert<hbmie> (configure_update_id, x_compile, cr);
r.insert<bmia> (perform_update_id, x_compile, cr);
r.insert<bmia> (perform_clean_id, x_compile, cr);
r.insert<bmia> (configure_update_id, x_compile, cr);
r.insert<hbmia> (perform_update_id, x_compile, cr);
r.insert<hbmia> (perform_clean_id, x_compile, cr);
r.insert<hbmia> (configure_update_id, x_compile, cr);
if (s)
{
r.insert<bmis> (perform_update_id, x_compile, cr);
r.insert<bmis> (perform_clean_id, x_compile, cr);
r.insert<bmis> (configure_update_id, x_compile, cr);
r.insert<hbmis> (perform_update_id, x_compile, cr);
r.insert<hbmis> (perform_clean_id, x_compile, cr);
r.insert<hbmis> (configure_update_id, x_compile, cr);
}
}
r.insert<libue> (perform_update_id, x_link, lr);
r.insert<libue> (perform_clean_id, x_link, lr);
r.insert<libue> (configure_update_id, x_link, lr);
r.insert<libua> (perform_update_id, x_link, lr);
r.insert<libua> (perform_clean_id, x_link, lr);
r.insert<libua> (configure_update_id, x_link, lr);
if (s)
{
r.insert<libus> (perform_update_id, x_link, lr);
r.insert<libus> (perform_clean_id, x_link, lr);
r.insert<libus> (configure_update_id, x_link, lr);
}
r.insert<exe> (perform_update_id, x_link, lr);
r.insert<exe> (perform_clean_id, x_link, lr);
r.insert<exe> (configure_update_id, x_link, lr);
r.insert<liba> (perform_update_id, x_link, lr);
r.insert<liba> (perform_clean_id, x_link, lr);
r.insert<liba> (configure_update_id, x_link, lr);
if (s)
{
r.insert<libs> (perform_update_id, x_link, lr);
r.insert<libs> (perform_clean_id, x_link, lr);
r.insert<libs> (configure_update_id, x_link, lr);
}
// Note that while libu*{} are not installable, we need to see through
// them in case they depend on stuff that we need to install (see the
// install rule implementations for details).
//
if (install_loaded)
{
const install_rule& ir (*this);
r.insert<exe> (perform_install_id, x_install, ir);
r.insert<exe> (perform_uninstall_id, x_uninstall, ir);
r.insert<liba> (perform_install_id, x_install, ir);
r.insert<liba> (perform_uninstall_id, x_uninstall, ir);
if (s)
{
r.insert<libs> (perform_install_id, x_install, ir);
r.insert<libs> (perform_uninstall_id, x_uninstall, ir);
}
const libux_install_rule& lr (*this);
r.insert<libue> (perform_install_id, x_install, lr);
r.insert<libue> (perform_uninstall_id, x_uninstall, lr);
r.insert<libua> (perform_install_id, x_install, lr);
r.insert<libua> (perform_uninstall_id, x_uninstall, lr);
if (s)
{
r.insert<libus> (perform_install_id, x_install, lr);
r.insert<libus> (perform_uninstall_id, x_uninstall, lr);
}
}
}
}
}
}
| 32.958781
| 81
| 0.520635
|
build2
|
8721d1a22273035cf5721033a04becee7caa421b
| 1,068
|
cc
|
C++
|
libs/crypto/legacy-test-pkcs5.cc
|
sandtreader/obtools
|
2382e2d90bb62c9665433d6d01bbd31b8ad66641
|
[
"MIT"
] | null | null | null |
libs/crypto/legacy-test-pkcs5.cc
|
sandtreader/obtools
|
2382e2d90bb62c9665433d6d01bbd31b8ad66641
|
[
"MIT"
] | null | null | null |
libs/crypto/legacy-test-pkcs5.cc
|
sandtreader/obtools
|
2382e2d90bb62c9665433d6d01bbd31b8ad66641
|
[
"MIT"
] | null | null | null |
//==========================================================================
// ObTools::Crypto: test-pkcs5.cc
//
// Test harness for Crypto library PKCS5 padding functions
//
// Copyright (c) 2006 Paul Clark. All rights reserved
// This code comes with NO WARRANTY and is subject to licence agreement
//==========================================================================
#include "ot-crypto.h"
#include "ot-misc.h"
#include <iostream>
using namespace std;
using namespace ObTools;
//--------------------------------------------------------------------------
// Main
int main(int argc, char **argv)
{
Misc::Dumper dumper(cout, 16, 4, true);
const char *s = (argc>1)?argv[1]:"ABCD";
int length = strlen(s);
unsigned char *ps = Crypto::PKCS5::pad(
reinterpret_cast<const unsigned char *>(s),
length, 8);
cout << "Padded:\n";
dumper.dump(ps, length);
cout << "Original length is " << Crypto::PKCS5::original_length(ps, length)
<< endl;
free(ps);
return 0;
}
| 24.837209
| 77
| 0.481273
|
sandtreader
|
87232c2882af6dadaade39d821c6436e24b74a84
| 577
|
cpp
|
C++
|
cap03/cap03-01-01-test_search_value.cpp
|
ggaaaff/think_like_a_programmer--test_code
|
fb081d24d70db6dd503608562625b84607c7a3ab
|
[
"MIT"
] | 1
|
2020-12-08T10:54:39.000Z
|
2020-12-08T10:54:39.000Z
|
cap03/cap03-01-01-test_search_value.cpp
|
ggaaaff/think_like_a_programmer--test_code
|
fb081d24d70db6dd503608562625b84607c7a3ab
|
[
"MIT"
] | null | null | null |
cap03/cap03-01-01-test_search_value.cpp
|
ggaaaff/think_like_a_programmer--test_code
|
fb081d24d70db6dd503608562625b84607c7a3ab
|
[
"MIT"
] | null | null | null |
//2014.02.09 Gustaf - CTG.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "TEST Searching for a Specific Value \n";
const int ARRAY_SIZE = 10;
int intArray[ARRAY_SIZE] = {4, 5, 9, 12, -4, 0, -57, 30987, -287, 1};
int targetValue = 12;
int targetPos = 0;
while ((intArray[targetPos] != targetValue) && (targetPos < ARRAY_SIZE))
targetPos++;
if (targetPos < ARRAY_SIZE)
{
cout << targetValue << " Target Value Finded \n";
}
else
{
cout << targetValue << " Target Value NOT Finded \n";
}
return 0;
}
| 17.484848
| 74
| 0.613518
|
ggaaaff
|
872b2005306393fab82c78a2703a3027748461a7
| 2,358
|
cpp
|
C++
|
tutorial/test_async_stop_token.cpp
|
tearshark/librf
|
4299e2ff264aac9bcd9e4788e528de80044252c8
|
[
"Apache-2.0"
] | 434
|
2017-09-24T06:41:06.000Z
|
2022-03-29T10:24:14.000Z
|
tutorial/test_async_stop_token.cpp
|
tearshark/librf
|
4299e2ff264aac9bcd9e4788e528de80044252c8
|
[
"Apache-2.0"
] | 7
|
2017-12-06T13:08:33.000Z
|
2021-12-01T07:46:12.000Z
|
tutorial/test_async_stop_token.cpp
|
tearshark/librf
|
4299e2ff264aac9bcd9e4788e528de80044252c8
|
[
"Apache-2.0"
] | 95
|
2017-09-24T06:14:04.000Z
|
2022-03-22T06:23:14.000Z
|
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include "librf.h"
using namespace resumef;
using namespace std::chrono;
//_Ctype签名:void(bool, int64_t)
template<class _Ctype, typename=std::enable_if_t<std::is_invocable_v<_Ctype, bool, int64_t>>>
static void callback_get_long_with_stop(stop_token token, int64_t val, _Ctype&& cb)
{
std::thread([val, token = std::move(token), cb = std::forward<_Ctype>(cb)]
{
for (int i = 0; i < 10; ++i)
{
if (token.stop_requested())
{
cb(false, 0);
return;
}
std::this_thread::sleep_for(10ms);
}
//有可能未检测到token的停止要求
//如果使用stop_callback来停止,则务必保证检测到的退出要求是唯一的,且线程安全的
//否则,多次调用cb,会导致协程在半退出状态下,外部的awaitable_t管理的state获取跟root出现错误。
cb(true, val * val);
}).detach();
}
//token触发后,设置canceled_exception异常。
static future_t<int64_t> async_get_long_with_stop(stop_token token, int64_t val)
{
awaitable_t<int64_t> awaitable;
//在这里通过stop_callback来处理退出,并将退出转化为error_code::stop_requested异常。
//则必然会存在线程竞争问题,导致协程提前于callback_get_long_with_stop的回调之前而退出。
//同时,callback_get_long_with_stop还未必一定能检测到退出要求----毕竟只是一个要求,而不是强制。
callback_get_long_with_stop(token, val, [awaitable](bool ok, int64_t val)
{
if (ok)
awaitable.set_value(val);
else
awaitable.throw_exception(canceled_exception{error_code::stop_requested});
});
return awaitable.get_future();
}
//如果关联的协程被取消了,则触发canceled_exception异常。
static future_t<int64_t> async_get_long_with_stop(int64_t val)
{
task_t* task = current_task();
co_return co_await async_get_long_with_stop(task->get_stop_token(), val);
}
//测试取消协程
static void test_get_long_with_stop(int64_t val)
{
//异步获取值的协程
task_t* task = GO
{
try
{
int64_t result = co_await async_get_long_with_stop(val);
std::cout << result << std::endl;
}
catch (const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
};
//task的生命周期只在task代表的协程生存期间存在。
//但通过复制与其关联的stop_source,生存期可以超过task的生存期。
stop_source stops = task->get_stop_source();
//取消上一个协程的延迟协程
GO
{
co_await sleep_for(1ms * (rand() % 300));
stops.request_stop();
};
this_scheduler()->run_until_notask();
}
void resumable_main_stop_token()
{
srand((int)time(nullptr));
for (int i = 0; i < 10; ++i)
test_get_long_with_stop(i);
std::cout << "OK - stop_token!" << std::endl;
}
int main()
{
resumable_main_stop_token();
return 0;
}
| 22.673077
| 93
| 0.719254
|
tearshark
|
872bcde54549bdee3ba77e4d5909035efc2bb063
| 34,879
|
cpp
|
C++
|
PVPersonal.cpp
|
nardinan/vulture
|
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
|
[
"FTL"
] | null | null | null |
PVPersonal.cpp
|
nardinan/vulture
|
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
|
[
"FTL"
] | null | null | null |
PVPersonal.cpp
|
nardinan/vulture
|
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
|
[
"FTL"
] | null | null | null |
/* PSYCHO GAMES(C) STUDIOS - 2007 www.psychogames.net
* Project: Vulture(c)
* Author : Andrea Nardinocchi
* eMail : andrea@nardinan.it
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "PVPersonal.h"
int PVpersonal::login(void) {
FILE *configurationfile = NULL;
char *pathname = NULL;
int length = 0;
int times = 0;
if (infos.player->logics.hasvalue("STATUS", "Account") == 0) {
if ((pathname = (char *) pvmalloc(length = (sizeof (_PVFILES "players/") + strlen(infos.message) + sizeof (".dp") + 1)))) {
snprintf(pathname, (length), _PVFILES "players/%s.dp", infos.message);
if ((configurationfile = fopen(pathname, "r"))) {
if (!(pvulture.characters.gamecharacters.getaccount(infos.message))) {
if (infos.player->load(configurationfile, pvulture.objects.gameobjects, pvulture.map.gamemap) > 0) return 1;
else {
if (infos.player->setaccount(infos.message) > 0) return 1;
if (infos.player->opvsend(pvulture.server, "[reset][bold][green]Account esistente![n]Password:[hide]") > 0) return 1;
if (infos.player->logics.delvalue("STATUS", "Account") > 0) LOG_ERROR("Unable to find STATUS->Account Logic");
if (infos.player->logics.addvalue("STATUS", "Password", 1) > 0) LOG_ERROR("Unable to add STATUS->Password Logic");
}
} else if (infos.player->opvsend(pvulture.server, "[reset][bold][red]Account gia' in uso![n]Account:") > 0) return 1;
fclose(configurationfile);
} else {
if (infos.player->opvsend(pvulture.server, "[reset][bold][red]Account non esistente![n]") > 0) return 1;
times = getvalue("TIMES", "Account", infos.player->logics, 0);
if (++times >= logintries) {
if (infos.player->opvsend(pvulture.server, "[reset][red]hai sbagliato account per %d volte![n]", logintries) > 0) return 1;
if (pathname) {
pvfree(pathname);
pathname = NULL;
}
return -1;
} else {
infos.player->logics.addvalue("TIMES", "Account", times);
if (infos.player->opvsend(pvulture.server, "Account:") > 0) return 1;
}
}
} else return 1;
if (pathname) {
pvfree(pathname);
pathname = NULL;
}
} else if (infos.player->logics.hasvalue("STATUS", "Password") == 0) {
if (compare.vcmpcase(infos.message, LSTRSIZE(infos.player->getpassword())) == 0) {
if (infos.player->opvsend(pvulture.server, "[reset][bold][green]Password corretta![n]") > 0) return 1;
if (infos.player->logics.delvalue("STATUS", "Password") > 0) LOG_ERROR("Unable to delete STATUS->Password Logic");
if (infos.player->logics.addvalue("STATUS", "Online", pvulture.stopwatch.pause()) > 0) LOG_ERROR("Unable to add STATUS->Online Logic");
if (!infos.player->position) {
if (!(infos.player->position = pvulture.map.gamemap.gettilesroot()->tile)) return 1;
}
infos.player->setonline();
if (infos.player->setlogging(true) > 0) LOG_ERROR("Unable to run SETLOGGING()");
if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) {
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name entra in gioco[n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
}
if (environmentcommands.lookenvironment() > 0) return 1;
if (players.hasvalue(infos.player->getID()) != 0) {
if (players.addvalue(pvulture.characters.getsimplename(infos.player), infos.player->getID()) > 0) return 1;
else if (infos.player->pvsend(pvulture.server, "[reset][green]sei stato aggiunto alla lista utenti di gioco![n]") > 0) return 1;
}
if (infos.player->logics.hascategory("GROUP") == 0) {
if (groups.hasvalue(infos.player->logics.getvalue("GROUP", 3)) != 0) {
if (infos.player->logics.delcategory("GROUP") > 0) return 1;
if (infos.player->pvsend(pvulture.server, "[reset][red]il tuo gruppo si e' sciolto![n]") > 0) return 1;
}
}
if (infos.player->spvsend(pvulture.server, sshell) > 0) return 1;
} else {
if (infos.player->opvsend(pvulture.server, "[reset][bold][red]Password Errata![n]") > 0) return 1;
times = getvalue("TIMES", "Password", infos.player->logics, 0);
if (++times >= logintries) {
if (infos.player->opvsend(pvulture.server, "[reset][red]hai sbagliato password per %d volte![n]", logintries) > 0) return 1;
return -1;
} else {
infos.player->logics.addvalue("TIMES", "Password", times);
if (infos.player->opvsend(pvulture.server, "Password:[hide]") > 0) return 1;
}
}
}
return 0;
}
int PVpersonal::logout(bool message) {
if (compare.vcmpcase(infos.player->getaccount(), CSTRSIZE("###")) != 0) {
infos.player->logics.delvalue("STATUS", "Online");
infos.player->logics.delvalue("STATUS", "Last");
if (infos.player->logics.hascategory("FIGHT") == 0)
if (infos.player->logics.delcategory("FIGHT") > 0) LOG_ERROR("Unable to delete FIGHT Category");
if (infos.player->logics.hascategory("TIMES") == 0)
if (infos.player->logics.delcategory("TIMES") > 0) LOG_ERROR("Unable to delete TIMES Category");
if (infos.player->logics.hascategory("FOLLOW") == 0)
if (infos.player->logics.delcategory("FOLLOW") > 0) LOG_ERROR("Unable to delete FOLLOW Category");
if (pvulture.characters.gamecharacters.saveplayer(infos.player->getID(), _PVFILES "players/", pvulture.objects.gameobjects) > 0) return 1;
if (infos.player->position) {
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (message) {
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name esce dal gioco[n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
}
}
}
if (pvulture.server.unload(infos.player->getsocketID()) > 0) return 1;
if (pvulture.characters.gamecharacters.delplayer(infos.player->getID()) > 0) return 1;
infos.player = NULL;
return 0;
}
int PVpersonal::status(void) {
char *command = NULL;
char *message = NULL;
Cplayer *player = NULL;
Cmob *mob = NULL;
int value = 0;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if ((command = strings.vpop(&message)) &&
((!message) || ((infos.player->logics.hasvalue("RANK", "Admin") != 0) &&
(infos.player->logics.hasvalue("RANK", "Moderator") != 0)))) {
value = status(infos.player);
} else {
if ((player = pvulture.characters.getplayer(message, infos.player->position))) {
value = status(player);
} else if ((mob = pvulture.characters.getmob(message, infos.player->position))) {
value = status(mob);
} else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome![n]") > 0) return 1;
}
} else return 1;
if (message) {
pvfree(message);
message = NULL;
}
if (command) {
pvfree(command);
command = NULL;
}
return value;
}
int PVpersonal::status(Cplayer *player) {
char *charactername = NULL;
char *backup = NULL;
int index = 0;
if (infos.player->getID() != player->getID()) {
if (infos.player->pvsend(pvulture.server, "Lo status di %s e' il seguente:[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
}
if (infos.player->pvsend(pvulture.server, "Livello Vita %s[n]", (backup = funny.vbar(getvalue("STATS", "LPoints", player->logics, 0), 100)) ? backup : "") > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
if (infos.player->pvsend(pvulture.server, "Livello Stamina %s[n]", (backup = funny.vbar(getvalue("STATS", "SPoints", player->logics, 0), 100)) ? backup : "") > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
if (infos.player->pvsend(pvulture.server, "[reset][n][bold]ABILITA':[n]") > 0) return 1;
while (compare.vcmpcase(chacharas[index].representation, CSTRSIZE("NULL")) != 0) {
if ((backup = pvulture.characters.getability(player, chacharas[index].representation))) {
if (infos.player->pvsend(pvulture.server, backup) > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
}
index++;
}
return 0;
}
int PVpersonal::status(Cmob *mob) {
char *charactername = NULL;
char *backup = NULL;
int index = 0;
if (infos.player->pvsend(pvulture.server, "Lo status di %s e' il seguente:[n]", charactername = pvulture.characters.gettargetname(mob, infos.player)) > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
if (infos.player->pvsend(pvulture.server, "Livello Vita %s[n]", (backup = funny.vbar(getvalue("STATS", "LPoints", mob->logics, 0), 100)) ? backup : "") > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
if (infos.player->pvsend(pvulture.server, "Livello Stamina %s[n]", (backup = funny.vbar(getvalue("STATS", "SPoints", mob->logics, 0), 100)) ? backup : "") > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
if (infos.player->pvsend(pvulture.server, "[reset][n][bold]ABILITA':[n]") > 0) return 1;
while (compare.vcmpcase(chacharas[index].representation, CSTRSIZE("NULL")) != 0) {
if ((backup = pvulture.characters.getability(mob, chacharas[index].representation))) {
if (infos.player->pvsend(pvulture.server, backup) > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
}
index++;
}
return 0;
}
int PVpersonal::position(void) {
if (compare.vcmpcase(infos.message, CSTRSIZE("alza")) == 0) {
if (getvalue("STATS", "Legs", infos.player->logics, 0) > 0) {
if ((infos.player->logics.hasvalue("STATUS", "Seated") == 0) ||
(infos.player->logics.hasvalue("STATUS", "Stretched") == 0)) {
infos.player->logics.delvalue("STATUS", "Seated");
infos.player->logics.delvalue("STATUS", "Stretched");
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][green]ti alzi in piedi[n]") > 0) return 1;
if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) {
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name si alza in piedi[n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
}
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
} else if (infos.player->pvsend(pvulture.server, "[reset]sei gia' in piedi![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]hai le gambe distrutte! non riesci a muoverti![n]") > 0) return 1;
} else if (compare.vcmpcase(infos.message, CSTRSIZE("siedi")) == 0) {
if ((infos.player->logics.hasvalue("STATUS", "Seated") != 0) ||
(infos.player->logics.hasvalue("STATUS", "Stretched") == 0)) {
infos.player->logics.addvalue("STATUS", "Seated", 1);
infos.player->logics.delvalue("STATUS", "Stretched");
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][green]ti metti a sedere[n]") > 0) return 1;
if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) {
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name si siede a terra[n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
}
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
} else if (infos.player->pvsend(pvulture.server, "[reset]sei gia' sedut%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1;
} else {
if ((infos.player->logics.hasvalue("STATUS", "Seated") == 0) ||
(infos.player->logics.hasvalue("STATUS", "Stretched") != 0)) {
infos.player->logics.delvalue("STATUS", "Seated");
infos.player->logics.addvalue("STATUS", "Stretched", 1);
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][green]ti sdrai a terra[n]") > 0) return 1;
if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) {
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name si sdraia a terra[n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
}
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
} else if (infos.player->pvsend(pvulture.server, "[reset]sei gia' sdraiat%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1;
}
return 0;
}
int PVpersonal::inventory(void) {
char *message = NULL;
char *command = NULL;
char *backup = NULL;
char *charactername = NULL;
Cplayer *player = NULL;
Cmob *mob = NULL;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if ((command = strings.vpop(&message)) &&
((!message) || ((infos.player->logics.hasvalue("RANK", "Admin") != 0) &&
(infos.player->logics.hasvalue("RANK", "Moderator") != 0)))) {
if (!(backup = pvulture.objects.getinventory(infos.player)))
return 1;
} else {
if ((player = pvulture.characters.getplayer(message, infos.player->position))) {
if (!(backup = pvulture.objects.getinventory(player)))
return 1;
} else if ((mob = pvulture.characters.getmob(message, infos.player->position))) {
if (!(backup = pvulture.objects.getinventory(mob)))
return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome![n]") > 0)
return 1;
}
}
if (backup) {
if (mob) {
if (infos.player->pvsend(pvulture.server, "%s sta' portando:[n]", charactername = pvulture.characters.gettargetname(mob, infos.player)) > 0)
return 1;
} else if (player) {
if (player->getID() != infos.player->getID()) {
if (infos.player->pvsend(pvulture.server, "%s sta' portando:[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0)
return 1;
} else
if (infos.player->pvsend(pvulture.server, "stai portando:[n]") > 0)
return 1;
} else
if (infos.player->pvsend(pvulture.server, "stai portando:[n]") > 0)
return 1;
if (infos.player->pvsend(pvulture.server, backup) > 0)
return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
pvfree(backup);
backup = NULL;
}
if (message) {
pvfree(message);
message = NULL;
}
if (command) {
pvfree(command);
command = NULL;
}
return 0;
}
int PVpersonal::points(void) {
char *command = NULL;
char *message = NULL;
char *text = NULL;
char *pointer = NULL;
Cplayer *player = NULL;
Cmob *mob = NULL;
int value = 0;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if ((command = strings.vpop(&message)) && (message)) {
if ((pointer = strchr(message, ':'))) {
for (text = pointer + 1; *text == ' '; text++);
do {
*pointer-- = '\0';
} while ((pointer > message) && (*pointer == ' '));
if (strlen(text) > 0) {
if ((player = pvulture.characters.getplayer(message, infos.player->position))) {
value = points(player, text);
} else if ((mob = pvulture.characters.getmob(message, infos.player->position))) {
value = points(mob, text);
} else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare una categoria e un punteggio[n]") > 0) return 1;
} else {
value = points(infos.player, message);
}
} else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare una categoria e un punteggio[n]") > 0) return 1;
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
} else return 1;
if (command) {
pvfree(command);
command = NULL;
}
if (message) {
pvfree(message);
message = NULL;
}
return 0;
}
int PVpersonal::points(Cplayer *player, char *message) {
char *charactername = NULL;
char *category = NULL;
char *key = NULL;
int value = 0;
if ((strings.vsscanf(message, '.', "ssd", &category, &key, &value) == 0) &&
(player->logics.hasvalue(category, key) == 0)) {
if (player->logics.delvalue(category, key) > 0) LOG_ERROR("Unable to delete %s->%s Logic", category, key);
else if (player->logics.addvalue(category, key, value) > 0) LOG_ERROR("Unable to add %s->%s Logic", category, key);
else if (player->getID() != infos.player->getID()) {
if (infos.player->pvsend(pvulture.server, "[reset][green]hai modificato il valore di %s.%s di %s in %d[n]", category, key, charactername = pvulture.characters.gettargetname(player, infos.player), value) > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
} else if (infos.player->pvsend(pvulture.server, "[reset][green]hai modificato il tuo valore di %s.%s in %d[n]", category, key, value) > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]non esiste una simile categoria/chiave nella logica[n]") > 0) return 1;
if (key) {
pvfree(key);
key = NULL;
}
if (category) {
pvfree(category);
category = NULL;
}
return 0;
}
int PVpersonal::points(Cmob *mob, char *message) {
char *charactername = NULL;
char *category = NULL;
char *key = NULL;
int value = 0;
if ((strings.vsscanf(message, '.', "ssd", &category, &key, &value) == 0) &&
(mob->logics.hasvalue(category, key) == 0)) {
if (mob->logics.delvalue(category, key) > 0) LOG_ERROR("Unable to delete %s->%s Logic", category, key);
else if (mob->logics.addvalue(category, key, value) > 0) LOG_ERROR("Unable to add %s->%s Logic", category, key);
else if (mob->getID() != infos.player->getID()) {
if (infos.player->pvsend(pvulture.server, "[reset]hai modificato il valore di %s.%s di %s in %d[n]", category, key, charactername = pvulture.characters.gettargetname(mob, infos.player), value) > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
} else if (infos.player->pvsend(pvulture.server, "[reset][green]hai modificato il tuo valore di %s.%s in %d[n]", category, key, value) > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]non esiste una simile categoria/chiave nella logica[n]") > 0) return 1;
if (key) {
pvfree(key);
key = NULL;
}
if (category) {
pvfree(category);
category = NULL;
}
return 0;
}
int PVpersonal::password(void) {
char *message = NULL;
char *command = NULL;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if ((command = strings.vpop(&message)) && (message)) {
if (infos.player->setpassword(message) > 0) {
if (infos.player->pvsend(pvulture.server, "[reset]la password e' troppo corta![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset][green]hai cambiato la password![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]devi specificare la nuova password![n]") > 0) return 1;
} else return 1;
if (message) {
pvfree(message);
message = NULL;
}
if (command) {
pvfree(command);
command = NULL;
}
return 0;
}
int PVpersonal::appearance(void) {
int position = 0;
char *message = NULL;
char *command = NULL;
char *completename = NULL;
char *smalldescription = NULL;
char *largedescription = NULL;
char *race = NULL;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if ((command = strings.vpop(&message)) && (message)) {
position = getvalue("SYSTEM", "Position", infos.player->logics, 0);
if (strings.vsscanf(message, ':', "ssss", &completename, &smalldescription, &largedescription, &race) == 0) {
if (infos.player->logics.hasvalue("RACE", 0) == 0) {
if (infos.player->logics.delvalue("RACE", 0) > 0) LOG_ERROR("Unable to delete RACE->%s Logic", race);
}
if (infos.player->logics.addvalue("RACE", race, 0) > 0) LOG_ERROR("Unable to add RACE->%s Logic", race);
if (infos.player->descriptions.deldescription(position) == 0) {
infos.player->descriptions.adddescription(position, completename, smalldescription, largedescription);
if (infos.player->pvsend(pvulture.server, "[reset][green]hai cambiato il tuo aspetto e la tua razza![n]") > 0) return 1;
} else return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]devi specificare un nuovo aspetto per il tuo personaggio![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]devi specificare un nuovo aspetto per il tuo personaggio![n]") > 0) return 1;
} else return 1;
if (message) {
pvfree(message);
message = NULL;
}
if (command) {
pvfree(command);
command = NULL;
}
if (completename) {
pvfree(completename);
completename = NULL;
}
if (smalldescription) {
pvfree(smalldescription);
smalldescription = NULL;
}
if (largedescription) {
pvfree(largedescription);
largedescription = NULL;
}
if (race) {
pvfree(race);
race = NULL;
}
return 0;
}
int PVpersonal::emoticon(void) {
char *message = NULL;
char *text = NULL;
char *emoticon = NULL;
char *buffer = NULL;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
emoticon = getemoticon(&message);
for (text = message + 1; *text == ' '; text++);
if (strlen(text) > 0) {
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][green]ti vedi mentre il tuo [bold]'io'[reset][green], %s %s[n]", text, (emoticon) ? emoticon : "") > 0) return 1;
if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) {
if (spvsend(pvulture.server, infos.player->position, (buffer = allocate.vsalloc("[n][yellow]$name %s %s[n]", text, (emoticon) ? emoticon : "")), (Ccharacter *) infos.player) > 0) return 1;
}
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
} else if (infos.player->pvsend(pvulture.server, "[reset]devi specificare un'azione![n]") > 0) return 1;
} else return 1;
if (message) {
pvfree(message);
message = NULL;
}
if (emoticon) {
pvfree(emoticon);
emoticon = NULL;
}
if (buffer) {
pvfree(buffer);
buffer = NULL;
}
return 0;
}
int PVpersonal::meet(void) {
char *command = NULL;
char *message = NULL;
Cplayer *player = NULL;
Cmob *mob = NULL;
int value = 0;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if ((command = strings.vpop(&message)) && (message)) {
if ((player = pvulture.characters.getplayer(message, infos.player->position))) {
value = meet(player);
} else if ((mob = pvulture.characters.getmob(message, infos.player->position))) {
value = meet(mob);
} else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1;
} else return 1;
if (message) {
pvfree(message);
message = NULL;
}
if (command) {
pvfree(command);
command = NULL;
}
return value;
}
int PVpersonal::meet(Cplayer *player) {
char *charactername = NULL;
if (player->getID() != infos.player->getID()) {
if (!(player->getcharacter(infos.player->getID(), PLAYER))) {
if (player->addcharacter(infos.player->getID(), PLAYER) > 0) return 1;
if (infos.player->pvsend(pvulture.server, "[reset][yellow]ti presenti a %s[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1;
if (player->pvsend(pvulture.server, "[reset][n][yellow]%s ti si presenta[n]", pvulture.characters.getsimplename(infos.player)) > 0) return 1;
if (player->spvsend(pvulture.server, sshell) > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]da quel che sembra, lui ti conosce di gia'![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
return 0;
}
int PVpersonal::meet(Cmob *mob) {
char *charactername = NULL;
if (!(mob->getcharacter(infos.player->getID(), PLAYER))) {
if (mob->addcharacter(infos.player->getID(), PLAYER) > 0) return 1;
if (infos.player->pvsend(pvulture.server, "[reset][yellow]ti presenti a %s[n]", charactername = pvulture.characters.gettargetname(mob, infos.player)) > 0) return 1;
if (intelligenceevents.meet(mob, infos.player) > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]da quel che sembra, lui ti conosce di gia'![n]") > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
return 0;
}
int PVpersonal::hide(void) {
if (infos.player->logics.hasvalue("STATUS", "Hide") == 0) {
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][yellow]spunti fuori dall'ombra![n]") > 0) return 1;
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name appare da una nuvola di fumo![n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
if (infos.player->logics.delvalue("STATUS", "Hide") > 0) LOG_ERROR("Unable to delete STATUS->Hide Logic");
} else {
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][yellow]ti nascondi nell'ombra![n]") > 0) return 1;
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name scompare in una nuvola di fumo![n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
if (infos.player->logics.addvalue("STATUS", "Hide", 1) > 0) LOG_ERROR("Unable to add STATUS->Hide Logic");
}
return 0;
}
PVpersonal personalcommands;
int personal(void) {
if (compare.vcmpcase(infos.message, CSTRSIZE("status")) == 0) {
if (personalcommands.status() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.STATUS()");
} else if (compare.vcmpcase(infos.message, CSTRSIZE("inventario")) == 0) {
if (personalcommands.inventory() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.INVENTORY()");
} else if (compare.vcmpcase(infos.message, CSTRSIZE("passwd")) == 0) {
if (personalcommands.password() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.PASSWORD()");
} else if ((compare.vcmpcase(infos.message, CSTRSIZE("alza")) == 0) ||
(compare.vcmpcase(infos.message, CSTRSIZE("siedi")) == 0) ||
(compare.vcmpcase(infos.message, CSTRSIZE("sdraia")) == 0)) {
if (personalcommands.position() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.POSITION()");
} else if ((compare.vcmpcase(infos.message, CSTRSIZE("aspetto")) == 0) &&
((infos.player->logics.hasvalue("RANK", "Admin") == 0) ||
(infos.player->logics.hasvalue("RANK", "Moderator") == 0))) {
if (personalcommands.appearance() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.APPEARANCE()");
} else if ((compare.vcmpcase(infos.message, CSTRSIZE("valore")) == 0) &&
((infos.player->logics.hasvalue("RANK", "Admin") == 0) ||
(infos.player->logics.hasvalue("RANK", "Moderator") == 0))) {
if (personalcommands.points() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.POINTS()");
} else if (compare.vcmpcase(infos.message, CSTRSIZE(":")) == 0) {
if (personalcommands.emoticon() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.EMOTICON()");
} else if (compare.vcmpcase(infos.message, CSTRSIZE("presenta")) == 0) {
if (personalcommands.meet() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.MEET()");
} else if ((compare.vcmpcase(infos.message, CSTRSIZE("nascondi")) == 0) &&
((infos.player->logics.hasvalue("RANK", "Admin") == 0) ||
(infos.player->logics.hasvalue("RANK", "Moderator") == 0))) {
if (personalcommands.hide() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.HIDE()");
} else if (infos.player->pvsend(pvulture.server, "[reset]prego?[n]") > 0) return 1;
return 0;
}
| 50.918248
| 229
| 0.579718
|
nardinan
|
872d353085923567ca1f97e3c39511c08b594fde
| 5,076
|
cpp
|
C++
|
csapex_sample_consensus/src/nodes/ransac.cpp
|
AdrianZw/csapex_core_plugins
|
1b23c90af7e552c3fc37c7dda589d751d2aae97f
|
[
"BSD-3-Clause"
] | 2
|
2016-09-02T15:33:22.000Z
|
2019-05-06T22:09:33.000Z
|
csapex_sample_consensus/src/nodes/ransac.cpp
|
AdrianZw/csapex_core_plugins
|
1b23c90af7e552c3fc37c7dda589d751d2aae97f
|
[
"BSD-3-Clause"
] | 1
|
2021-02-14T19:53:30.000Z
|
2021-02-14T19:53:30.000Z
|
csapex_sample_consensus/src/nodes/ransac.cpp
|
AdrianZw/csapex_core_plugins
|
1b23c90af7e552c3fc37c7dda589d751d2aae97f
|
[
"BSD-3-Clause"
] | 6
|
2016-10-12T00:55:23.000Z
|
2021-02-10T17:49:25.000Z
|
/// PROJECT
#include "sample_consensus.hpp"
namespace csapex
{
using namespace connection_types;
class Ransac : public SampleConsensus
{
public:
Ransac() = default;
void setupParameters(Parameterizable& parameters) override
{
SampleConsensus::setupParameters(parameters);
parameters.addParameter(param::factory::declareBool("use outlier probability", false), ransac_parameters_.use_outlier_probability);
parameters.addConditionalParameter(param::factory::declareRange("outlier probability", 0.01, 1.0, 0.9, 0.01), [this]() { return ransac_parameters_.use_outlier_probability; },
ransac_parameters_.outlier_probability);
parameters.addParameter(param::factory::declareValue("random seed", -1), std::bind(&Ransac::setupRandomGenerator, this));
parameters.addParameter(param::factory::declareRange("maximum sampling retries", 1, 1000, 100, 1), ransac_parameters_.maximum_sampling_retries);
}
virtual void process() override
{
PointCloudMessage::ConstPtr msg(msg::getMessage<PointCloudMessage>(in_cloud_));
boost::apply_visitor(PointCloudMessage::Dispatch<Ransac>(this, msg), msg->value);
}
template <class PointT>
void inputCloud(typename pcl::PointCloud<PointT>::ConstPtr cloud)
{
std::shared_ptr<std::vector<pcl::PointIndices>> out_inliers(new std::vector<pcl::PointIndices>);
std::shared_ptr<std::vector<pcl::PointIndices>> out_outliers(new std::vector<pcl::PointIndices>);
std::shared_ptr<std::vector<ModelMessage>> out_models(new std::vector<ModelMessage>);
/// retrieve the model to use
auto model = getModel<PointT>(cloud);
/// get indices of points to use
std::vector<int> prior_inlier;
std::vector<int> prior_outlier;
getInidicesFromInput(prior_inlier);
if (prior_inlier.empty()) {
if (keep_invalid_as_outlier_)
getIndices<PointT>(cloud, prior_inlier, prior_outlier);
else
getIndices<PointT>(cloud, prior_inlier);
}
/// prepare algorithm
ransac_parameters_.assign(sac_parameters_);
typename csapex_sample_consensus::Ransac<PointT>::Ptr sac(new csapex_sample_consensus::Ransac<PointT>(prior_inlier, ransac_parameters_, rng_));
pcl::PointIndices outliers;
pcl::PointIndices inliers;
inliers.header = cloud->header;
outliers.header = cloud->header;
if (fit_multiple_models_) {
outliers.indices = sac->getIndices();
int model_searches = 0;
while ((int)outliers.indices.size() >= minimum_residual_cloud_size_) {
auto working_model = model->clone();
sac->computeModel(working_model);
if (working_model) {
inliers.indices.clear();
outliers.indices.clear();
working_model->getInliersAndOutliers(ransac_parameters_.model_search_distance, inliers.indices, outliers.indices);
if ((int)inliers.indices.size() > minimum_model_cloud_size_)
out_inliers->emplace_back(inliers);
else
out_outliers->emplace_back(inliers);
sac->setIndices(outliers.indices);
}
++model_searches;
if (maximum_model_count_ != -1 && model_searches >= maximum_model_count_)
break;
}
out_outliers->emplace_back(outliers);
} else {
sac->computeModel(model);
if (model) {
model->getInliersAndOutliers(prior_inlier, ransac_parameters_.model_search_distance, inliers.indices, outliers.indices);
if ((int)inliers.indices.size() > minimum_model_cloud_size_) {
out_inliers->emplace_back(inliers);
} else {
out_outliers->emplace_back(inliers);
}
outliers.indices.insert(outliers.indices.end(), prior_outlier.begin(), prior_outlier.end());
out_outliers->emplace_back(outliers);
}
}
msg::publish<GenericVectorMessage, pcl::PointIndices>(out_inlier_indices_, out_inliers);
msg::publish<GenericVectorMessage, pcl::PointIndices>(out_outlier_indices_, out_outliers);
msg::publish<GenericVectorMessage, ModelMessage>(out_models_, out_models);
}
protected:
csapex_sample_consensus::RansacParameters ransac_parameters_;
std::default_random_engine rng_; /// keep the random engine alive for better number generation
inline void setupRandomGenerator()
{
int seed = readParameter<int>("random seed");
if (seed >= 0) {
rng_ = std::default_random_engine(seed);
} else {
std::random_device rd;
rng_ = std::default_random_engine(rd());
}
}
};
} // namespace csapex
CSAPEX_REGISTER_CLASS(csapex::Ransac, csapex::Node)
| 40.608
| 182
| 0.635737
|
AdrianZw
|
873048c42c07552f2c28839f97f603836ea52a78
| 1,362
|
cc
|
C++
|
chromecast/android/cast_jni_registrar.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chromecast/android/cast_jni_registrar.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chromecast/android/cast_jni_registrar.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/android/cast_jni_registrar.h"
#include "base/android/jni_android.h"
#include "base/android/jni_registrar.h"
#include "base/macros.h"
#include "chromecast/base/android/system_time_change_notifier_android.h"
#include "chromecast/base/chromecast_config_android.h"
#include "chromecast/chromecast_features.h"
#if BUILDFLAG(IS_CAST_USING_CMA_BACKEND)
#include "chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.h"
#include "chromecast/media/cma/backend/android/volume_control_android.h"
#endif
namespace chromecast {
namespace android {
namespace {
static base::android::RegistrationMethod kMethods[] = {
{"ChromecastConfigAndroid", ChromecastConfigAndroid::RegisterJni},
{"SystemTimeChangeNotifierAndroid",
SystemTimeChangeNotifierAndroid::RegisterJni},
#if BUILDFLAG(IS_CAST_USING_CMA_BACKEND)
{"AudioSinkAudioTrackImpl",
media::AudioSinkAndroidAudioTrackImpl::RegisterJni},
{"VolumeControlAndroid", media::VolumeControlAndroid::RegisterJni},
#endif
};
} // namespace
bool RegisterJni(JNIEnv* env) {
return RegisterNativeMethods(env, kMethods, arraysize(kMethods));
}
} // namespace android
} // namespace chromecast
| 31.674419
| 84
| 0.792217
|
metux
|
8730b3d7ae083b97f36ae568df4cb7d400b15331
| 6,147
|
cpp
|
C++
|
src/sylvaneth/DrychaHamadreth.cpp
|
rweyrauch/AoSSimulator
|
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
|
[
"MIT"
] | 5
|
2019-02-01T01:41:19.000Z
|
2021-06-17T02:16:13.000Z
|
src/sylvaneth/DrychaHamadreth.cpp
|
rweyrauch/AoSSimulator
|
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
|
[
"MIT"
] | 2
|
2020-01-14T16:57:42.000Z
|
2021-04-01T00:53:18.000Z
|
src/sylvaneth/DrychaHamadreth.cpp
|
rweyrauch/AoSSimulator
|
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
|
[
"MIT"
] | 1
|
2019-03-02T20:03:51.000Z
|
2019-03-02T20:03:51.000Z
|
/*
* Warhammer Age of Sigmar battle simulator.
*
* Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <algorithm>
#include <sylvaneth/DrychaHamadreth.h>
#include <UnitFactory.h>
#include <spells/MysticShield.h>
#include <sylvaneth/SylvanethSpells.h>
#include "SylvanethPrivate.h"
namespace Sylvaneth {
static const int g_basesize = 105; // x70 oval
static const int g_wounds = 10;
static const int g_pointsPerUnit = 330;
bool DrychaHamadreth::s_registered = false;
struct TableEntry {
int m_flitterfuriesRange;
int m_squirmlingsHit;
int m_talonAttacks;
};
const size_t g_numTableEntries = 5;
const int g_woundThresholds[g_numTableEntries] = {2, 4, 6, 8, g_wounds};
const TableEntry g_damageTable[g_numTableEntries] =
{
{18, 3, 6},
{15, 4, 5},
{12, 4, 4},
{9, 5, 3},
{6, 5, 2}
};
DrychaHamadreth::DrychaHamadreth(Glade glade, Lore lore, bool isGeneral) :
SylvanethBase("Drycha Hamadreth", 9, g_wounds, 8, 3, false, g_pointsPerUnit),
m_colonyOfFlitterfuries(Weapon::Type::Missile, "Colony of Flitterfuries", 18, 10, 4, 3, -1, 1),
m_swarmOfSquirmlings(Weapon::Type::Missile, "Swarm of Squirmlings", 2, 10, 3, 4, 0, 1),
m_slashingTalons(Weapon::Type::Melee, "Slashing Talons", 2, 6, 4, 3, -2, 2) {
m_keywords = {ORDER, SYLVANETH, OUTCASTS, MONSTER, HERO, WIZARD, DRYCHA_HAMADRETH};
m_weapons = {&m_colonyOfFlitterfuries, &m_swarmOfSquirmlings, &m_slashingTalons};
m_battleFieldRole = Role::Leader_Behemoth;
m_totalUnbinds = 1;
m_totalSpells = 1;
s_globalToWoundReroll.connect(this, &DrychaHamadreth::songOfSpiteToWoundRerolls, &m_songSlot);
setGlade(glade);
setGeneral(isGeneral);
auto model = new Model(g_basesize, wounds());
model->addMissileWeapon(&m_colonyOfFlitterfuries);
model->addMissileWeapon(&m_swarmOfSquirmlings);
model->addMeleeWeapon(&m_slashingTalons);
model->addMeleeWeapon(&m_thornedSlendervines);
addModel(model);
m_knownSpells.push_back(std::unique_ptr<Spell>(CreatePrimalTerror(this)));
m_knownSpells.push_back(std::unique_ptr<Spell>(CreateLore(lore, this)));
m_knownSpells.push_back(std::unique_ptr<Spell>(CreateArcaneBolt(this)));
m_knownSpells.push_back(std::make_unique<MysticShield>(this));
m_points = g_pointsPerUnit;
}
DrychaHamadreth::~DrychaHamadreth() {
m_songSlot.disconnect();
}
void DrychaHamadreth::onWounded() {
SylvanethBase::onWounded();
const auto damageIndex = getDamageTableIndex();
m_colonyOfFlitterfuries.setRange(g_damageTable[damageIndex].m_flitterfuriesRange);
m_swarmOfSquirmlings.setToHit(g_damageTable[damageIndex].m_squirmlingsHit);
m_slashingTalons.setAttacks(g_damageTable[damageIndex].m_talonAttacks);
}
size_t DrychaHamadreth::getDamageTableIndex() const {
auto woundsInflicted = wounds() - remainingWounds();
for (auto i = 0u; i < g_numTableEntries; i++) {
if (woundsInflicted < g_woundThresholds[i]) {
return i;
}
}
return 0;
}
Unit *DrychaHamadreth::Create(const ParameterList ¶meters) {
auto glade = (Glade) GetEnumParam("Glade", parameters, g_glade[0]);
auto lore = (Lore) GetEnumParam("Lore", parameters, g_loreOfTheDeepwood[0]);
auto general = GetBoolParam("General", parameters, false);
return new DrychaHamadreth(glade, lore, general);
}
void DrychaHamadreth::Init() {
if (!s_registered) {
static FactoryMethod factoryMethod = {
DrychaHamadreth::Create,
SylvanethBase::ValueToString,
SylvanethBase::EnumStringToInt,
DrychaHamadreth::ComputePoints,
{
EnumParameter("Glade", g_glade[0], g_glade),
EnumParameter("Lore", g_loreOfTheDeepwood[0], g_loreOfTheDeepwood),
BoolParameter("General")
},
ORDER,
{SYLVANETH}
};
s_registered = UnitFactory::Register("Drycha Hamadreth", factoryMethod);
}
}
Wounds DrychaHamadreth::weaponDamage(const Model* attackingModel, const Weapon *weapon, const Unit *target, int hitRoll, int woundRoll) const {
// Deadly Infestation
if (((weapon->name() == m_colonyOfFlitterfuries.name()) || weapon->name() == m_swarmOfSquirmlings.name()) &&
(woundRoll == 6)) {
return {0, 1};
}
return SylvanethBase::weaponDamage(attackingModel, weapon, target, hitRoll, woundRoll);
}
void DrychaHamadreth::onBeginRound(int battleRound) {
// Mercurial Aspect
m_enraged = (m_meleeTarget == nullptr);
SylvanethBase::onBeginRound(battleRound);
}
int DrychaHamadreth::extraAttacks(const Model *attackingModel, const Weapon *weapon, const Unit *target) const {
auto extra = SylvanethBase::extraAttacks(attackingModel, weapon, target);
// Mecurial Aspect
if (weapon->name() == m_colonyOfFlitterfuries.name() && m_enraged) {
extra += 10;
}
if (weapon->name() == m_swarmOfSquirmlings.name() && !m_enraged) {
extra += 10;
}
return extra;
}
int DrychaHamadreth::ComputePoints(const ParameterList& /*parameters*/) {
return g_pointsPerUnit;
}
Rerolls DrychaHamadreth::songOfSpiteToWoundRerolls(const Unit *attacker, const Weapon *weapon, const Unit *target) {
if (isFriendly(attacker) && attacker->hasKeyword(SPITE_REVENANTS) && (distanceTo(attacker) < 16.0))
return Rerolls::Ones;
return Rerolls::None;
}
} // namespace Sylvaneth
| 38.660377
| 147
| 0.626647
|
rweyrauch
|
873294da4f704846cd5adfaf011522e881ea2829
| 4,418
|
cpp
|
C++
|
pymaplib_cpp/src/pixelbuf.cpp
|
Grk0/MapsEvolved
|
e058a324e7d3c9b4c9b7e00d65b6f9da029fc7de
|
[
"PSF-2.0"
] | 3
|
2015-06-09T10:41:15.000Z
|
2021-05-22T07:42:19.000Z
|
pymaplib_cpp/src/pixelbuf.cpp
|
Grk0/MapsEvolved
|
e058a324e7d3c9b4c9b7e00d65b6f9da029fc7de
|
[
"PSF-2.0"
] | null | null | null |
pymaplib_cpp/src/pixelbuf.cpp
|
Grk0/MapsEvolved
|
e058a324e7d3c9b4c9b7e00d65b6f9da029fc7de
|
[
"PSF-2.0"
] | null | null | null |
#include "pixelbuf.h"
#include <assert.h>
#include "util.h"
#include "coordinates.h"
PixelBuf::PixelBuf(int width, int height)
// Zero-initialize the memory block (notice the parentheses).
: m_data(std::shared_ptr<unsigned int>(new unsigned int[width*height](),
ArrayDeleter<unsigned int>())),
m_width(width), m_height(height)
{
if (width < 0 || height < 0) {
throw std::runtime_error(
"PixelBuf width and height must be positive.");
}
}
PixelBuf::PixelBuf(int width, int height, unsigned int value)
: m_data(std::shared_ptr<unsigned int>(new unsigned int[width*height],
ArrayDeleter<unsigned int>())),
m_width(width), m_height(height)
{
if (width < 0 || height < 0) {
throw std::runtime_error(
"PixelBuf width and height must be positive.");
}
auto buf = m_data.get();
for (int i=0; i < width*height; i++) {
buf[i] = value;
}
}
PixelBuf::PixelBuf(const std::shared_ptr<unsigned int> &data,
int width, int height)
: m_data(data), m_width(width), m_height(height)
{
if (width < 0 || height < 0) {
throw std::runtime_error(
"PixelBuf width and height must be positive.");
}
}
void PixelBuf::Insert(const PixelBufCoord &pos, const PixelBuf &source) {
int x_dst_start = std::max(pos.x, 0);
int y_dst_start = std::max(pos.y, 0);
int x_src_offset = x_dst_start - pos.x;
int y_src_offset = y_dst_start - pos.y;
int x_dst_end = std::min(pos.x + source.GetWidth(), m_width);
int y_dst_end = std::min(pos.y + source.GetHeight(), m_height);
int x_delta = x_dst_end - x_dst_start;
int y_delta = y_dst_end - y_dst_start;
if (x_delta <= 0 || y_delta <= 0) {
return;
}
for (int y = 0; y < y_delta; ++y) {
auto dest = GetPixelPtr(x_dst_start, y + y_dst_start);
auto src = source.GetPixelPtr(x_src_offset, y + y_src_offset);
assert(dest >= GetRawData());
assert(dest + x_delta <= &GetRawData()[m_width*m_height]);
memcpy(dest, src, x_delta * sizeof(*dest));
}
}
void PixelBuf::SetPixel(const PixelBufCoord &pos, unsigned int val) {
// We ensure (int)m_width/(int)m_height >= 0 in the c'tors.
if (pos.x >= 0 && pos.x < static_cast<int>(m_width) &&
pos.y >= 0 && pos.y < static_cast<int>(m_height))
{
GetRawData()[pos.x + (m_height - pos.y - 1) * m_width] = val;
}
}
void PixelBuf::Line(const PixelBufCoord &start,
const PixelBufCoord &end,
const unsigned int color)
{
Line(start, end, 1, color);
}
void PixelBuf::Line(const PixelBufCoord &start,
const PixelBufCoord &end,
const unsigned int width,
const unsigned int color)
{
int x1 = start.x;
int x2 = end.x;
int y1 = start.y;
int y2 = end.y;
// Bresenham's line algorithm
const bool is_steep = (abs(y2 - y1) > abs(x2 - x1));
if (is_steep) {
std::swap(x1, y1);
std::swap(x2, y2);
}
if (x1 > x2) {
std::swap(x1, x2);
std::swap(y1, y2);
}
const int dx = x2 - x1;
const int dy = abs(y2 - y1);
int error = dx;
const int ystep = (y1 < y2) ? 1 : -1;
int y = y1;
for (int x = x1; x < x2; x++) {
if (is_steep) {
Rect(PixelBufCoord(y, x), width, color);
} else {
Rect(PixelBufCoord(x, y), width, color);
}
error -= 2 * dy;
if (error < 0) {
y += ystep;
error += 2 * dx;
}
}
}
void PixelBuf::Rect(const PixelBufCoord &start,
const PixelBufCoord &end,
const unsigned int color)
{
for (int y = start.y; y < end.y; y++) {
for (int x = start.x; x < end.x; x++) {
SetPixel(PixelBufCoord(x, y), color);
}
}
}
void PixelBuf::Rect(const class PixelBufCoord ¢er,
const unsigned int side_length,
const unsigned int color)
{
if (side_length == 0) {
return;
}
unsigned int size = (side_length - 1) / 2;
unsigned int offset = (side_length - 1) % 2;
Rect(center - PixelBufDelta(size, size),
center + PixelBufDelta(size + offset + 1, size + offset + 1),
color);
}
| 29.651007
| 76
| 0.549796
|
Grk0
|
87333c57e10f31f952c2db09e68af7fde29094ba
| 1,514
|
hpp
|
C++
|
commands.hpp
|
openbmc/google-ipmi-sys
|
f647e99165065feabb35aa744059cf6a2af46f1e
|
[
"Apache-2.0"
] | 2
|
2020-01-16T02:04:13.000Z
|
2021-01-13T21:47:30.000Z
|
commands.hpp
|
openbmc/google-ipmi-sys
|
f647e99165065feabb35aa744059cf6a2af46f1e
|
[
"Apache-2.0"
] | null | null | null |
commands.hpp
|
openbmc/google-ipmi-sys
|
f647e99165065feabb35aa744059cf6a2af46f1e
|
[
"Apache-2.0"
] | 3
|
2019-12-10T21:56:33.000Z
|
2021-03-02T23:56:06.000Z
|
// Copyright 2021 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
namespace google
{
namespace ipmi
{
enum SysOEMCommands
{
// The Sys cable check command.
SysCableCheck = 0,
// The Sys cpld version over ipmi command.
SysCpldVersion = 1,
// The Sys get eth device command.
SysGetEthDevice = 2,
// The Sys psu hard reset command.
SysPsuHardReset = 3,
// The Sys pcie slot count command.
SysPcieSlotCount = 4,
// The Sys pcie slot to i2c bus mapping command.
SysPcieSlotI2cBusMapping = 5,
// The Sys "entity id:entity instance" to entity name mapping command.
SysEntityName = 6,
// Returns the machine name of the image
SysMachineName = 7,
// Arm for psu reset on host shutdown
SysPsuHardResetOnShutdown = 8,
// The Sys get flash size command
SysGetFlashSize = 9,
// The Sys Host Power Off with disabled fallback watchdog
SysHostPowerOff = 10,
};
} // namespace ipmi
} // namespace google
| 30.28
| 75
| 0.702774
|
openbmc
|
873b2b9ba23dd7eaec97f9dbf040f79215dfd8a4
| 3,904
|
hpp
|
C++
|
kernel/integration/x64/amd/arch_support.hpp
|
lusceu/hypervisor
|
012a2d16f96dcfc256a3cac9aa22e238c8160a0c
|
[
"MIT"
] | null | null | null |
kernel/integration/x64/amd/arch_support.hpp
|
lusceu/hypervisor
|
012a2d16f96dcfc256a3cac9aa22e238c8160a0c
|
[
"MIT"
] | null | null | null |
kernel/integration/x64/amd/arch_support.hpp
|
lusceu/hypervisor
|
012a2d16f96dcfc256a3cac9aa22e238c8160a0c
|
[
"MIT"
] | null | null | null |
/// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
#ifndef ARCH_SUPPORT_HPP
#define ARCH_SUPPORT_HPP
#include <mk_interface.hpp>
#include <bsl/convert.hpp>
#include <bsl/debug.hpp>
#include <bsl/discard.hpp>
#include <bsl/errc_type.hpp>
#include <bsl/safe_integral.hpp>
#include <bsl/unlikely.hpp>
namespace integration
{
/// <!-- description -->
/// @brief Initializes a VPS with architecture specific stuff.
///
/// <!-- inputs/outputs -->
/// @param handle the handle to use
/// @param vpsid the VPS being intialized
/// @return Returns bsl::errc_success on success and bsl::errc_failure
/// on failure.
///
[[nodiscard]] constexpr auto
init_vps(syscall::bf_handle_t &handle, bsl::safe_uint16 const &vpsid) noexcept -> bsl::errc_type
{
bsl::errc_type ret{};
/// NOTE:
/// - Set up ASID
///
constexpr bsl::safe_uint64 guest_asid_idx{bsl::to_u64(0x0058U)};
constexpr bsl::safe_uint32 guest_asid_val{bsl::to_u32(0x1U)};
ret = syscall::bf_vps_op_write32(handle, vpsid, guest_asid_idx, guest_asid_val);
if (bsl::unlikely(!ret)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
/// NOTE:
/// - Set up intercept controls. On AMD, we need to intercept
/// VMRun, and CPUID if we plan to support reporting and stopping.
///
constexpr bsl::safe_uint64 intercept_instruction1_idx{bsl::to_u64(0x000CU)};
constexpr bsl::safe_uint32 intercept_instruction1_val{bsl::to_u32(0x00040000U)};
constexpr bsl::safe_uint64 intercept_instruction2_idx{bsl::to_u64(0x0010U)};
constexpr bsl::safe_uint32 intercept_instruction2_val{bsl::to_u32(0x00000001U)};
ret = syscall::bf_vps_op_write32(
handle, vpsid, intercept_instruction1_idx, intercept_instruction1_val);
if (bsl::unlikely(!ret)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
ret = syscall::bf_vps_op_write32(
handle, vpsid, intercept_instruction2_idx, intercept_instruction2_val);
if (bsl::unlikely(!ret)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
/// NOTE:
/// - Report success. Specifically, when we return to the root OS,
/// setting RAX tells the loader that the hypervisor was successfully
/// set up.
///
ret = syscall::bf_vps_op_write_reg(
handle, vpsid, syscall::bf_reg_t::bf_reg_t_rax, bsl::ZERO_UMAX);
if (bsl::unlikely(!ret)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
return ret;
}
}
#endif
| 36.148148
| 100
| 0.649078
|
lusceu
|
873caa37bbce2f14d1786d96714d740dd2881fc6
| 3,233
|
cpp
|
C++
|
Problems/LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.cpp
|
avramidis/leetcode-problems
|
66bf8eecdebe8d2b6bb45a23897a0c1938725116
|
[
"BSL-1.0"
] | null | null | null |
Problems/LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.cpp
|
avramidis/leetcode-problems
|
66bf8eecdebe8d2b6bb45a23897a0c1938725116
|
[
"BSL-1.0"
] | null | null | null |
Problems/LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.cpp
|
avramidis/leetcode-problems
|
66bf8eecdebe8d2b6bb45a23897a0c1938725116
|
[
"BSL-1.0"
] | null | null | null |
#define CATCH_CONFIG_MAIN
#include <iostream>
#include "catch.hpp"
class Solution {
public:
bool uniquestring(std::string s, int start, int end) {
for (int i = start; i < end; i++) {
for (int j = i + 1; j <= end; j++) {
if (s[i] == s[j]) {
return false;
}
}
}
return true;
}
int lengthOfLongestSubstring(std::string s) {
if (s.size() == 0)
{
return 0;
}
if (s.size() == 1)
{
return 1;
}
int result = 1;
for (size_t i = 0; i < s.size(); i++) {
for (size_t j = i + result; j < s.size(); j++) {
if (uniquestring(s, i, j)) {
if (j - i + 1 > result) {
result = j - i + 1;
}
}
}
}
return result;
}
};
TEST_CASE("Unique characters in string")
{
Solution solution;
SECTION("Input set 1") {
std::string input = "abcabcbb";
bool result = false;
BENCHMARK("Check if the string is made of unique characters")
{
result = solution.uniquestring(input, 0, 7);
}
REQUIRE(result == false);
}
SECTION("Input set 2") {
std::string input = "a";
bool result = false;
BENCHMARK("Check if the string is made of unique characters")
{
result = solution.uniquestring(input, 0, 0);
}
REQUIRE(result == true);
}
SECTION("Input set 3") {
std::string input = "au";
bool result = false;
BENCHMARK("Check if the string is made of unique characters")
{
result = solution.uniquestring(input, 0, 1);
}
REQUIRE(result == true);
}
}
TEST_CASE("Longest Substring Without Repeating Characters")
{
Solution solution;
SECTION("Input set 1") {
std::string input = "abcabcbb";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 3);
}
SECTION("Input set 2") {
std::string input = "bbbbb";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 1);
}
SECTION("Input set 3") {
std::string input = "pwwkew";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 3);
}
SECTION("Input set 4") {
std::string input = "c";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 1);
}
SECTION("Input set 5") {
std::string input = "au";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 2);
}
SECTION("Input set 6") {
std::string input = "";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 0);
}
SECTION("Input set 6") {
std::string input = "dvdf";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 3);
}
}
| 20.993506
| 79
| 0.63656
|
avramidis
|
873d5ba06c2499a76b4caaa26d68da4ab04e88e0
| 4,161
|
cxx
|
C++
|
Modules/Nonunit/Review/test/itkValuedRegionalMinimaImageFilterTest.cxx
|
eile/ITK
|
2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1
|
[
"Apache-2.0"
] | 4
|
2015-05-22T03:47:43.000Z
|
2016-06-16T20:57:21.000Z
|
Modules/Nonunit/Review/test/itkValuedRegionalMinimaImageFilterTest.cxx
|
GEHC-Surgery/ITK
|
f5df62749e56c9036e5888cfed904032ba5fdfb7
|
[
"Apache-2.0"
] | null | null | null |
Modules/Nonunit/Review/test/itkValuedRegionalMinimaImageFilterTest.cxx
|
GEHC-Surgery/ITK
|
f5df62749e56c9036e5888cfed904032ba5fdfb7
|
[
"Apache-2.0"
] | 9
|
2016-06-23T16:03:12.000Z
|
2022-03-31T09:25:08.000Z
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* 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.
*
*=========================================================================*/
// a test routine for regional extrema using flooding
#include "itkValuedRegionalMinimaImageFilter.h"
#include "itkMaximumImageFilter.h"
#include "itkHConcaveImageFilter.h"
#include "itkInvertIntensityImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkAndImageFilter.h"
#include "itkSimpleFilterWatcher.h"
int itkValuedRegionalMinimaImageFilterTest(int argc, char * argv[])
{
const int dim = 2;
if( argc < 5 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " InputImage OutputImageFile1 OutputImageFile2 "
<< "OutputImageFile3" << std::endl;
return EXIT_FAILURE;
}
typedef unsigned char PixelType;
typedef itk::Image< PixelType, dim > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
typedef itk::ValuedRegionalMinimaImageFilter< ImageType, ImageType >
FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
filter->SetFullyConnected( atoi(argv[1]) );
itk::SimpleFilterWatcher watcher(filter, "filter");
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( argv[3] );
writer->Update();
// produce the same output with other filters
typedef itk::HConcaveImageFilter< ImageType, ImageType > ConcaveType;
ConcaveType::Pointer concave = ConcaveType::New();
concave->SetInput( reader->GetOutput() );
concave->SetFullyConnected( atoi(argv[1]) );
concave->SetHeight( 1 );
// concave gives minima with value=1 and others with value=0
// rescale the image so we have minima=255 other=0
typedef itk::RescaleIntensityImageFilter< ImageType, ImageType > RescaleType;
RescaleType::Pointer rescale = RescaleType::New();
rescale->SetInput( concave->GetOutput() );
rescale->SetOutputMaximum( 255 );
rescale->SetOutputMinimum( 0 );
// in the input image, select the values of the pixel at the minima
typedef itk::AndImageFilter< ImageType, ImageType, ImageType > AndType;
AndType::Pointer a = AndType::New();
a->SetInput(0, rescale->GetOutput() );
a->SetInput(1, reader->GetOutput() );
// all pixel which are not minima must have value=255.
// get the non minima pixel by inverting the rescaled image
// we will have minima value=0 and non minima value=255
typedef itk::InvertIntensityImageFilter< ImageType, ImageType > InvertType;
InvertType::Pointer invert = InvertType::New();
invert->SetInput( rescale->GetOutput() );
// get the highest value from "a" and from invert. The minima have
// value>=0 in "a" image and the non minima have a value=0. In invert,
// the non minima have a value=255 and the minima a value=0
typedef itk::MaximumImageFilter< ImageType, ImageType, ImageType > MaxType;
MaxType::Pointer max = MaxType::New();
max->SetInput(0, invert->GetOutput() );
max->SetInput(1, a->GetOutput() );
WriterType::Pointer writer2 = WriterType::New();
writer2->SetInput( max->GetOutput() );
writer2->SetFileName( argv[4] );
writer2->Update();
return EXIT_SUCCESS;
}
| 39.628571
| 79
| 0.681086
|
eile
|
874365d921d57769ce83eae4b8a2a5f3cfdd58e2
| 763
|
cpp
|
C++
|
src/Boring32/src/Guid/Guid.cpp
|
yottaawesome/boring32
|
ecf843c200b133a4fad711dcf52419c0c88af49c
|
[
"MIT"
] | 3
|
2021-11-25T13:44:57.000Z
|
2022-02-22T05:50:34.000Z
|
src/Boring32/src/Guid/Guid.cpp
|
yottaawesome/boring32
|
ecf843c200b133a4fad711dcf52419c0c88af49c
|
[
"MIT"
] | 3
|
2021-10-13T10:58:30.000Z
|
2021-12-21T05:46:41.000Z
|
src/Boring32/src/Guid/Guid.cpp
|
yottaawesome/boring32
|
ecf843c200b133a4fad711dcf52419c0c88af49c
|
[
"MIT"
] | null | null | null |
#include "pch.hpp"
#include "Objbase.h"
#include "include/Error/Error.hpp"
#include "include/Guid/Guid.hpp"
namespace Boring32::Guid
{
// Adapted from https://stackoverflow.com/a/19941516/7448661
std::wstring GetGuidAsWString(const GUID& guid)
{
wchar_t rawGuid[64] = { 0 };
HRESULT result = StringFromGUID2(guid, rawGuid, 64);
if (StringFromGUID2(guid, rawGuid, 64) == 0)
throw std::runtime_error("GetGuidAsWString(): StringFromGUID2() failed");
return rawGuid;
}
std::wstring GetGuidAsWString()
{
GUID guidReference;
HRESULT result = CoCreateGuid(&guidReference);
if (FAILED(result))
throw Error::ComError("GetGuidAsWString(): CoCreateGuid() failed", result);
return GetGuidAsWString(guidReference);
}
}
| 28.259259
| 79
| 0.70249
|
yottaawesome
|
87448d25f36aecf10d18da35b06ac2ad09acc6df
| 6,583
|
cc
|
C++
|
StRoot/StTrsMaker/src/StTpcDbElectronics.cc
|
xiaohaijin/RHIC-STAR
|
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
|
[
"MIT"
] | 2
|
2018-12-24T19:37:00.000Z
|
2022-02-28T06:57:20.000Z
|
StRoot/StTrsMaker/src/StTpcDbElectronics.cc
|
xiaohaijin/RHIC-STAR
|
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
|
[
"MIT"
] | null | null | null |
StRoot/StTrsMaker/src/StTpcDbElectronics.cc
|
xiaohaijin/RHIC-STAR
|
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
|
[
"MIT"
] | null | null | null |
/*****************************************************************
*
* $Id: StTpcDbElectronics.cc,v 1.7 2008/08/02 14:33:09 fisyak Exp $
*
* Author: Manuel Calderon de la Barca Sanchez & Brian Lasiuk Sept 13, 1999
*
*****************************************************************
* Description: Electronics parameters for TRS taken from DB for
* the STAR Main TPC
*
*****************************************************************
*
* $Log: StTpcDbElectronics.cc,v $
* Revision 1.7 2008/08/02 14:33:09 fisyak
* new interface to tpcT0
*
* Revision 1.6 2008/06/20 15:01:12 fisyak
* move from StTrsData to StTpcRawData
*
* Revision 1.5 2000/03/15 17:39:48 calderon
* Remove beeps
*
* Revision 1.4 2000/02/10 01:21:49 calderon
* Switch to use StTpcDb.
* Coordinates checked for consistency.
* Fixed problems with StTrsIstream & StTrsOstream.
*
* Revision 1.3 2000/01/10 23:14:29 lasiuk
* Include MACROS for compatiblity with SUN CC5
*
* Revision 1.2 1999/12/08 02:10:41 calderon
* Modified to eliminate warnings on Linux.
*
* Revision 1.1 1999/10/11 23:55:20 calderon
* Version with Database Access and persistent file.
* Not fully tested due to problems with cons, it
* doesn't find the local files at compile time.
* Yuri suggests forcing commit to work directly with
* files in repository.
*
******************************************************************/
#include "SystemOfUnits.h"
#include "StTpcDbElectronics.hh"
//#include "StUtilities/StMessMgr.h"
#include "StTpcDb/StTpcDb.h"
#ifndef ST_NO_EXCEPTIONS
# include <stdexcept>
# if !defined(ST_NO_NAMESPACES)
using std::invalid_argument;
# endif
#endif
StTpcElectronics* StTpcDbElectronics::mInstance = 0; // static data member
StTpcDbElectronics::StTpcDbElectronics() { /* nopt */ }
StTpcDbElectronics::StTpcDbElectronics(StTpcDb* globalDbPointer)
{
gTpcDbPtr = globalDbPointer;
mNominalGain = gTpcDbPtr->Electronics()->nominalGain();
mSamplingFrequency = gTpcDbPtr->Electronics()->samplingFrequency();
mTZero = gTpcDbPtr->Electronics()->tZero();
mAdcConversion = gTpcDbPtr->Electronics()->adcConversion();
mAdcConversionCharge = gTpcDbPtr->Electronics()->adcCharge();
mNumberOfTimeBins = gTpcDbPtr->Electronics()->numberOfTimeBins();
mAveragePedestal = static_cast<int>(gTpcDbPtr->Electronics()->averagePedestal());
mShapingTime = gTpcDbPtr->Electronics()->shapingTime();
mTau = gTpcDbPtr->Electronics()->tau();
#ifndef ST_NO_NAMESPACES
using namespace units;
#endif
//Units Integrity
mNominalGain *= (millivolt)/(coulomb*1.e-15); // mV/fC
mSamplingFrequency *= MHz;
mTZero *= microsecond;
mAdcConversion *= (millivolt);
mAdcConversionCharge *= (coulomb*1.e-15);
mShapingTime *= nanosecond;
mTau *= nanosecond;
}
StTpcElectronics*
StTpcDbElectronics::instance()
{
if (!mInstance) {
#ifndef ST_NO_EXCEPTIONS
throw invalid_argument("StTpcDbElectronics::getInstance(): Argument Missing!");
#else
cerr << "StTpcDbElectronics::getInstance(): Argument Missing!" << endl;
cerr << "No arguments for instantiantion" << endl;
cerr << "Exiting..." << endl;
#endif
}
return mInstance;
}
StTpcElectronics*
StTpcDbElectronics::instance(StTpcDb* gTpcDbPtr)
{
if (!mInstance) {
mInstance = new StTpcDbElectronics(gTpcDbPtr);
}
else {
cerr << "StTpcDbElectronics::instance()" << endl;
cerr << "\tWARNING:" << endl;
cerr << "\tSingleton class is already instantiated" << endl;
cerr << "\tArgument ignored!!" << endl;
cerr << "\tContinuing..." << endl;
}
return mInstance;
}
double StTpcDbElectronics::channelGain(int sector, int row, int pad) const
{
// This should be where channel by channel gains are looked up
// Note: the DB has getGain(), getOnlineGain(), getNominalGain(), and
// getRelativeGain(). We use Nominal gain I believe.
return 1.;//gTpcDbPtr->Gain(sector)->getNominalGain(row,pad);
}
double StTpcDbElectronics::channelGain(StTpcPadCoordinate& coord) const
{
return channelGain(coord.sector(), coord.row(), (Int_t) coord.pad());
}
int StTpcDbElectronics::pedestal(int sector, int row, int pad, int timeB) const
{
return averagePedestal();
}
int StTpcDbElectronics::pedestal(StTpcPadCoordinate& coord) const
{
return pedestal(coord.sector(), coord.row(), (Int_t) coord.pad(), (Int_t) coord.timeBucket());
}
double StTpcDbElectronics::tZero(int sector, int row, int pad) const
{
return gTpcDbPtr->tpcT0()->T0(sector,row,pad);
}
double StTpcDbElectronics::tZero(StTpcPadCoordinate& coord) const
{
return tZero(coord.sector(), coord.row(), (Int_t) coord.pad());
}
void StTpcDbElectronics::print(ostream& os) const
{
#ifndef ST_NO_NAMESPACES
using namespace units;
#endif
os << "Electronics Data Base Parameters" << endl;
os << "=======================================" << endl;
os << "Analog:" << endl;
os << "nominalGain: " << mNominalGain/((volt*.001)/(coulomb*1.e-15)) << " mV/fC" << endl;
os << "samplingFrequency: " << mSamplingFrequency/MHz << " MHz" << endl;
os << "tZero: " << mTZero/microsecond << " us" << endl;
os << "shapingTime: " << mShapingTime/nanosecond << " ns" << endl;
os << "shapingTime2: " << mTau/nanosecond << " ns" << endl;
os << "\nDigital:" << endl;
os << "adcConversion: " << mAdcConversion/(volt*.001) << " mV/channel" << endl;
os << "adcConversionCharge: " << mAdcConversionCharge/(coulomb*1.e-15) << " mV/fC" << endl;
os << "numberOfTimeBins: " << mNumberOfTimeBins << endl;
os << "averagePedestal: " << mAveragePedestal << " channels" << endl;
os << endl;
// os << "Example of Gain per pad for Sector 1, Row 1" << endl;
// os << " Row Pad Gain for this Pad" << endl;
// os << "==========================================" << endl;
// for(int i=0; i<gTpcDbPtr->PadPlaneGeometry()->numberOfPadsAtRow(1); i++) {
// os.width(3);
// os.setf(ios::right,ios::adjustfield);
// os << 1;
// os.width(9);
// os << i+1;
// os.width(15);
// os << channelGain(1,1,i+1) << endl;
// }
// os << endl;
}
| 36.572222
| 108
| 0.588789
|
xiaohaijin
|
87457da4b1247ff3584eeeccebd30216871749ea
| 1,586
|
cpp
|
C++
|
tests/unit/countersignature.cpp
|
LaudateCorpus1/authenticode-parser
|
7653bb1c60b9eed74613dceb84b61ddd7b5127a1
|
[
"MIT"
] | 4
|
2022-01-10T09:44:47.000Z
|
2022-03-15T11:50:46.000Z
|
tests/unit/countersignature.cpp
|
LaudateCorpus1/authenticode-parser
|
7653bb1c60b9eed74613dceb84b61ddd7b5127a1
|
[
"MIT"
] | 1
|
2022-01-20T04:14:24.000Z
|
2022-01-22T16:51:07.000Z
|
tests/unit/countersignature.cpp
|
LaudateCorpus1/authenticode-parser
|
7653bb1c60b9eed74613dceb84b61ddd7b5127a1
|
[
"MIT"
] | 2
|
2022-02-02T13:36:09.000Z
|
2022-03-15T11:50:48.000Z
|
#include "../../src/countersignature.h"
#include <cstdint>
#include <cstring>
#include <gtest/gtest.h>
TEST(CountersignatureModule, countersignature_array_insert)
{
CountersignatureArray array;
array.counters = nullptr;
array.count = 0;
Countersignature countersig1 = {};
int res = countersignature_array_insert(&array, &countersig1);
EXPECT_EQ(res, 0);
ASSERT_EQ(array.count, 1);
ASSERT_TRUE(array.counters);
EXPECT_EQ(array.counters[0], &countersig1);
Countersignature countersig2;
res = countersignature_array_insert(&array, &countersig2);
EXPECT_EQ(res, 0);
ASSERT_EQ(array.count, 2);
ASSERT_TRUE(array.counters);
EXPECT_EQ(array.counters[1], &countersig2);
free(array.counters);
}
TEST(CountersignatureModule, countersignature_array_move)
{
CountersignatureArray array1;
array1.counters = nullptr;
array1.count = 0;
CountersignatureArray array2;
array2.counters = nullptr;
array2.count = 0;
Countersignature countersig1;
Countersignature countersig2;
int res = countersignature_array_insert(&array2, &countersig1);
EXPECT_EQ(res, 0);
res = countersignature_array_insert(&array2, &countersig2);
EXPECT_EQ(res, 0);
res = countersignature_array_move(&array1, &array2);
EXPECT_EQ(res, 0);
ASSERT_TRUE(array1.counters);
ASSERT_EQ(array1.count, 2);
EXPECT_EQ(array1.counters[0], &countersig1);
EXPECT_EQ(array1.counters[1], &countersig2);
EXPECT_EQ(array2.count, 0);
EXPECT_FALSE(array2.counters);
free(array1.counters);
}
| 24.78125
| 67
| 0.710593
|
LaudateCorpus1
|
8750c0266c8d52d61c41c50a4592b2709ca57cc0
| 27,434
|
cpp
|
C++
|
experiment.cpp
|
ChristophKuhfuss/stneatexperiment
|
ca754fb679658072f4dacc4354a319db3faf660b
|
[
"BSD-3-Clause"
] | null | null | null |
experiment.cpp
|
ChristophKuhfuss/stneatexperiment
|
ca754fb679658072f4dacc4354a319db3faf660b
|
[
"BSD-3-Clause"
] | null | null | null |
experiment.cpp
|
ChristophKuhfuss/stneatexperiment
|
ca754fb679658072f4dacc4354a319db3faf660b
|
[
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include <string.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <sstream>
#include <algorithm>
#include <vector>
#include <stdlib.h>
#include <sstream>
#include <stdio.h>
#include <string>
#include <math.h>
#include <chrono>
#include <sys/stat.h>
#include <sqlite3.h>
#include "experiment.hpp"
#include <signal.h>
string Experiment::temp_pop_filename = "temp_pop";
string Experiment::db_filename = "neat.db";
int Experiment::max_db_retry = 100;
int Experiment::db_sleeptime = 50;
string Experiment::path_to_supertux_executable = "./bin/build/supertux2";
int Experiment::cur_gen = 0;
bool Experiment::new_top = true;
int Experiment::top_genome_gen_id = 0;
int Experiment::top_genome_id = 0;
double Experiment::top_fitness = 0;
int Experiment::num_winner_genomes = 0;
float Experiment::fitness_sum = 0;
float Experiment::airtime_sum = 0;
float Experiment::groundtime_sum = 0;
int Experiment::jump_sum = 0;
double Experiment::evaluation_time = 0;
Parameters Experiment::params;
vector<Genome*> Experiment::genomes;
vector<PhenotypeBehavior> Experiment::archive;
int main(int argc, char **argv) {
std::cout << "SuperTux + NEAT interface and experiment code by Christoph Kuhfuss 2018" << std::endl;
std::cout << "Using the original SuperTux source and the MultiNEAT framework by Peter Chervenski (https://github.com/peter-ch/MultiNEAT)" << std::endl;
Experiment::parse_commandline_arguments(argc, argv);
Experiment::fix_filenames();
Experiment::parse_experiment_parameters();
Experiment::params = Experiment::init_params();
Experiment experiment;
experiment.run_evolution();
return 0;
}
Experiment::Experiment() :
start_genome(0, ExperimentParameters::AMOUNT_RANGE_SENSORS + ExperimentParameters::AMOUNT_DEPTH_SENSORS + ExperimentParameters::AMOUNT_PIESLICE_SENSORS * 2 + 1, ExperimentParameters::num_hidden_start_neurons,
6, false, UNSIGNED_SIGMOID, UNSIGNED_SIGMOID, 1, params),
pop(strcmp(ExperimentParameters::pop_filename.c_str(), "") ?
Population(ExperimentParameters::pop_filename.c_str()) : Population(start_genome, params, true, 2.0, (ExperimentParameters::using_seed ? ExperimentParameters::seed : (int) time(0)))),
total_gen_time(0)
{
if (ExperimentParameters::hyperneat)
{
generate_substrate();
}
}
Experiment::~Experiment()
{
}
void Experiment::run_evolution() {
std::remove(db_filename.c_str());
init_db();
for (int i = 1; i <= ExperimentParameters::max_gens; i++) {
std::cout << "Working on generation #" << i << "..." << std::endl;
Experiment::new_top = false;
num_winner_genomes = 0;
fitness_sum = 0;
airtime_sum = 0;
groundtime_sum = 0;
jump_sum = 0;
evaluation_time = 0;
cur_gen = i;
refresh_genome_list();
if (ExperimentParameters::novelty_search) {
std::vector<PhenotypeBehavior>* behaviors = new std::vector<PhenotypeBehavior>();
for (int i = 0; i < genomes.size(); i++)
behaviors->push_back(Behavior());
pop.InitPhenotypeBehaviorData(behaviors, &archive);
}
// Prepare db file...
update_db();
// Run supertux processes...
start_processes();
// ... and get the fitness values from the db file
// Also update info about the generation
set_fitness_values();
update_gen_info();
std::cout << "Done. Top fitness: " << top_fitness << " by individual #" << top_genome_id << ", generation #" << top_genome_gen_id << std::endl;
std::cout << "Evaluation time: " << (int) (evaluation_time / 60) << "min" << (int) evaluation_time % 60 << "sec" << std::endl;
std::cout << num_winner_genomes << " genome(s) out of " << genomes.size() << " finished the level (" << num_winner_genomes / (double) genomes.size() * 100 << "%)" << std::endl;
if (ExperimentParameters::autosave_best && Experiment::new_top) {
std::ostringstream ss;
ss << "./neat_gen" << cur_gen;
save_pop(ss.str().c_str());
}
else if (!ExperimentParameters::autosave_best && i % ExperimentParameters::autosave_interval == 0) {
std::ostringstream ss;
ss << "./neat_gen" << cur_gen;
save_pop(ss.str().c_str());
}
std::chrono::time_point<std::chrono::high_resolution_clock> start = std::chrono::high_resolution_clock::now();
pop.Epoch();
std::chrono::time_point<std::chrono::high_resolution_clock> finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
total_gen_time += elapsed.count();
}
}
void Experiment::start_processes()
{
// Save pop to single file for all child processes to read
pop.Save(temp_pop_filename.c_str());
// Distribute genomes as evenly as possible
int remaining_genome_count = genomes.size();
int cores_left = ExperimentParameters::num_cores;
std::vector<int> startindices;
std::vector<int> endindices;
int curindex = 0;
for (int j = 0; j < ExperimentParameters::num_cores; j++) {
startindices.push_back(++curindex - 1);
int single_genome_count = remaining_genome_count / cores_left;
if (remaining_genome_count % cores_left)
single_genome_count++;
remaining_genome_count -= single_genome_count;
cores_left--;
curindex += single_genome_count - 1;
endindices.push_back(curindex - 1);
}
// Build the GNU parallel command, include all parameter files and the levelfile
std::stringstream ss;
ss << "parallel --no-notice --xapply ";
ss << path_to_supertux_executable;
ss << " --neat";
// if (Experiment::novelty_search) ss << " --noveltysearch";
if (ExperimentParameters::hyperneat) ss << " --hyperneat";
// All child processes read from the same population file
ss << " --popfile " << boost::filesystem::canonical(temp_pop_filename);
// Only add experiment and MultiNEAT param files if they're configured...
if (strcmp(ExperimentParameters::experimentparam_filename.c_str(), "")) ss << " --experimentparamfile " << ExperimentParameters::experimentparam_filename;
if (strcmp(ExperimentParameters::param_filename.c_str(), "")) ss << " --paramfile " << ExperimentParameters::param_filename;
ss << " --dbfile " << boost::filesystem::canonical(db_filename);
ss << " --curgen " << cur_gen;
ss << " --fromtogenome ::: ";
for (std::vector<int>::iterator it = startindices.begin(); it != startindices.end(); ++it) {
ss << *it << " ";
}
ss << "::: ";
for (std::vector<int>::iterator it = endindices.begin(); it != endindices.end(); ++it) {
ss << *it << " ";
}
ss << "::: '";
ss << ExperimentParameters::path_to_level;
ss << "'";
// std::cout << ss.str() << std::endl;
// Ready to rumble, don't forget to measure the time
std::chrono::time_point<std::chrono::high_resolution_clock> start = std::chrono::high_resolution_clock::now();
std::system(ss.str().c_str());
std::chrono::time_point<std::chrono::high_resolution_clock> finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
evaluation_time = elapsed.count();
// Remove temporary population file. If we have to, we'll make a new one
std::remove(temp_pop_filename.c_str());
}
void Experiment::init_db()
{
sqlite3* db;
sqlite3_open("neat.db", &db);
sqlite3_busy_handler(db, busy_handler, (void*) nullptr);
char* err;
std::stringstream ss;
ss << "CREATE TABLE RUN_INFO (id INT PRIMARY KEY NOT NULL, num_genomes INT, avg_fitness REAL, time REAL, avg_airtime REAL, avg_groundtime REAL, avg_jumps REAL, top_fitness REAL, amt_winners INT);";
sqlite3_exec(db, ss.str().c_str(), 0, 0, &err);
sqlite3_close(db);
}
void Experiment::update_db()
{
sqlite3* db;
sqlite3_open("neat.db", &db);
sqlite3_busy_handler(db, busy_handler, (void*) nullptr);
char* err;
std::stringstream ss;
ss.str("");
ss << "CREATE TABLE GEN" << cur_gen << "(id INT PRIMARY KEY NOT NULL, fitness REAL, airtime REAL, groundtime REAL, num_jumps INT, qLeft REAL, qRight REAL, qUp REAL, qDown REAL, qJump REAL, qAction REAL, won INT);";
sqlite3_exec(db, ss.str().c_str(), 0, 0, &err);
for(std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it) {
ss.str("");
// Negative fitness if not evaluated yet. If fitness values stay negative, NEAT might just break
// Last values are for ns behavior
ss << "INSERT INTO GEN" << cur_gen << " VALUES(" << (*it)->GetID() << ", -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);";
sqlite3_exec(db, ss.str().c_str(), 0, 0, &err);
}
sqlite3_close(db);
}
void Experiment::set_fitness_values()
{
sqlite3* db;
sqlite3_open("neat.db", &db);
sqlite3_busy_handler(db, busy_handler, (void*) nullptr);
char* err;
std::stringstream ss;
ss << "SELECT * FROM gen" << cur_gen << ";";
sqlite3_exec(db, ss.str().c_str(), (ExperimentParameters::novelty_search ? select_handler_ns : select_handler), 0, &err);
if (ExperimentParameters::novelty_search) {
for (std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it) {
if ((*it)->m_PhenotypeBehavior->m_Data[0].size() == 0) {
std::cout << "ERROR OCCURED WITH GENOME #" << (*it)->GetID() << std::endl;
}
}
update_sparsenesses();
}
sqlite3_close(db);
}
void Experiment::update_gen_info()
{
sqlite3* db;
sqlite3_open("neat.db", &db);
sqlite3_busy_handler(db, busy_handler, (void*) nullptr);
char* err;
std::stringstream ss;
ss << "INSERT INTO RUN_INFO VALUES(" << cur_gen << ", " << genomes.size() << ", " << fitness_sum / genomes.size() << ", " << evaluation_time << ", " << (airtime_sum / (double) genomes.size()) << ", " << (groundtime_sum / (double) genomes.size()) << ", " << ((double) jump_sum) / genomes.size() << ", " << top_fitness << ", " << num_winner_genomes << ");";
sqlite3_exec(db, ss.str().c_str(), 0, 0, &err);
sqlite3_close(db);
}
void Experiment::refresh_genome_list()
{
genomes.clear();
for (unsigned int i = 0; i < pop.m_Species.size(); i++) {
Species* cur = &pop.m_Species[i];
// std::cout << "Species #" << cur->ID() << " has " << cur->m_Individuals.size() << " individuals" << std::endl;
for (unsigned int j = 0; j < cur->m_Individuals.size(); j++) {
cur->m_Individuals[j].m_PhenotypeBehavior = new Behavior();
genomes.push_back(&cur->m_Individuals[j]);
}
// Probably unneccessary
sort(genomes.begin(), genomes.end(), [ ](const Genome* lhs, const Genome* rhs)
{
return lhs->GetID() < rhs->GetID();
});
}
}
double Experiment::sparseness(Genome* g)
{
std::vector<double> distances;
double sum = 0;
int amt = 0;
for (std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it) {
//std::cout << "Calculating distance between genomes #" << g->GetID() << " and #" << (*it)->GetID() << std::endl;
amt++;
distances.push_back(g->m_PhenotypeBehavior->Distance_To((*it)->m_PhenotypeBehavior));
}
for (std::vector<PhenotypeBehavior>::iterator it = archive.begin(); it != archive.end(); ++it) {
amt++;
distances.push_back(g->m_PhenotypeBehavior->Distance_To(&(*it)));
}
sort(distances.begin(), distances.end(), [ ](const double lhs, const double rhs)
{
return lhs < rhs;
});
for (int i = 0; i < params.NoveltySearch_K; i++) {
sum += distances[i];
}
// std::cout << "Sparseness for genome #" << g->GetID() << " is " << sum / amt << std::endl;
if (amt > 0) {
double sparseness = sum / amt;
if (sparseness > params.NoveltySearch_P_min) {
archive.push_back(*(g->m_PhenotypeBehavior));
}
return sum / amt;
}
else
return 0;
}
void Experiment::update_sparsenesses()
{
for (std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it)
{
(*it)->SetFitness(pop.ComputeSparseness(*(*it)));
(*it)->SetEvaluated();
}
}
void Experiment::generate_substrate()
{
SensorManager sm;
sm.initSensors();
std::vector<std::vector<double>> input_coords;
std::vector<std::vector<double>> hidden_coords; // TODO: Add support for hidden neurons (third dimension, arrange in a circle)
std::vector<std::vector<double>> output_coords;
std::vector<std::shared_ptr<RangeFinderSensor>>* rfsensors = sm.get_cur_rangefinder_sensors();
std::vector<std::shared_ptr<DepthFinderSensor>>* dfsensors = sm.get_cur_depthfinder_sensors();
std::vector<std::shared_ptr<PieSliceSensor>>* pssensors = sm.get_cur_pieslice_sensors();
double inputZ = -1;
double outputZ = 1;
double hiddenZ = 0;
// First, calculate maximum x and y coordinates so we can normalize substrate coordinates to (-1, 1)
int maxX = 0;
int maxY = 0;
if (ExperimentParameters::num_hidden_start_neurons > 0) {
std::vector<double> coords;
if (ExperimentParameters::num_hidden_start_neurons == 1) {
// If there is only one hidden start neuron, place it in the center and be done with it
coords.push_back(0);
coords.push_back(0);
coords.push_back(hiddenZ);
hidden_coords.push_back(coords);
} else {
// If there are more than one, arrange in a circle
coords.push_back(1);
coords.push_back(0);
coords.push_back(hiddenZ);
double cur_angle = 0;
// How many neurons per full rotation?
double angle_step = 2 * M_PI / ExperimentParameters::num_hidden_start_neurons;
for (int i = 0; i < ExperimentParameters::num_hidden_start_neurons - 1; i++) {
// Push back coordinates, rotate by the angle step each iteration
hidden_coords.push_back(coords);
std::vector<double> coords_new;
coords_new.push_back(coords.at(0) * cos(angle_step) + coords.at(1) * sin(angle_step));
coords_new.push_back(coords.at(1) * cos(angle_step) - coords.at(0) * sin(angle_step));
coords_new.push_back(hiddenZ);
coords = coords_new;
}
}
}
for (std::vector<std::shared_ptr<RangeFinderSensor>>::iterator it = rfsensors->begin(); it != rfsensors->end(); ++it)
{
Vector v = (*it)->get_offset();
// Get middle point of the RangeFinderSensor
int x = abs(v.x / 2.0);
int y = abs(v.y);
if (x > maxX)
maxX = x;
if (y > maxY)
maxY = y;
}
for (std::vector<std::shared_ptr<DepthFinderSensor>>::iterator it = dfsensors->begin(); it != dfsensors->end(); ++it)
{
Vector v = (*it)->get_offset();
// Get middle point of the DepthFinderSensor
int x = abs(v.x);
int y = abs(v.y / 2.0);
if (x > maxX)
maxX = x;
if (y > maxY)
maxY = y;
}
for (std::vector<std::shared_ptr<PieSliceSensor>>::iterator it = pssensors->begin(); it != pssensors->end(); ++it)
{
Vector v1 = (*it)->get_offset();
Vector v2 = (*it)->get_offset2();
// Get middle point of the PieSliceSensor
// Divide by three because both vectors form a triangle with (0, 0) as the third point
int x = abs((v1.x + v2.x) / 3.0);
int y = abs((v1.y + v2.y) / 3.0);
if (x > maxX)
maxX = x;
if (y > maxY)
maxY = y;
}
for (std::vector<std::shared_ptr<RangeFinderSensor>>::iterator it = rfsensors->begin(); it != rfsensors->end(); ++it)
{
std::vector<double> coords;
Vector v = (*it)->get_offset();
// Normalize between (0, 1) and then between (-1, 1)
coords.push_back(v.x / (double) maxX);
coords.push_back(v.y / (double) maxY);
coords.push_back(v.x);
coords.push_back(v.y);
if (ExperimentParameters::num_hidden_start_neurons > 0) coords.push_back(inputZ);
input_coords.push_back(coords);
}
for (std::vector<std::shared_ptr<DepthFinderSensor>>::iterator it = dfsensors->begin(); it != dfsensors->end(); ++it)
{
std::vector<double> coords;
Vector v = (*it)->get_offset();
coords.push_back((v.x / (double) maxX));
coords.push_back((v.y / (double) maxY));
coords.push_back(v.x);
coords.push_back(v.y);
if (ExperimentParameters::num_hidden_start_neurons > 0) coords.push_back(inputZ);
input_coords.push_back(coords);
}
for (std::vector<std::shared_ptr<PieSliceSensor>>::iterator it = pssensors->begin(); it != pssensors->end(); ++it)
{
std::vector<double> coords;
Vector v1 = (*it)->get_offset();
Vector v2 = (*it)->get_offset2();
// Same procedure as above, third point is (0, 0)
coords.push_back(((v1.x + v2.x) / 3.0) / (double) maxX);
coords.push_back(((v1.y + v2.y) / 3.0) / (double) maxY);
if (ExperimentParameters::num_hidden_start_neurons > 0) coords.push_back(inputZ);
input_coords.push_back(coords);
}
std::vector<double> bias;
bias.push_back(0);
bias.push_back(0);
if (ExperimentParameters::num_hidden_start_neurons > 0) bias.push_back(inputZ);
input_coords.push_back(bias);
std::vector<double> output;
// Arrange output substrate coordinates around Tux
// UP should be above Tux, DOWN below, etc. with Tux "being" at (0, 0)
// UP
output.push_back(0);
output.push_back(1);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
output.clear();
// DOWN
output.push_back(0);
output.push_back(-1);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
output.clear();
// LEFT
output.push_back(-1);
output.push_back(0);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
output.clear();
// RIGHT
output.push_back(1);
output.push_back(0);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
output.clear();
// JUMP
output.push_back(0);
output.push_back(0.8);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
output.clear();
// ACTION
output.push_back(0);
output.push_back(0.1);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
// Parameters taken from MultiNEAT's HyperNEAT example
substrate = Substrate(input_coords, hidden_coords, output_coords);
substrate.m_allow_hidden_hidden_links = false;
substrate.m_allow_hidden_output_links = true;
substrate.m_allow_input_hidden_links = true;
substrate.m_allow_input_output_links = true;
substrate.m_allow_looped_hidden_links = false;
substrate.m_allow_looped_output_links = false;
substrate.m_allow_output_hidden_links = false;
substrate.m_allow_output_output_links = false;
substrate.m_query_weights_only = true;
substrate.m_max_weight_and_bias = 8;
substrate.m_hidden_nodes_activation = ActivationFunction::SIGNED_SIGMOID;
substrate.m_output_nodes_activation = ActivationFunction::UNSIGNED_SIGMOID;
start_genome = Genome(0, substrate.GetMinCPPNInputs(), ExperimentParameters::num_hidden_start_neurons_cppn,
substrate.GetMinCPPNOutputs(), false, TANH, TANH, 0, params);
pop = strcmp(ExperimentParameters::pop_filename.c_str(), "") ? Population(ExperimentParameters::pop_filename.c_str()) : Population(start_genome, params, true, 1.0, (ExperimentParameters::using_seed ? ExperimentParameters::seed : (int) time(0)));
}
int Experiment::select_handler(void* data, int argc, char** argv, char** colNames)
{
int id = std::stoi(argv[0]);
double fitness = std::stod(argv[1]);
for (std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it) {
if ((*it)->GetID() == id) {
(*it)->SetFitness((ExperimentParameters::novelty_search) ? sparseness(*it) : fitness);
(*it)->SetEvaluated();
if (fitness > top_fitness) {
new_top = true;
top_fitness = fitness;
top_genome_id = id;
top_genome_gen_id = cur_gen;
}
break;
}
}
fitness_sum += std::stod(argv[1]);
airtime_sum += std::stod(argv[2]);
groundtime_sum += std::stod(argv[3]);
jump_sum += std::stoi(argv[4]);
if (std::stod(argv[11]) > 0) num_winner_genomes++;
return 0;
}
int Experiment::select_handler_ns(void* data, int argc, char** argv, char** colNames)
{
int id = std::stoi(argv[0]);
double fitness = std::stod(argv[1]);
for (std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it) {
if ((*it)->GetID() == id) {
for (int i = 5; i < 11; i++) {
(*it)->m_PhenotypeBehavior->m_Data[0][i - 5] = std::stod(argv[i]);
}
if (fitness > top_fitness) {
new_top = true;
top_fitness = fitness;
top_genome_id = id;
top_genome_gen_id = cur_gen;
}
break;
}
}
fitness_sum += std::stod(argv[1]);
airtime_sum += std::stod(argv[2]);
groundtime_sum += std::stod(argv[3]);
jump_sum += std::stoi(argv[4]);
if (std::stod(argv[11]) > 0) num_winner_genomes++;
return 0;
}
void Experiment::parse_commandline_arguments(int argc, char** argv)
{
for (int i = 0; i < argc; i++) {
string arg = argv[i];
if (arg == "--help")
{
print_usage();
exit(0);
}
else if (arg == "--experimentparamfile")
{
if (i + 1 < argc)
{
ExperimentParameters::experimentparam_filename = argv[++i];
}
else
{
std::cout << "Please specify path to experiment parameter file after using --experimentparamfile" << std::endl;
}
}
else if (arg == "--paramfile")
{
if (i + 1 < argc)
{
ExperimentParameters::param_filename = argv[++i];
}
else
{
std::cout << "Please specify path to MultiNEAT parameter file after using --paramfile" << std::endl;
}
}
else if (arg == "--popfile")
{
if (i + 1 < argc)
{
ExperimentParameters::pop_filename = argv[++i];
}
else
{
std::cout << "Please specify path to population file after using --popfile" << std::endl;
}
}
// We'll take seeds as a console argument for convenience,
// i.e. start multiple experiments via shellscript
else if (arg == "--seed")
{
int seed = 0;
if (i + 1 < argc && sscanf(argv[i + 1], "%d", &seed) == 1) {
ExperimentParameters::using_seed = true;
} else {
std::cout << "Please specify a proper seed after '--seed'" << std::endl;
}
}
else if (arg == "--noveltysearch")
{
ExperimentParameters::novelty_search = true;
}
else if (arg == "--hyperneat")
{
ExperimentParameters::hyperneat = true;
}
else if (i > 0 && arg[0] != '-')
{
ExperimentParameters::path_to_level = arg;
}
}
}
Parameters Experiment::init_params()
{
Parameters res;
if (strcmp(ExperimentParameters::param_filename.c_str(), "") != 0) {
res.Load(ExperimentParameters::param_filename.c_str());
}
return res;
}
void Experiment::parse_experiment_parameters()
{
string line, s;
double d;
std::ifstream stream(ExperimentParameters::experimentparam_filename);
while (std::getline(stream, line)) {
stringstream ss;
ss << line;
if (!(ss >> s >> d)) continue;
if (s == "maxgens") ExperimentParameters::max_gens = (int) d;
else if (s == "numcores") ExperimentParameters::num_cores = (int) d;
else if (s == "randseed") {
ExperimentParameters::using_seed = true;
ExperimentParameters::seed = (int) d;
}
else if (s == "autosaveinterval")
if ((int) d == 0) ExperimentParameters::autosave_best = true;
else ExperimentParameters::autosave_interval = (int) d;
else if (s == "numrangesensors") ExperimentParameters::AMOUNT_RANGE_SENSORS = (int) d;
else if (s == "numdepthsensors") ExperimentParameters::AMOUNT_DEPTH_SENSORS = (int) d;
else if (s == "numpiesensors") ExperimentParameters::AMOUNT_PIESLICE_SENSORS = (int) d;
else if (s == "spacingdepthsensors") ExperimentParameters::SPACING_DEPTH_SENSORS = (int) d;
else if (s == "radiuspiesensors") ExperimentParameters::RADIUS_PIESLICE_SENSORS = (int) d;
else if (s == "numhiddenstartneurons") ExperimentParameters::num_hidden_start_neurons = (int) d;
else if (s == "numhiddenstartneuronscppn") ExperimentParameters::num_hidden_start_neurons_cppn = (int) d;
else if (s == "noveltysearch" && (int) d) ExperimentParameters::novelty_search = true;
else if (s == "hyperneat" && (int) d) ExperimentParameters::hyperneat = true;
}
}
void Experiment::save_pop(string filename)
{
mkdir("popfiles", S_IRWXU);
std::stringstream ss = std::stringstream();
ss << "popfiles/";
ss << filename;
pop.Save(ss.str().c_str());
}
void Experiment::fix_filenames()
{
try {
ExperimentParameters::path_to_level = boost::filesystem::canonical(ExperimentParameters::path_to_level).string();
} catch (const std::exception& e) {
std::cerr << "Bad level file specified" << std::endl;
exit(-1);
}
if (strcmp(ExperimentParameters::pop_filename.c_str(), "")) {
try {
ExperimentParameters::pop_filename = boost::filesystem::canonical(ExperimentParameters::pop_filename).string();
} catch (const std::exception& e) {
std::cerr << "Bad population file specified" << std::endl;
exit(-1);
}
}
if (strcmp(ExperimentParameters::param_filename.c_str(), "")) {
try {
ExperimentParameters::param_filename = boost::filesystem::canonical(ExperimentParameters::param_filename).string();
} catch (const std::exception& e) {
std::cerr << "Bad parameter file specified" << std::endl;
exit(-1);
}
}
if (strcmp(ExperimentParameters::experimentparam_filename.c_str(), "")) {
try {
ExperimentParameters::experimentparam_filename = boost::filesystem::canonical(ExperimentParameters::experimentparam_filename).string();
} catch (const std::exception& e) {
std::cerr << "Bad experiment parameter file specified" << std::endl;
exit(-1);
}
}
}
int Experiment::busy_handler(void *data, int retry)
{
std::cout << "Busy handler";
if (retry < max_db_retry) {
std::cout << ", try #" << retry << std::endl;
sqlite3_sleep(db_sleeptime);
return 1;
} else {
return 0;
}
}
void Experiment::print_usage()
{
stringstream ss;
ss << std::endl;
ss << "====================================================" << std::endl;
ss << "== Help for SuperTux + NEAT experiment executable ==" << std::endl;
ss << "== Available arguments: ==" << std::endl;
ss << "====================================================" << std::endl;
ss << "--paramfile\t\tMultiNEAT parameter file" << std::endl;
ss << "--experimentparamfile\tCustom experiment parameter file. Check README for usage" << std::endl;
ss << std::endl;
ss << "The following arguments can be overriden by the experiment parameter file:" << std::endl;
ss << "--seed\t\t\tSeed for MultiNEAT" << std::endl;
ss << "--noveltysearch\t\tUse Novelty Search instead of objective-based fitness for evolution" << std::endl;
std::cout << ss.str();
}
| 30.516129
| 357
| 0.640082
|
ChristophKuhfuss
|
875281638813f52013ee2ac0ad9bab0cc0c37e9e
| 10,910
|
cpp
|
C++
|
src/core/Film.cpp
|
IDragnev/pbrt
|
0eef2a23fb840a73d70c888b4eb2ad5caa278d63
|
[
"MIT"
] | null | null | null |
src/core/Film.cpp
|
IDragnev/pbrt
|
0eef2a23fb840a73d70c888b4eb2ad5caa278d63
|
[
"MIT"
] | null | null | null |
src/core/Film.cpp
|
IDragnev/pbrt
|
0eef2a23fb840a73d70c888b4eb2ad5caa278d63
|
[
"MIT"
] | null | null | null |
#include "pbrt/core/Film.hpp"
#include "pbrt/core/geometry/Utility.hpp"
#include "pbrt/memory/Memory.hpp"
namespace idragnev::pbrt {
Film::Film(const Point2i& resolution,
const Bounds2f& cropWindow,
std::unique_ptr<const Filter> filt,
Float diagonal,
const std::string& filename,
Float scale,
Float maxSampleLuminance)
: fullResolution(resolution)
, diagonal(Float(diagonal * 0.001))
, filter(std::move(filt))
, filename(filename)
// clang-format off
, croppedPixelBounds(Bounds2i(
Point2i(static_cast<int>(std::ceil(fullResolution.x * cropWindow.min.x)),
static_cast<int>(std::ceil(fullResolution.y * cropWindow.min.y))),
Point2i(static_cast<int>(std::ceil(fullResolution.x * cropWindow.max.x)),
static_cast<int>(std::ceil(fullResolution.y * cropWindow.max.y)))))
// clang-format on
, pixels(new Pixel[croppedPixelBounds.area()])
, scale(scale)
, maxSampleLuminance(maxSampleLuminance) {
/*TODO: log resolution, crop window and cropped bounds */
const Float invTableExt = 1.f / static_cast<Float>(FILTER_TABLE_EXTENT);
std::size_t offset = 0;
for (int y = 0; y < FILTER_TABLE_EXTENT; ++y) {
for (int x = 0; x < FILTER_TABLE_EXTENT; ++x) {
// clang-format off
Point2f p;
p.x = (static_cast<Float>(x) + 0.5f) * invTableExt * filter->radius.x;
p.y = (static_cast<Float>(y) + 0.5f) * invTableExt * filter->radius.y;
// clang-format on
filterTable[offset++] = filter->eval(p);
}
}
}
Film::Pixel& Film::getPixel(const Point2i& p) {
assert(insideExclusive(p, croppedPixelBounds));
const int width = croppedPixelBounds.max.x - croppedPixelBounds.min.x;
const int offset = (p.x - croppedPixelBounds.min.x) +
(p.y - croppedPixelBounds.min.y) * width;
return pixels[offset];
}
Bounds2i Film::getSampleBounds() const {
Point2i min(math::floor(Point2f(croppedPixelBounds.min) +
Vector2f(0.5f, 0.5f) - filter->radius));
Point2i max(math::ceil(Point2f(croppedPixelBounds.max) -
Vector2f(0.5f, 0.5f) + filter->radius));
Bounds2i bounds;
bounds.min = min;
bounds.max = max;
return bounds;
}
Bounds2f Film::getPhysicalExtent() const {
const Float aspect = static_cast<Float>(fullResolution.y) /
static_cast<Float>(fullResolution.x);
const Float x =
std::sqrt(diagonal * diagonal / (1.f + aspect * aspect));
const Float y = aspect * x;
return Bounds2f{Point2f(-x / 2.f, -y / 2.f), Point2f(x / 2.f, y / 2.f)};
}
std::unique_ptr<FilmTile> Film::getFilmTile(const Bounds2i& sampleBounds) {
const Bounds2f floatBounds{sampleBounds};
const Point2i p0{
math::ceil(toDiscrete(floatBounds.min) - filter->radius)};
const Point2i p1 =
Point2i{math::floor(toDiscrete(floatBounds.max) + filter->radius)} +
Vector2i(1, 1);
Bounds2i tilePixelBounds =
intersectionOf(Bounds2i(p0, p1), croppedPixelBounds);
return std::unique_ptr<FilmTile>(new FilmTile(
tilePixelBounds,
filter->radius,
std::span<const Float>(filterTable,
FILTER_TABLE_EXTENT * FILTER_TABLE_EXTENT),
FILTER_TABLE_EXTENT,
maxSampleLuminance));
}
void Film::mergeFilmTile(std::unique_ptr<FilmTile> tile) {
// TODO: Log tile->pixelBounds ...
std::lock_guard<std::mutex> lock(mutex);
for (const Point2i pixel : tile->getPixelBounds()) {
const FilmTilePixel& tilePixel = tile->getPixel(pixel);
const std::array<Float, 3> xyz = tilePixel.contribSum.toXYZ();
Pixel& filmPixel = this->getPixel(pixel);
for (std::size_t i = 0; i < 3; ++i) {
filmPixel.xyz[i] += xyz[i];
}
filmPixel.filterWeightSum += tilePixel.filterWeightSum;
}
}
void Film::setImage(const std::span<Spectrum> imagePixels) const {
if (const int filmPixels = croppedPixelBounds.area();
filmPixels == static_cast<int>(imagePixels.size()))
{
const std::size_t nPixels = imagePixels.size();
for (std::size_t i = 0; i < nPixels; ++i) {
const std::array xyz = imagePixels[i].toXYZ();
Pixel& filmPixel = this->pixels[i];
filmPixel.xyz[0] = xyz[0];
filmPixel.xyz[1] = xyz[1];
filmPixel.xyz[2] = xyz[2];
filmPixel.filterWeightSum = 1.f;
filmPixel.splatXYZ[0] = 0.f;
filmPixel.splatXYZ[1] = 0.f;
filmPixel.splatXYZ[2] = 0.f;
}
}
else {
// TODO : Log ...
assert(false);
}
}
void Film::clear() {
for (const Point2i p : croppedPixelBounds) {
Pixel& filmPixel = getPixel(p);
filmPixel.xyz[0] = 0.f;
filmPixel.xyz[1] = 0.f;
filmPixel.xyz[2] = 0.f;
filmPixel.filterWeightSum = 0.f;
filmPixel.splatXYZ[0] = 0.f;
filmPixel.splatXYZ[1] = 0.f;
filmPixel.splatXYZ[2] = 0.f;
}
}
void
FilmTile::addSample(Point2f pFilm, Spectrum L, const Float sampleWeight) {
if (L.y() > maxSampleLuminance) {
L *= maxSampleLuminance / L.y();
}
pFilm = toDiscrete(pFilm);
auto p0 = Point2i{math::ceil(pFilm - filterRadius)};
auto p1 = Point2i{math::floor(pFilm + filterRadius)} + Vector2i(1, 1);
p0 = math::max(p0, pixelBounds.min);
p1 = math::min(p1, pixelBounds.max);
std::size_t* const filterXOffsets =
PBRT_ALLOCA(std::size_t, std::max(p1.x - p0.x, 1));
for (int x = p0.x; x < p1.x; ++x) {
const Float fx = std::abs((x - pFilm.x) * invFilterRadius.x *
static_cast<Float>(filterTableExtent));
filterXOffsets[x - p0.x] =
std::min(static_cast<std::size_t>(std::floor(fx)),
filterTableExtent - 1);
}
std::size_t* const filterYOffsets =
PBRT_ALLOCA(std::size_t, std::max(p1.y - p0.y, 1));
for (int y = p0.y; y < p1.y; ++y) {
const Float fy = std::abs((y - pFilm.y) * invFilterRadius.y *
static_cast<Float>(filterTableExtent));
filterYOffsets[y - p0.y] =
std::min(static_cast<std::size_t>(std::floor(fy)),
filterTableExtent - 1);
}
for (int y = p0.y; y < p1.y; ++y) {
for (int x = p0.x; x < p1.x; ++x) {
std::size_t offset =
filterYOffsets[y - p0.y] * filterTableExtent +
filterXOffsets[x - p0.x];
const Float filterWeight = filterTable[offset];
FilmTilePixel& pixel = getPixel(Point2i(x, y));
pixel.contribSum += L * sampleWeight * filterWeight;
pixel.filterWeightSum += filterWeight;
}
}
}
void Film::addSplat(const Point2f& p, Spectrum v) {
if (v.hasNaNs()) {
// TODO: log nans
return;
}
else if (v.y() < Float(0)) {
// log negative luminace
return;
}
else if (std::isinf(v.y())) {
// log inf luminace
return;
}
const Point2i pi(math::floor(p));
if (insideExclusive(pi, croppedPixelBounds)) {
if (v.y() > maxSampleLuminance) {
v *= maxSampleLuminance / v.y();
}
const std::array xyz = v.toXYZ();
Pixel& pixel = getPixel(pi);
pixel.splatXYZ[0].add(xyz[0]);
pixel.splatXYZ[1].add(xyz[1]);
pixel.splatXYZ[2].add(xyz[2]);
}
}
void Film::writeImage(const Float splatScale) {
// TODO: Log info: "Converting image to RGB and computing final weighted pixel values..."
const int nPixels = croppedPixelBounds.area();
std::unique_ptr<Float[]> imageRGB(new Float[3 * nPixels]);
for (std::size_t pixelIndex = 0; const Point2i p : croppedPixelBounds) {
const std::span<Float, 3> pixelRGB{&(imageRGB[3 * pixelIndex]), 3};
Pixel& pixel = getPixel(p);
const std::array arrRGB =
XYZToRGB(std::span<const Float, 3>{pixel.xyz});
pixelRGB[0] = arrRGB[0];
pixelRGB[1] = arrRGB[1];
pixelRGB[2] = arrRGB[2];
// normalize pixel with weight sum
if (pixel.filterWeightSum != 0.f) {
const Float invWt = Float(1) / pixel.filterWeightSum;
pixelRGB[0] = std::max(Float(0), pixelRGB[0] * invWt);
pixelRGB[1] = std::max(Float(0), pixelRGB[1] * invWt);
pixelRGB[2] = std::max(Float(0), pixelRGB[2] * invWt);
}
const Float splatXYZ[3] = {pixel.splatXYZ[0],
pixel.splatXYZ[1],
pixel.splatXYZ[2]};
const std::array splatRGB = XYZToRGB(splatXYZ);
pixelRGB[0] += splatScale * splatRGB[0];
pixelRGB[1] += splatScale * splatRGB[1];
pixelRGB[2] += splatScale * splatRGB[2];
pixelRGB[0] *= scale;
pixelRGB[1] *= scale;
pixelRGB[2] *= scale;
++pixelIndex;
}
// TODO: log_info("Writing image to {}. bounds = {}, scale = {}, splatScale = {}",
// filename, croppedPixelBounds, scale, splatScale)
// pbrt::writeImage(filename, &imageRGB[0], croppedPixelBounds, fullResolution);
}
FilmTilePixel& FilmTile::getPixel(const Point2i& p) {
assert(insideExclusive(p, pixelBounds));
int width = pixelBounds.max.x - pixelBounds.min.x;
int offset = (p.y - pixelBounds.min.y) * width +
(p.x - pixelBounds.min.x);
return pixels[offset];
}
const FilmTilePixel& FilmTile::getPixel(const Point2i& p) const {
assert(insideExclusive(p, pixelBounds));
int width = pixelBounds.max.x - pixelBounds.min.x;
int offset = (p.y - pixelBounds.min.y) * width +
(p.x - pixelBounds.min.x);
return pixels[offset];
}
} // namespace idragnev::pbrt
| 36.366667
| 97
| 0.528323
|
IDragnev
|
875325064a37bb256fef9507b5a7598a2bfe6fe6
| 2,824
|
cc
|
C++
|
UX/src/LogView.cc
|
frankencode/CoreComponents
|
4c66d7ff9fc5be19222906ba89ba0e98951179de
|
[
"Zlib"
] | null | null | null |
UX/src/LogView.cc
|
frankencode/CoreComponents
|
4c66d7ff9fc5be19222906ba89ba0e98951179de
|
[
"Zlib"
] | null | null | null |
UX/src/LogView.cc
|
frankencode/CoreComponents
|
4c66d7ff9fc5be19222906ba89ba0e98951179de
|
[
"Zlib"
] | null | null | null |
/*
* Copyright (C) 2022 Frank Mertens.
*
* Distribution and use is allowed under the terms of the zlib license
* (see cc/LICENSE-zlib).
*
*/
#include <cc/LogView>
#include <cc/Text>
#include <cc/LineSource>
#include <cc/Format>
namespace cc {
struct LogView::State final: public ListView::State
{
State()
{
font([this]{ return style().defaultFont(); });
margin([this]{
double m = style().flickableIndicatorThickness();
return Size{m, m};
});
leadSpace([this]{ return margin()[1]; });
tailSpace([this]{ return margin()[1]; });
font.onChanged([this]{ reload(); });
}
void reload()
{
ListView::State::deplete();
for (const String &line: lines_) {
appendLine(line);
}
}
void appendText(const String &text)
{
bool carrierAtEnd =
carrier().height() <= height() ||
carrier().pos()[1] <= height() - carrier().height() + sp(42);
for (const String &line: LineSource{text}) {
appendLine(line);
}
if (carrierAtEnd && height() < carrier().height()) {
if (carrier().moving()) carrierStop();
carrier().pos(Point{0, height() - carrier().height()});
}
}
void appendLine(const String &line)
{
carrier().add(
Text{line, font()}
.margin([this]{ return Size{margin()[0], 0}; })
.maxWidth([this]{ return width(); })
);
}
void clearText()
{
ListView::State::deplete();
lines_.deplete();
}
Property<Font> font;
Property<Size> margin;
List<String> lines_;
};
LogView::LogView():
ListView{onDemand<State>}
{}
LogView::LogView(double width, double height):
ListView{new State}
{
size(width, height);
}
LogView &LogView::associate(Out<LogView> self)
{
return View::associate<LogView>(self);
}
Font LogView::font() const
{
return me().font();
}
LogView &LogView::font(Font newValue)
{
me().font(newValue);
return *this;
}
LogView &LogView::font(Definition<Font> &&f)
{
me().font(move(f));
return *this;
}
Size LogView::margin() const
{
return me().margin();
}
LogView &LogView::margin(Size newValue)
{
me().margin(newValue);
return *this;
}
LogView &LogView::margin(Definition<Size> &&f)
{
me().margin(move(f));
return *this;
}
LogView &LogView::appendText(const String &text)
{
me().appendText(text);
return *this;
}
void LogView::clearText()
{
me().clearText();
}
List<String> LogView::textLines() const
{
return me().lines_;
}
LogView::State &LogView::me()
{
return Object::me.as<State>();
}
const LogView::State &LogView::me() const
{
return Object::me.as<State>();
}
} // namespace cc
| 18.337662
| 73
| 0.56551
|
frankencode
|
8755e97bf465d7b049f60568f861e6be78a58164
| 5,944
|
cc
|
C++
|
src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_bus.cc
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | null | null | null |
src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_bus.cc
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | null | null | null |
src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_bus.cc
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2019 The Fuchsia 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 "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_bus.h"
#include <zircon/errors.h>
#include <algorithm>
#include <string>
#include <ddk/metadata.h>
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/core.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/debug.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/device.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/firmware.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_buscore.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_firmware.h"
namespace wlan {
namespace brcmfmac {
PcieBus::PcieBus() = default;
PcieBus::~PcieBus() {
if (device_ != nullptr) {
if (device_->drvr()->settings == brcmf_mp_device_.get()) {
device_->drvr()->settings = nullptr;
}
if (device_->drvr()->bus_if == brcmf_bus_.get()) {
device_->drvr()->bus_if = nullptr;
}
device_ = nullptr;
}
}
// static
zx_status_t PcieBus::Create(Device* device, std::unique_ptr<PcieBus>* bus_out) {
zx_status_t status = ZX_OK;
auto pcie_bus = std::make_unique<PcieBus>();
std::unique_ptr<PcieBuscore> pcie_buscore;
if ((status = PcieBuscore::Create(device->parent(), &pcie_buscore)) != ZX_OK) {
return status;
}
std::unique_ptr<PcieFirmware> pcie_firmware;
if ((status = PcieFirmware::Create(device, pcie_buscore.get(), &pcie_firmware)) != ZX_OK) {
return status;
}
auto bus = std::make_unique<brcmf_bus>();
bus->bus_priv.pcie = pcie_bus.get();
bus->ops = PcieBus::GetBusOps();
auto mp_device = std::make_unique<brcmf_mp_device>();
brcmf_get_module_param(brcmf_bus_type::BRCMF_BUS_TYPE_PCIE, pcie_buscore->chip()->chip,
pcie_buscore->chip()->chiprev, mp_device.get());
device->drvr()->bus_if = bus.get();
device->drvr()->settings = mp_device.get();
pcie_bus->device_ = device;
pcie_bus->pcie_buscore_ = std::move(pcie_buscore);
pcie_bus->pcie_firmware_ = std::move(pcie_firmware);
pcie_bus->brcmf_bus_ = std::move(bus);
pcie_bus->brcmf_mp_device_ = std::move(mp_device);
*bus_out = std::move(pcie_bus);
return ZX_OK;
}
// static
const brcmf_bus_ops* PcieBus::GetBusOps() {
static constexpr brcmf_bus_ops bus_ops = {
.get_bus_type = []() { return PcieBus::GetBusType(); },
.stop = [](brcmf_bus* bus) { return bus->bus_priv.pcie->Stop(); },
.txdata = [](brcmf_bus* bus,
brcmf_netbuf* netbuf) { return bus->bus_priv.pcie->TxData(netbuf); },
.txctl = [](brcmf_bus* bus, unsigned char* msg,
uint len) { return bus->bus_priv.pcie->TxCtl(msg, len); },
.rxctl = [](brcmf_bus* bus, unsigned char* msg, uint len,
int* rxlen_out) { return bus->bus_priv.pcie->RxCtl(msg, len, rxlen_out); },
.wowl_config = [](brcmf_bus* bus,
bool enabled) { return bus->bus_priv.pcie->WowlConfig(enabled); },
.get_ramsize = [](brcmf_bus* bus) { return bus->bus_priv.pcie->GetRamsize(); },
.get_memdump = [](brcmf_bus* bus, void* data,
size_t len) { return bus->bus_priv.pcie->GetMemdump(data, len); },
.get_fwname =
[](brcmf_bus* bus, uint chip, uint chiprev, unsigned char* fw_name,
size_t* fw_name_size) {
return bus->bus_priv.pcie->GetFwname(chip, chiprev, fw_name, fw_name_size);
},
.get_bootloader_macaddr =
[](brcmf_bus* bus, uint8_t* mac_addr) {
return bus->bus_priv.pcie->GetBootloaderMacaddr(mac_addr);
},
.get_wifi_metadata =
[](brcmf_bus* bus, void* config, size_t exp_size, size_t* actual) {
return bus->bus_priv.pcie->GetWifiMetadata(config, exp_size, actual);
},
};
return &bus_ops;
}
// static
brcmf_bus_type PcieBus::GetBusType() { return BRCMF_BUS_TYPE_PCIE; }
void PcieBus::Stop() {}
zx_status_t PcieBus::TxData(brcmf_netbuf* netbuf) { return ZX_OK; }
zx_status_t PcieBus::TxCtl(unsigned char* msg, uint len) { return ZX_OK; }
zx_status_t PcieBus::RxCtl(unsigned char* msg, uint len, int* rxlen_out) {
if (rxlen_out != nullptr) {
*rxlen_out = 0;
}
return ZX_OK;
}
void PcieBus::WowlConfig(bool enabled) { BRCMF_ERR("PcieBus::WowlConfig unimplemented\n"); }
size_t PcieBus::GetRamsize() {
return pcie_buscore_->chip()->ramsize - pcie_buscore_->chip()->srsize;
}
zx_status_t PcieBus::GetMemdump(void* data, size_t len) {
pcie_buscore_->RamRead(0, data, len);
return ZX_OK;
}
zx_status_t PcieBus::GetFwname(uint chip, uint chiprev, unsigned char* fw_name,
size_t* fw_name_size) {
zx_status_t status = ZX_OK;
if (fw_name == nullptr || fw_name_size == nullptr || *fw_name_size == 0) {
return ZX_ERR_INVALID_ARGS;
}
std::string_view firmware_name;
if ((status = GetFirmwareName(brcmf_bus_type::BRCMF_BUS_TYPE_PCIE, pcie_buscore_->chip()->chip,
pcie_buscore_->chip()->chiprev, &firmware_name)) != ZX_OK) {
return status;
}
// Almost, but not quite, entirely unlike strlcpy().
const size_t copy_size = std::min<size_t>(*fw_name_size - 1, firmware_name.size());
std::copy(firmware_name.begin(), firmware_name.begin() + copy_size, fw_name);
fw_name[copy_size] = '\0';
return ZX_OK;
}
zx_status_t PcieBus::GetBootloaderMacaddr(uint8_t* mac_addr) {
BRCMF_ERR("PcieBus::GetBootloaderMacaddr unimplemented\n");
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t PcieBus::GetWifiMetadata(void* config, size_t exp_size, size_t* actual) {
return device_->DeviceGetMetadata(DEVICE_METADATA_WIFI_CONFIG, config, exp_size, actual);
}
} // namespace brcmfmac
} // namespace wlan
| 36.024242
| 100
| 0.677995
|
opensource-assist
|
875bdcc9c2e25b38fd819a6bff10e7a0970c52a1
| 10,674
|
cpp
|
C++
|
src/libc9/loader.cpp
|
stormbrew/channel9
|
626b42c208ce1eb54fff09ebd9f9e9fd0311935d
|
[
"MIT"
] | 1
|
2015-02-13T02:03:29.000Z
|
2015-02-13T02:03:29.000Z
|
src/libc9/loader.cpp
|
stormbrew/channel9
|
626b42c208ce1eb54fff09ebd9f9e9fd0311935d
|
[
"MIT"
] | null | null | null |
src/libc9/loader.cpp
|
stormbrew/channel9
|
626b42c208ce1eb54fff09ebd9f9e9fd0311935d
|
[
"MIT"
] | null | null | null |
#include <fstream>
#include <algorithm>
#include <stdlib.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "json/json.h"
#include "json/reader.h"
#include "c9/loader.hpp"
#include "c9/script.hpp"
#include "c9/istream.hpp"
#include "c9/variable_frame.hpp"
#include "c9/context.hpp"
namespace Channel9
{
class NothingChannel : public CallableContext
{
public:
NothingChannel(){}
~NothingChannel(){}
void send(Environment *env, const Value &val, const Value &ret)
{
}
std::string inspect() const
{
return "Nothing Channel";
}
};
NothingChannel *nothing_channel = new NothingChannel;
template <typename tRight>
loader_error operator<<(const loader_error &left, const tRight &right)
{
std::stringstream stream;
stream << left.reason;
stream << right;
return loader_error(stream.str());
}
Value convert_json(const Json::Value &val);
Value convert_json_array(const Json::Value &arr)
{
std::vector<Value> vals(arr.size());
std::vector<Value>::iterator oiter = vals.begin();
Json::Value::const_iterator iiter = arr.begin();
while (iiter != arr.end())
*oiter++ = convert_json(*iiter++);
return value(new_tuple(vals.begin(), vals.end()));
}
Value convert_json_complex(const Json::Value &obj)
{
if (!obj["undef"].isNull())
{
return Undef;
} else if (obj["message_id"].isString()) {
return value((int64_t)make_message_id(obj["message_id"].asString()));
} else if (obj["protocol_id"].isString()) {
return value((int64_t)make_protocol_id(obj["protocol_id"].asString()));
}
throw loader_error("Unknown complex object ") << obj.toStyledString();
}
Value convert_json(const Json::Value &val)
{
using namespace Json;
switch (val.type())
{
case nullValue:
return Nil;
case intValue:
return value(val.asInt64());
case uintValue:
return value((int64_t)val.asUInt64());
case realValue:
return value(val.asDouble());
case stringValue:
return value(val.asString());
case booleanValue:
return bvalue(val.asBool());
case arrayValue:
return convert_json_array(val);
case objectValue:
return convert_json_complex(val);
default:
throw loader_error("Invalid value encountered while parsing json");
}
}
GCRef<RunnableContext*> load_program(Environment *env, const Json::Value &code)
{
using namespace Channel9;
GCRef<IStream*> istream = new IStream;
int num = 0;
for (Json::Value::const_iterator it = code.begin(); it != code.end(); it++, num++)
{
const Json::Value &line = *it;
if (!line.isArray() || line.size() < 1)
{
throw loader_error("Malformed line ") << num << ": not an array or not enough elements";
}
const Json::Value &ival = line[0];
if (!ival.isString())
{
throw loader_error("Instruction on line ") << num << " was not a string (" << ival.toStyledString() << ")";
}
const std::string &instruction = ival.asString();
if (instruction == "line")
{
if (line.size() > 1)
{
std::string file = "(unknown)", extra;
uint64_t lineno = 0, linepos = 0;
file = line[1].asString();
if (line.size() > 2)
lineno = line[2].asUInt64();
if (line.size() > 3)
linepos = line[3].asUInt64();
if (line.size() > 4)
extra = line[4].asString();
(*istream)->set_source_pos(SourcePos(file, lineno, linepos, extra));
}
} else if (instruction == "set_label") {
if (line.size() != 2 || !line[1].isString())
{
throw loader_error("Invalid set_label line at ") << num;
}
(*istream)->set_label(line[1].asString());
} else {
INUM insnum = inum(instruction);
if (insnum == INUM_INVALID)
{
throw loader_error("Invalid instruction ") << instruction << " at " << num;
}
Instruction ins = {insnum};
InstructionInfo info = iinfo(ins);
if (line.size() - 1 < info.argc)
{
throw loader_error("Instruction ") << instruction << " takes "
<< info.argc << "arguments, but was given " << line.size() - 1
<< " at line " << num;
}
if (info.argc > 0)
ins.arg1 = convert_json(line[1]);
if (info.argc > 1)
ins.arg2 = convert_json(line[2]);
if (info.argc > 2)
ins.arg3 = convert_json(line[3]);
(*istream)->add(ins);
}
}
(*istream)->normalize();
GCRef<VariableFrame*> frame = new_variable_frame(*istream);
GCRef<RunnableContext*> ctx = new_context(*istream, *frame);
return ctx;
}
GCRef<RunnableContext*> load_bytecode(Environment *env, const std::string &filename)
{
std::ifstream file(filename.c_str());
if (file.is_open())
{
Json::Reader reader;
Json::Value body;
if (reader.parse(file, body, false))
{
Json::Value code = body["code"];
if (!code.isArray())
{
throw loader_error("No code block in ") << filename;
}
return load_program(env, code);
} else {
throw loader_error("Failed to parse json in ") << filename << ":\n"
<< reader.getFormattedErrorMessages();
}
} else {
throw loader_error("Could not open file ") << filename;
}
}
GCRef<RunnableContext*> load_bytecode(Environment *env, const std::string &filename, const std::string &str)
{
Json::Reader reader;
Json::Value body;
if (reader.parse(str, body, false))
{
Json::Value code = body["code"];
if (!code.isArray())
{
throw loader_error("No code block in ") << filename;
}
return load_program(env, code);
} else {
throw loader_error("Failed to parse json in ") << filename << ":\n"
<< reader.getFormattedErrorMessages();
}
}
int run_bytecode(Environment *env, const std::string &filename)
{
GCRef<RunnableContext*> ctx = load_bytecode(env, filename);
channel_send(env, value(*ctx), Nil, value(nothing_channel));
return 0;
}
GCRef<RunnableContext*> load_c9script(Environment *env, const std::string &filename)
{
GCRef<IStream*> istream = new IStream;
script::compile_file(filename, **istream);
(*istream)->normalize();
GCRef<VariableFrame*> frame = new_variable_frame(*istream);
GCRef<RunnableContext*> ctx = new_context(*istream, *frame);
return ctx;
}
int run_c9script(Environment *env, const std::string &filename)
{
GCRef<RunnableContext*> ctx = load_c9script(env, filename);
channel_send(env, value(*ctx), Nil, value(nothing_channel));
return 0;
}
int run_list(Environment *env, const std::string &filename)
{
std::ifstream file(filename.c_str());
if (file.is_open())
{
while (!file.eof())
{
std::string line;
std::getline(file, line);
if (line.size() > 0)
{
if (line[0] != '/')
{
// if the path is not absolute it's relative
// to the c9l file.
size_t last_slash_pos = filename.rfind('/');
if (last_slash_pos == std::string::npos)
run_file(env, line);
else
run_file(env, filename.substr(0, last_slash_pos+1) + line);
}
} else {
break;
}
}
return 0;
} else {
throw loader_error("Could not open file ") << filename << ".";
}
}
typedef int (*entry_point)(Environment*, const std::string&);
int run_shared_object(Environment *env, std::string filename)
{
#ifdef __APPLE__
// on macs change the .so to .dylib
filename.replace(filename.length()-3, std::string::npos, ".dylib");
#endif
void *shobj = dlopen(filename.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!shobj)
{
throw loader_error("Could not load shared object ") << filename;
}
entry_point shobj_entry = (entry_point)dlsym(shobj, "Channel9_environment_initialize");
if (!shobj_entry)
{
throw loader_error("Could not load entry point to shared object ") << filename;
}
return shobj_entry(env, filename);
}
void set_argv(Environment *env, int argc, const char **argv)
{
std::vector<Channel9::Value> args;
for (int i = 0; i < argc; i++)
{
args.push_back(Channel9::value(Channel9::new_string(argv[i])));
}
env->set_special_channel("argv", Channel9::value(Channel9::new_tuple(args.begin(), args.end())));
}
int load_environment_and_run(Environment *env, std::string program, int argc, const char **argv, bool trace_loaded)
{
// let the program invocation override the filename (ie. c9.rb always runs ruby)
// but if the exe doesn't match the exact expectation, use the first argument's
// extension to decide what to do.
size_t slash_pos = program.rfind('/');
if (slash_pos != std::string::npos)
program = program.substr(slash_pos + 1, std::string::npos);
if (program.length() < 3 || !std::equal(program.begin(), program.begin()+3, "c9."))
{
if (argc < 1)
throw loader_error("No program file specified.");
program = argv[0];
}
std::string ext = "";
size_t ext_pos = program.rfind('.');
if (ext_pos != std::string::npos)
ext = program.substr(ext_pos);
if (ext == "")
throw loader_error("Can't discover environment for file with no extension.");
if (ext == ".c9s" || ext == ".c9b" || ext == ".c9l" || ext == ".so")
{
// chop off the c9x file so it doesn't try to load itself.
set_argv(env, argc-1, argv+1);
return run_file(env, program);
} else {
// get the path of libc9.so. We expect c9 environments to be near it.
// They'll be at dirname(libc9.so)/c9-env/ext/ext.c9l.
Dl_info fninfo;
dladdr((void*)load_environment_and_run, &fninfo);
std::string search_path = std::string(fninfo.dli_fname);
search_path = search_path.substr(0, search_path.find_last_of('/') + 1);
search_path += "c9-env/";
std::string extname = ext.substr(1, std::string::npos);
search_path += extname + "/" + extname + ".c9l";
// find a matching module
struct stat match = {0};
if (stat(search_path.c_str(), &match) != 0)
throw loader_error("Could not find c9-env loader at ") << search_path;
// include the program name argument so it knows what to load.
set_argv(env, argc, argv);
env->set_special_channel("trace_loaded", bvalue(trace_loaded));
return run_file(env, search_path);
}
return 1;
}
int run_file(Environment *env, const std::string &filename)
{
// find the extension
std::string ext = "";
size_t ext_pos = filename.rfind('.');
if (ext_pos != std::string::npos)
ext = filename.substr(ext_pos);
if (ext == ".c9s")
{
return run_c9script(env, filename);
} else if (ext == ".c9b")
{
return run_bytecode(env, filename);
} else if (ext == ".c9l") {
return run_list(env, filename);
} else if (ext == ".so") {
return run_shared_object(env, filename);
} else if (ext == "") {
throw loader_error("Don't know what to do with no extension.");
} else {
throw loader_error("Don't know what to do with extension `") << ext << "`";
}
}
}
| 28.089474
| 116
| 0.643152
|
stormbrew
|
875d513837ce2208a4dbad201f5696b50d67f6b7
| 2,279
|
hpp
|
C++
|
library/L1_Peripheral/lpc17xx/i2c.hpp
|
SJSURoboticsTeam/urc-control_systems-2020
|
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
|
[
"Apache-2.0"
] | 1
|
2020-02-22T20:26:41.000Z
|
2020-02-22T20:26:41.000Z
|
library/L1_Peripheral/lpc17xx/i2c.hpp
|
SJSURoboticsTeam/urc-control_systems-2020
|
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
|
[
"Apache-2.0"
] | null | null | null |
library/L1_Peripheral/lpc17xx/i2c.hpp
|
SJSURoboticsTeam/urc-control_systems-2020
|
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
|
[
"Apache-2.0"
] | 4
|
2019-10-17T03:42:03.000Z
|
2020-05-23T20:32:03.000Z
|
#pragma once
#include "L1_Peripheral/lpc17xx/pin.hpp"
#include "L1_Peripheral/lpc17xx/system_controller.hpp"
#include "L1_Peripheral/lpc40xx/i2c.hpp"
namespace sjsu
{
namespace lpc17xx
{
// Bring in and using the LPC40xx driver as it is compatible with the lpc17xx
// peripheral.
using ::sjsu::lpc40xx::I2c;
/// Structure used as a namespace for predefined I2C Bus definitions.
struct I2cBus // NOLINT
{
private:
inline static lpc17xx::Pin i2c0_sda_pin = lpc17xx::Pin(0, 27);
inline static lpc17xx::Pin i2c0_scl_pin = lpc17xx::Pin(0, 28);
inline static lpc17xx::Pin i2c1_sda_pin = lpc17xx::Pin(0, 0);
inline static lpc17xx::Pin i2c1_scl_pin = lpc17xx::Pin(0, 1);
inline static lpc17xx::Pin i2c2_sda_pin = lpc17xx::Pin(0, 10);
inline static lpc17xx::Pin i2c2_scl_pin = lpc17xx::Pin(0, 11);
inline static I2c::Transaction_t transaction_i2c0;
inline static I2c::Transaction_t transaction_i2c1;
inline static I2c::Transaction_t transaction_i2c2;
public:
// Definition for I2C bus 0 for LPC17xx.
/// NOTE: I2C0 is not available for the 80-pin package.
inline static const lpc40xx::I2c::Bus_t kI2c0 = {
.registers = reinterpret_cast<lpc40xx::LPC_I2C_TypeDef *>(LPC_I2C0),
.id = SystemController::Peripherals::kI2c0,
.irq_number = I2C0_IRQn,
.transaction = transaction_i2c0,
.sda_pin = i2c0_sda_pin,
.scl_pin = i2c0_scl_pin,
.pin_function = 0b01,
};
/// Definition for I2C bus 1 for LPC17xx.
inline static const lpc40xx::I2c::Bus_t kI2c1 = {
.registers = reinterpret_cast<lpc40xx::LPC_I2C_TypeDef *>(LPC_I2C1),
.id = SystemController::Peripherals::kI2c1,
.irq_number = I2C1_IRQn,
.transaction = transaction_i2c1,
.sda_pin = i2c1_sda_pin,
.scl_pin = i2c1_scl_pin,
.pin_function = 0b11,
};
/// Definition for I2C bus 2 for LPC17xx.
inline static const lpc40xx::I2c::Bus_t kI2c2 = {
.registers = reinterpret_cast<lpc40xx::LPC_I2C_TypeDef *>(LPC_I2C2),
.id = SystemController::Peripherals::kI2c2,
.irq_number = I2C2_IRQn,
.transaction = transaction_i2c2,
.sda_pin = i2c2_sda_pin,
.scl_pin = i2c2_scl_pin,
.pin_function = 0b10,
};
};
} // namespace lpc17xx
} // namespace sjsu
| 33.028986
| 77
| 0.69197
|
SJSURoboticsTeam
|
876034cd377244f6c74963ed63ac430e03463d8b
| 477
|
cpp
|
C++
|
src/exchange/offer.cpp
|
cvauclair/marketsim
|
3ce669716a7c061fe05a6e4765c07808f4a89138
|
[
"MIT"
] | null | null | null |
src/exchange/offer.cpp
|
cvauclair/marketsim
|
3ce669716a7c061fe05a6e4765c07808f4a89138
|
[
"MIT"
] | 1
|
2021-02-10T14:12:34.000Z
|
2021-02-10T22:42:57.000Z
|
src/exchange/offer.cpp
|
cvauclair/marketsim
|
3ce669716a7c061fe05a6e4765c07808f4a89138
|
[
"MIT"
] | null | null | null |
#include "offer.h"
unsigned int Offer::offerCounter = 0;
Offer::Offer(OfferType type, const std::string &symbol, unsigned int quantity, float price, unsigned int accountId)
{
this->offerId = ++offerCounter;
this->symbol_ = symbol;
this->quantity = quantity;
this->price = Offer::round(price);
this->accountId_ = accountId;
this->status_ = Offer::PENDING;
this->type_ = type;
}
float Offer::round(float price)
{
return std::floor(1000.0f * price + 0.5f)/1000.0f;
}
| 21.681818
| 115
| 0.704403
|
cvauclair
|
8761aee44c3de02b1b13cbb08869509837aaaf6d
| 435
|
hpp
|
C++
|
Quasar/src/Quasar/Renderer/Camera.hpp
|
rvillegasm/Quasar
|
69a3e518030b52502bd1bf700cd6a44dc104d697
|
[
"Apache-2.0"
] | null | null | null |
Quasar/src/Quasar/Renderer/Camera.hpp
|
rvillegasm/Quasar
|
69a3e518030b52502bd1bf700cd6a44dc104d697
|
[
"Apache-2.0"
] | null | null | null |
Quasar/src/Quasar/Renderer/Camera.hpp
|
rvillegasm/Quasar
|
69a3e518030b52502bd1bf700cd6a44dc104d697
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <glm/glm.hpp>
namespace Quasar
{
class Camera
{
protected:
glm::mat4 m_Projection = glm::mat4(1.0f);
public:
Camera() = default;
Camera(const glm::mat4 &projection)
: m_Projection(projection)
{
}
virtual ~Camera() = default;
const glm::mat4 &getProjection() const { return m_Projection; }
};
} // namespace Quasar
| 16.730769
| 71
| 0.556322
|
rvillegasm
|
876250b484f53bcb46a7ba99c24475a765debd41
| 6,897
|
cpp
|
C++
|
data/haptic_teleoperation/src/robotteleop_keyboard.cpp
|
khairulislam/phys
|
fc702520fcd3b23022b9253e7d94f878978b4500
|
[
"MIT"
] | null | null | null |
data/haptic_teleoperation/src/robotteleop_keyboard.cpp
|
khairulislam/phys
|
fc702520fcd3b23022b9253e7d94f878978b4500
|
[
"MIT"
] | null | null | null |
data/haptic_teleoperation/src/robotteleop_keyboard.cpp
|
khairulislam/phys
|
fc702520fcd3b23022b9253e7d94f878978b4500
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/TwistStamped.h>
#include <std_msgs/Bool.h>
#include <signal.h>
#include <termios.h>
#include <stdio.h>
#include "boost/thread/mutex.hpp"
#include "boost/thread/thread.hpp"
#include <geometry_msgs/PoseStamped.h>
#include <tf/transform_broadcaster.h>
#include <Eigen/Eigen>
#define KEYCODE_R 0x43
#define KEYCODE_L 0x44
#define KEYCODE_U 0x41
#define KEYCODE_D 0x42
#define KEYCODE_Q 0x71
class RobotTeleop
{
public:
RobotTeleop();
void keyLoop();
void watchdog();
private:
ros::NodeHandle nh_,ph_;
double linear_x, linear_y, angular_z ;
ros::Time first_publish_;
ros::Time last_publish_;
double l_scale_, a_scale_;
ros::Publisher vel_pub_;
ros::Subscriber pose_sub_, collision_flag ;
double robot_ox;
double robot_oz;
double robot_oy;
void publish(double, double, double);
void poseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg);
double roll, pitch, yaw;
boost::mutex publish_mutex_;
// bool inCollision ;
};
RobotTeleop::RobotTeleop():
ph_("~"),
linear_x(0),
linear_y(0),
angular_z(0),
l_scale_(1.0),
a_scale_(1.0)
{
ph_.param("scale_angular", a_scale_, a_scale_);
ph_.param("scale_linear", l_scale_, l_scale_);
vel_pub_ = nh_.advertise<geometry_msgs::TwistStamped>("/uav/cmd_vel", 1);
pose_sub_ = nh_.subscribe("/mavros/vision_pose/pose" ,1, &RobotTeleop::poseCallback, this );
// collision_flag = nh_.subscribe<std_msgs::Bool>("/collision_flag" , 1, &SlaveController::get_inCollision , this);
}
void RobotTeleop::poseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
tf::Quaternion q( msg->pose.orientation.x,msg->pose.orientation.y,msg->pose.orientation.z,msg->pose.orientation.w);
tf::Matrix3x3(q).getRPY(roll, pitch, yaw);
std::cout << "pitch" << pitch << std::endl ;
std::cout << "roll" << roll << std::endl ;
std::cout << "yaw" << yaw << std::endl ;
std::cout << "yaw in degrees: " << yaw * 180 / 3.14 << std::endl ;
}
int kfd = 0;
struct termios cooked, raw;
void quit(int sig)
{
tcsetattr(kfd, TCSANOW, &cooked);
ros::shutdown();
exit(0);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "turtlebot_teleop");
RobotTeleop turtlebot_teleop;
ros::NodeHandle n;
signal(SIGINT,quit);
boost::thread my_thread(boost::bind(&RobotTeleop::keyLoop, &turtlebot_teleop));
ros::Timer timer = n.createTimer(ros::Duration(10.0), boost::bind(&RobotTeleop::watchdog, &turtlebot_teleop));
ros::spin();
my_thread.interrupt() ;
my_thread.join() ;
return(0);
}
void RobotTeleop::watchdog()
{
boost::mutex::scoped_lock lock(publish_mutex_);
if ((ros::Time::now() > last_publish_ + ros::Duration(10.0)) &&
(ros::Time::now() > first_publish_ + ros::Duration(10.0)))
publish(0, 0, 0);
}
void RobotTeleop::keyLoop()
{
char c;
// get the console in raw mode
tcgetattr(kfd, &cooked);
memcpy(&raw, &cooked, sizeof(struct termios));
raw.c_lflag &=~ (ICANON | ECHO);
// Setting a new line, then end of file
raw.c_cc[VEOL] = 1;
raw.c_cc[VEOF] = 2;
tcsetattr(kfd, TCSANOW, &raw);
puts("Reading from keyboard");
puts("---------------------------");
puts("Use arrow keys to move the quadrotor.");
while (ros::ok())
{
// get the next event from the keyboard
if(read(kfd, &c, 1) < 0)
{
perror("read():");
exit(-1);
}
linear_x=linear_y=0;
ROS_DEBUG("value: 0x%02X\n", c);
switch(c)
{
case KEYCODE_L:
ROS_DEBUG("LEFT");
angular_z = 0.0;
linear_x = 0.0;
linear_y = 0.1;
break;
case KEYCODE_R:
ROS_DEBUG("RIGHT");
angular_z = 0.0;
linear_x = 0.0;
linear_y = -0.1;
break;
case KEYCODE_U:
ROS_DEBUG("UP");
linear_y = 0.0;
angular_z = 0.0;
linear_x = 0.1;
break;
case KEYCODE_D:
ROS_DEBUG("DOWN");
linear_x = -0.1;
linear_y = 0.0;
angular_z = 0.0;
break;
case KEYCODE_Q:
ROS_DEBUG("Emergancy");
linear_x = 0.0;
linear_y = 0.0;
angular_z = 0.0;
break;
}
boost::mutex::scoped_lock lock(publish_mutex_);
if (ros::Time::now() > last_publish_ + ros::Duration(1.0)) {
first_publish_ = ros::Time::now();
}
last_publish_ = ros::Time::now();
publish(linear_y, linear_x, angular_z);
}
return;
}
void RobotTeleop::publish(double linear_y, double linear_x , double angular_z)
{
geometry_msgs::TwistStamped vel;
vel.twist.linear.x = linear_x*cos(yaw ) - linear_y * sin(yaw) ;
vel.twist.linear.y = linear_x*sin (yaw) + linear_y * cos(yaw) ;
std::cout << "vel.twist.linear.x" << vel.twist.linear.x << std::endl ;
std::cout << "vel.twist.linear.y" << vel.twist.linear.y<< std::endl ;
vel.twist.angular.z = angular_z;
vel_pub_.publish(vel);
return;
}
| 29.101266
| 119
| 0.627954
|
khairulislam
|
87688dec8b9c4eeed4df313af29a91625230542b
| 5,642
|
cpp
|
C++
|
cpp/Combinatorial-search/TSP-branch-and-bound.cpp
|
fossabot/a-grim-loth
|
a6c8d549289a39ec981c1e0d0c754bb2708dfff9
|
[
"MIT"
] | 4
|
2021-06-26T17:18:47.000Z
|
2022-02-02T15:02:27.000Z
|
cpp/Combinatorial-search/TSP-branch-and-bound.cpp
|
fossabot/a-grim-loth
|
a6c8d549289a39ec981c1e0d0c754bb2708dfff9
|
[
"MIT"
] | 8
|
2021-06-29T07:00:32.000Z
|
2021-12-01T11:26:22.000Z
|
cpp/Combinatorial-search/TSP-branch-and-bound.cpp
|
fossabot/a-grim-loth
|
a6c8d549289a39ec981c1e0d0c754bb2708dfff9
|
[
"MIT"
] | 3
|
2021-07-14T14:42:08.000Z
|
2021-12-07T19:36:53.000Z
|
/**
* @file travelling-salesman-problem.cpp
* @author prakash (prakashsellathurai@gmail.com)
* @brief travelling-salesman-problem using branch and bound
* @version 0.1
* @date 2021-08-01
*
* @copyright Copyright (c) 2021
*
*/
#include <algorithm>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
class TSP {
public:
int n;
int final_res = INT_MAX;
vector<int> final_path;
vector<bool> visited;
vector<vector<int>> graph;
TSP(vector<vector<int>> input_, int n_) {
graph = input_;
n = n_;
visited.resize(n, false);
final_path.resize(n + 1, 0);
}
// implement travelling salesman problem
void solve(int p) {
int curr_path[n + 1];
// Calculate initial lower bound for the root node
// using the formula 1/2 * (sum of first min +
// second min) for all edges.
// Also initialize the curr_path and visited array
int curr_bound = 0;
memset(curr_path, -1, sizeof(curr_path));
visited.resize(sizeof(curr_path), false);
// Compute initial bound
for (int i = 0; i < n; i++)
curr_bound += (firstMin(graph, i) + secondMin(graph, i));
// Rounding off the lower bound to an integer
curr_bound = (curr_bound & 1) ? curr_bound / 2 + 1 : curr_bound / 2;
// We start at vertex 1 so the first vertex
// in curr_path[] is 0
visited[0] = true;
curr_path[0] = 0;
TSP_Recursive(graph, curr_bound, 0, 1, curr_path);
}
// function that takes as arguments:
// curr_bound -> lower bound of the root node
// curr_weight-> stores the weight of the path so far
// level-> current level while moving in the search
// space tree
// curr_path[] -> where the solution is being stored which
// would later be copied to final_path[]
void TSP_Recursive(vector<vector<int>> adj, int curr_bound, int curr_weight,
int level, int curr_path[]) {
// base case is when we have reached level N which
// means we have covered all the nodes once
if (level == n) {
// check if there is an edge from last vertex in
// path back to the first vertex
if (adj[curr_path[level - 1]][curr_path[0]] != 0) {
// curr_res has the total weight of the
// solution we got
int curr_res = curr_weight + adj[curr_path[level - 1]][curr_path[0]];
// Update final result and final path if
// current result is better.
if (curr_res < final_res) {
copyToFinal(curr_path);
final_res = curr_res;
}
}
return;
}
// for any other level iterate for all vertices to
// build the search space tree recursively
for (int i = 0; i < n; i++) {
// Consider next vertex if it is not same (diagonal
// entry in adjacency matrix and not visited
// already)
if (adj[curr_path[level - 1]][i] != 0 && visited[i] == false) {
int temp = curr_bound;
curr_weight += adj[curr_path[level - 1]][i];
// different computation of curr_bound for
// level 2 from the other levels
if (level == 1)
curr_bound -=
((firstMin(adj, curr_path[level - 1]) + firstMin(adj, i)) / 2);
else
curr_bound -=
((secondMin(adj, curr_path[level - 1]) + firstMin(adj, i)) / 2);
// curr_bound + curr_weight is the actual lower bound
// for the node that we have arrived on
// If current lower bound < final_res, we need to explore
// the node further
if (curr_bound + curr_weight < final_res) {
curr_path[level] = i;
visited[i] = true;
// call TSP_Recursive for the next level
TSP_Recursive(adj, curr_bound, curr_weight, level + 1, curr_path);
}
// Else we have to prune the node by resetting
// all changes to curr_weight and curr_bound
curr_weight -= adj[curr_path[level - 1]][i];
curr_bound = temp;
// Also reset the visited array
visited.resize(visited.size(), false);
for (int j = 0; j <= level - 1; j++)
visited[curr_path[j]] = true;
}
}
}
// Function to copy temporary solution to
// the final solution
void copyToFinal(int curr_path[]) {
for (int i = 0; i < n; i++)
final_path[i] = curr_path[i];
final_path[n] = curr_path[0];
}
// print result
void print_result() {
cout << "Minimum Cost : " << final_res << endl;
std::cout << "Path taken :" << std::endl;
for (int i = 0; i < n; i++) {
std::cout << final_path[i] << " ";
}
std::cout << std::endl;
}
// Function to find the minimum edge cost
// having an end at the vertex i
int firstMin(vector<vector<int>> graph, int i) {
int min = INT_MAX;
for (int k = 0; k < n; k++)
if (graph[i][k] < min && i != k)
min = graph[i][k];
return min;
}
// function to find the second minimum edge cost
// having an end at the vertex i
int secondMin(vector<vector<int>> graph, int i) {
int first = INT_MAX, second = INT_MAX;
for (int j = 0; j < n; j++) {
if (i == j)
continue;
if (graph[i][j] <= first) {
second = first;
first = graph[i][j];
} else if (graph[i][j] <= second && graph[i][j] != first)
second = graph[i][j];
}
return second;
}
};
int main(int argc, const char **argv) {
vector<vector<int>> graph = {
{0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0}};
int n = graph.size();
int s = 0; /* source vertex*/
TSP tsp(graph, n);
tsp.solve(s);
tsp.print_result();
return 0;
}
| 30.010638
| 78
| 0.584722
|
fossabot
|
87722eeb4905a7d547f6a2faaecd8eb968ada488
| 1,281
|
cc
|
C++
|
leetcode/1300-critical-connections-in-a-network.cc
|
Magic07/online-judge-solutions
|
02a289dd7eb52d7eafabc97bd1a043213b65f70a
|
[
"MIT"
] | null | null | null |
leetcode/1300-critical-connections-in-a-network.cc
|
Magic07/online-judge-solutions
|
02a289dd7eb52d7eafabc97bd1a043213b65f70a
|
[
"MIT"
] | null | null | null |
leetcode/1300-critical-connections-in-a-network.cc
|
Magic07/online-judge-solutions
|
02a289dd7eb52d7eafabc97bd1a043213b65f70a
|
[
"MIT"
] | null | null | null |
#include <vector>
class Solution {
public:
int currentDfn;
vector<vector<int>> answer;
void dfs(int start,
const vector<vector<int>>& graph,
vector<int>& dfn,
vector<int>& low,
int parent) {
for (const auto& v : graph[start]) {
if (v == parent) {
continue;
}
if (dfn[v] == -1) {
low[v] = currentDfn;
dfn[v] = currentDfn++;
dfs(v, graph, dfn, low, start);
low[start] = min(low[start], low[v]);
if (low[v] > dfn[start]) {
answer.push_back({start, v});
}
} else {
low[start] = min(low[start], dfn[v]);
}
}
}
void resizeAndFill(vector<int>& v, int n) {
v.resize(n);
fill(v.begin(), v.end(), -1);
}
vector<vector<int>> criticalConnections(int n,
vector<vector<int>>& connections) {
vector<vector<int>> graph;
vector<int> dfn, low;
graph.resize(n);
resizeAndFill(dfn, n);
resizeAndFill(low, n);
currentDfn = 0;
for (const auto& con : connections) {
graph[con[0]].push_back(con[1]);
graph[con[1]].push_back(con[0]);
}
dfs(0, graph, dfn, low, 0);
return answer;
}
};
| 26.6875
| 78
| 0.489461
|
Magic07
|
87736715930f209007aa2a51c75f7a44eba804d7
| 7,927
|
cc
|
C++
|
components/page_load_metrics/browser/responsiveness_metrics_normalization_unittest.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
components/page_load_metrics/browser/responsiveness_metrics_normalization_unittest.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86
|
2015-10-21T13:02:42.000Z
|
2022-03-14T07:50:50.000Z
|
components/page_load_metrics/browser/responsiveness_metrics_normalization_unittest.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/page_load_metrics/browser/responsiveness_metrics_normalization.h"
#include "base/test/scoped_feature_list.h"
#include "components/page_load_metrics/common/page_load_metrics.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
using UserInteractionLatenciesPtr =
page_load_metrics::mojom::UserInteractionLatenciesPtr;
using UserInteractionLatencies =
page_load_metrics::mojom::UserInteractionLatencies;
using UserInteractionLatency = page_load_metrics::mojom::UserInteractionLatency;
using UserInteractionType = page_load_metrics::mojom::UserInteractionType;
class ResponsivenessMetricsNormalizationTest : public testing::Test {
public:
ResponsivenessMetricsNormalizationTest() = default;
void AddNewUserInteractions(uint64_t num_new_interactions,
UserInteractionLatencies& max_event_durations,
UserInteractionLatencies& total_event_durations) {
responsiveness_metrics_normalization_.AddNewUserInteractionLatencies(
num_new_interactions, max_event_durations, total_event_durations);
}
const page_load_metrics::NormalizedResponsivenessMetrics&
normalized_responsiveness_metrics() const {
return responsiveness_metrics_normalization_
.GetNormalizedResponsivenessMetrics();
}
private:
page_load_metrics::ResponsivenessMetricsNormalization
responsiveness_metrics_normalization_;
};
TEST_F(ResponsivenessMetricsNormalizationTest, OnlySendWorstInteractions) {
UserInteractionLatenciesPtr max_event_duration1 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(120));
UserInteractionLatenciesPtr total_event_durations1 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(140));
AddNewUserInteractions(1, *max_event_duration1, *total_event_durations1);
UserInteractionLatenciesPtr max_event_duration2 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(200));
UserInteractionLatenciesPtr total_event_durations2 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(250));
AddNewUserInteractions(2, *max_event_duration2, *total_event_durations2);
UserInteractionLatenciesPtr max_event_duration3 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(70));
UserInteractionLatenciesPtr total_event_durations3 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(70));
AddNewUserInteractions(3, *max_event_duration3, *total_event_durations3);
EXPECT_EQ(normalized_responsiveness_metrics().num_user_interactions, 6u);
// When the flag is disabled, only worst_latency has a meaningful value and
// other metrics should have default values.
auto& normalized_max_event_durations =
normalized_responsiveness_metrics().normalized_max_event_durations;
EXPECT_EQ(normalized_max_event_durations.worst_latency,
base::Milliseconds(200));
EXPECT_EQ(normalized_max_event_durations.worst_latency_over_budget,
base::Milliseconds(0));
EXPECT_EQ(normalized_max_event_durations.sum_of_latency_over_budget,
base::Milliseconds(0));
EXPECT_EQ(
normalized_max_event_durations.pseudo_second_worst_latency_over_budget,
base::Milliseconds(0));
auto& normalized_total_event_durations =
normalized_responsiveness_metrics().normalized_total_event_durations;
EXPECT_EQ(normalized_total_event_durations.worst_latency,
base::Milliseconds(250));
EXPECT_EQ(normalized_total_event_durations.worst_latency_over_budget,
base::Milliseconds(0));
EXPECT_EQ(normalized_total_event_durations.sum_of_latency_over_budget,
base::Milliseconds(0));
EXPECT_EQ(
normalized_total_event_durations.pseudo_second_worst_latency_over_budget,
base::Milliseconds(0));
}
TEST_F(ResponsivenessMetricsNormalizationTest, SendAllInteractions) {
// Flip the flag to send all user interaction latencies to browser.
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
blink::features::kSendAllUserInteractionLatencies);
UserInteractionLatenciesPtr max_event_durations =
UserInteractionLatencies::NewUserInteractionLatencies({});
auto& user_interaction_latencies1 =
max_event_durations->get_user_interaction_latencies();
user_interaction_latencies1.emplace_back(UserInteractionLatency::New(
base::Milliseconds(50), UserInteractionType::kKeyboard));
user_interaction_latencies1.emplace_back(UserInteractionLatency::New(
base::Milliseconds(100), UserInteractionType::kTapOrClick));
user_interaction_latencies1.emplace_back(UserInteractionLatency::New(
base::Milliseconds(150), UserInteractionType::kDrag));
UserInteractionLatenciesPtr total_event_durations =
UserInteractionLatencies::NewUserInteractionLatencies({});
auto& user_interaction_latencies2 =
total_event_durations->get_user_interaction_latencies();
user_interaction_latencies2.emplace_back(UserInteractionLatency::New(
base::Milliseconds(55), UserInteractionType::kKeyboard));
user_interaction_latencies2.emplace_back(UserInteractionLatency::New(
base::Milliseconds(105), UserInteractionType::kTapOrClick));
user_interaction_latencies2.emplace_back(UserInteractionLatency::New(
base::Milliseconds(155), UserInteractionType::kDrag));
AddNewUserInteractions(3, *max_event_durations, *total_event_durations);
auto worst_ten_max_event_durations =
normalized_responsiveness_metrics()
.normalized_max_event_durations.worst_ten_latencies_over_budget;
EXPECT_EQ(worst_ten_max_event_durations.size(), 3u);
EXPECT_EQ(worst_ten_max_event_durations.top(), base::Milliseconds(0));
worst_ten_max_event_durations.pop();
EXPECT_EQ(worst_ten_max_event_durations.top(), base::Milliseconds(0));
worst_ten_max_event_durations.pop();
EXPECT_EQ(worst_ten_max_event_durations.top(), base::Milliseconds(50));
auto worst_ten_total_event_durations =
normalized_responsiveness_metrics()
.normalized_total_event_durations.worst_ten_latencies_over_budget;
EXPECT_EQ(worst_ten_total_event_durations.size(), 3u);
EXPECT_EQ(worst_ten_total_event_durations.top(), base::Milliseconds(5));
worst_ten_total_event_durations.pop();
EXPECT_EQ(worst_ten_total_event_durations.top(), base::Milliseconds(5));
worst_ten_total_event_durations.pop();
EXPECT_EQ(worst_ten_total_event_durations.top(), base::Milliseconds(55));
EXPECT_EQ(normalized_responsiveness_metrics().num_user_interactions, 3u);
auto& normalized_max_event_durations =
normalized_responsiveness_metrics().normalized_max_event_durations;
EXPECT_EQ(normalized_max_event_durations.worst_latency,
base::Milliseconds(150));
EXPECT_EQ(normalized_max_event_durations.worst_latency_over_budget,
base::Milliseconds(50));
EXPECT_EQ(normalized_max_event_durations.sum_of_latency_over_budget,
base::Milliseconds(50));
EXPECT_EQ(
normalized_max_event_durations.pseudo_second_worst_latency_over_budget,
base::Milliseconds(0));
auto& normalized_total_event_durations =
normalized_responsiveness_metrics().normalized_total_event_durations;
EXPECT_EQ(normalized_total_event_durations.worst_latency,
base::Milliseconds(155));
EXPECT_EQ(normalized_total_event_durations.worst_latency_over_budget,
base::Milliseconds(55));
EXPECT_EQ(normalized_total_event_durations.sum_of_latency_over_budget,
base::Milliseconds(65));
EXPECT_EQ(
normalized_total_event_durations.pseudo_second_worst_latency_over_budget,
base::Milliseconds(5));
}
| 48.042424
| 86
| 0.799167
|
zealoussnow
|
8776383a5697804b88328a7a61733778662837a1
| 1,400
|
hpp
|
C++
|
src/cf_libs/dskcf/ScaleChangeObserver.hpp
|
liguanqun/Test_code
|
523f4ed4c29b2b2092b40a8c9c3ce1ddbcf0737b
|
[
"Apache-2.0"
] | null | null | null |
src/cf_libs/dskcf/ScaleChangeObserver.hpp
|
liguanqun/Test_code
|
523f4ed4c29b2b2092b40a8c9c3ce1ddbcf0737b
|
[
"Apache-2.0"
] | null | null | null |
src/cf_libs/dskcf/ScaleChangeObserver.hpp
|
liguanqun/Test_code
|
523f4ed4c29b2b2092b40a8c9c3ce1ddbcf0737b
|
[
"Apache-2.0"
] | null | null | null |
#ifndef _SCALECHANGEOBSERVER_HPP_
#define _SCALECHANGEOBSERVER_HPP_
/*
This class represents a C++ implementation of the DS-KCF Tracker [1]. In particular
the scaling system presented in [1] is implemented within this class
References:
[1] S. Hannuna, M. Camplani, J. Hall, M. Mirmehdi, D. Damen, T. Burghardt, A. Paiement, L. Tao,
DS-KCF: A ~real-time tracker for RGB-D data, Journal of Real-Time Image Processing
*/
#include "Typedefs.hpp"
/**
* ScaleChangeObserver is an abstract class.
* This class is designed to be derived by any class which needs to observe
* a ScaleAnalyser. An instance of ScaleChangeObserver should only be
* registered to observe a single ScaleAnalyser.
*/
class ScaleChangeObserver
{
public:
/**
* onScaleChange is called whenever a scale change has been detected.
* @param targetSize The new size of the target object's bounding box.
* @param windowSize The new padded size of the bounding box around the target.
* @param yf The new gaussian shaped labels for this scale.
* @param cosineWindow The new cosine window for this scale.
*
* @warning If an instance of this class is registered to observe multiple
* ScaleAnalyser, then this method will likely cause a crash.
*/
virtual void onScaleChange(const Size & targetSize, const Size & windowSize, const cv::Mat2d & yf, const cv::Mat1d & cosineWindow) = 0;
};
#endif
| 36.842105
| 137
| 0.738571
|
liguanqun
|
8778b21cc3238d4b53bd280e8c3e1765e1cd28c2
| 1,879
|
cpp
|
C++
|
src/tools/dnd/targets/ContainerFileTransitiveDataTarget.cpp
|
etrange02/Fux
|
2f49bcd8ec82eb521092c9162e01c8b0d00222ab
|
[
"CECILL-B"
] | 2
|
2016-03-21T10:48:34.000Z
|
2017-03-17T19:50:34.000Z
|
src/tools/dnd/targets/ContainerFileTransitiveDataTarget.cpp
|
etrange02/Fux
|
2f49bcd8ec82eb521092c9162e01c8b0d00222ab
|
[
"CECILL-B"
] | null | null | null |
src/tools/dnd/targets/ContainerFileTransitiveDataTarget.cpp
|
etrange02/Fux
|
2f49bcd8ec82eb521092c9162e01c8b0d00222ab
|
[
"CECILL-B"
] | null | null | null |
/***************************************************************
* Name: ContainerFileTransitiveDataTarget.cpp
* Purpose: Code for Fu(X) 2.0
* Author: David Lecoconnier (david.lecoconnier@free.fr)
* Created: 2015-06-26
* Copyright: David Lecoconnier (http://www.getfux.fr)
* License:
**************************************************************/
#include "tools/dnd/targets/ContainerFileTransitiveDataTarget.h"
#include "explorer/state/FileDriveManagerState.h"
#include "tools/dnd/dataObjects/ContainerFileTransitiveData.h"
#include <algorithm>
using namespace dragAndDrop;
/** @brief Constructor.
*/
ContainerFileTransitiveDataTarget::ContainerFileTransitiveDataTarget(DroppedMarkedLineListCtrl& source, explorer::FileDriveManagerState& managerState) :
TransitiveDataTarget(source),
m_managerState(managerState)
{
}
/** @brief Destructor.
*/
ContainerFileTransitiveDataTarget::~ContainerFileTransitiveDataTarget()
{
}
bool ContainerFileTransitiveDataTarget::isSameKind() const
{
if (m_data == NULL)
return false;
return m_data->isContainerFileKind();
}
void ContainerFileTransitiveDataTarget::doCopyProcessing(const wxArrayString& data, const long position)
{
m_managerState.insertElements(data, position);
}
void ContainerFileTransitiveDataTarget::doCutProcessing(TransitiveData& transitiveData, const long position)
{
ContainerFileTransitiveData& fileTransitiveData = static_cast<ContainerFileTransitiveData&>(transitiveData);
const unsigned long pos = position;
const std::vector<unsigned long>& items = fileTransitiveData.getItems();
std::vector<unsigned long>::const_iterator iter = std::find(items.begin(), items.end(), pos);
if (iter == items.end())
return;
m_managerState.insertElements(fileTransitiveData.getFilenames(), position);
fileTransitiveData.deleteFromSource();
}
| 33.553571
| 152
| 0.717935
|
etrange02
|
877bdeb46a7ef2936fac4605fbf5b303b6eb9e14
| 1,734
|
hpp
|
C++
|
headers/lagrangian.hpp
|
bluemner/scientific_computing
|
db7c2d2372e7b493feece406de21f091369bbc0b
|
[
"MIT"
] | null | null | null |
headers/lagrangian.hpp
|
bluemner/scientific_computing
|
db7c2d2372e7b493feece406de21f091369bbc0b
|
[
"MIT"
] | null | null | null |
headers/lagrangian.hpp
|
bluemner/scientific_computing
|
db7c2d2372e7b493feece406de21f091369bbc0b
|
[
"MIT"
] | null | null | null |
/** MIT License
Copyright (c) 2017 Brandon Bluemner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef _BETACORE_LAGRANGIAN_H_
#define _BETACORE_LAGRANGIAN_H_
namespace betacore {
template <typename T>
class Lagrangian{
template <size_t size>
static T Polynomial( T x, size_t point, T (&points)[size] ){
size_t i;
T h=1;
for(i=0; i<size; i++){
if(i != point){
h = h * (x - points[i]) / (points[point] - points[i]);
}
return h;
}
}
template <size_t size>
static T Interpolant( T x, T (&points)[size], T (&values)[size] ){
size_t i;
T sum = (T) 0; // cast needed
for( i = 0; i < size; i++){
sum = sum + values[i] * Polynomial(x, i, points);
}
return sum;
}
};
}
#endif
| 33.346154
| 79
| 0.711649
|
bluemner
|
877e5cb185a7fc44f80c03ed816965492643bb6a
| 3,555
|
hpp
|
C++
|
frame/object.hpp
|
joydit/solidframe
|
0539b0a1e77663ac4c701a88f56723d3e3688e8c
|
[
"BSL-1.0"
] | null | null | null |
frame/object.hpp
|
joydit/solidframe
|
0539b0a1e77663ac4c701a88f56723d3e3688e8c
|
[
"BSL-1.0"
] | null | null | null |
frame/object.hpp
|
joydit/solidframe
|
0539b0a1e77663ac4c701a88f56723d3e3688e8c
|
[
"BSL-1.0"
] | null | null | null |
// frame/object.hpp
//
// Copyright (c) 2007, 2008 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.
//
#ifndef SOLID_FRAME_OBJECT_HPP
#define SOLID_FRAME_OBJECT_HPP
#include "system/timespec.hpp"
#include "frame/common.hpp"
#include "utility/dynamictype.hpp"
#include "utility/dynamicpointer.hpp"
#include <boost/concept_check.hpp>
#ifdef HAS_STDATOMIC
#include <atomic>
#else
#include "boost/atomic.hpp"
#endif
namespace solid{
class Mutex;
namespace frame{
class Manager;
class Service;
class ObjectPointerBase;
class Message;
class SelectorBase;
class Object;
class Object: public Dynamic<Object, DynamicShared<> >{
public:
struct ExecuteContext{
enum RetValE{
WaitRequest,
WaitUntilRequest,
RescheduleRequest,
CloseRequest,
LeaveRequest,
};
size_t eventMask()const{
return evsmsk;
}
const TimeSpec& currentTime()const{
return rcrttm;
}
void reschedule();
void close();
void leave();
void wait();
void waitUntil(const TimeSpec &_rtm);
void waitFor(const TimeSpec &_rtm);
protected:
ExecuteContext(
const size_t _evsmsk,
const TimeSpec &_rcrttm
): evsmsk(_evsmsk), rcrttm(_rcrttm), retval(WaitRequest){}
size_t evsmsk;
const TimeSpec &rcrttm;
RetValE retval;
TimeSpec waittm;
};
struct ExecuteController: ExecuteContext{
ExecuteController(
const size_t _evsmsk,
const TimeSpec &_rcrttm
): ExecuteContext(_evsmsk, _rcrttm){}
const RetValE returnValue()const{
return this->retval;
}
const TimeSpec& waitTime()const{
return this->waittm;
}
};
static const TimeSpec& currentTime();
//!Get the object associated to the current thread
/*!
\see Object::associateToCurrentThread
*/
static Object& specific();
//! Returns true if the object is signaled
bool notified() const;
bool notified(size_t _s) const;
//! Get the id of the object
IndexT id() const;
/**
* Returns true if the signal should raise the object ASAP
* \param _smask The signal bitmask
*/
bool notify(size_t _smask);
//! Signal the object with a signal
virtual bool notify(DynamicPointer<Message> &_rmsgptr);
protected:
friend class Service;
friend class Manager;
friend class SelectorBase;
//! Constructor
Object();
//! Grab the signal mask eventually leaving some bits set- CALL this inside lock!!
size_t grabSignalMask(size_t _leave = 0);
//! Virtual destructor
virtual ~Object();//only objptr base can destroy an object
void unregister();
bool isRegistered()const;
virtual void doStop();
private:
static void doSetCurrentTime(const TimeSpec *_pcrtts);
//! Set the id
void id(const IndexT &_fullid);
//! Gets the id of the thread the object resides in
IndexT threadId()const;
//! Assigns the object to the current thread
/*!
This is usualy called by the pool's Selector.
*/
void associateToCurrentThread();
//! Executes the objects
/*!
This method is calle by selectpools with support for
events and timeouts
*/
virtual void execute(ExecuteContext &_rexectx);
void stop();
//! Set the thread id
void threadId(const IndexT &_thrid);
private:
IndexT fullid;
ATOMIC_NS::atomic<size_t> smask;
ATOMIC_NS::atomic<IndexT> thrid;
};
inline IndexT Object::id() const {
return fullid;
}
#ifndef NINLINES
#include "frame/object.ipp"
#endif
}//namespace frame
}//namespace solid
#endif
| 20.084746
| 89
| 0.719269
|
joydit
|
8781a3e7aec776a34a38c7f30aac146996651ab0
| 53
|
cpp
|
C++
|
xperf/vc_parallel_compiles/Group1_A.cpp
|
ariccio/main
|
c1dce7b2f4b2682a984894cce995fadee0fe717a
|
[
"MIT"
] | 17
|
2015-03-02T18:19:24.000Z
|
2021-07-26T11:20:24.000Z
|
xperf/vc_parallel_compiles/Group1_A.cpp
|
ariccio/main
|
c1dce7b2f4b2682a984894cce995fadee0fe717a
|
[
"MIT"
] | 3
|
2015-03-02T04:14:25.000Z
|
2015-09-05T23:04:42.000Z
|
xperf/vc_parallel_compiles/Group1_B.cpp
|
randomascii/main
|
e5c3a1f84922b912edc1f859c455e1f80a9b0f83
|
[
"MIT"
] | 6
|
2015-02-08T04:19:57.000Z
|
2016-04-22T11:34:26.000Z
|
#include "stdafx.h"
static int s_value = CALC_FIB1;
| 13.25
| 31
| 0.735849
|
ariccio
|
8781f7120eeb763696c4e9a344e0b5c1ec458bba
| 12,049
|
cpp
|
C++
|
MediaCodecRT/DllLoader.cpp
|
gaobowen/MediaCodecRT
|
8c0136eaf9c6cec50c9e4106d60988bdd0957e59
|
[
"MIT"
] | 2
|
2019-02-18T09:25:46.000Z
|
2019-04-19T08:05:58.000Z
|
MediaCodecRT/DllLoader.cpp
|
gaobowen/MediaCodecRT
|
8c0136eaf9c6cec50c9e4106d60988bdd0957e59
|
[
"MIT"
] | null | null | null |
MediaCodecRT/DllLoader.cpp
|
gaobowen/MediaCodecRT
|
8c0136eaf9c6cec50c9e4106d60988bdd0957e59
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "DllLoader.h"
using namespace MediaCodecRT;
HMODULE avutil_55_mod;
HMODULE avcodec_57_mod;
HMODULE avformat_57_mod;
HMODULE swscale_4_mod;
HMODULE swresample_2_mod;
HMODULE avdevice_57_mod;
HMODULE avfilter_6_mod;
HMODULE kernelAddr;
def_av_register_all * m_av_register_all;
def_av_malloc* m_av_malloc;
def_avio_alloc_context* m_avio_alloc_context;
def_avformat_alloc_context* m_avformat_alloc_context;
def_avformat_open_input* m_avformat_open_input;
def_av_dict_free* m_av_dict_free;
def_avformat_find_stream_info* m_avformat_find_stream_info;
def_av_find_best_stream* m_av_find_best_stream;
def_avcodec_alloc_context3* m_avcodec_alloc_context3;
//def_avcodec_parameters_to_context* m_avcodec_parameters_to_context;
def_avcodec_open2* m_avcodec_open2;
def_av_frame_free* m_av_frame_free;
def_av_frame_alloc* m_av_frame_alloc;
def_av_image_get_buffer_size* m_av_image_get_buffer_size;
def_av_image_fill_arrays* m_av_image_fill_arrays;
def_sws_getContext* m_sws_getContext;
def_av_seek_frame* m_av_seek_frame;
def_avcodec_flush_buffers* m_avcodec_flush_buffers;
def_av_read_frame* m_av_read_frame;
def_av_packet_unref* m_av_packet_unref;
def_avcodec_decode_video2* m_avcodec_decode_video2;
def_sws_scale* m_sws_scale;
def_avcodec_close* m_avcodec_close;
def_avformat_close_input* m_avformat_close_input;
def_av_free* m_av_free;
def_avcodec_free_context* m_avcodec_free_context;
def_avcodec_find_decoder* m_avcodec_find_decoder;
def_avcodec_find_decoder_by_name* m_avcodec_find_decoder_by_name;
def_av_guess_format* m_av_guess_format;
def_avformat_alloc_output_context2* m_avformat_alloc_output_context2;
def_avformat_new_stream* m_avformat_new_stream;
def_avcodec_encode_video2* m_avcodec_encode_video2;
def_av_write_frame* m_av_write_frame;;
def_av_write_trailer* m_av_write_trailer;
def_avio_close* m_avio_close;
def_avformat_free_context* m_avformat_free_context;
def_avformat_write_header* m_avformat_write_header;
def_av_new_packet* m_av_new_packet;
def_avcodec_find_encoder* m_avcodec_find_encoder;
def_avcodec_find_encoder_by_name* m_avcodec_find_encoder_by_name;
def_avcodec_register_all* m_avcodec_register_all;
def_av_codec_next* m_av_codec_next;
//def_avio_alloc_context* m_static_avio_alloc_context;
//def_avformat_alloc_context* m_static_avformat_alloc_context;
//def_avcodec_open2* m_static_avcodec_open2;
//def_av_guess_format* m_static_av_guess_format;
//def_avformat_alloc_output_context2* m_static_avformat_alloc_output_context2;
//def_avformat_new_stream* m_static_avformat_new_stream;
//def_avcodec_encode_video2* m_static_avcodec_encode_video2;
//def_av_write_frame* m_static_av_write_frame;
//def_av_write_trailer* m_static_av_write_trailer;
//def_avio_close* m_static_avio_close;
//def_avformat_free_context* m_static_avformat_free_context;
//def_avformat_write_header* m_static_avformat_write_header;
//def_avcodec_find_encoder* m_static_avcodec_find_encoder;
//def_avcodec_find_encoder_by_name* m_static_avcodec_find_encoder_by_name;
//def_av_malloc* m_static_av_malloc;
//def_av_frame_alloc* m_static_av_frame_alloc;
//def_av_new_packet* m_static_av_new_packet;
//def_av_packet_unref * m_static_av_packet_unref;
//def_avcodec_close* m_static_avcodec_close;
//def_av_free* m_static_av_free;
//def_av_register_all * my_static_av_register_all;
DllLoader::DllLoader()
{
}
bool MediaCodecRT::DllLoader::LoadAll()
{
MEMORY_BASIC_INFORMATION info = {};
if (VirtualQuery(VirtualQuery, &info, sizeof(info)))
{
kernelAddr = (HMODULE)info.AllocationBase;
auto loadlibraryPtr = (int64_t)GetProcAddress(kernelAddr, "LoadLibraryExW");
auto loadLibrary = (LoadLibraryExWPtr*)loadlibraryPtr;
auto user32_mod = loadLibrary(L"user32.dll", nullptr, 0);
//auto kernel32Addr = loadLibrary(L"kernel32.dll", nullptr, 0);
//auto allfmpeg = loadLibrary(L"ffmpeg.adll", nullptr, 0);
//m_av_malloc/av_frame_free/av_frame_alloc/av_image_get_buffer_size/av_image_fill_arrays/
avutil_55_mod = loadLibrary(L"avutil-55.dll", nullptr, 0);
//avutil_55_mod = allfmpeg;
m_av_malloc = (def_av_malloc*)GetProcAddress(avutil_55_mod, "av_malloc");
m_av_frame_free = (def_av_frame_free*)GetProcAddress(avutil_55_mod, "av_frame_free");
m_av_frame_alloc = (def_av_frame_alloc*)GetProcAddress(avutil_55_mod, "av_frame_alloc");
m_av_image_get_buffer_size = (def_av_image_get_buffer_size*)GetProcAddress(avutil_55_mod, "av_image_get_buffer_size");
m_av_image_fill_arrays = (def_av_image_fill_arrays*)GetProcAddress(avutil_55_mod, "av_image_fill_arrays");
m_av_free = (def_av_free*)GetProcAddress(avutil_55_mod, "av_free");
m_av_dict_free = (def_av_dict_free*)GetProcAddress(avutil_55_mod, "av_dict_free");
//avcodec_alloc_context3/avcodec_find_decoder/avcodec_open2/avcodec_flush_buffers/av_packet_unref/avcodec_decode_video2
avcodec_57_mod = loadLibrary(L"avcodec-57.dll", nullptr, 0);
//avcodec_57_mod = allfmpeg;
m_avcodec_alloc_context3 = (def_avcodec_alloc_context3*)GetProcAddress(avcodec_57_mod, "avcodec_alloc_context3");
m_avcodec_find_decoder = (def_avcodec_find_decoder*)GetProcAddress(avcodec_57_mod, "avcodec_find_decoder");
m_avcodec_open2 = (def_avcodec_open2*)GetProcAddress(avcodec_57_mod, "avcodec_open2");
m_avcodec_flush_buffers = (def_avcodec_flush_buffers*)GetProcAddress(avcodec_57_mod, "avcodec_flush_buffers");
m_av_packet_unref = (def_av_packet_unref*)GetProcAddress(avcodec_57_mod, "av_packet_unref");
m_avcodec_decode_video2 = (def_avcodec_decode_video2*)GetProcAddress(avcodec_57_mod, "avcodec_decode_video2");
//m_avcodec_parameters_to_context = (def_avcodec_parameters_to_context*)GetProcAddress(avcodec_57_mod, "avcodec_parameters_to_context");
m_avcodec_free_context = (def_avcodec_free_context*)GetProcAddress(avcodec_57_mod, "avcodec_free_context");
m_avcodec_find_decoder_by_name = (def_avcodec_find_decoder_by_name*)GetProcAddress(avcodec_57_mod, "avcodec_find_decoder_by_name");
m_avcodec_close = (def_avcodec_close*)GetProcAddress(avcodec_57_mod, "avcodec_close");
m_avcodec_find_encoder = (def_avcodec_find_encoder*)GetProcAddress(avcodec_57_mod, "avcodec_find_encoder");
m_avcodec_encode_video2 = (def_avcodec_encode_video2*)GetProcAddress(avcodec_57_mod, "avcodec_encode_video2");
m_av_new_packet = (def_av_new_packet*)GetProcAddress(avcodec_57_mod, "av_new_packet");
m_avcodec_find_encoder_by_name = (def_avcodec_find_encoder_by_name*)GetProcAddress(avcodec_57_mod, "avcodec_find_encoder_by_name");
m_avcodec_register_all = (def_avcodec_register_all*)GetProcAddress(avcodec_57_mod, "avcodec_register_all");
m_av_codec_next = (def_av_codec_next*)GetProcAddress(avcodec_57_mod, "av_codec_next");
//m_av_register_all/avio_alloc_context/avformat_alloc_context/avformat_open_input/avformat_find_stream_info/av_find_best_stream
//av_seek_frame/av_read_frame
avformat_57_mod = loadLibrary(L"avformat-57.dll", nullptr, 0);
//avformat_57_mod = allfmpeg;
m_av_register_all = (def_av_register_all*)GetProcAddress(avformat_57_mod, "av_register_all");
m_avio_alloc_context = (def_avio_alloc_context*)GetProcAddress(avformat_57_mod, "avio_alloc_context");
m_avformat_alloc_context = (def_avformat_alloc_context*)GetProcAddress(avformat_57_mod, "avformat_alloc_context");
m_avformat_open_input = (def_avformat_open_input*)GetProcAddress(avformat_57_mod, "avformat_open_input");
m_avformat_find_stream_info = (def_avformat_find_stream_info*)GetProcAddress(avformat_57_mod, "avformat_find_stream_info");
m_av_find_best_stream = (def_av_find_best_stream*)GetProcAddress(avformat_57_mod, "av_find_best_stream");
m_av_seek_frame = (def_av_seek_frame*)GetProcAddress(avformat_57_mod, "av_seek_frame");
m_av_read_frame = (def_av_read_frame*)GetProcAddress(avformat_57_mod, "av_read_frame");
m_avformat_close_input = (def_avformat_close_input*)GetProcAddress(avformat_57_mod, "avformat_close_input");
m_av_guess_format = (def_av_guess_format*)GetProcAddress(avformat_57_mod, "av_guess_format");
m_avformat_alloc_output_context2 = (def_avformat_alloc_output_context2*)GetProcAddress(avformat_57_mod, "avformat_alloc_output_context2");
m_avformat_new_stream = (def_avformat_new_stream*)GetProcAddress(avformat_57_mod, "avformat_new_stream");
m_avio_close = (def_avio_close*)GetProcAddress(avformat_57_mod, "avio_close");
m_avformat_free_context = (def_avformat_free_context*)GetProcAddress(avformat_57_mod, "avformat_free_context");
m_avformat_write_header = (def_avformat_write_header*)GetProcAddress(avformat_57_mod, "avformat_write_header");
m_av_write_frame = (def_av_write_frame*)GetProcAddress(avformat_57_mod, "av_write_frame");
m_av_write_trailer = (def_av_write_trailer*)GetProcAddress(avformat_57_mod, "av_write_trailer");
//sws_getContext/sws_scale
swscale_4_mod = loadLibrary(L"swscale-4.dll", nullptr, 0);
//swscale_4_mod = allfmpeg;
m_sws_getContext = (def_sws_getContext*)GetProcAddress(swscale_4_mod, "sws_getContext");
m_sws_scale = (def_sws_scale*)GetProcAddress(swscale_4_mod, "sws_scale");
//swresample_2_mod = loadLibrary(L"swresample-2.dll", nullptr, 0);
//avdevice_57_mod = loadLibrary(L"avdevice-57.dll", nullptr, 0);
//avfilter_6_mod = loadLibrary(L"avfilter-6.dll", nullptr, 0);
if (avutil_55_mod != nullptr && avcodec_57_mod != nullptr&& avformat_57_mod != nullptr&& swscale_4_mod != nullptr)
{
m_avcodec_register_all();
//AVCodec *c = m_av_codec_next(NULL);
//AVCodec* bbb = m_avcodec_find_encoder_by_name("mjpeg");
//decodec->
//if (encodec == NULL)
//{
// return false;
//}
//auto allfmpeg = loadLibrary(L"ffmpeg.txt", nullptr, 0);
//if (allfmpeg != NULL)
//{
// my_static_av_register_all = (def_av_register_all*)GetProcAddress(allfmpeg, "av_register_all");
// m_static_avio_alloc_context = (def_avio_alloc_context*)GetProcAddress(allfmpeg, "avio_alloc_context");
// m_static_avformat_alloc_context = (def_avformat_alloc_context*)GetProcAddress(allfmpeg, "avformat_alloc_context");
// m_static_avcodec_open2 = (def_avcodec_open2*)GetProcAddress(allfmpeg, "avcodec_open2");
// m_static_av_guess_format = (def_av_guess_format*)GetProcAddress(allfmpeg, "av_guess_format");
// m_static_avformat_alloc_output_context2 = (def_avformat_alloc_output_context2*)GetProcAddress(allfmpeg, "avformat_alloc_output_context2");
// m_static_avformat_new_stream = (def_avformat_new_stream*)GetProcAddress(allfmpeg, "avformat_new_stream");
// m_static_avcodec_encode_video2 = (def_avcodec_encode_video2*)GetProcAddress(allfmpeg, "avcodec_encode_video2");
// m_static_av_write_frame = (def_av_write_frame*)GetProcAddress(allfmpeg, "av_write_frame");
// m_static_av_write_trailer = (def_av_write_trailer*)GetProcAddress(allfmpeg, "av_write_trailer");
// m_static_avio_close = (def_avio_close*)GetProcAddress(allfmpeg, "avio_close");
// m_static_avformat_free_context = (def_avformat_free_context*)GetProcAddress(allfmpeg, "avformat_free_context");
// m_static_avformat_write_header = (def_avformat_write_header*)GetProcAddress(allfmpeg, "avformat_write_header");
// m_static_avcodec_find_encoder = (def_avcodec_find_encoder*)GetProcAddress(allfmpeg, "avcodec_find_encoder");
// m_static_avcodec_find_encoder_by_name = (def_avcodec_find_encoder_by_name*)GetProcAddress(allfmpeg, "avcodec_find_encoder_by_name");
// m_static_av_malloc = (def_av_malloc*)GetProcAddress(allfmpeg, "av_malloc");
// m_static_av_frame_alloc = (def_av_frame_alloc*)GetProcAddress(allfmpeg, "av_frame_alloc");
// m_static_av_new_packet = (def_av_new_packet*)GetProcAddress(allfmpeg, "av_new_packet");
// m_static_av_packet_unref = (def_av_packet_unref*)GetProcAddress(allfmpeg, "av_packet_unref");
// m_static_avcodec_close = (def_avcodec_close*)GetProcAddress(allfmpeg, "avcodec_close");
// m_static_av_free = (def_av_free*)GetProcAddress(allfmpeg, "av_free");
//}
return true;
}
}
return false;
}
DllLoader::~DllLoader()
{
}
| 54.768182
| 144
| 0.822226
|
gaobowen
|
8784146ac13d6b974322b8364facab1e6964f0b1
| 2,947
|
cpp
|
C++
|
actividades/sesion4/OSalvador/Actividad1/Vectores final.cpp
|
gsosad/Programacion-I
|
16bba6989fa09f6c9801a1092cf4ab4a2833876e
|
[
"MIT"
] | 1
|
2019-01-12T18:13:54.000Z
|
2019-01-12T18:13:54.000Z
|
actividades/sesion4/OSalvador/Actividad1/Vectores final.cpp
|
gsosad/Programacion-I
|
16bba6989fa09f6c9801a1092cf4ab4a2833876e
|
[
"MIT"
] | 1
|
2018-10-14T18:12:28.000Z
|
2018-10-14T18:12:28.000Z
|
actividades/sesion4/OSalvador/Actividad1/Vectores final.cpp
|
gsosad/Programacion-I
|
16bba6989fa09f6c9801a1092cf4ab4a2833876e
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <math.h>
using namespace std;
class Vector3D{
private:
float x,y,z;
float a,b,c;
public:
Vector3D(float _x, float _y, float _z){
x = _x;
y = _y;
z = _z;
}
void getCoordinates(float &a, float &b, float &c){
a = x;
b = y;
c = z;
}
//no dar valores de las coordenadas, llamar al vector
void scalarMultiplyBy(float num){
//x* = num es un atajo de x = x * num
x*= num;
y*= num;
z*= num;
}
//no estoy seguro de que el resultado del modulo sea correcto, pero la formula parece estar bien
float module(){
return sqrt(pow(x,2)+pow(y,2)+pow(z,2));
}
void add (Vector3D a ){
x = x + a.x;
y = y + a.y;
z = z + a.z;
}
void vectorMultiplyBy (Vector3D a ){
x = x * a.x;
y = y * a.y;
z = z * a.z;
}
};
int main(){
//declaracion de vectores y modulo
float x,y,z;
cout << "Introduce las coordenadas un primer vector: " << endl;
cin >> x >> y >> z;
Vector3D VectorUno(x,y,z);
VectorUno.getCoordinates(x,y,z);
cout << "El primer vector tiene coordenadas "<< "x: " << x << ", y: " << y << ", z: " << z << endl;
cout << "El modulo del vector vale: " << VectorUno.module() << endl;
float operador;
cout << "Por que numero quieres multiplicar tu vector?" << endl;
cin >> operador;
cout << "El resultado es: " << endl;
VectorUno.scalarMultiplyBy(operador);
//getCoordinates lo que hace es sobreescribir los valores de x,y,z con los x,y,z del vector
VectorUno.getCoordinates(x,y,z);
cout << "x: " << x << ", y: " << y << ", z: " << z << endl << endl;
cout << "Introduce las coordernadas de un segundo vector por el que multiplicar al primero: " << endl;
cin >> x >> y >> z;
Vector3D VectorDos(x,y,z);
VectorDos.getCoordinates(x,y,z);
cout << "Las coordenadas del segundo vector valen "<< "x: " << x << ", y: " << y << ", z: " << z << endl;
cout << "El modulo del segundo vector vale: " << VectorDos.module() << endl;
cout << "Introduce las coordernadas de un tercer vector que suma al segundo: " << endl;
cin >> x >> y >> z;
Vector3D VectorTres(x,y,z);
VectorTres.getCoordinates(x,y,z);
cout << "Las coordenadas del tercer vector valen "<< "x: " << x << ", y: " << y << ", z: " << z << endl;
cout << "El modulo del tercer vector vale: " << VectorTres.module() << endl;
//operaciones de vectores
VectorUno.vectorMultiplyBy(VectorDos);
VectorUno.getCoordinates(x,y,z);
cout << "El producto del primer y segundo vectores es el vector de coordenadas x: " << x << ", y:" << y << ", z:" << z << endl;
VectorDos.add(VectorTres);
VectorDos.getCoordinates(x,y,z);
cout << "La suma del segundo y tercer vectores es el vector de coordenadas x: " << x << ", y: " << y << ", z: " << z << endl;
return 0;
}
| 27.287037
| 130
| 0.556159
|
gsosad
|
8784aced478528d638b9691c26e77057c0b11a1f
| 10,048
|
cpp
|
C++
|
editor/src/window/window.cpp
|
TSAVideoGame/Skidibidipop
|
62a8f949266df13cd759e3b98e36e16e05aabd11
|
[
"Zlib"
] | 1
|
2020-12-26T21:52:59.000Z
|
2020-12-26T21:52:59.000Z
|
editor/src/window/window.cpp
|
TSAVideoGame/Skidibidipop
|
62a8f949266df13cd759e3b98e36e16e05aabd11
|
[
"Zlib"
] | 2
|
2021-01-15T04:05:00.000Z
|
2021-03-03T18:37:08.000Z
|
editor/src/window/window.cpp
|
TSAVideoGame/Skidibidipop
|
62a8f949266df13cd759e3b98e36e16e05aabd11
|
[
"Zlib"
] | null | null | null |
#include "window.h"
#include "constants.h"
#include <ctime>
#include <SDL2/SDL_ttf.h>
bool Editor::Window::running = true;
SDLW::Window* Editor::Window::window;
SDLW::Renderer* Editor::Window::renderer;
Editor::Inputs Editor::Window::inputs;
Editor::Tool::Manager* Editor::Window::tool_manager;
std::string Editor::Window::current_file;
SDLW::Texture* Editor::Window::current_file_tex;
std::string Editor::Window::queue_file;
std::uint16_t Editor::Window::current_section = 0;
std::uint16_t Editor::Window::queue_section = current_section;
unsigned int Editor::Window::current_zoom = 1;
Data::Save::Data Editor::Window::data = Data::Save::load("res/default.sbbd");
SDLW::Texture* Editor::Window::spritesheet;
size_t Editor::Window::firstTile; // Top-left most tile
Editor::Tool::Base* Editor::Window::selected_tool = nullptr;
void Editor::Window::init()
{
SDL_Init(SDL_INIT_EVERYTHING);
TTF_Init();
window = new SDLW::Window("SBB Editor", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Constants::Window.width, Constants::Window.height, 0);
renderer = new SDLW::Renderer(window);
inputs = {false, false, 0, 0, 0, 0, 0, 0, 0};
spritesheet = new SDLW::Texture("res/spritesheet.png", renderer);
// The default file name is SBBD_time.sbbd
char timeNameBuffer[20];
std::time_t rawtime;
time(&rawtime);
std::tm* timeinfo = localtime(&rawtime);
strftime(timeNameBuffer, sizeof(timeNameBuffer), "%Y_%m_%d_%T", timeinfo);
current_file = "SBBD_";
current_file.append(timeNameBuffer);
current_file += ".sbbd";
current_file_tex = nullptr;
create_current_file_texture();
queue_file = current_file;
firstTile = 0;
tool_manager = new Tool::Manager(renderer);
}
void Editor::Window::close()
{
delete spritesheet;
delete current_file_tex;
delete tool_manager;
delete renderer;
delete window;
TTF_Quit();
SDL_Quit();
}
void Editor::Window::input()
{
inputs.oldMouseDown = inputs.mouseDown;
inputs.oldMouseX = inputs.mouseX;
inputs.oldMouseY = inputs.mouseY;
inputs.mouseWheelY = 0;
SDL_Event e;
while(SDL_PollEvent(&e))
{
switch (e.type)
{
case SDL_QUIT:
{
running = false;
break;
}
case SDL_MOUSEBUTTONDOWN:
{
switch (e.button.button)
{
case SDL_BUTTON_LEFT:
{
inputs.mouseDown = true;
if (!inputs.oldMouseDown)
SDL_GetMouseState(&inputs.clickMouseX, &inputs.clickMouseY);
break;
}
}
break;
}
case SDL_MOUSEBUTTONUP:
{
switch (e.button.button)
{
case SDL_BUTTON_LEFT:
{
inputs.mouseDown = false;
break;
}
}
break;
}
case SDL_MOUSEWHEEL:
{
inputs.mouseWheelY = e.wheel.y;
break;
}
case SDL_WINDOWEVENT:
{
if (SDL_GetWindowID(window->get_SDL()) != e.window.windowID)
{
inputs.mouseDown = false;
}
break;
}
}
}
SDL_GetMouseState(&inputs.mouseX, &inputs.mouseY);
}
void Editor::Window::update()
{
if (queue_file != current_file)
{
update_current_file();
}
if (queue_section != current_section)
{
update_current_section();
}
static unsigned int tempFirstTile = firstTile, tempViewX = firstTile % data.map.sections[current_section].size.x, tempViewY = firstTile / data.map.sections[current_section].size.y;
tool_manager->update(MouseState::HOVER);
if (inputs.mouseDown)
{
if (!inputs.oldMouseDown) // Click
{
tool_manager->update(MouseState::CLICK);
}
// Drag
if (selected_tool != nullptr)
{
tool_manager->update(MouseState::DRAG);
}
// This camera movement is all broken
else
{
int maxDrag = 29; // This will help in solving overflow messes
int y = -((inputs.mouseY - inputs.clickMouseY) / Constants::Grid.size);
int x = ((inputs.mouseX - inputs.clickMouseX) / Constants::Grid.size);
// Make y within bounds
if (tempFirstTile / data.map.sections[current_section].size.x < maxDrag && static_cast<int>(tempFirstTile / data.map.sections[current_section].size.x) + y < 0)
y = -(tempFirstTile / data.map.sections[current_section].size.x);
else if (tempFirstTile / data.map.sections[current_section].size.x + y >= data.map.sections[current_section].size.y)
y = (data.map.sections[current_section].size.y - 1) - (tempFirstTile / data.map.sections[current_section].size.x);
// Make x within bounds
if (tempFirstTile % data.map.sections[current_section].size.x < maxDrag && static_cast<int>(tempFirstTile % data.map.sections[current_section].size.x) + x < 0)
x = -(tempFirstTile % data.map.sections[current_section].size.x);
else if (tempFirstTile % data.map.sections[current_section].size.x + x >= data.map.sections[current_section].size.x)
x = (data.map.sections[current_section].size.x - 1) - (tempFirstTile % data.map.sections[current_section].size.x);
// Change firstTile
firstTile = tempFirstTile + data.map.sections[current_section].size.x * y + x;
}
}
// Release
if (!inputs.mouseDown && inputs.oldMouseDown)
{
if (selected_tool == nullptr)
{
tempFirstTile = firstTile;
tempViewX = firstTile % data.map.sections[current_section].size.x;
tempViewY = firstTile / data.map.sections[current_section].size.y;
}
}
// Scroll
if (std::abs(inputs.mouseWheelY) > 0)
{
if (inputs.mouseWheelY > 0) // Decrease zoom
{
if (current_zoom > 0)
--current_zoom;
}
else // Increase zoom
{
if (current_zoom < 4)
++current_zoom;
}
}
}
static void drawGrid(SDL_Renderer* renderer)
{
int size = 32;
SDL_SetRenderDrawColor(renderer, 36, 82, 94, 255);
// Draw vertical lines
for (int i = 1; i < Editor::Constants::Window.width / size; i++)
SDL_RenderDrawLine(renderer, i * size, 0, i * size, Editor::Constants::Window.height);
// Draw horizontal lines
for (int i = 1; i < Editor::Constants::Window.height / size; i++)
SDL_RenderDrawLine(renderer, 0, i * size, Editor::Constants::Window.width, i * size);
}
void Editor::Window::draw_tiles()
{
int size = Constants::Grid.size / std::pow(2, current_zoom);
SDL_Rect dRect = {0, 0, size, size};
SDL_Rect sRect = {0, 0, 32, 32};
unsigned int windowXTiles = Constants::Window.width / size;
unsigned int maxXTiles = data.map.sections[current_section].size.x - (firstTile % data.map.sections[current_section].size.x) < windowXTiles ? data.map.sections[current_section].size.x - (firstTile % data.map.sections[current_section].size.x) : windowXTiles;
unsigned int windowYTiles = (Constants::Window.height - Constants::Window.toolBarHeight) / size;
unsigned int maxYTiles = data.map.sections[current_section].size.y - (firstTile / data.map.sections[current_section].size.x) < windowYTiles ? data.map.sections[current_section].size.y - (firstTile / data.map.sections[current_section].size.x) : windowYTiles;
for (unsigned int row = 0; row < maxYTiles; ++row)
{
for (unsigned int col = 0; col < maxXTiles; ++col)
{
// Draw tile (id)
sRect.x = data.map.sections[current_section].tiles[firstTile + (row * data.map.sections[current_section].size.x) + col].id * 32;
sRect.y = 0;
renderer->copy(spritesheet, &sRect, &dRect);
// Draw tile objects (state)
sRect.x = data.map.sections[current_section].tiles[firstTile + (row * data.map.sections[current_section].size.x) + col].state * 32;
sRect.y = 32;
renderer->copy(spritesheet, &sRect, &dRect);
// Increment dRect
dRect.x += size;
}
dRect.x = 0;
dRect.y += size;
}
}
void Editor::Window::draw()
{
renderer->set_draw_color(10, 56, 69, 255);
renderer->clear();
// Draw map stuff
drawGrid(renderer->get_SDL());
draw_tiles();
// Draw tool stuff
// Draw the toolbar
SDL_Color c = tool_manager->getColor();
renderer->set_draw_color(c.r, c.g, c.b, 255);
SDL_Rect toolbar = {0, Constants::Window.height - Constants::Window.toolBarHeight, Constants::Window.width, Constants::Window.toolBarHeight};
SDL_RenderFillRect(renderer->get_SDL(), &toolbar);
tool_manager->draw();
// Draw the current file
SDL_Rect dRect = {4, Constants::Window.height - 24, 0, 0};
SDL_QueryTexture(current_file_tex->get_SDL(), 0, 0, &dRect.w, &dRect.h);
renderer->copy(current_file_tex, 0, &dRect);
renderer->present();
}
void Editor::Window::create_current_file_texture()
{
std::string displayText = "File: " + current_file;
TTF_Font* font = TTF_OpenFont("res/fonts/open-sans/OpenSans-Regular.ttf", 16);
SDL_Surface* txtSurface = TTF_RenderText_Blended(font, displayText.c_str(), {255, 255, 255});
if (current_file_tex != nullptr)
delete current_file_tex;
current_file_tex = new SDLW::Texture(SDL_CreateTextureFromSurface(renderer->get_SDL(), txtSurface));
SDL_FreeSurface(txtSurface);
TTF_CloseFont(font);
}
void Editor::Window::update_current_file()
{
current_file = queue_file;
create_current_file_texture();
data = Data::Save::load(current_file);
}
void Editor::Window::update_current_section()
{
if (queue_section < 0 || queue_section > data.map.sections.size() - 1)
{
queue_section = current_section;
return; // Queue is invalid
}
current_section = queue_section;
}
void Editor::Window::set_current_file(const std::string& new_file)
{
queue_file = new_file;
}
void Editor::Window::set_current_section(std::uint16_t new_section)
{
queue_section = new_section;
}
bool Editor::Window::is_running() { return running; }
Editor::Inputs Editor::Window::get_inputs() { return inputs; }
std::string Editor::Window::get_current_file() { return current_file; };
size_t Editor::Window::get_first_tile() { return firstTile; };
std::uint16_t Editor::Window::get_current_section() { return current_section; }
unsigned int Editor::Window::get_current_zoom() { return current_zoom; }
| 31.012346
| 259
| 0.670681
|
TSAVideoGame
|
8788aefd5cb7545ca8a430ef9120d41c793624b2
| 13,725
|
cpp
|
C++
|
groups/bdl/bdlb/bdlb_indexspanutil.t.cpp
|
seanbaxter/bde-1
|
149176ebc2ae49c3b563895a7332fe638a760782
|
[
"Apache-2.0"
] | 1
|
2020-02-03T17:15:53.000Z
|
2020-02-03T17:15:53.000Z
|
groups/bdl/bdlb/bdlb_indexspanutil.t.cpp
|
seanbaxter/bde-1
|
149176ebc2ae49c3b563895a7332fe638a760782
|
[
"Apache-2.0"
] | 2
|
2020-11-05T15:20:55.000Z
|
2021-01-05T19:38:43.000Z
|
groups/bdl/bdlb/bdlb_indexspanutil.t.cpp
|
seanbaxter/bde-1
|
149176ebc2ae49c3b563895a7332fe638a760782
|
[
"Apache-2.0"
] | 2
|
2020-01-16T17:58:12.000Z
|
2020-08-11T20:59:30.000Z
|
// bdlb_indexspanutil.t.cpp -*-C++-*-
#include <bdlb_indexspanutil.h>
#include <bdlb_indexspan.h>
#include <bslim_testutil.h>
#include <bsls_asserttest.h>
#include <bsls_buildtarget.h>
#include <bsl_cstdlib.h>
#include <bsl_cstring.h>
#include <bsl_iostream.h>
#include <bsl_string.h> // For the usage example
using namespace BloombergLP;
using namespace bsl;
// ============================================================================
// TEST PLAN
// ----------------------------------------------------------------------------
// Overview
// --------
// This component is a utility operating on 'bldb::IndexSpan' objects.
// ----------------------------------------------------------------------------
// CLASS METHODS
// [2] IndexSpan shrink(original, shrinkBegin, shrinkEnd);
// ----------------------------------------------------------------------------
// [1] BREATHING TEST
// [3] USAGE EXAMPLE
// ============================================================================
// STANDARD BDE ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
cout << "Error " __FILE__ "(" << line << "): " << message
<< " (failed)" << endl;
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLIM_TESTUTIL_ASSERT
#define ASSERTV BSLIM_TESTUTIL_ASSERTV
#define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT
#define Q BSLIM_TESTUTIL_Q // Quote identifier literally.
#define P BSLIM_TESTUTIL_P // Print identifier and value.
#define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLIM_TESTUTIL_L_ // current Line number
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)
//=============================================================================
// TYPE DEFINITIONS
//-----------------------------------------------------------------------------
typedef bdlb::IndexSpanUtil Util;
//=============================================================================
// USAGE EXAMPLE
//-----------------------------------------------------------------------------
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example1: Taking a IPv6 address out of a URI
/// - - - - - - - - - - - - - - - - - - - - - -
// Suppose we a class that stores a parsed URL using a string to store the full
// URL and 'IndexSpan' objects to describe the individual parts of the URL and.
// we want to add accessors that handle the case when the host part of the URL
// is an IPv6 address, such as "http://[ff:fe:9]/index.html". As observed, an
// IPv6 address is indicated by the '[' and ']' characters (the URL is ill
// formed if the closing ']' is not present). We want to implement two
// methods, one to query if the host part of the URL is IPv6 ('isIPv6Host') and
// another to get the IPv6 address (the part without the square brackets) if
// the host is actually an IPv6 address ('getIPv6Host').
//
// First let us create a 'ParsedUrl' class. For brevity, the class has only
// those parts that are needed to implement 'isIPv6Host' and 'getIPv6Host'.
//..
class ParsedUrl {
private:
// DATA
bsl::string d_url;
bdlb::IndexSpan d_host;
public:
// CREATORS
ParsedUrl(const bslstl::StringRef& url, bdlb::IndexSpan host)
// Create a 'ParsedUrl' from the specified 'url', and 'host'.
: d_url(url)
, d_host(host)
{
}
// ACCESSORS
bool isIPv6Host() const;
// Return 'true' if the host part represents an IPv6 address and
// 'false' otherwise.
bslstl::StringRef getIPv6Host() const;
// Return a string reference to the IPv6 address in the host part
// of this URL. The behavior is undefined unless
// 'isIPv6Host() == true' for this object.
};
//..
// Next, we implement 'isIPv6Host'.
//..
bool ParsedUrl::isIPv6Host() const
{
return !d_host.isEmpty() && '[' == d_url[d_host.position()];
}
//..
// Then, to make the accessors simple (and readable), we implement a helper
// function that creates a 'StringRef' from a 'StringRef' and an 'IndexSpan'.
// (Don't do this in real code, use 'IndexSpanStringUtil::bind' that is
// levelized above this component - so we cannot use it here.)
//..
bslstl::StringRef bindSpan(const bslstl::StringRef& full,
const bdlb::IndexSpan& part)
// Return a string reference to the substring of the specified 'full'
// thing defined by the specified 'part'.
{
BSLS_ASSERT(part.position() <= full.length());
BSLS_ASSERT(part.position() + part.length() <= full.length());
return bslstl::StringRef(full.data() + part.position(), part.length());
}
//..
// Next, we implement 'getIPv6Host' using 'bdlb::IndexSpanUtil::shrink'.
//..
bslstl::StringRef ParsedUrl::getIPv6Host() const
{
BSLS_ASSERT(isIPv6Host());
return bindSpan(d_url, bdlb::IndexSpanUtil::shrink(d_host, 1, 1));
}
//..
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? bsl::atoi(argv[1]) : 0;
bool verbose = argc > 2;
bool veryVerbose = argc > 3;
bool veryVeryVerbose = argc > 4; (void)veryVeryVerbose;
cout << "TEST " << __FILE__ << " CASE " << test << endl;;
switch (test) { case 0:
case 3: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
// Extracted from component header file.
//
// Concerns:
//: 1 The usage example provided in the component header file compiles,
//: links, and runs as shown.
//
// Plan:
//: 1 Incorporate usage example from header into test driver, replace
//: leading comment characters with spaces, replace 'assert' with
//: 'ASSERT', and insert 'if (veryVerbose)' before all output
//: operations. (C-1)
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) cout << "\nUSAGE EXAMPLE"
"\n=============\n";
// See the rest of the code just before the 'main' function.
//
// Finally, we verify the two methods with URLs.
//..
ParsedUrl pu1("https://host/path/", bdlb::IndexSpan(8, 4));
ASSERT(false == pu1.isIPv6Host());
ParsedUrl pu2("https://[12:3:fe:9]/path/", bdlb::IndexSpan(8, 11));
ASSERT(true == pu2.isIPv6Host());
ASSERT("12:3:fe:9" == pu2.getIPv6Host());
//..
} break;
case 2: {
// --------------------------------------------------------------------
// TESTING SHRINK
//
// Concerns:
//: 1 Shrinking from the beginning increases position and decreases
//: length.
//:
//: 2 Shrinking from the end decreases length only.
//:
//: 2 Shrinking beyond the size 'BSLS_ASSERT's.
//
// Plan:
//: 1 Table based testing.
//
// Testing:
// IndexSpan shrink(original, shrinkBegin, shrinkEnd);
// --------------------------------------------------------------------
if (verbose) cout << "\nTESTING SHRINK"
"\n==============\n";
static struct TestData {
long long d_line;
bsl::size_t d_pos;
bsl::size_t d_len;
bsl::size_t d_beginShrink;
bsl::size_t d_endShrink;
char d_bad; // 'X' if the shrink is too big
bsl::size_t d_expectedPos;
bsl::size_t d_expectedLen;
} k_DATA[] = {
// pos len beg end bad pos len
// --- --- --- --- ---- --- ---
{ L_, 0, 0, 0, 0, ' ', 0, 0 },
{ L_, 0, 0, 1, 0, 'X', 0, 0 },
{ L_, 0, 0, 0, 1, 'X', 0, 0 },
{ L_, 0, 0, 1, 1, 'X', 0, 0 },
{ L_, 0, 1, 1, 0, ' ', 1, 0 },
{ L_, 0, 1, 0, 1, ' ', 0, 0 },
{ L_, 0, 2, 1, 0, ' ', 1, 1 },
{ L_, 0, 2, 0, 1, ' ', 0, 1 },
{ L_, 1, 1, 1, 0, ' ', 2, 0 },
{ L_, 1, 1, 0, 1, ' ', 1, 0 },
};
static const bsl::size_t k_NUM_TESTS = sizeof k_DATA / sizeof *k_DATA;
for (bsl::size_t i = 0; i < k_NUM_TESTS; ++i) {
const TestData& k_TEST = k_DATA[i];
const long long k_LINE = k_TEST.d_line;
const bsl::size_t k_POS = k_TEST.d_pos;
const bsl::size_t k_LEN = k_TEST.d_len;
const bsl::size_t k_BEGIN_SHRINK = k_TEST.d_beginShrink;
const bsl::size_t k_END_SHRINK = k_TEST.d_endShrink;
const char k_BAD = k_TEST.d_bad;
const bsl::size_t k_EXPECTED_POS = k_TEST.d_expectedPos;
const bsl::size_t k_EXPECTED_LEN = k_TEST.d_expectedLen;
if (veryVerbose) {
P_(k_LINE) P_(k_POS) P_(k_LEN)
P_(k_BEGIN_SHRINK) P(k_END_SHRINK)
}
if ('X' != k_BAD) {
const bdlb::IndexSpan X(k_POS, k_LEN);
const bdlb::IndexSpan R = Util::shrink(X,
k_BEGIN_SHRINK,
k_END_SHRINK);
ASSERTV(k_LINE, R.position(), k_EXPECTED_POS,
k_EXPECTED_POS == R.position());
ASSERTV(k_LINE, R.length(), k_EXPECTED_LEN,
k_EXPECTED_LEN == R.length());
}
else {
#ifdef BDE_BUILD_TARGET_EXC
bsls::AssertTestHandlerGuard g; (void)g;
const bdlb::IndexSpan X(k_POS, k_LEN);
ASSERT_FAIL(Util::shrink(X, k_BEGIN_SHRINK, k_END_SHRINK));
#endif
}
}
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST
// This case exercises (but does not fully test) basic functionality.
//
// Concerns:
//: 1 The class is sufficiently functional to enable comprehensive
//: testing in subsequent test cases.
//
// Plan:
//: 1 Call the utility functions to verify their existence and basics.
//
// Testing:
// BREATHING TEST
// --------------------------------------------------------------------
if (verbose) cout << "\nBREATHING TEST"
"\n==============\n";
const bdlb::IndexSpan span(1, 2);
ASSERT(bdlb::IndexSpan(2, 0) == Util::shrink(span, 1, 1));
} break;
default: {
cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl;
testStatus = -1;
} break;
}
if (testStatus > 0) {
cerr << "Error, non-zero test status = " << testStatus << "." << endl;
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2018 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
| 38.771186
| 79
| 0.485173
|
seanbaxter
|
878a5b9179b13aeab45163038d767f436d87e349
| 2,140
|
cpp
|
C++
|
Algorithms Design and Analysis II/knapsack.cpp
|
cbrghostrider/Coursera
|
0b509adb57f2e96e0d7b4119d50cdf2e555abafe
|
[
"MIT"
] | null | null | null |
Algorithms Design and Analysis II/knapsack.cpp
|
cbrghostrider/Coursera
|
0b509adb57f2e96e0d7b4119d50cdf2e555abafe
|
[
"MIT"
] | null | null | null |
Algorithms Design and Analysis II/knapsack.cpp
|
cbrghostrider/Coursera
|
0b509adb57f2e96e0d7b4119d50cdf2e555abafe
|
[
"MIT"
] | null | null | null |
// -------------------------------------------------------------------------------------
// Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
// For email, run on linux (perl v5.8.5):
// perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
// -------------------------------------------------------------------------------------
#include <iostream>
#include <cstdio>
#include <vector>
struct Item {
unsigned long long value;
unsigned long long weight;
Item (unsigned long long v, unsigned long long w) : value(v), weight(w) {}
};
void readProblem (std::vector<Item>& items, unsigned long long& wt)
{
unsigned int number;
std::cin >> wt >> number;
for (unsigned int i=0;i<number; i++) {
unsigned long long value=0, weight=0;
std::cin >> value >> weight;
items.push_back(Item(value, weight));
}
}
unsigned long long solveProblem (const std::vector<Item>& items, unsigned long long weight)
{
unsigned long long ** arr = new unsigned long long*[2];
arr[0] = new unsigned long long[weight];
arr[1] = new unsigned long long[weight];
for (unsigned int w=0; w<weight+1; w++) {
arr[0][w] = 0;
}
unsigned int last_iter = 0;
unsigned int this_iter = 1;
for (unsigned int i=1; i<items.size()+1; i++) {
for (unsigned int w=0; w<weight+1; w++) {
unsigned int ci = i-1;
unsigned long long opt1 = arr[last_iter][w];
unsigned long long opt2 = (w < items[ci].weight ) ? 0 : arr[last_iter][w-items[ci].weight] + items[ci].value;
arr[this_iter][w] = opt1 > opt2 ? opt1 : opt2;
}
last_iter = 1 - last_iter;
this_iter = 1 - this_iter;
}
unsigned long long ret = arr[last_iter][weight];
delete [] arr[1];
delete [] arr[0];
delete [] arr;
return ret;
}
int main()
{
std::vector<Item> items;
unsigned long long weight=0;
readProblem(items, weight);
unsigned long long answer = solveProblem(items, weight);
std::cout << "Answer = " << answer << std::endl;
}
| 30.571429
| 121
| 0.55
|
cbrghostrider
|