blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6bbb3c9ccfe46b64bb6aad499dc0e5b6460b3665 | 58b3a98e05b255f682936df9437c6eaf5ab78326 | /chapter1/main.cpp | bc800d263803f9feff18a987be8bbb07252bd819 | [] | no_license | PanupongDeve/learn-cpp | 79498e5269f5e0c2add7347525655cbcb5ea33ff | 05817e3d6891054942f6b869ec12589b8187cda3 | refs/heads/master | 2022-04-27T23:32:48.591646 | 2020-05-02T15:45:48 | 2020-05-02T15:45:48 | 258,563,161 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 309 | cpp | #include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int year = 2020, mon = 3, day = 16;
std::cout << "Today is: "
<< std::setw (2) << std::setfill ('0') << day
<< std::setw (2) << std::setfill ('0') << mon
<< "."
<< year << ".";
return 0;
}
| [
"5635512110@psu.ac.th"
] | 5635512110@psu.ac.th |
3980c00909b697acb3e9ed02e74245aa7e9727b8 | 121bc8316f81c94b1dd7c43ddc8291b0f672b2b2 | /assignment/assignment.cpp | c971a1b1b1a0f6b0564f934e05a3f534450d83fb | [] | no_license | ppatoria/cpp | e05e1bef3cd562d4bc3cbdc254ff5a879f53e8bf | 16ae7bf2854bd975aa0c24a0da8d901e9338143d | refs/heads/master | 2021-01-10T05:18:38.822420 | 2016-02-27T20:12:43 | 2016-02-27T20:12:43 | 51,691,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,975 | cpp | #include <iostream>
#include <cstring>
using namespace std;
class mystring
{
char* string;
size_t length;
int id;
public:
void setID (int id) { this->id = id; }
int getID () { return id; }
mystring (const char* string){
this->length = strlen(string) + 1;
this->string = new char[length];
strcpy (this->string, string);
}
const char* c_str (){
return string;
}
void clear(){
if(string != 0){
cout << "deleting: " << id << endl;
delete[] string;
cout << "deleted: " << id << endl;
string = 0;
}
}
void swap(const mystring& right){
this->string = right.string;
this->length = right.length;
}
/** using strcpy:
* need an additional byte to store the \0,
* so always do something like new char[strlen(somestring)+1];.
* However, there is no need to manually add the \0;
* strcpy already does this.
**/
mystring (const mystring& right){
length = right.length;
char* temp = new char [length];
strcpy (temp, right.string);
string = temp;
}
mystring& operator = (const mystring& right){
// check self assignment
if(this == &right)
return *this;
// make sure the state is not changed if exception occurs.
// in this case exception can occur while new if memory is full
char* temp = new char [strlen(right.string + 1)];
strcpy (temp,right.string);
delete[] string;
string = temp;
// mystring tmp(right);
// clear();
// swap(right);
return *this;
}
virtual ~mystring(){
cout << "~mystring()" << endl;
//if(id != 1)
clear();
}
};
// char* temp = new char [strlen(right.string + 1)];
// delete[] string;
// strcpy (temp,right.string);
// string = temp;
int main()
{
// try{
mystring str1 ("str1");
str1.setID(1);
mystring str2 ("str2");
str2.setID(2);
mystring str3 (str2);
str3.setID(3);
cout << "** before assignment **" << endl;
cout << str1.c_str () << endl;
cout << str2.c_str () << endl;
cout << str3.c_str () << endl;
mystring str = str1 = str2;
str.setID(4);
cout << "** after assignment **" << endl;
cout << str1.c_str () << endl;
cout << str2.c_str () << endl;
cout << str.c_str () << endl;
cout << "done" << endl;
// }catch(exception& ex){
// cout << "exception" << endl;
// cout << ex.what () << endl;
// }
cout << "done final" << endl;
return 1;
}
| [
"ppatoria@gmail.com"
] | ppatoria@gmail.com |
b95ebd13942e38d22767523412f712a7e8a783ff | b16d370b74422644e2cc92cb1573f2495bb6c637 | /c/acmp/acmp1369.cpp | 2c56ba237102f929854f01e20252a8c1b853528e | [] | no_license | deniskokarev/practice | 8646a3a29b9e4f9deca554d1a277308bf31be188 | 7e6742b6c24b927f461857a5509c448ab634925c | refs/heads/master | 2023-09-01T03:37:22.286458 | 2023-08-22T13:01:46 | 2023-08-22T13:01:46 | 76,293,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | cpp | /* ACMP 1369 */
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
int n;
cin >> n;
int64_t mm[n][n];
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
cin >> mm[i][j];
// floyd
for (int k=0; k<n; k++)
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
mm[i][j] = min(mm[i][j], mm[i][k]+mm[k][j]);
int64_t ans = -1;
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
ans = max(ans, mm[i][j]);
cout << ans << endl;
return 0;
}
| [
"d_kokarev@mail.ru"
] | d_kokarev@mail.ru |
dedf2250dcb6c5e9ccfb7f2fa23f251bb5c8df4c | 466b60afe24a082756c5f3620c01fb547873c435 | /Source/Interface/Surrounder.cpp | 9975d6f951b60adba28c3641aedc316625005ffa | [] | no_license | exidhor/LudumDare_37 | 9de3d4ed14321d2f13b329eed86aa2a248e91798 | 9685019f2d73a125fbec1449463c47159027ffec | refs/heads/master | 2020-06-10T06:07:19.150016 | 2017-05-10T02:29:08 | 2017-05-10T02:29:08 | 76,062,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,408 | cpp | /*!
* \file Surrounder.hpp
* \brief Surround a object with lines
* \author Aredhele
* \version 0.1
* \date 2016-01-02
*/
#include "Interface/Surrounder.hpp"
/*!
* \brief Constructor
* \return None
*/
Surrounder::Surrounder() :
m_position(sf::Vector2f(0, 0)),
m_size(sf::Vector2u(0, 0)),
m_rectShape(m_size)
{
// None
}
/*!
* \brief Destructor
* \return None
*/
Surrounder::~Surrounder() {
// None
}
/*!
* \brief Initialize the surrounder
* \param pos The position of the rectangle
* \param size The size of the rectangle
* \return None
*/
void Surrounder::init(const sf::Vector2f & pos,
const sf::Vector2u & size, const sf::Color & color) {
m_position.x = pos.x;
m_position.y = pos.y;
m_size.x = (float)size.x;
m_size.y = (float)size.y;
m_rectShape.setPosition(m_position);
m_rectShape.setSize(m_size);
m_rectShape.setFillColor(sf::Color::Transparent);
m_rectShape.setOutlineColor(color);
m_rectShape.setOutlineThickness(1);
}
/*!
* \brief Return the shape to surround an object
* \return m_rectShape The shape
*/
sf::RectangleShape * Surrounder::getShape() {
return &m_rectShape;
}
/*!
* \brief Set the position of the rectangle
* \param x The abscisse of the rectangle
* \param y The ordinate of the rectangle
* \return none
*/
void Surrounder::setPosition(float x, float y) {
m_position.x = x;
m_position.y = y;
m_rectShape.setPosition(m_position);
} | [
"vincentstehly@hotmail.fr"
] | vincentstehly@hotmail.fr |
568fdaca48b0edcd80c3cb9f3a5e1d25b8ed56a8 | bdd6458bc1dfb60fdd9b4bfd4afeec20e740794b | /Other/Operator Overloading/Polynomial/Monomial.cpp | bc727973c189b13b006c47de21c10d4a4b1c62ca | [] | no_license | NearHuscarl/C-Exercise | 876954746ab9a3fdd9c198d1188ef28829e109cc | e95bfaae8da3933d0adb895917eefd4d5bee1044 | refs/heads/master | 2021-01-17T14:05:33.070837 | 2017-05-31T13:15:30 | 2017-05-31T13:15:30 | 83,463,305 | 3 | 1 | null | 2017-03-17T13:10:33 | 2017-02-28T17:59:10 | C++ | UTF-8 | C++ | false | false | 1,364 | cpp | #include <iostream>
#include "Monomial.h"
using namespace std;
Monomial::Monomial(int c, int i):
mConst(c),
mIndex(i)
{
}
Monomial::~Monomial()
{
}
istream& operator>>(istream &x, Monomial &m)
{
cout << "Const Input: ";
x >> m.mConst;
cout << "Index Input: ";
x >> m.mIndex;
return x;
}
ostream& operator<<(ostream &x, const Monomial &m)
{
if(m.mConst < 0)
{
x << "(" << m.mConst << ")X^" << m.mIndex;
}
else
{
x << m.mConst << "X^" << m.mIndex;
}
return x;
}
int Monomial::GetConst(void)
{
return mConst;
}
int Monomial::GetIndex(void)
{
return mIndex;
}
void Monomial::SetMonomial(int co, int ix)
{
mConst = co;
mIndex = ix;
}
void Monomial::SetIndex(int ix)
{
mIndex = ix;
}
void Monomial::SetConst(int x)
{
mConst = x;
}
Monomial Monomial::operator+(const Monomial &x)
{
Monomial sum;
sum.mConst = mConst + x.mConst;
sum.mIndex = mIndex;
return sum;
}
Monomial& Monomial::operator+=(const Monomial &x)
{
*this = *this + x;
return *this;
}
Monomial Monomial::operator-(const Monomial &x)
{
Monomial diff;
diff.mConst = mConst - x.mConst;
diff.mIndex = mIndex;
return diff;
}
Monomial Monomial::operator*(const Monomial &x)
{
Monomial product;
product.mConst = mConst * x.mConst;
product.mIndex = mIndex + x.mIndex;
return product;
}
| [
"16520846@gm.uit.edu.vn"
] | 16520846@gm.uit.edu.vn |
607618a7d0fd2e8c0854e3d1f696b25d90bad062 | d305e9667f18127e4a1d4d65e5370cf60df30102 | /mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/coco_node.h | d3b4275d7f4929c6bb85b9f415ce5dfa2535b990 | [
"Apache-2.0",
"MIT",
"Libpng",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-only",
"AGPL-3.0-only",
"MPL-2.0-no-copyleft-exception",
"IJG",
"Zlib",
"MPL-1.1",
"BSD-3-Clause",
"BSD-3-Clause-Open-MPI",
"MPL-1.0",
"GPL-2.0-only",
"MPL-2.0",
"BSL-1.0",
"LicenseRef-scancode-unknow... | permissive | imyzx2017/mindspore_pcl | d8e5bd1f80458538d07ef0a8fc447b552bd87420 | f548c9dae106879d1a83377dd06b10d96427fd2d | refs/heads/master | 2023-01-13T22:28:42.064535 | 2020-11-18T11:15:41 | 2020-11-18T11:15:41 | 313,906,414 | 6 | 1 | Apache-2.0 | 2020-11-18T11:25:08 | 2020-11-18T10:57:26 | null | UTF-8 | C++ | false | false | 2,092 | h | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_IR_DATASETOPS_SOURCE_COCO_NODE_H_
#define MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_IR_DATASETOPS_SOURCE_COCO_NODE_H_
#include <memory>
#include <string>
#include <vector>
#include "minddata/dataset/engine/ir/datasetops/dataset_node.h"
namespace mindspore {
namespace dataset {
class CocoNode : public DatasetNode {
public:
/// \brief Constructor
CocoNode(const std::string &dataset_dir, const std::string &annotation_file, const std::string &task,
const bool &decode, const std::shared_ptr<SamplerObj> &sampler, std::shared_ptr<DatasetCache> cache);
/// \brief Destructor
~CocoNode() = default;
/// \brief a base class override function to create the required runtime dataset op objects for this class
/// \return shared pointer to the list of newly created DatasetOps
std::vector<std::shared_ptr<DatasetOp>> Build() override;
/// \brief Parameters validation
/// \return Status Status::OK() if all the parameters are valid
Status ValidateParams() override;
/// \brief Get the shard id of node
/// \return Status Status::OK() if get shard id successfully
Status GetShardId(int32_t *shard_id) override;
private:
std::string dataset_dir_;
std::string annotation_file_;
std::string task_;
bool decode_;
std::shared_ptr<SamplerObj> sampler_;
};
} // namespace dataset
} // namespace mindspore
#endif // MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_IR_DATASETOPS_SOURCE_COCO_NODE_H_
| [
"513344092@qq.com"
] | 513344092@qq.com |
7335eea68a371b76544075a2f41d4dee5c7499ae | d7b52e8598aac836d941186fb5d55f09ee84aa2e | /recast/DetourTileCache/DetourTileCache.cpp | cca667ff22ae9cb1b3b476232cb0ffe8e0dd2f7a | [] | no_license | Greentwip/external | 1ac9d88ff328d7b2c07aad665a22610263da61e7 | 9ab80480e53c2c826f0d859a69df2d56a1181bbd | refs/heads/master | 2022-11-15T10:53:08.060618 | 2020-07-11T21:59:42 | 2020-07-11T21:59:42 | 278,929,872 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130 | cpp | version https://git-lfs.github.com/spec/v1
oid sha256:6c4b6943cc81d60c55efb6756c80a194069736a224d3d3ffe9dc180fc1bf72cd
size 18200
| [
"vjlopezcarrillo@gmail.com"
] | vjlopezcarrillo@gmail.com |
d457e2ad7a1fda42271ab7f8efbaa17c48de0117 | 055e6e36ea9ab675d9246ee45c0d81348709f7a1 | /MeshMetaData/MeshMetaData.h | 228911103e6e6666785ccd098d4d1a7c2b2edba4 | [
"BSD-3-Clause"
] | permissive | minhpvo/MRef | f63f30f1e124180734efc34d74aee7d5883cb404 | ecd4c6cafe9c800c76e4f7853fda2ffd7771fb67 | refs/heads/master | 2022-12-27T22:45:27.390727 | 2018-02-28T17:45:04 | 2018-02-28T17:45:04 | 123,321,254 | 2 | 1 | BSD-3-Clause | 2020-10-02T19:00:41 | 2018-02-28T17:52:34 | C++ | UTF-8 | C++ | false | false | 585 | h | // Copyright ETHZ 2017
// author: mathias.rothermel@geod.baug.ethz.ch
#pragma once
#include<string>
class MeshMetaData
{
public:
MeshMetaData();
MeshMetaData( const std::string& file );
~MeshMetaData();
void readMetaData( const std::string& file );
void writeMetaData( const std::string& file);
double _offsetx;
double _offsety;
double _offsetz;
double _minx;
double _miny;
double _minz;
double _maxx;
double _maxy;
double _maxz;
// The actual gsd if derived from DSM
double _gsd;
private:
void init();
int _numelements;
};
| [
"phuocminhvo@gmail.com"
] | phuocminhvo@gmail.com |
46cb9879ef249158001d098f5d33517ad6b2c82b | 1f013e822124dfe9b4611f1fe08675a23871566e | /home/MichalDrygala/z4/pd4/include/vect.h | 0c85d3a2a155a68f693eb5a5eaefb3b3938c1020 | [] | no_license | dtraczewski/zpk2014 | a1d9a26d25ff174561e3b20c8660901178d827a5 | 548970bc5a9a02215687cb143d2f3f44307ff252 | refs/heads/master | 2021-01-21T06:06:32.044028 | 2015-09-06T12:17:07 | 2015-09-06T12:17:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,903 | h | #ifndef __VECT_H__
#define __VECT_H__
#include<iostream>
#include<math.h>
#include <assert.h>
using namespace std;
class Vect
{
int dim; // wymiar przestrzeni
double* v; // tablica wspó³rzêdnych
public:
// Konstruktor domyœlnie przyjmuje wymiar = 3
Vect(int _dim = 3)
{
assert(_dim > 0);
dim = _dim;
v = new double[_dim];
}
// Konstruktor inicjalizuj¹cy wspó³rzêdne wektora
Vect (int _dim, initializer_list<double> _v) : Vect(_dim)
{
assert(_dim > 0);
int i = 0;
for (const double & d: _v)
{
assert(i < _dim);
v[i++] = d;
}
}
// Destruktor
~Vect()
{
delete[] v;
}
// konstruktor kopiuj¹cy
Vect(const Vect &w);
// Operator podstawienia
Vect& operator=(const Vect &w);
// Metoda ustawiaj¹ca wartoœæ wspó³rzêdnej
void setCoordinate(int,double);
// Metoda pobieraj¹ca wartoœæ wspó³rzêdnej
double getCoordinate(int) const;
// Metoda zwracaj¹ca wymiar przestrzeni
int getDimension() const;
friend istream& operator>>(istream&, Vect&);
// Operatory dodawania i odejmowania od danego wektora
Vect& operator+=(const Vect& p);
Vect& operator-=(const Vect& p);
// Metoda obliczaj¹ca normê tego wektora
double norm() const;
// Metoda normalizuj¹ca wektor
void normalize();
};
// Dodawanie i odejmowanie wektorów
Vect operator+(const Vect &p1, const Vect &p2);
Vect operator-(const Vect &p1, const Vect &p2);
// Iloczyn skalarny
double operator*(const Vect &p1, const Vect &p2);
// Mno¿enie wektora przez skalar
Vect operator*(const Vect &p, double d);
Vect operator*(double d, const Vect& p);
// Wypisywanie i odczytywanie wektora ze strumieni
ostream& operator<<(ostream &, const Vect);
istream& operator>>(istream &, Vect&);
#endif
| [
"michal.drygala@gmail.com"
] | michal.drygala@gmail.com |
db78ac6ee6ead85136c7f076691f9cf456856e32 | a86298c63510f8c4b7e01c17cdd3965e7528c14c | /utility.cpp | e1f9fb2be8383b3d31842a8c5d5d5c8b1ad361b2 | [] | no_license | ciaoSora/Snake | 9edeefe7384505689244e9b52fab097e9fd53a2d | ce63ecf85118f139ecd67f5d3aa0c1265e7a58db | refs/heads/master | 2020-04-11T17:27:34.360643 | 2018-12-16T02:41:20 | 2018-12-16T02:41:20 | 161,961,678 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,203 | cpp | /*****************************************************************************
File: utility.cpp
Author: ciaoSora
Desc: Utilities for DirectX operations
*****************************************************************************/
#include "utility.h"
#include "GameObject.h"
#pragma comment(lib, "winmm.lib")
LPDIRECT3DTEXTURE9 util::LoadTexture(std::string filename, D3DCOLOR transcolor) {
LPDIRECT3DTEXTURE9 texture = NULL;
D3DXIMAGE_INFO info;
HRESULT result = D3DXGetImageInfoFromFile(filename.c_str(), &info);
if (result != D3D_OK) {
return NULL;
}
D3DXCreateTextureFromFileEx(pDevice,
filename.c_str(),
info.Width,
info.Height,
1,
D3DPOOL_DEFAULT,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
transcolor,
&info,
NULL,
&texture);
if (result != D3D_OK) {
return NULL;
}
return texture;
}
extern LPD3DXSPRITE pSprite;
extern std::ofstream fout("log.txt");
extern GameObject* gameobjects[10];
extern bool gameover;
int util::deltaTime;
void util::UpdateDeltaTime() {
static DWORD last_time = timeGetTime();
util::deltaTime = timeGetTime() - last_time;
last_time = timeGetTime();
}
void util::DrawSprite(LPDIRECT3DTEXTURE9 pTexture, D3DXVECTOR2 position, float rotation, D3DXVECTOR2 scale, D3DCOLOR color) {
if (pTexture == NULL) {
return;
}
D3DXMATRIX mat;
D3DXMatrixTransformation2D(&mat, NULL, 0, &scale, NULL, 0, &position);
pSprite->SetTransform(&mat);
pSprite->Draw(pTexture, NULL, NULL, NULL, color);
}
bool util::isKeyDown(int vk) {
return ::GetAsyncKeyState(vk) & 0x8000;
}
bool util::hasKeyDowned(int vk) {
return ::GetAsyncKeyState(vk) & 1;
}
int util::randint(int n) {
return rand() % n;
}
int util::randint(int mn, int mx) {
return rand() % (mx - mn) + mn;
}
GameObject * util::FindWithTag(const std::string tag) {
for (int i = 0; i < sizeof gameobjects / sizeof(GameObject*); ++i) {
if (gameobjects[i]) {
if (gameobjects[i]->GetTag() == tag) {
return gameobjects[i];
}
}
}
return NULL;
}
void util::GameOver(const std::string prompt) {
gameover = true;
::MessageBox(0, prompt.c_str(), "Game Over", 0);
}
| [
"657913055@qq.com"
] | 657913055@qq.com |
29bcd2146277c464ee62e3029bbd6890c06604c4 | a0539c3818c833dcadb1ee21db6516211beab357 | /Exercises/ex5/src/person.cc | 6bac5c49e6671b0d7882576ecd03474145e98076 | [] | no_license | myllern/EDAF50-1 | dce265702d0656d00486455c2a2b4af5a5b794ae | d6a12a38a2d7a1967dc67ef2fc40e6ebba9ab58a | refs/heads/master | 2022-02-21T07:01:43.922486 | 2019-01-31T17:35:43 | 2019-01-31T17:35:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | cc | #include "person.h"
#include <iostream>
#include <string>
std::ostream& operator<<(std::ostream& os, const Person& p) {
return os << p.get_name() << " " << p.get_phone();
}
bool operator<(const Person& p1, const Person& p2) {
std::string name1 = p1.get_name();
std::string name2 = p2.get_name();
std::string phone1 = p1.get_phone();
std::string phone2 = p2.get_phone();
if(name1 == name2) {
std::cout << "hej" << std::endl;
return phone1 < phone2;
} else {
return name1 < name2;
}
return false;
}
| [
"hanna.lindwall93@gmail.com"
] | hanna.lindwall93@gmail.com |
8db84b136b37ee473eafa4ca104b37c0667b2333 | f2e38023f424ea53e270fd93e41e5ec1c8cdb2cf | /src/gpu/effects/GrMatrixEffect.h | 69fd1be37e10911cb63bec3b97965b50a8ebd805 | [
"BSD-3-Clause"
] | permissive | skui-org/skia | 3dc425dba0142390b13dcd91d2a877c604436e1c | 1698b32e63ddc8a06343e1a2f03c2916a08f519e | refs/heads/m85 | 2021-01-22T21:02:53.355312 | 2020-08-16T10:53:34 | 2020-08-16T13:53:35 | 85,350,036 | 23 | 11 | BSD-3-Clause | 2020-09-03T09:23:38 | 2017-03-17T19:59:37 | C++ | UTF-8 | C++ | false | false | 1,778 | h | /*
* Copyright 2020 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef GrMatrixEffect_DEFINED
#define GrMatrixEffect_DEFINED
#include "include/core/SkM44.h"
#include "include/core/SkTypes.h"
#include "src/gpu/GrCoordTransform.h"
#include "src/gpu/GrFragmentProcessor.h"
class GrMatrixEffect : public GrFragmentProcessor {
public:
static std::unique_ptr<GrFragmentProcessor> Make(
const SkMatrix& matrix, std::unique_ptr<GrFragmentProcessor> child) {
if (matrix.isIdentity()) {
return child;
}
SkASSERT(!child->isSampledWithExplicitCoords());
SkASSERT(child->sampleMatrix().fKind == SkSL::SampleMatrix::Kind::kNone);
return std::unique_ptr<GrFragmentProcessor>(
new GrMatrixEffect(matrix, std::move(child)));
}
std::unique_ptr<GrFragmentProcessor> clone() const override;
const char* name() const override { return "MatrixEffect"; }
const SkMatrix& matrix() const { return fMatrix; }
private:
GrMatrixEffect(const GrMatrixEffect& src);
GrMatrixEffect(SkMatrix matrix, std::unique_ptr<GrFragmentProcessor> child)
: INHERITED(kGrMatrixEffect_ClassID, kNone_OptimizationFlags)
, fMatrix(matrix) {
SkASSERT(child);
this->registerChild(std::move(child), SkSL::SampleMatrix::MakeConstUniform("matrix"));
}
GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;
void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override;
bool onIsEqual(const GrFragmentProcessor&) const override;
SkMatrix fMatrix;
GR_DECLARE_FRAGMENT_PROCESSOR_TEST
typedef GrFragmentProcessor INHERITED;
};
#endif
| [
"skia-commit-bot@chromium.org"
] | skia-commit-bot@chromium.org |
3422f1632750935c444b94005133f923a1013637 | 95c97b93ca08045bbea7978f9dd192d796098778 | /10018.cpp | aff521906ec196540cfbad940b501b5c4007debb | [] | no_license | tanvir-rahman-ewu/UVA-Solutions | 0d133bf276fd45fe57b88fa6f75e55ac5a6dc275 | 7c8bd8671e230790e5e757bafd1b201f115ede8c | refs/heads/master | 2020-12-23T15:11:13.808029 | 2020-08-22T06:54:42 | 2020-08-22T06:54:42 | 237,186,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
long long int a,c,t,inverse,r;
int test_case;
scanf("%d",&test_case);
while(test_case--)
{
c=0;
scanf("%lld",&a);
t=a;
while(1)
{
inverse=0;
while(a>0)
{
r=a%10;
inverse=inverse*10 + r;
a=a/10;
}
if(a==inverse)
{
break;
}
else{
t=a+inverse;
a=a+inverse;
c++;
}
}
printf("%lld %lld\n",c,a);
}
return 0;
}
| [
"tanvir.rahman.ewu@gmail.com"
] | tanvir.rahman.ewu@gmail.com |
f0cfead4cdca1eace0c52c5e70bb227c1ad650ee | d6b4bdf418ae6ab89b721a79f198de812311c783 | /teo/include/tencentcloud/teo/v20220106/model/CreateApplicationProxyResponse.h | 5fe164214efb24d2866697a1d835b4fc25cba003 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp-intl-en | d0781d461e84eb81775c2145bacae13084561c15 | d403a6b1cf3456322bbdfb462b63e77b1e71f3dc | refs/heads/master | 2023-08-21T12:29:54.125071 | 2023-08-21T01:12:39 | 2023-08-21T01:12:39 | 277,769,407 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,338 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_TEO_V20220106_MODEL_CREATEAPPLICATIONPROXYRESPONSE_H_
#define TENCENTCLOUD_TEO_V20220106_MODEL_CREATEAPPLICATIONPROXYRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Teo
{
namespace V20220106
{
namespace Model
{
/**
* CreateApplicationProxy response structure.
*/
class CreateApplicationProxyResponse : public AbstractModel
{
public:
CreateApplicationProxyResponse();
~CreateApplicationProxyResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
/**
* 获取Layer-4 application proxy ID
* @return ProxyId Layer-4 application proxy ID
*
*/
std::string GetProxyId() const;
/**
* 判断参数 ProxyId 是否已赋值
* @return ProxyId 是否已赋值
*
*/
bool ProxyIdHasBeenSet() const;
private:
/**
* Layer-4 application proxy ID
*/
std::string m_proxyId;
bool m_proxyIdHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_TEO_V20220106_MODEL_CREATEAPPLICATIONPROXYRESPONSE_H_
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
1d566edbba606ae877d1c43c41aa825f36400328 | b41dddb6722fffce17f09537797a2cd37a97c8ec | /LeetCode/medium/Copy_List_with_Random_Pointer.cxx | 50f03b141138bd126fb3e4b47bb265af2d02b3ad | [] | no_license | zinsmatt/Programming | 29a6141eba8d9f341edcad2f4c41b255d290b06a | 96978c6496d90431e75467026b59cd769c9eb493 | refs/heads/master | 2023-07-06T11:18:08.597210 | 2023-06-25T10:40:18 | 2023-06-25T10:40:18 | 188,894,324 | 0 | 0 | null | 2021-03-06T22:53:57 | 2019-05-27T18:51:32 | C++ | UTF-8 | C++ | false | false | 842 | cxx | /*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
Node* nouv_head = new Node(0);
Node* p = head;
Node* prev = nouv_head;
unordered_map<Node*, Node*> m;
while (p)
{
Node* n = new Node(p->val);
prev->next = n;
n->random = p->random;
m[p] = n;
prev = n;
p = p->next;
}
p = nouv_head->next;
while (p)
{
p->random = m[p->random];
p = p->next;
}
auto* res = nouv_head->next;
delete nouv_head;
return res;
}
};
| [
"zins.matthieu@gmail.com"
] | zins.matthieu@gmail.com |
84fa2971f3b75574e4fda4021395c64bba905de0 | d3d1429da6d94ec4b3c003db06607bc9daa35804 | /vendor/github.com/cockroachdb/c-rocksdb/internal/util/thread_status_util.h | 455c9f14fb4da0faed2335adcef1b919d58f5f6c | [
"BSD-3-Clause",
"ISC"
] | permissive | zipper-project/zipper | f61a12b60445dfadf5fd73d289ff636ce958ae23 | c9d2d861e1b920ed145425e63d019d6870bbe808 | refs/heads/master | 2021-05-09T14:48:04.286860 | 2018-05-25T05:52:46 | 2018-05-25T05:52:46 | 119,074,801 | 97 | 75 | ISC | 2018-03-01T10:18:22 | 2018-01-26T16:23:40 | Go | UTF-8 | C++ | false | false | 5,227 | h | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#pragma once
#include <string>
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/thread_status.h"
#include "util/thread_status_updater.h"
namespace rocksdb {
class ColumnFamilyData;
// The static utility class for updating thread-local status.
//
// The thread-local status is updated via the thread-local cached
// pointer thread_updater_local_cache_. During each function call,
// when ThreadStatusUtil finds thread_updater_local_cache_ is
// left uninitialized (determined by thread_updater_initialized_),
// it will tries to initialize it using the return value of
// Env::GetThreadStatusUpdater(). When thread_updater_local_cache_
// is initialized by a non-null pointer, each function call will
// then update the status of the current thread. Otherwise,
// all function calls to ThreadStatusUtil will be no-op.
class ThreadStatusUtil {
public:
// Register the current thread for tracking.
static void RegisterThread(
const Env* env, ThreadStatus::ThreadType thread_type);
// Unregister the current thread.
static void UnregisterThread();
// Create an entry in the global ColumnFamilyInfo table for the
// specified column family. This function should be called only
// when the current thread does not hold db_mutex.
static void NewColumnFamilyInfo(const DB* db, const ColumnFamilyData* cfd,
const std::string& cf_name, const Env* env);
// Erase the ConstantColumnFamilyInfo that is associated with the
// specified ColumnFamilyData. This function should be called only
// when the current thread does not hold db_mutex.
static void EraseColumnFamilyInfo(const ColumnFamilyData* cfd);
// Erase all ConstantColumnFamilyInfo that is associated with the
// specified db instance. This function should be called only when
// the current thread does not hold db_mutex.
static void EraseDatabaseInfo(const DB* db);
// Update the thread status to indicate the current thread is doing
// something related to the specified column family.
static void SetColumnFamily(const ColumnFamilyData* cfd, const Env* env,
bool enable_thread_tracking);
static void SetThreadOperation(ThreadStatus::OperationType type);
static ThreadStatus::OperationStage SetThreadOperationStage(
ThreadStatus::OperationStage stage);
static void SetThreadOperationProperty(
int code, uint64_t value);
static void IncreaseThreadOperationProperty(
int code, uint64_t delta);
static void SetThreadState(ThreadStatus::StateType type);
static void ResetThreadStatus();
#ifndef NDEBUG
static void TEST_SetStateDelay(
const ThreadStatus::StateType state, int micro);
static void TEST_StateDelay(const ThreadStatus::StateType state);
#endif
protected:
// Initialize the thread-local ThreadStatusUpdater when it finds
// the cached value is nullptr. Returns true if it has cached
// a non-null pointer.
static bool MaybeInitThreadLocalUpdater(const Env* env);
#ifdef ROCKSDB_USING_THREAD_STATUS
// A boolean flag indicating whether thread_updater_local_cache_
// is initialized. It is set to true when an Env uses any
// ThreadStatusUtil functions using the current thread other
// than UnregisterThread(). It will be set to false when
// UnregisterThread() is called.
//
// When this variable is set to true, thread_updater_local_cache_
// will not be updated until this variable is again set to false
// in UnregisterThread().
static __thread bool thread_updater_initialized_;
// The thread-local cached ThreadStatusUpdater that caches the
// thread_status_updater_ of the first Env that uses any ThreadStatusUtil
// function other than UnregisterThread(). This variable will
// be cleared when UnregisterThread() is called.
//
// When this variable is set to a non-null pointer, then the status
// of the current thread will be updated when a function of
// ThreadStatusUtil is called. Otherwise, all functions of
// ThreadStatusUtil will be no-op.
//
// When thread_updater_initialized_ is set to true, this variable
// will not be updated until this thread_updater_initialized_ is
// again set to false in UnregisterThread().
static __thread ThreadStatusUpdater* thread_updater_local_cache_;
#else
static bool thread_updater_initialized_;
static ThreadStatusUpdater* thread_updater_local_cache_;
#endif
};
// A helper class for updating thread state. It will set the
// thread state according to the input parameter in its constructor
// and set the thread state to the previous state in its destructor.
class AutoThreadOperationStageUpdater {
public:
explicit AutoThreadOperationStageUpdater(
ThreadStatus::OperationStage stage);
~AutoThreadOperationStageUpdater();
#ifdef ROCKSDB_USING_THREAD_STATUS
private:
ThreadStatus::OperationStage prev_stage_;
#endif
};
} // namespace rocksdb
| [
"2539373634@qq.com"
] | 2539373634@qq.com |
89ceaedab5ffb858607bd1a29bbd1431cb9ba0b5 | e69054ef4973adb1dcffb437d171d14e46d547a1 | /scu/비쥬얼C++/과제/AddressBook/AddressBook/AddressBook.h | 2aa0b01913af9eb0eaa97a2379a0bc4996797e3a | [] | no_license | cruel32/study | 087b39337a11fd98bc6dacfa0562874df24099f8 | 8d747514a8e4b44c999b93b2ca330b27ddcd72d9 | refs/heads/master | 2020-05-22T03:57:51.930818 | 2018-03-17T04:35:30 | 2018-03-17T04:35:30 | 73,540,556 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 592 | h |
// AddressBook.h : PROJECT_NAME 응용 프로그램에 대한 주 헤더 파일입니다.
//
#pragma once
#ifndef __AFXWIN_H__
#error "PCH에 대해 이 파일을 포함하기 전에 'stdafx.h'를 포함합니다."
#endif
#include "resource.h" // 주 기호입니다.
// CAddressBookApp:
// 이 클래스의 구현에 대해서는 AddressBook.cpp을 참조하십시오.
//
class CAddressBookApp : public CWinApp
{
public:
CAddressBookApp();
// 재정의입니다.
public:
virtual BOOL InitInstance();
// 구현입니다.
DECLARE_MESSAGE_MAP()
};
extern CAddressBookApp theApp; | [
"cshee8508@gmail.com"
] | cshee8508@gmail.com |
d346a60d60800f223e850694a5be291c64cd6ac7 | b25958e30fdcfe8fd9c19dc260cdb0491d344bb2 | /rgbpanel/fixedpoint.h | ca6396f4517fdb52c3ee49538fb29f5069570401 | [] | no_license | corum/ZPUinoSketches | fd047503f65ba6f71dd403bd5184433c19d49d38 | a948702a2eed521709a12282dd53cdf1bdca0d00 | refs/heads/master | 2023-03-16T00:41:39.415517 | 2014-09-04T07:54:13 | 2014-09-04T07:54:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,405 | h | #ifndef __FIXEDPOINT_H__
#define __FIXEDPOINT_H__
#include <Arduino.h>
char *sprintint(char *dest, int max, unsigned v);
extern "C" void printhex(unsigned int c);
template<typename t_signed, typename t_unsigned, unsigned int bits>
struct fpval {
static const unsigned int nbits = bits;
typedef t_unsigned size_type;
typedef t_signed ssize_type;
// Helpers
static const unsigned int storage_bits = 8 * sizeof(size_type);
static const ssize_type low_mask = (1<<bits)-1;
// The value
ssize_type v;
inline struct fpval<t_signed,t_unsigned,bits> &operator=(unsigned int c) {
v=(c<<bits);
return *this;
}
fpval<t_signed,t_unsigned,bits> inverse() const {
/*
fpval<t_signed,t_unsigned,bits> r;
printf("Inverse %08x\n", v);
r.v = (1<< (storage_bits-1))/(v*(1<<bits)) << 1;
printf("equals %08x\n", r.v);
return r;*/
fpval<t_signed,t_unsigned,bits> r(1.0);
r/=v;
return r;
}
fpval(unsigned int c) {
v=(c<<bits);
}
fpval(unsigned int c, int raw): v(c) {
}
fpval(int c) {
v=(c<<bits);
}
template< typename T >
inline void setFromRangedValue( T value, T max ) {
}
struct fpval<t_signed,t_unsigned,bits> &operator*=(const struct fpval<t_signed,t_unsigned,bits> &o);
inline struct fpval<t_signed,t_unsigned,bits> &operator+=(const struct fpval<t_signed,t_unsigned,bits> &o) {
v+=o.v;
return *this;
}
inline struct fpval<t_signed,t_unsigned,bits> operator+(const struct fpval<t_signed,t_unsigned,bits> &o) {
fpval<t_signed,t_unsigned,bits> r = *this;
r+=o;
return r;
}
inline struct fpval<t_signed,t_unsigned,bits> &operator-=(const struct fpval<t_signed,t_unsigned,bits> &o) {
v-=o.v;
return *this;
}
inline struct fpval<t_signed,t_unsigned,bits> operator-(const struct fpval<t_signed,t_unsigned,bits> &o) {
fpval<t_signed,t_unsigned,bits> r = *this;
r-=o;
return r;
}
inline struct fpval<t_signed,t_unsigned,bits> operator*(const struct fpval<t_signed,t_unsigned,bits> &o)const {
fpval<t_signed,t_unsigned,bits> ret = *this;
ret*=o;
return ret;
/*
ssize_type hi[2] = { (o2.v >> bits), (o1.v >> bits) };
ssize_type lo[2] = { (o2.v & low_mask), (o1.v & low_mask) };
ssize_type r_hi = hi[0] * hi[1];
ssize_type r_md = (hi[0] * lo[1]) + (hi[1] * lo[0]);
size_type r_lo = lo[0] * lo[1];
r_lo += low_mask;
r_md += (r_hi & low_mask) << (storage_bits-bits);
r_md += (r_lo >> bits);
ret = r_md;
return ret;*/
}
/* template<unsigned b>
struct fpval<int,unsigned int,b> operator/=(const fpval<int,unsigned int,b> &o)
{
int64_t tempResult = v;
tempResult <<= b;
tempResult += (o.v >> 1);
tempResult /= o.v;
v = tempResult;
return *this;
}
template<unsigned bt>
struct fpval<int,unsigned int,bt> operator/=(double b)
{
const fpval<int,unsigned int,bt> nb(b);
int64_t tempResult = v;
tempResult <<= b;
tempResult += (nb.v >> 1);
tempResult /= nb.v;
v = tempResult;
return *this;
}*/
struct fpval<t_signed,t_unsigned,bits> operator/(const fpval<t_signed,t_unsigned,bits> &o) const {
fpval<t_signed,t_unsigned,bits> other = *this;
other/=o;
return other;
}
struct fpval<t_signed,t_unsigned,bits> &operator/=(const fpval<t_signed,t_unsigned,bits> &o) {
size_type other = o.v;
int neg = ((v < 0) != (other < 0));
v = (v < 0 ? -v : v);
other = (other < 0 ? -other : other);
while(((v | other) & 1) == 0) {
v >>= 1;
other >>= 1;
}
uint32_t r_hi = (v / other);
uint32_t n_lo = (v % other);
uint32_t n_hi = (n_lo >> 16);
n_lo <<= 16;
uint32_t n_lo_orig = n_lo;
uint32_t i, arg;
for(i = 1, arg = other; ((n_lo | arg) & 1) == 0; i <<= 1) {
n_lo = ((n_lo >> 1) | (n_hi << 31));
n_hi = (n_hi >> 1);
arg >>= 1;
}
n_lo = n_lo_orig;
uint32_t res = 0;
if(n_hi) {
uint32_t arg_lo, arg_hi;
for(arg_lo = other; (arg_lo >> 31) == 0; arg_lo <<= 1, i <<= 1);
for(arg_hi = (arg_lo >> 31), arg_lo <<= 1, i <<= 1; arg_hi < n_hi; arg_hi = (arg_hi << 1) | (arg_lo >> 31), arg_lo <<= 1, i <<= 1);
do {
arg_lo = (arg_lo >> 1) | (arg_hi << 31);
arg_hi = (arg_hi >> 1);
i >>= 1;
if(arg_hi < n_hi) {
n_hi -= arg_hi;
if(arg_lo > n_lo)
n_hi--;
n_lo -= arg_lo;
res += i;
} else if((arg_hi == n_hi) && (arg_lo <= n_lo)) {
n_hi -= arg_hi;
n_lo -= arg_lo;
res += i;
}
} while(n_hi);
}
res += (n_lo / other);
if((n_lo % other) >= (other >> 1))
res++;
res += (r_hi << 16);
v = neg ? -res : res;
return *this;
}
void setFromBitRange(unsigned value, unsigned nb)
{
if (value > (unsigned)((1<<(nb-1))-1))
value++;
if (bits>nb) {
value<<=(bits-nb);
} else {
value>>=(nb-bits);
}
v=(ssize_type)value;
}
// struct fpval<t_signed,t_unsigned,bits> &operator/=(const struct fpval<t_signed,t_unsigned,bits> &o);
inline struct fpval<t_signed,t_unsigned,bits> &operator=(const double c) {
v = (size_type)(c*(double)(1<<bits)+0.5);
return *this;
}
inline double asDouble() const {
return (double)v/(double)(1<<bits);
}
inline bool isNegative() const {
return v<0;
}
template<typename T>
fpval(const T &);
fpval(double c) {
v = (size_type)(c*(1<<bits));
}
fpval() {
}
ssize_type asInt() const {
return (v>>bits);
}
inline ssize_type asNative() const {
return v;
}
void sprint(char *dest, int sizemax, int decimal);
void sqrt() {
#if 0
size_type root, remHi, remLo, testDiv, count;
root = 0; /* Clear root */
remHi = 0; /* Clear high part of partial remainder */
remLo = v; /* Get argument into low part of partial remainder */
count = 20; /* Load loop counter */
do {
remHi = (remHi<<16) | (remLo>>16); remLo <<= 16; /* get 2 bits of arg */
root <<= 1; /* Get ready for the next bit in the root */
testDiv = (root << 1) + 1; /* Test radical */
if (remHi >= testDiv) {
remHi -= testDiv;
root++;
}
} while (count-- != 0);
v=root;
#endif
#define value v
#define step(shift) \
if((0x40000000l >> shift) + root <= value) \
{ \
value -= (0x40000000l >> shift) + root; \
root = (root >> 1) | (0x40000000l >> shift); \
} \
else \
{ \
root = root >> 1; \
}
int root = 0;
int shift;
for (shift=0;shift<32;shift+=2) {
//printhex(0x40000000>>shift);
//Serial.print(" ");
//printhex(root);
//Serial.print(" ");
//printhex(value);
//Serial.println("");
if((0x40000000l >> shift) + root <= value)
{
value -= (0x40000000l >> shift) + root;
root = (root >> 1) | (0x40000000l >> shift);
}
else
{
root = root >> 1;
}
}
// round to the nearest integer, cuts max error in half
if(root < value)
{
++root;
}
root <<=8;
v=root;
}
};
static inline __attribute__((always_inline)) int __chars_needed(unsigned int bits)
{
/*
switch(bits) {
case 0: return 0; // 0
case 1: return 1; // 1
case 2: return 1; // 2
case 3: return 1; // 4
case 4: return 1; // 8
case 5: return 2; // 16
}
*/
return 10;
}
template<typename t_signed, typename t_unsigned, unsigned int bits>
void fpval<t_signed,t_unsigned,bits>::sprint(char *dest, int sizemax, int decimal) {
char tmp[ __chars_needed(bits) + 1];
fpval<t_signed,t_unsigned,bits> radd = 0.5;
int i;
/*
if (isNegative())
radd *= -1.0;
*/
for (i = 0; i < decimal; i++)
radd/= fpval<t_signed,t_unsigned,bits>(10.0);
// Round
radd+=(*this);
if (isNegative()) {
*dest++='-';
radd *= -1.0;
}
// Integer part
size_type intpart = radd.v>>bits;
//printf("INT part: %u\n",intpart);
char *start = sprintint( tmp, __chars_needed(bits),intpart);
/* copy */
while (*start) {
*dest++=*start++;
}
*dest++='.';
int mval=1;
for (i=1;i<=decimal;i++) {
size_type low = radd.v & ((1<<bits)-1);
mval*=10;
low *= mval;
low>>=bits;
low %= 10;
*dest++=('0'+low);
}
*dest='\0';
}
typedef fpval<int, unsigned int, 16> fp32_16_16;
extern "C" unsigned fmul16(unsigned,unsigned);
extern "C" unsigned fsqrt16(unsigned);
template<>
inline struct fpval<int,unsigned,16> & fpval<int,unsigned,16>::operator*=(const fp32_16_16 &o)
{
v=fmul16(v,o.v);
return *this;
}
#endif
| [
"alvieboy@alvie.com"
] | alvieboy@alvie.com |
4430b9b1f5309e60b5576d18c9eb1d44de0c568f | 5e0f2e0a55b26b55ebbe39c3a8a39304b722e013 | /Sources/GLCPP/VertexArray/Kit.h | ad8a5822eb8e8a47b526d675bd2d8058c52d28f1 | [] | no_license | mutexre/Base | 77eb4d78c54abfaaa2998bd2696f42b2ac905176 | 40cf06212dcf1bed7da4af631f6063c2cc34d404 | refs/heads/master | 2021-01-23T06:25:42.969054 | 2014-05-12T19:35:22 | 2014-05-12T19:35:22 | 23,832,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,143 | h | #ifndef header_5D060615232E
#define header_5D060615232E
namespace GL
{
class VertexArrayKit : public Renderer
{
public:
class Options
{
public:
typedef std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>> BindingPoints;
public:
bool enabled;
unsigned int offset, count;
GLenum type;
GLint baseVertex;
GLsizei numberOfInstances;
std::shared_ptr<ShaderProgram> program;
std::shared_ptr<VertexArray> array;
std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>> bindingPoints;
protected:
void init(bool enabled, unsigned int offset = 0, unsigned int count = 0, GLenum type = GL_UNSIGNED_INT,
GLint baseVertex = 0, GLsizei numberOfInstances = 0,
Rt::Option<std::shared_ptr<ShaderProgram>> = Rt::Option<std::shared_ptr<ShaderProgram>>(),
Rt::Option<std::shared_ptr<VertexArray>> = Rt::Option<std::shared_ptr<VertexArray>>(),
Rt::Option<std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>>> = Rt::Option<std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>>>());
public:
Options() {}
Options(bool enabled, unsigned int offset = 0, unsigned int count = 0, GLenum type = GL_UNSIGNED_INT,
GLint baseVertex = 0, GLsizei numberOfInstances = 0,
Rt::Option<std::shared_ptr<ShaderProgram>> = Rt::Option<std::shared_ptr<ShaderProgram>>(),
Rt::Option<std::shared_ptr<VertexArray>> = Rt::Option<std::shared_ptr<VertexArray>>(),
Rt::Option<std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>>> = Rt::Option<std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>>>());
Options(bool enabled, unsigned int offset, unsigned int count, GLenum type,
GLint baseVertex, GLsizei numberOfInstances,
std::shared_ptr<ShaderProgram> program,
Rt::Option<std::shared_ptr<VertexArray>> array = Rt::Option<std::shared_ptr<VertexArray>>(),
Rt::Option<std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>>> = Rt::Option<std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>>>());
Options(bool enabled, unsigned int offset, unsigned int count, GLenum type,
GLint baseVertex, GLsizei numberOfInstances,
std::shared_ptr<ShaderProgram>,
std::shared_ptr<VertexArray>,
Rt::Option<std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>>> = Rt::Option<std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>>>());
Options(bool enabled, unsigned int offset, unsigned int count, GLenum type,
GLint baseVertex, GLsizei numberOfInstances,
std::shared_ptr<ShaderProgram>,
std::shared_ptr<VertexArray>,
std::set<std::shared_ptr<GL::UniformBlock::BindingPoint>>);
virtual ~Options() {}
virtual void bind();
};
public:
Options points, lines, triangles;
public:
VertexArrayKit();
VertexArrayKit(Options points,
Options lines,
Options triangles);
virtual ~VertexArrayKit() {}
virtual void render() override;
virtual Options getPointsOptions() const;
virtual void setPointsOptions(Options options);
virtual void setPointsShaderProgram(std::shared_ptr<ShaderProgram> program);
virtual Options getLinesOptions() const;
virtual void setLinesOptions(Options options);
virtual void setLinesShaderProgram(std::shared_ptr<ShaderProgram> program);
virtual Options getTrianglesOptions() const;
virtual void setTrianglesOptions(Options options);
virtual void setTrianglesShaderProgram(std::shared_ptr<ShaderProgram> program);
virtual void setEnabled(bool points, bool lines, bool triangles);
};
}
#endif
| [
"alexander.obuschenko@gmail.com"
] | alexander.obuschenko@gmail.com |
2c8cedf338fed0a654b04b80093e9048b2614e4e | 8fb4e03e7c5a60ce2ed61aa06770736d808a4990 | /src/opencl_sort_by_key.h | d60cc2d00ce5b108c628ae1236dbf61eaa6879ff | [] | no_license | kingofthebongo2008/dare12_opencl | ec0ab54e1a382b95146b279f690cca85af895436 | 0482dc35cf26cf5d47ed8480233950ee0bf23fbc | refs/heads/master | 2016-09-06T14:22:03.467594 | 2015-08-23T15:46:03 | 2015-08-23T15:46:03 | 39,424,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 401 | h | #pragma once
#include "opencl/opencl_radix_sort_histogram.h"
#include "opencl/opencl_radix_sort_permute.h"
#include "opencl/opencl_radix_sort_block_addition.h"
#include "opencl/opencl_radix_sort_prefix_sum.h"
#include "opencl/opencl_radix_sort_fix_offset.h"
#include "opencl/opencl_radix_sort_scan_arrays_dim1.h"
#include "opencl/opencl_radix_sort_scan_arrays_dim2.h"
namespace freeform
{
}
| [
"stefan.dyulgerov@gmail.com"
] | stefan.dyulgerov@gmail.com |
1fa1886e54fbab9df01b1dc51c703af515a42be9 | 57608dab2ae381735997dee7a26e135ca31e6e25 | /tests/utils_test.cpp | f738128affb3a024b53c56b92eb3a0a073f7709b | [
"Apache-2.0"
] | permissive | dariadb/dariadb | 05b8b9ce07d9e89f4fbc8306ad4eee1aca813ba5 | 1edf637122752ba21c582675e2a9183fff91fa50 | refs/heads/master | 2021-04-28T22:26:06.933618 | 2017-01-24T04:44:39 | 2017-01-24T04:44:39 | 77,751,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,416 | cpp | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <libdariadb/timeutil.h>
#include <libdariadb/utils/async/thread_manager.h>
#include <libdariadb/utils/async/thread_pool.h>
#include <libdariadb/utils/crc.h>
#include <libdariadb/utils/cz.h>
#include <libdariadb/utils/fs.h>
#include <libdariadb/utils/in_interval.h>
#include <libdariadb/utils/strings.h>
#include <libdariadb/utils/utils.h>
#include <boost/test/unit_test.hpp>
#include <chrono>
#include <ctime>
#include <ctime>
#include <iostream>
#include <thread>
BOOST_AUTO_TEST_CASE(TimeToString) {
auto ct = dariadb::timeutil::current_time();
BOOST_CHECK(ct != dariadb::Time(0));
auto ct_str = dariadb::timeutil::to_string(ct);
BOOST_CHECK(ct_str.size() != 0);
}
BOOST_AUTO_TEST_CASE(TimeRound) {
auto ct = dariadb::timeutil::current_time();
{
auto rounded = dariadb::timeutil::round_to_seconds(ct);
auto rounded_d = dariadb::timeutil::to_datetime(rounded);
BOOST_CHECK_EQUAL(rounded_d.millisecond, uint16_t(0));
}
{
auto rounded = dariadb::timeutil::round_to_minutes(ct);
auto rounded_d = dariadb::timeutil::to_datetime(rounded);
BOOST_CHECK_EQUAL(rounded_d.millisecond, uint16_t(0));
BOOST_CHECK_EQUAL(rounded_d.second, uint16_t(0));
}
{
auto rounded = dariadb::timeutil::round_to_hours(ct);
auto rounded_d = dariadb::timeutil::to_datetime(rounded);
BOOST_CHECK_EQUAL(rounded_d.millisecond, uint16_t(0));
BOOST_CHECK_EQUAL(rounded_d.second, uint16_t(0));
BOOST_CHECK_EQUAL(rounded_d.minute, uint16_t(0));
}
}
BOOST_AUTO_TEST_CASE(CRC32Test) {
uint64_t data;
char *pdata = (char *)&data;
data = 1;
auto res1 = dariadb::utils::crc32(pdata, sizeof(data));
auto res2 = dariadb::utils::crc32(pdata, sizeof(data));
data++;
auto res3 = dariadb::utils::crc32(pdata, sizeof(data));
BOOST_CHECK_EQUAL(res1, res2);
BOOST_CHECK(res1 != res3);
}
BOOST_AUTO_TEST_CASE(CRC16Test) {
uint64_t data;
char *pdata = (char *)&data;
data = 1;
auto res1 = dariadb::utils::crc16(pdata, sizeof(data));
auto res2 = dariadb::utils::crc16(pdata, sizeof(data));
data++;
auto res3 = dariadb::utils::crc16(pdata, sizeof(data));
BOOST_CHECK_EQUAL(res1, res2);
BOOST_CHECK(res1 != res3);
}
BOOST_AUTO_TEST_CASE(CountZero) {
BOOST_CHECK_EQUAL(dariadb::utils::clz(67553994410557440), 8);
BOOST_CHECK_EQUAL(dariadb::utils::clz(3458764513820540928), 2);
BOOST_CHECK_EQUAL(dariadb::utils::clz(15), 60);
BOOST_CHECK_EQUAL(dariadb::utils::ctz(240), 4);
BOOST_CHECK_EQUAL(dariadb::utils::ctz(3840), 8);
}
BOOST_AUTO_TEST_CASE(InInterval) {
BOOST_CHECK(dariadb::utils::inInterval(1, 5, 1));
BOOST_CHECK(dariadb::utils::inInterval(1, 5, 2));
BOOST_CHECK(dariadb::utils::inInterval(1, 5, 5));
BOOST_CHECK(!dariadb::utils::inInterval(1, 5, 0));
BOOST_CHECK(!dariadb::utils::inInterval(0, 1, 2));
}
BOOST_AUTO_TEST_CASE(BitOperations) {
uint8_t value = 0;
for (int8_t i = 0; i < 7; i++) {
value = dariadb::utils::BitOperations::set(value, i);
BOOST_CHECK_EQUAL(dariadb::utils::BitOperations::check(value, i), true);
}
for (int8_t i = 0; i < 7; i++) {
value = dariadb::utils::BitOperations::clr(value, i);
}
for (int8_t i = 0; i < 7; i++) {
BOOST_CHECK_EQUAL(dariadb::utils::BitOperations::check(value, i), false);
}
}
BOOST_AUTO_TEST_CASE(FileUtils) {
std::string filename = "foo/bar/test.txt";
BOOST_CHECK_EQUAL(dariadb::utils::fs::filename(filename), "test");
BOOST_CHECK_EQUAL(dariadb::utils::fs::parent_path(filename), "foo/bar");
BOOST_CHECK_EQUAL(dariadb::utils::fs::extract_filename(filename), "test.txt");
auto ls_res = dariadb::utils::fs::ls(".");
BOOST_CHECK(ls_res.size() > 0);
std::string parent_p = "path1";
std::string child_p = "path2";
auto concat_p = dariadb::utils::fs::append_path(parent_p, child_p);
BOOST_CHECK_EQUAL(dariadb::utils::fs::parent_path(concat_p), parent_p);
}
BOOST_AUTO_TEST_CASE(ThreadsPool) {
using namespace dariadb::utils::async;
const ThreadKind tk = 1;
{
const size_t threads_count = 2;
ThreadPool tp(ThreadPool::Params(threads_count, tk));
BOOST_CHECK_EQUAL(tp.threads_count(), threads_count);
BOOST_CHECK(!tp.isStoped());
tp.stop();
BOOST_CHECK(tp.isStoped());
}
{
const size_t threads_count = 2;
ThreadPool tp(ThreadPool::Params(threads_count, tk));
const size_t tasks_count = 100;
AsyncTask at = [tk](const ThreadInfo &ti) {
if (tk != ti.kind) {
BOOST_TEST_MESSAGE("(tk != ti.kind)");
throw MAKE_EXCEPTION("(tk != ti.kind)");
}
return false;
};
for (size_t i = 0; i < tasks_count; ++i) {
tp.post(AT(at));
}
tp.flush();
auto lock = tp.post(AT(at));
lock->wait();
tp.stop();
}
{ // without flush
const size_t threads_count = 2;
ThreadPool tp(ThreadPool::Params(threads_count, tk));
const size_t tasks_count = 100;
AsyncTask at = [tk](const ThreadInfo &ti) {
if (tk != ti.kind) {
BOOST_TEST_MESSAGE("(tk != ti.kind)");
throw MAKE_EXCEPTION("(tk != ti.kind)");
}
return false;
};
for (size_t i = 0; i < tasks_count; ++i) {
tp.post(AT(at));
}
tp.stop();
}
}
BOOST_AUTO_TEST_CASE(ThreadsManager) {
using namespace dariadb::utils::async;
const ThreadKind tk1 = 1;
const ThreadKind tk2 = 2;
size_t threads_count = 2;
ThreadPool::Params tp1(threads_count, tk1);
ThreadPool::Params tp2(threads_count, tk2);
ThreadManager::Params tpm_params(std::vector<ThreadPool::Params>{tp1, tp2});
{
BOOST_CHECK(ThreadManager::instance() == nullptr);
ThreadManager::start(tpm_params);
BOOST_CHECK(ThreadManager::instance() != nullptr);
ThreadManager::stop();
BOOST_CHECK(ThreadManager::instance() == nullptr);
}
// while(1)
{
const size_t tasks_count = 10;
ThreadManager::start(tpm_params);
int called = 0;
AsyncTask at_while = [&called](const ThreadInfo &ti) {
if (called < 10) {
++called;
return true;
}
return false;
};
AsyncTask at1 = [tk1](const ThreadInfo &ti) {
if (tk1 != ti.kind) {
BOOST_TEST_MESSAGE("(tk1 != ti.kind)");
std::this_thread::sleep_for(std::chrono::milliseconds(400));
throw MAKE_EXCEPTION("(tk1 != ti.kind)");
}
return false;
};
AsyncTask at2 = [tk2](const ThreadInfo &ti) {
if (tk2 != ti.kind) {
BOOST_TEST_MESSAGE("(tk2 != ti.kind)");
std::this_thread::sleep_for(std::chrono::milliseconds(400));
throw MAKE_EXCEPTION("(tk2 != ti.kind)");
}
return false;
};
auto at_while_res = ThreadManager::instance()->post(tk1, AT(at_while));
for (size_t i = 0; i < tasks_count; ++i) {
// logger("test #"<<i);
ThreadManager::instance()->post(tk1, AT(at1));
ThreadManager::instance()->post(tk2, AT(at2));
}
BOOST_CHECK_GE(ThreadManager::instance()->active_works(), size_t(0));
at_while_res->wait();
BOOST_CHECK_EQUAL(called, int(10));
ThreadManager::instance()->flush();
ThreadManager::instance()->stop();
}
}
BOOST_AUTO_TEST_CASE(SplitString) {
std::string str = "1 2 3 4 5 6 7 8";
auto splitted = dariadb::utils::strings::tokens(str);
BOOST_CHECK_EQUAL(splitted.size(), size_t(8));
splitted = dariadb::utils::strings::split(str, ' ');
BOOST_CHECK_EQUAL(splitted.size(), size_t(8));
}
| [
"lysevi@gmail.com"
] | lysevi@gmail.com |
248e43f4e589128965c9d5f1bacc661bd91661e7 | e9bdce6b07a12d6ddc768f9da2677125e17d680f | /sandbox/sb_texture.cpp | 85d66308712ae0bc4733cb727568796666e3859e | [] | no_license | artMacBookPro/sandbox | b79635399013d308e683dc428fd7998913843950 | 47ab1e867359ef0dc6be2c4c5490259072aac8a8 | refs/heads/master | 2020-04-02T00:13:39.009204 | 2019-05-14T10:19:32 | 2019-05-14T10:19:32 | 153,794,949 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,249 | cpp | //
// sb_texture.cpp
// sr-osx
//
// Created by Andrey Kunitsyn on 5/5/13.
// Copyright (c) 2013 Andrey Kunitsyn. All rights reserved.
//
#include "sb_texture.h"
#include "sb_resources.h"
#include "sb_bitmask.h"
#include <ghl_texture.h>
namespace Sandbox {
const size_t TEXTURE_TTL = 16;
Texture::Texture(const sb::string& file, float scale,bool premul, GHL::UInt32 w, GHL::UInt32 h) :
m_texture(0),m_file(file),m_original_w(w),
m_original_h(h),m_width(w),m_height(h),m_live_ticks(0),m_filtered(false),m_tiled(false),m_scale(scale){
m_need_premultiply = premul;
}
Texture::Texture(GHL::Texture* tex, float scale, GHL::UInt32 w, GHL::UInt32 h) :
m_texture(tex),m_file(),m_original_w(w),m_original_h(h),m_live_ticks(0),m_filtered(false),m_tiled(false),m_scale(scale){
m_need_premultiply = false;
if (m_texture) {
m_width = m_texture->GetWidth();
m_height = m_texture->GetHeight();
if (m_original_w==0) m_original_w = m_width;
if (m_original_h==0) m_original_h = m_height;
}
}
Texture::~Texture() {
if (m_texture) m_texture->Release();
}
void Texture::SetTextureSize(GHL::UInt32 tw,GHL::UInt32 th) {
m_width = tw;
m_height = th;
}
GHL::Texture* Texture::Present(Resources* resources) {
if (!m_texture) {
bool variant = false;
m_texture = resources->ManagedLoadTexture( m_file ,variant, m_need_premultiply );
if (m_texture) {
m_texture->SetMinFilter(m_filtered?GHL::TEX_FILTER_LINEAR:GHL::TEX_FILTER_NEAR);
m_texture->SetMagFilter(m_filtered?GHL::TEX_FILTER_LINEAR:GHL::TEX_FILTER_NEAR);
m_texture->SetWrapModeU(m_tiled?GHL::TEX_WRAP_REPEAT:GHL::TEX_WRAP_CLAMP);
m_texture->SetWrapModeV(m_tiled?GHL::TEX_WRAP_REPEAT:GHL::TEX_WRAP_CLAMP);
}
}
m_live_ticks = resources->GetLiveTicks() + TEXTURE_TTL;
return m_texture;
}
BitmaskPtr Texture::GetBitmask(Resources* resources) {
if (!m_bitmask && !m_file.empty()) {
m_bitmask = resources->LoadBitmask(m_file);
}
return m_bitmask;
}
void Texture::SetFiltered(bool f) {
if (m_texture) {
m_texture->SetMinFilter(f?GHL::TEX_FILTER_LINEAR:GHL::TEX_FILTER_NEAR);
m_texture->SetMagFilter(f?GHL::TEX_FILTER_LINEAR:GHL::TEX_FILTER_NEAR);
}
m_filtered = f;
}
void Texture::SetTiled(bool t) {
if (m_texture) {
m_texture->SetWrapModeU(t?GHL::TEX_WRAP_REPEAT:GHL::TEX_WRAP_CLAMP);
m_texture->SetWrapModeV(t?GHL::TEX_WRAP_REPEAT:GHL::TEX_WRAP_CLAMP);
}
m_tiled = t;
}
size_t Texture::Release() {
if (m_file.empty()) return 0;
size_t res = 0;
if (m_texture) {
res = m_texture->GetMemoryUsage();
m_texture->Release();
}
m_texture = 0;
m_live_ticks = 0;
return res;
}
size_t Texture::GetMemoryUsage() const {
if (m_texture) return m_texture->GetMemoryUsage();
return 0;
}
}
| [
"blackicebox@gmail.com"
] | blackicebox@gmail.com |
d19967486373ffd9cccebb77c1072782b7ebc46f | a304a970d9ee0f6f21663a5a344be7de36b1bfad | /contest.cpp | f2660d3a507999190a84935f5198fc37b5d674ad | [] | no_license | molla276/Problem_solving | 53cbf8ae34325ec689da5b1ed44ea17584a38b18 | 842dcf56a7c497965138863f1cd1f0efbae1bd2c | refs/heads/master | 2023-03-19T14:41:01.005821 | 2020-01-23T07:00:16 | 2020-01-23T07:00:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 383 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int a[100],i,j,t, n;
scanf("%d", &t);
for(j=0; j<t; j++)
{
scanf("%d", &n);
for(i=0; i<3; i++)
{
scanf("%d", &a[i]);
}
sort(a,a+3);
for(i=0; i<3; i++){
printf("Data set #%d:\n Orginal order:\n smallest to largest: a[i]\n");
}
}
return 0;
}
| [
"tithi.cse3.bu@gmail.com"
] | tithi.cse3.bu@gmail.com |
91f4746a101ca28ae3f1ce05a27e87d01b09350a | 9d2aec0bc8a3187523cc5a66bcae62ef4bbac3f5 | /cyan/src/engine/ecs/single_component_registry.hpp | 10e711fb944404e40d6543df19df3061692bb4c9 | [] | no_license | akortman/cyanengine | 5732571ef17f6bc722bc844809cf78883f198b85 | ab1078576ec95b4b1ab7bce3f932a7c5ce20c326 | refs/heads/master | 2023-06-29T10:27:18.035108 | 2021-04-21T08:17:55 | 2021-04-21T08:17:55 | 358,542,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,688 | hpp | #pragma once
#include "entity.hpp"
#include "cyan/src/logging/assert.hpp"
#include "cyan/src/engine/ecs/object_registry.hpp"
#include "cyan/src/logging/logger.hpp"
#include "cyan/src/logging/error.hpp"
#include <queue>
#include <unordered_map>
#include <vector>
namespace cyan {
/** SingleComponentRegistry
* Provides a wrapper over an ObjectRegistry with the addition of an entity-to-component ID mapping (and also in
* reverse).
* @tparam T The type of the component to wrap.
*/
template <typename T>
struct SingleComponentRegistry {
/// Handle on an ID for cleaner code.
struct Id { EcsIndexT id = ECS_NULL_INDEX; };
/**
* ComponentArray<T>::Entry objects are used to refer to component values.
* These act as a pointer to the value.
* Should **not** be stored as a handle to the component (use an ID for that).
*/
struct Entry {
Entity entity;
Id id;
T* value;
/// operator* overloads to allow this object to be used as if it's a pointer.
T& operator*() { return *value; }
const T& operator*() const { return *value; }
/// Boolean conversion to check if the entry is valid.
explicit operator bool() { return value != nullptr; }
/// get() allows easy unwrapping of the underlying component.
T& get() {
if (!value) throw cyan::Error("Attempt to unwrap invalid component");
return *value;
}
private:
/// Constructor to move an underlying ObjectRegistry entry into this entry.
static Entry make_from_object_registry_entry(Entity e, typename ecs_impl::ObjectRegistry<T>::Entry entry)
{
return Entry{e, Id{entry.id}, entry.value};
}
friend SingleComponentRegistry<T>;
};
/**
* Set the component type name, used for debugging purposes.
* @param name The name to be assigned to the component type.
*/
void set_component_type_name(const std::string& name) {
this->component_type_name = name;
}
/**
* Get the name of the component. Useful for debugging purposes.
* @return A std::string of the name that has been assigned to this component type.
*/
std::string get_component_type_name() {
return component_type_name;
}
/**
* Add a copy of an object to the array and return a reference entry.
* @param object The object to make a copy of.
* @return An entry which can be used to retrieve the value.
*/
Entry add(Entity e, const T& object) {
auto entity_component_iter = entity_component_map.find(e.id);
if (entity_component_iter != entity_component_map.end()) {
LOG(WARN, "Attempted to add a component of type \"{}\" to entity {}, but that component "
"already has an existing component of this type. The provided component will be discarded.",
component_type_name, e.id);
// We return the existing component, disregarding the provided component.
// TODO: There's an argument that adding a component to an Entity that already has a component of that
// type should throw an error, and this may be a good idea in non-release builds. This is a
// non-fatal error though, so in release we want the engine to keep running wherever possible
// rather than failing outright.
return get(Id{entity_component_iter->second});
}
auto component_entry = components.add(object);
entity_component_map.insert({e.id, component_entry.id});
component_entity_map.insert({component_entry.id, e.id});
return Entry::make_from_object_registry_entry(e, component_entry);
}
/**
* Create an object in-place and return a reference entry.
* @tparam Args The types to construct the object from.
* @param args The values to construct the object from.
* @return An entry which can be used to retrieve the value.
*/
template <typename ...Args>
Entry emplace(Entity e, Args... args) {
auto entity_component_iter = entity_component_map.find(e.id);
if (entity_component_iter != entity_component_map.end()) {
LOG(WARN, "Attempted to emplace a component of type \"{}\" to entity {}, but that component "
"already has an existing component of this type. The provided component will be discarded.",
component_type_name, e.id);
// We return the existing component.
return get(Id{entity_component_iter->second});
}
auto component_entry = components.emplace(std::forward(args...));
entity_component_map.insert({e.id, component_entry.id});
component_entity_map.insert({component_entry.id, e.id});
return Entry::make_from_object_registry_entry(e, component_entry);
}
/**
* Look up an entry from an Entity ID.
* @param id The id of the object.
* @return An entry corresponding with the component associated with the provided entity
*/
Entry get(Entity e) {
auto entity_component_iter = entity_component_map.find(e.id);
if (entity_component_iter == entity_component_map.end()) return make_null_entry();
auto id = entity_component_iter->second;
return get(Id{id});
}
/**
* Look up an entry from an Component ID.
* @param id The id of the object.
* @return An entry for the matching component for the provided ID
*/
Entry get(Id id) {
auto component_entry = components.get(id.id);
if (!component_entry) return make_null_entry();
return Entry::make_from_object_registry_entry(Entity{component_entity_map[id.id]}, component_entry);
}
/**
* Remove an object from the array.
* @param id The id of the object to remove.
*/
void remove(Id id) {
auto component_entity_iter = component_entity_map.find(id.id);
if (component_entity_iter == component_entity_map.end()) return;
auto entity_id = component_entity_iter->second;
entity_component_map.erase(entity_id);
component_entity_map.erase(component_entity_iter);
components.remove(id.id);
}
/**
* Remove an object from the array via the ID of it's owning entity.
* @param e The entity id from which to remove the component.
*/
void remove(Entity e) {
auto entity_component_iter = entity_component_map.find(e.id);
// TODO: since remove(Id) looks up in component_entity_map to clear the values there, this is inefficient,
// TODO: so it should be checked with a profiler to double-check the multiple lookups aren't a problem.
if (entity_component_iter == entity_component_map.end()) return;
remove(Id{entity_component_iter->second});
}
/**
* Get the number of currently active elements in the registry.
*/
[[nodiscard]]
std::size_t size() const {
return components.size();
}
/**
* Utility function to make a null entry.
*/
static Entry make_null_entry() {
return Entry{Entity{ECS_NULL_INDEX}, Id{ECS_NULL_INDEX}, nullptr};
}
private:
std::unordered_map<EcsIdT, EcsIdT> entity_component_map;
std::unordered_map<EcsIdT, EcsIdT> component_entity_map;
ecs_impl::ObjectRegistry<T> components;
// We store the name of the component type here.
// This is redundant, because it's also stored in ComponentMap. However, it's very useful to have it accessible
// from within SingleComponentRegistry (so the assigned component name can be quoted on error logs) and also in
// ComponentMap for use in a debugger (because ComponentMap uses void* to store these Registries, it's not easy
// to debug.
// TODO: We can likely clean up this system when we move to making SingleComponentRegistry<T> inherit from a
// non-templated abstract class.
std::string component_type_name;
};
} | [
"april.kortman@gmail.com"
] | april.kortman@gmail.com |
a9d26b1bd04284b848517cb1fc35923724504e94 | 4703ab4f910e6af3f8d935b69e35b4da7defabf7 | /nauEngine/nauUtilities/include/nauBox2d.h | 4ffc3b287a433eb64bb0679064e31ebe4a535152 | [] | no_license | USwampertor/NautilusEngine | 6ae96839086832cd9490afe237dc987015fa105f | df027468b4f58691b3b5f4866190ce395dab3d5a | refs/heads/master | 2021-06-07T12:11:09.162039 | 2018-10-01T23:05:38 | 2018-10-01T23:05:38 | 148,564,586 | 1 | 0 | null | null | null | null | BIG5 | C++ | false | false | 1,817 | h | /*||偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|*/
/**
* @file nauBox2d.h
* @author Marco "Swampy" Millan
* @date 2018/09/27 2018
* @brief 2D Box primitive object
*
*/
/*||偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|*/
#pragma once
#include "nauMath.h"
#include "nauPrerequisitesUtil.h"
#include "nauVector2.h"
namespace nauEngineSDK {
/**
* Description:
* A 2d Box Primitive Object
* Sample usage:
* 2dBox for a sprite
*/
class nauBox2d
{
public:
/**
* Default constructor
*/
nauBox2d() = default;
/**
* @brief Constructor with limits of box2d
* @param vector2 min and vector2 max
* @return
*
*/
nauBox2d(const nauVector2& min, const nauVector2& max);
/**
* @brief Constructor with
* @param origin min position and height width and length
* @return
*
*/
nauBox2d(const nauVector2& origin, float height, float width);
/**
* Default Destructor
*/
~nauBox2d() = default;
/**
* Collisions
*/
/**
* @brief checks if theres a collision between 2 box2d
* @param nauBox2d the other box
* @return true if its colliding
*
*/
bool
collidingBox2d(const nauBox2d& other);
/**
* @brief checks if one of the points is inside the box
* @param nauVector2 the other point
* @return true if the point is inside the box
*
*/
bool
insideBox2d(const nauVector2& other);
/**
* Member declaration
*/
public:
/**
* lower corner component
*/
nauVector2 m_min;
/**
* higher corner component
*/
nauVector2 m_max;
};
}
| [
"idv16c.mmillan@uartesdigitales.edu.mx"
] | idv16c.mmillan@uartesdigitales.edu.mx |
ae817b3daff34b36fef8e6a29615d96b42e7e167 | 0654e9d37bb13aeef7d006a5372ad57b6a165fe2 | /src/client/config.cpp | e9b2d86bbb1f47f542d2f39df4aad607295e174e | [
"Apache-2.0"
] | permissive | kahrl/buildat | 4401c75849e14f7e7eac68bf3e1619fdbcdc35e2 | 8e11727c1c1c69af4eb3f4d75e061e815a708a19 | refs/heads/master | 2021-01-21T03:39:35.878734 | 2014-10-01T06:30:03 | 2014-10-01T06:31:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,751 | cpp | // http://www.apache.org/licenses/LICENSE-2.0
// Copyright 2014 Perttu Ahola <celeron55@gmail.com>
#include "client/config.h"
#include "core/log.h"
#include "interface/fs.h"
#include <fstream>
#define MODULE "config"
namespace client {
static bool check_file_readable(const ss_ &path)
{
std::ifstream ifs(path);
bool readable = ifs.good();
if(!readable)
log_e(MODULE, "File is not readable: \"%s\"", cs(path));
return readable;
}
static bool check_file_writable(const ss_ &path)
{
std::ofstream ofs(path);
bool writable = ofs.good();
if(!writable)
log_e(MODULE, "File is not writable: \"%s\"", cs(path));
return writable;
}
void Config::make_paths_absolute()
{
auto *fs = interface::getGlobalFilesystem();
share_path = fs->get_absolute_path(share_path);
cache_path = fs->get_absolute_path(cache_path);
urho3d_path = fs->get_absolute_path(urho3d_path);
}
bool Config::check_paths()
{
bool fail = false;
if(!check_file_readable(share_path+"/extensions/test/init.lua")){
log_e(MODULE, "Static files don't seem to exist in share_path=\"%s\"",
cs(share_path));
fail = true;
}
else if(!check_file_readable(share_path+"/client/init.lua")){
log_e(MODULE, "Static files don't seem to exist in share_path=\"%s\"",
cs(share_path));
fail = true;
}
if(!check_file_readable(urho3d_path +
"/Bin/CoreData/Shaders/GLSL/Basic.glsl")){
log_e(MODULE, "Urho3D doesn't seem to exist in urho3d_path=\"%s\"",
cs(urho3d_path));
fail = true;
}
auto *fs = interface::getGlobalFilesystem();
fs->create_directories(cache_path);
if(!check_file_writable(cache_path+"/write.test")){
log_e(MODULE, "Cannot write into cache_path=\"%s\"", cs(cache_path));
fail = true;
}
return !fail;
}
}
// vim: set noet ts=4 sw=4:
| [
"celeron55@gmail.com"
] | celeron55@gmail.com |
b1a479eb20005d7b06e37ebef3673051417e0d30 | 558379dfe2ff6c840e4c81b7d56eb37241c634f4 | /Majatek.cpp | b5fdcd6d40fb5b5e6c8ae9321bcfdf4f9c96d8e3 | [] | no_license | S-Maciejewski/Oszczednosci | c8a2e7e882dbdc15b0fc860152d2831d1e1e9e33 | af293fff72004b17a7cc84b83b3ad90727fdea21 | refs/heads/master | 2021-03-27T17:00:08.593516 | 2018-03-13T20:33:23 | 2018-03-13T20:33:23 | 118,369,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,777 | cpp | #include "stdafx.h"
#include "Majatek.h"
#include<fstream>
using namespace std;
Majatek::Majatek() {
lokaty = new Aktywa<Lokata>(maxElementow);
produkty = new Aktywa<ProduktStrukturyzowany>(maxElementow);
iki = new Aktywa<IKE>(maxElementow);
nieruchomosci = new Aktywa<Nieruchomosc>(maxElementow);
kontrakty = new Aktywa<Kontrakt>(maxElementow);
jednostkiFunduszu = new Aktywa<JednostkaFunduszu>(maxElementow);
}
Majatek::~Majatek() = default;
string Majatek::podajNazwe()
{
string nazwa;
cin >> nazwa;
return nazwa;
}
double Majatek::podajWartosc()
{
double wartosc;
cin >> wartosc;
return wartosc;
}
template<class T>
double obliczWartosc(Aktywa<T> *aktywa, int ileLat) {
double wartosc = 0;
if (ileLat == 0) {
for (int i = 0; i < aktywa->getIloscAktywow(); i++) {
wartosc += aktywa->getTab()[i].getWartosc();
}
}
else {
for (int i = 0; i < aktywa->getIloscAktywow(); i++) {
aktywa->getTab()[i].obliczZmianeWartosci(ileLat);
wartosc += aktywa->getTab()[i].getWartosc();
}
}
return wartosc;
}
double Majatek::obliczWartoscMajatku(int ileLat) {
double wartosc = 0;
wartosc += obliczWartosc<Lokata>(lokaty, ileLat);
wartosc += obliczWartosc<ProduktStrukturyzowany>(produkty, ileLat);
wartosc += obliczWartosc<IKE>(iki, ileLat);
wartosc += obliczWartosc<Nieruchomosc>(nieruchomosci, ileLat);
wartosc += obliczWartosc<Kontrakt>(kontrakty, ileLat);
wartosc += obliczWartosc<JednostkaFunduszu>(jednostkiFunduszu, ileLat);
return wartosc;
}
void Majatek::dodajAktywa() {
cout << "Wybierz rodzaj aktywow\n---------Aktywa---------\n1. Lokata\n2. Produkt strukturyzowany\n3. IKE\n4. Nieruchomosc\n5. Kontrakt terminowy\n6. Jednostka funduszu inwestycyjnego\n";
string nazwa;
double wklad, roi;
int wybor;
cin >> wybor;
switch (wybor) {
case 1: { cout << "Podaj nazwe, wklad poczatkowy i zwrot z inwestycji (jako liczbe, np. 4% zwrotu to 0.04) swojej lokaty\nNazwa: ";
nazwa = podajNazwe();
cout << "Wklad poczatkowy: ";
wklad = podajWartosc();
cout << "Szacowany roczny zwrot z inwestycji: ";
roi = podajWartosc();
Lokata *lokata = new Lokata(nazwa, wklad, wklad, roi);
*lokaty+=lokata;
break; }
case 2: { cout << "Podaj nazwe, wklad poczatkowy i zwrot z inwestycji (jako liczbe, np. 4% zwrotu to 0.04) swojego pakiety instrumentow\nNazwa: ";
nazwa = podajNazwe();
cout << "Wklad poczatkowy: ";
wklad = podajWartosc();
cout << "Szacowany roczny zwrot z inwestycji: ";
roi = podajWartosc();
ProduktStrukturyzowany *produkt = new ProduktStrukturyzowany(nazwa, wklad, wklad, roi);
*produkty+=produkt;
break; }
case 3: { cout << "Podaj nazwe, wklad poczatkowy i zwrot z inwestycji (jako liczbe, np. 4% zwrotu to 0.04) swojego indywidualnego konta emerytalnego\nNazwa: ";
nazwa = podajNazwe();
cout << "Wklad poczatkowy: ";
wklad = podajWartosc();
cout << "Szacowany roczny zwrot z inwestycji: ";
roi = podajWartosc();
IKE *ike = new IKE(nazwa, wklad, wklad, roi);
*iki+=ike;
break; }
case 4: { cout << "Podaj nazwe, wklad poczatkowy i zwrot z inwestycji (jako liczbe, np. 4% zwrotu to 0.04) swojej nieruchomosci\nNazwa: ";
nazwa = podajNazwe();
cout << "Wklad poczatkowy: ";
wklad = podajWartosc();
cout << "Szacowany roczny zwrot z inwestycji: ";
roi = podajWartosc();
Nieruchomosc *nieruchomosc = new Nieruchomosc(nazwa, wklad, wklad, roi);
*nieruchomosci+=nieruchomosc;
break; }
case 5: { cout << "Podaj nazwe, wklad poczatkowy, zwrot z inwestycji (jako liczbe, np. 4% zwrotu to 0.04) i dlugosc trwania (np. pol roku to 0.5) swojego kontraktu terminowego\nNazwa: ";
nazwa = podajNazwe();
cout << "Wklad poczatkowy: ";
wklad = podajWartosc();
cout << "Szacowany roczny zwrot z inwestycji: ";
roi = podajWartosc();
double okres;
cout << "Czas trwania kontraktu: ";
okres = podajWartosc();
Kontrakt *kontrakt = new Kontrakt(nazwa, wklad, wklad, roi, okres);
*kontrakty+=kontrakt;
break; }
case 6: { cout << "Podaj nazwe, wklad poczatkowy i zwrot z inwestycji (jako liczbe, np. 4% zwrotu to 0.04) swojego funduszu inwestycyjnego\nNazwa: ";
nazwa = podajNazwe();
cout << "Wklad poczatkowy: ";
wklad = podajWartosc();
cout << "Szacowany roczny zwrot z inwestycji: ";
roi = podajWartosc();
JednostkaFunduszu *fundusz = new JednostkaFunduszu(nazwa, wklad, wklad, roi);
*jednostkiFunduszu+=fundusz;
break; }
default: break;
}
}
template<class T>
void usun(Aktywa<T> *aktywa) {
int element;
cout << "Obiekty, ktore mozesz usunac:" << endl;
for (int i = 0; i < aktywa->getIloscAktywow(); i++) {
cout << i << ". nazwa: " << aktywa->getTab()[i].getNazwa() << ", wartosc: " << aktywa->getTab()[i].getWartosc() << endl;
}
cout << "Wpisz numer elementu, ktory ma zostac usuniety: ";
cin >> element;
*aktywa -= element;
cout << "Element zostal usuniety";
}
void Majatek::usunAktywa() {
cout << "Wybierz rodzaj aktywow\n---------Aktywa---------\n1. Lokata\n2. Produkt strukturyzowany\n3. IKE\n4. Nieruchomosc\n5. Kontrakt terminowy\n6. Jednostka funduszu inwestycyjnego\n";
int wybor;
cin >> wybor;
switch (wybor) {
case 1: {
usun<Lokata>(lokaty);
break;
}
case 2: {
usun<ProduktStrukturyzowany>(produkty);
break;
}
case 3: {
usun<IKE>(iki);
break;
}
case 4: {
usun<Nieruchomosc>(nieruchomosci);
break;
}
case 5: {
usun<Kontrakt>(kontrakty);
break;
}
case 6: {
usun<JednostkaFunduszu>(jednostkiFunduszu);
break;
}
default: break;
}
}
template<class T>
void edytuj(Aktywa<T> *aktywa) {
int element, pole;
cout << "Obiekty, ktore mozesz edytowac:" << endl;
for (int i = 0; i < aktywa->getIloscAktywow(); i++) {
cout << i << ". nazwa: " << aktywa->getTab()[i].getNazwa() << ", wartosc: " << aktywa->getTab()[i].getWartosc() << endl;
}
cout << "Wpisz numer elementu, ktory chcesz edytowac: ";
cin >> element;
cout << "Co chcesz edytowac?\n1. Nazwe\n2. Wartosc\n3. Roczna stope zwrotu" << endl;
cin >> pole;
switch (pole)
{
case 1: cout << "Nazwa: "; aktywa->getTab()[element].setNazwa(Majatek::podajNazwe()); break;
case 2: cout << "Wartosc: "; aktywa->getTab()[element].setWartosc(Majatek::podajWartosc()); break;
case 3: cout << "Stopa zwrotu: "; aktywa->getTab()[element].setRoi(Majatek::podajWartosc()); break;
default: cout << "Nie ma takiej opcji"; break;
}
}
void Majatek::edytujAktywa() {
cout << "Wybierz rodzaj aktywow\n---------Aktywa---------\n1. Lokata\n2. Produkt strukturyzowany\n3. IKE\n4. Nieruchomosc\n5. Kontrakt terminowy\n6. Jednostka funduszu inwestycyjnego\n";
int wybor;
cin >> wybor;
switch (wybor) {
case 1: {
edytuj<Lokata>(lokaty);
break;
}
case 2: {
edytuj<ProduktStrukturyzowany>(produkty);
break;
}
case 3: {
edytuj<IKE>(iki);
break;
}
case 4: {
edytuj<Nieruchomosc>(nieruchomosci);
break;
}
case 5: {
edytuj<Kontrakt>(kontrakty);
break;
}
case 6: {
edytuj<JednostkaFunduszu>(jednostkiFunduszu);
break;
}
default: break;
}
}
void Majatek::wypiszAktywa() {
cout << "Twoje aktywa to:" << endl;
for (int i = 0; i < lokaty->getIloscAktywow(); i++) {
cout << "Lokata " << lokaty->getTab()[i].getNazwa() << " o wartosci " << lokaty->getTab()[i].getWartosc() << " i rocznej stopie zwrotu " << lokaty->getTab()[i].getRoi() << endl;
}
for (int i = 0; i < produkty->getIloscAktywow(); i++) {
cout << "Produkt strukturyzowany " << produkty->getTab()[i].getNazwa() << " o wartosci " << produkty->getTab()[i].getWartosc() <<
" i rocznej stopie zwrotu " << produkty->getTab()[i].getRoi() << endl;
}
for (int i = 0; i < iki->getIloscAktywow(); i++) {
cout << "Indywidualne konto emerytalne " << iki->getTab()[i].getNazwa() << " o wartosci " << iki->getTab()[i].getWartosc() << " i rocznej stopie zwrotu " <<
iki->getTab()[i].getRoi() << endl;
}
for (int i = 0; i < nieruchomosci->getIloscAktywow(); i++) {
cout << "Nieruchomosc " << nieruchomosci->getTab()[i].getNazwa() << " o wartosci " << nieruchomosci->getTab()[i].getWartosc() <<
" generujaca roczny przychod " << nieruchomosci->getTab()[i].getPrzychod(1) << endl;
}
for (int i = 0; i < kontrakty->getIloscAktywow(); i++) {
cout << "Kontrakt " << kontrakty->getTab()[i].getNazwa() << " o wartosci " << kontrakty->getTab()[i].getWartosc() << ", rocznej stopie zwrotu " <<
kontrakty->getTab()[i].getRoi() << " na okres lat " << kontrakty->getTab()[i].getOkresTrwania() << endl;
}
for (int i = 0; i < jednostkiFunduszu->getIloscAktywow(); i++) {
cout << "Jednostki funduszu inwestycyjneo " << jednostkiFunduszu->getTab()[i].getNazwa() << " o wartosci " << jednostkiFunduszu->getTab()[i].getWartosc() <<
" i rocznej stopie zwrotu " << jednostkiFunduszu->getTab()[i].getRoi() << endl;
}
}
void Majatek::przeprowadzSymulacje() {
int ileLat;
cout << "Podaj w przedziale ilu lat od teraz chcialbys przeprowadzic symulacje: ";
ileLat = (int)podajWartosc();
cout << "Obecna wartosc aktywow to " << obliczWartoscMajatku(0) << endl;
cout << "Za " << ileLat << " lat wartosc twoich aktywow bedzie wynosic "<<obliczWartoscMajatku(ileLat);
}
template <class T>
void zapiszAktywa(Aktywa<T> *aktywa, ofstream &out) {
out << aktywa->getIloscAktywow() << endl;
for (int i = 0; i < aktywa->getIloscAktywow(); i++) {
out << aktywa->getTab()[i].getNazwa() << " " << aktywa->getTab()[i].getWartosc() << " " << aktywa->getTab()[i].getWklad() << " " << aktywa->getTab()[i].getRoi() << endl;
}
}
void Majatek::zapis(ofstream &out) {
out << kontrakty->getIloscAktywow() << endl;
for (int i = 0; i < kontrakty->getIloscAktywow(); i++) {
out << kontrakty->getTab()[i].getNazwa() << " " << kontrakty->getTab()[i].getWartosc() << " " << kontrakty->getTab()[i].getWklad() << " " <<
kontrakty->getTab()[i].getRoi() << " " << kontrakty->getTab()[i].getOkresTrwania() << endl;
}
zapiszAktywa<Lokata>(lokaty, out);
zapiszAktywa<ProduktStrukturyzowany>(produkty, out);
zapiszAktywa<IKE>(iki, out);
zapiszAktywa<Nieruchomosc>(nieruchomosci, out);
zapiszAktywa<JednostkaFunduszu>(jednostkiFunduszu, out);
}
template<class T>
void odczytajAktywa(Aktywa<T> *aktywa, ifstream &in) {
int ile;
string nazwa;
double wartosc, wklad, roi;
in >> ile;
for (int i = 0; i < ile; i++) {
in >> nazwa >> wartosc >> wklad >> roi;
T *t = new T(nazwa, wartosc, wklad, roi);
aktywa->dodaj(t);
}
}
void Majatek::odczyt(ifstream &in){
int ile;
string nazwa;
double wartosc, wklad, roi, okres;
in >> ile;
for (int i = 0; i < ile; i++) {
in >> nazwa >> wartosc >> wklad >> roi >> okres;
Kontrakt *kontrakt = new Kontrakt(nazwa, wartosc, wklad, roi, okres);
kontrakty->dodaj(kontrakt);
}
odczytajAktywa<Lokata>(lokaty, in);
odczytajAktywa<ProduktStrukturyzowany>(produkty, in);
odczytajAktywa<IKE>(iki, in);
odczytajAktywa<Nieruchomosc>(nieruchomosci, in);
odczytajAktywa<JednostkaFunduszu>(jednostkiFunduszu, in);
} | [
"maciejewski.torun@gmail.com"
] | maciejewski.torun@gmail.com |
5a176dba448b3756942753aa8452594f0bb956cf | c2b6bd54bef3c30e53c846e9cf57f1e44f8410df | /Temp/il2cppOutput/il2cppOutput/mscorlib_System_Predicate_1_gen863237615.h | 73d52357da4ceb7bf188c70f14c2c2ea77f1f0d6 | [] | no_license | PriyeshWani/CrashReproduce-5.4p1 | 549a1f75c848bf9513b2f966f2f500ee6c75ba42 | 03dd84f7f990317fb9026cbcc3873bc110b1051e | refs/heads/master | 2021-01-11T12:04:21.140491 | 2017-01-24T14:01:29 | 2017-01-24T14:01:29 | 79,388,416 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_MulticastDelegate3201952435.h"
// UnityEngine.UI.Dropdown/OptionData
struct OptionData_t2420267500;
// System.IAsyncResult
struct IAsyncResult_t1999651008;
// System.AsyncCallback
struct AsyncCallback_t163412349;
// System.Object
struct Il2CppObject;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Predicate`1<UnityEngine.UI.Dropdown/OptionData>
struct Predicate_1_t863237615 : public MulticastDelegate_t3201952435
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"priyeshwani@gmail.com"
] | priyeshwani@gmail.com |
bffd89218b1a48cd375008d740b78e99e29e5900 | 297497957c531d81ba286bc91253fbbb78b4d8be | /ipc/chromium/src/base/message_pump_default.h | fe1177b5b296d4750a819926af76c81056238f01 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | marco-c/gecko-dev-comments-removed | 7a9dd34045b07e6b22f0c636c0a836b9e639f9d3 | 61942784fb157763e65608e5a29b3729b0aa66fa | refs/heads/master | 2023-08-09T18:55:25.895853 | 2023-08-01T00:40:39 | 2023-08-01T00:40:39 | 211,297,481 | 0 | 0 | NOASSERTION | 2019-09-29T01:27:49 | 2019-09-27T10:44:24 | C++ | UTF-8 | C++ | false | false | 680 | h |
#ifndef BASE_MESSAGE_PUMP_DEFAULT_H_
#define BASE_MESSAGE_PUMP_DEFAULT_H_
#include "base/message_pump.h"
#include "base/time.h"
#include "base/waitable_event.h"
namespace base {
class MessagePumpDefault : public MessagePump {
public:
MessagePumpDefault();
~MessagePumpDefault() {}
virtual void Run(Delegate* delegate) override;
virtual void Quit() override;
virtual void ScheduleWork() override;
virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
protected:
bool keep_running_;
WaitableEvent event_;
TimeTicks delayed_work_time_;
private:
DISALLOW_COPY_AND_ASSIGN(MessagePumpDefault);
};
}
#endif
| [
"mcastelluccio@mozilla.com"
] | mcastelluccio@mozilla.com |
b568591c05bf3c4a862b5c366a788709ca7f11f4 | e42df67dcb3b36aba3b7fd3e94ab381ef603446d | /poseidon/static/fiber_scheduler.hpp | bc7132e919b8510ab609ddf2df9331d69490772b | [
"BSD-3-Clause"
] | permissive | lhmouse/poseidon | 68d0a9b9d36ae62a6673d2a4e023c258dfe2ee67 | 5b08a06dc23da7552d369dc18e64f85387e528de | refs/heads/master | 2023-09-03T13:31:09.022860 | 2023-08-30T09:08:12 | 2023-08-30T09:08:12 | 23,041,217 | 186 | 49 | Apache-2.0 | 2018-03-22T08:10:28 | 2014-08-17T13:35:17 | C++ | UTF-8 | C++ | false | false | 1,859 | hpp | // This file is part of Poseidon.
// Copyleft 2022 - 2023, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_STATIC_FIBER_SCHEDULER_
#define POSEIDON_STATIC_FIBER_SCHEDULER_
#include "../fwd.hpp"
#include <ucontext.h> // ucontext_t
namespace poseidon {
class Fiber_Scheduler
{
private:
struct X_Queued_Fiber;
mutable plain_mutex m_conf_mutex;
uint32_t m_conf_stack_vm_size = 0;
seconds m_conf_warn_timeout = zero_duration;
seconds m_conf_fail_timeout = zero_duration;
mutable plain_mutex m_pq_mutex;
vector<shptr<X_Queued_Fiber>> m_pq;
::timespec m_pq_wait = { };
mutable recursive_mutex m_sched_mutex;
shptr<X_Queued_Fiber> m_sched_elem;
void* m_sched_asan_save; // private data for address sanitizer
::ucontext_t m_sched_outer[1]; // yield target
public:
// Constructs an empty scheduler.
explicit
Fiber_Scheduler();
private:
void
do_fiber_function() noexcept;
void
do_yield(shptrR<Abstract_Future> futr_opt, milliseconds fail_timeout_override);
public:
ASTERIA_NONCOPYABLE_DESTRUCTOR(Fiber_Scheduler);
// Reloads configuration from 'main.conf'.
// If this function fails, an exception is thrown, and there is no effect.
// This function is thread-safe.
void
reload(const Config_File& conf_file);
// Schedules fibers.
// This function should be called by the fiber thread repeatedly.
void
thread_loop();
// Returns the number of fibers that are being scheduled.
// This function is thread-safe.
ROCKET_PURE
size_t
size() const noexcept;
// Takes ownership of a fiber, and schedules it for execution. The fiber
// can only be deleted after it finishes execution.
// This function is thread-safe.
void
launch(shptrR<Abstract_Fiber> fiber);
};
} // namespace poseidon
#endif
| [
"lh_mouse@126.com"
] | lh_mouse@126.com |
750258e9630e164d20472e45c10d6545e7b04976 | 811a3592b0b8d324ddbed95042fb8dc7c14d8d7e | /Code/Lib/shuntingYard.cpp | a84b91c9bcee19a49725fa605771055c501d76a8 | [] | no_license | YsHaNgM/string-cal | 72cd0b530ec7cd8a1c82d34f96cc66b6616e7177 | bbf6db6ebeffe59c9c8086e3ab5dbf1d22714b32 | refs/heads/master | 2022-11-19T09:46:15.284032 | 2020-07-20T22:34:00 | 2020-07-20T22:34:00 | 280,270,220 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,273 | cpp | #include "shuntingYard.h"
std::variant<int, char> inputParser(std::string &line)
{
// Ex: std::string line("2+2*3-5");
while (!line.empty())
{
for (int i = 0; i < line.size(); i++)
{
if (isOperator(line[i]))
{
if (i != 0)
{
std::string temp = line.substr(0, i);
line.erase(0, i);
return std::stoi(temp);
}
else
{
auto temp = line[i];
line.erase(0, 1);
return temp;
}
}
else if (i == (line.size() - 1)) // By the end of input
{
auto temp = line;
line.erase(0, line.size());
return std::stoi(temp);
}
}
}
return 0;
}
int shuntingYard(std::string line)
{
std::stack<double> nums;
std::stack<char> ops;
while (!line.empty())
{
auto v = inputParser(line);
if (auto pval = std::get_if<int>(&v))
{
}
else if (auto pval = std::get_if<char>(&v))
{
}
else
{
return 0;
}
}
return 0;
}
| [
"ysh788@gmail.com"
] | ysh788@gmail.com |
f7e38b34bca7d5a6b4c5e99fe5d7fce1e19faab0 | db5204a0f8f7ee45d1505da6586e2286cd1fefa5 | /light_source.cpp | 5a3911f7e9f41b688813cc76f5c02610b7f6566b | [] | no_license | xiuyansyu/raytracer | a658e7c3b7f16c8a33a27207f7e4c7d0d4aa2dbc | f78235d8dc17c08dcd15f017d1c24535fc9ac31c | refs/heads/master | 2021-01-10T01:21:13.111834 | 2016-04-08T00:34:15 | 2016-04-08T00:34:15 | 55,461,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,025 | cpp | /***********************************************************
Starter code for Assignment 3
This code was originally written by Jack Wang for
CSC418, SPRING 2005
implements light_source.h
***********************************************************/
#include <cmath>
#include "light_source.h"
void PointLight::shade( Ray3D& ray ) {
// TODO: implement this function to fill in values for ray.col
// using phong shading. Make sure your vectors are normalized, and
// clamp colour values to 1.0.
//
// It is assumed at this point that the intersection information in ray
// is available. So be sure that traverseScene() is called on the ray
// before this function.
// Source: https://steveharveynz.wordpress.com/category/programming/c-raytracer/
Material* material = ray.intersection.mat;
Colour dif_col = _col_diffuse * material->diffuse;
Colour spe_col = _col_specular * material->specular;
Colour amb_col = _col_ambient * material->ambient;
Vector3D normal = ray.intersection.normal;
normal.normalize();
Vector3D light = _pos - ray.intersection.point;
light.normalize();
// Eyepoint vector
Vector3D eye = -ray.dir;
eye.normalize();
// Relection vector
Vector3D reflection = (2 * light.dot(normal)) * normal - light;
reflection.normalize();
double dif_comp = normal.dot(light);
dif_comp = fmax(0, dif_comp);
double spe_comp = pow(reflection.dot(eye), material->specular_exp);
spe_comp = fmax(0, spe_comp);
Colour diffuse = dif_comp * dif_col;
Colour specular = spe_comp * spe_col;
Colour ambient = amb_col;
/* For generating scene signature, do not multiply by the light component
Colour diffuse = dif_col;
Colour specular = spe_col;
Colour ambient = amb_col;
*/
Colour illuminate = ambient + diffuse + specular;
illuminate.clamp();
ray.col = illuminate;
}
| [
"c5yuxiuy@cdf.toronto.edu"
] | c5yuxiuy@cdf.toronto.edu |
ac31e3f40920811e5ea9a53e638d69da8c1d18db | cdccc3668cc34d874f224675794f02e66f3a3b13 | /hphp/runtime/vm/native-func-table.h | 127b735fee4e6d8b3a0ff9b99ef17e67f28d5843 | [
"MIT",
"PHP-3.01",
"Zend-2.0"
] | permissive | ecreeth/hhvm | 50fab8d88c52ce3bd7f25cbf52d6f00601e7e849 | 743948904dcf31985e25f68258f7afcd36d2b228 | refs/heads/master | 2020-11-24T17:51:35.714659 | 2020-01-31T20:06:56 | 2020-01-31T20:06:56 | 228,277,028 | 1 | 0 | NOASSERTION | 2019-12-16T01:12:28 | 2019-12-16T01:12:27 | null | UTF-8 | C++ | false | false | 1,549 | h | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_RUNTIME_VM_NATIVE_FUNC_TABLE_H
#define incl_HPHP_RUNTIME_VM_NATIVE_FUNC_TABLE_H
#include "hphp/runtime/vm/native.h"
#include "hphp/runtime/base/string-functors.h"
#include "hphp/util/hash-map.h"
namespace HPHP { namespace Native {
struct FuncTable {
void insert(const StringData* name, const NativeFunctionInfo&);
NativeFunctionInfo get(const StringData* name) const;
void dump() const;
private:
hphp_hash_map<const StringData*, NativeFunctionInfo,
string_data_hash, string_data_isame> m_infos;
};
}}
#endif
| [
"hhvm-bot@users.noreply.github.com"
] | hhvm-bot@users.noreply.github.com |
3a1d467172f55c6573216a10b8aac5ce4adf79ae | 282e49924ca2dc47628328b93b9d362b5201c928 | /config/toml11/toml/source_location.hpp | 8209928f45a4fe19f4b34003aa4c5efa8066843b | [
"MIT"
] | permissive | modao233/WebServer-cpp | 47723f3d4449b10acd55f44d1e595a67230dfd6f | 85dad7d63598ac15427396f3e8259b6de03689b6 | refs/heads/master | 2023-04-01T17:05:01.222696 | 2021-04-02T08:47:39 | 2021-04-02T08:47:39 | 353,959,975 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,226 | hpp | // Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_SOURCE_LOCATION_HPP
#define TOML11_SOURCE_LOCATION_HPP
#include <cstdint>
#include "region.hpp"
namespace toml
{
// A struct to contain location in a toml file.
// The interface imitates std::experimental::source_location,
// but not completely the same.
//
// It would be constructed by toml::value. It can be used to generate
// user-defined error messages.
//
// - std::uint_least32_t line() const noexcept
// - returns the line number where the region is on.
// - std::uint_least32_t column() const noexcept
// - returns the column number where the region starts.
// - std::uint_least32_t region() const noexcept
// - returns the size of the region.
//
// +-- line() +-- region of interest (region() == 9)
// v .---+---.
// 12 | value = "foo bar"
// ^
// +-- column()
//
// - std::string const& file_name() const noexcept;
// - name of the file.
// - std::string const& line_str() const noexcept;
// - the whole line that contains the region of interest.
//
struct source_location
{
public:
source_location()
: line_num_(1), column_num_(1), region_size_(1),
file_name_("unknown file"), line_str_("")
{}
explicit source_location(const detail::region_base* reg)
: line_num_(1), column_num_(1), region_size_(1),
file_name_("unknown file"), line_str_("")
{
if(reg)
{
if(reg->line_num() != detail::region_base().line_num())
{
line_num_ = static_cast<std::uint_least32_t>(
std::stoul(reg->line_num()));
}
column_num_ = static_cast<std::uint_least32_t>(reg->before() + 1);
region_size_ = static_cast<std::uint_least32_t>(reg->size());
file_name_ = reg->name();
line_str_ = reg->line();
}
}
explicit source_location(const detail::region& reg)
: line_num_(static_cast<std::uint_least32_t>(std::stoul(reg.line_num()))),
column_num_(static_cast<std::uint_least32_t>(reg.before() + 1)),
region_size_(static_cast<std::uint_least32_t>(reg.size())),
file_name_(reg.name()),
line_str_ (reg.line())
{}
explicit source_location(const detail::location& loc)
: line_num_(static_cast<std::uint_least32_t>(std::stoul(loc.line_num()))),
column_num_(static_cast<std::uint_least32_t>(loc.before() + 1)),
region_size_(static_cast<std::uint_least32_t>(loc.size())),
file_name_(loc.name()),
line_str_ (loc.line())
{}
~source_location() = default;
source_location(source_location const&) = default;
source_location(source_location &&) = default;
source_location& operator=(source_location const&) = default;
source_location& operator=(source_location &&) = default;
std::uint_least32_t line() const noexcept {return line_num_;}
std::uint_least32_t column() const noexcept {return column_num_;}
std::uint_least32_t region() const noexcept {return region_size_;}
std::string const& file_name() const noexcept {return file_name_;}
std::string const& line_str() const noexcept {return line_str_;}
private:
std::uint_least32_t line_num_;
std::uint_least32_t column_num_;
std::uint_least32_t region_size_;
std::string file_name_;
std::string line_str_;
};
namespace detail
{
// internal error message generation.
inline std::string format_underline(const std::string& message,
const std::vector<std::pair<source_location, std::string>>& loc_com,
const std::vector<std::string>& helps = {},
const bool colorize = TOML11_ERROR_MESSAGE_COLORIZED)
{
std::size_t line_num_width = 0;
for(const auto& lc : loc_com)
{
std::uint_least32_t line = lc.first.line();
std::size_t digit = 0;
while(line != 0)
{
line /= 10;
digit += 1;
}
line_num_width = (std::max)(line_num_width, digit);
}
// 1 is the minimum width
line_num_width = std::max<std::size_t>(line_num_width, 1);
std::ostringstream retval;
if(colorize)
{
retval << color::colorize; // turn on ANSI color
}
// XXX
// Here, before `colorize` support, it does not output `[error]` prefix
// automatically. So some user may output it manually and this change may
// duplicate the prefix. To avoid it, check the first 7 characters and
// if it is "[error]", it removes that part from the message shown.
if(message.size() > 7 && message.substr(0, 7) == "[error]")
{
retval << color::bold << color::red << "[error]" << color::reset
<< color::bold << message.substr(7) << color::reset << '\n';
}
else
{
retval << color::bold << color::red << "[error] " << color::reset
<< color::bold << message << color::reset << '\n';
}
const auto format_one_location = [line_num_width]
(std::ostringstream& oss,
const source_location& loc, const std::string& comment) -> void
{
oss << ' ' << color::bold << color::blue
<< std::setw(static_cast<int>(line_num_width))
<< std::right << loc.line() << " | " << color::reset
<< loc.line_str() << '\n';
oss << make_string(line_num_width + 1, ' ')
<< color::bold << color::blue << " | " << color::reset
<< make_string(loc.column()-1 /*1-origin*/, ' ');
if(loc.region() == 1)
{
// invalid
// ^------
oss << color::bold << color::red << "^---" << color::reset;
}
else
{
// invalid
// ~~~~~~~
const auto underline_len = (std::min)(
static_cast<std::size_t>(loc.region()), loc.line_str().size());
oss << color::bold << color::red
<< make_string(underline_len, '~') << color::reset;
}
oss << ' ';
oss << comment;
return;
};
assert(!loc_com.empty());
// --> example.toml
// |
retval << color::bold << color::blue << " --> " << color::reset
<< loc_com.front().first.file_name() << '\n';
retval << make_string(line_num_width + 1, ' ')
<< color::bold << color::blue << " |\n" << color::reset;
// 1 | key value
// | ^--- missing =
format_one_location(retval, loc_com.front().first, loc_com.front().second);
// process the rest of the locations
for(std::size_t i=1; i<loc_com.size(); ++i)
{
const auto& prev = loc_com.at(i-1);
const auto& curr = loc_com.at(i);
retval << '\n';
// if the filenames are the same, print "..."
if(prev.first.file_name() == curr.first.file_name())
{
retval << color::bold << color::blue << " ...\n" << color::reset;
}
else // if filename differs, print " --> filename.toml" again
{
retval << color::bold << color::blue << " --> " << color::reset
<< curr.first.file_name() << '\n';
retval << make_string(line_num_width + 1, ' ')
<< color::bold << color::blue << " |\n" << color::reset;
}
format_one_location(retval, curr.first, curr.second);
}
if(!helps.empty())
{
retval << '\n';
retval << make_string(line_num_width + 1, ' ');
retval << color::bold << color::blue << " |" << color::reset;
for(const auto& help : helps)
{
retval << color::bold << "\nHint: " << color::reset;
retval << help;
}
}
return retval.str();
}
} // detail
} // toml
#endif// TOML11_SOURCE_LOCATION_HPP
| [
"rustacean@aliyun.com"
] | rustacean@aliyun.com |
9d55b35cd8cf74a4577990566defaac2a3d00386 | 791eec0e4c23fdee170be52b8106c86910c22683 | /Direct3D_Source/22강/ToolDXUT/ToolBasic00View.cpp | 2d4f6b578750b44180c816b5b8bb7da0e0e076a8 | [] | no_license | lthel1047/DirectX-3D-Programming | d06aabb7484bac1c5ec8a1346a0285f68183067b | f83192982cbf9cc8edbaba08aff6ef984b626e2c | refs/heads/master | 2020-06-04T21:09:23.328571 | 2019-01-17T03:19:22 | 2019-01-17T03:19:22 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 7,710 | cpp |
// ToolBasic00View.cpp : CToolBasic00View 클래스의 구현
//
#include "stdafx.h"
#include <Strsafe.h>
// SHARED_HANDLERS는 미리 보기, 축소판 그림 및 검색 필터 처리기를 구현하는 ATL 프로젝트에서 정의할 수 있으며
// 해당 프로젝트와 문서 코드를 공유하도록 해 줍니다.
#ifndef SHARED_HANDLERS
#include "ToolBasic00.h"
#endif
#include "ToolBasic00Doc.h"
#include "ToolBasic00View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CToolBasic00View
IMPLEMENT_DYNCREATE(CToolBasic00View, CView)
BEGIN_MESSAGE_MAP(CToolBasic00View, CView)
ON_WM_CONTEXTMENU()
ON_WM_RBUTTONUP()
// ON_WM_KEYDOWN()
//ON_WM_KEYDOWN()
END_MESSAGE_MAP()
// 전역 함수들
//--------------------------------------------------------------------------------------
// Rejects any D3D9 devices that aren't acceptable to the app by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsD3D9DeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat,
bool bWindowed, void* pUserContext )
{
// Typically want to skip back buffer formats that don't support alpha blending
IDirect3D9* pD3D = DXUTGetD3D9Object();
if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat ) ) )
return false;
return true;
}
//--------------------------------------------------------------------------------------
// Before a device is created, modify the device settings as needed
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
pDeviceSettings->d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
return true;
}
//--------------------------------------------------------------------------------------
// Create any D3D9 resources that will live through a device reset (D3DPOOL_MANAGED)
// and aren't tied to the back buffer size
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext )
{
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create any D3D9 resources that won't live through a device reset (D3DPOOL_DEFAULT)
// or that are tied to the back buffer size
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D9ResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext )
{
return S_OK;
}
//--------------------------------------------------------------------------------------
// Handle updates to the scene. This is called regardless of which D3D API is used
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
}
//--------------------------------------------------------------------------------------
// Render the scene using the D3D9 device
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D9FrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext )
{
HRESULT hr;
// Clear the render target and the zbuffer
V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB( 0, 45, 50, 170 ), 1.0f, 0 ) );
// Render the scene
if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
V( pd3dDevice->EndScene() );
}
}
//--------------------------------------------------------------------------------------
// Handle messages to the application
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam,
bool* pbNoFurtherProcessing, void* pUserContext )
{
return 0;
}
//--------------------------------------------------------------------------------------
// Release D3D9 resources created in the OnD3D9ResetDevice callback
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D9LostDevice( void* pUserContext )
{
}
//--------------------------------------------------------------------------------------
// Release D3D9 resources created in the OnD3D9CreateDevice callback
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D9DestroyDevice( void* pUserContext )
{
}
// CToolBasic00View 생성/소멸
CToolBasic00View::CToolBasic00View()
{
// TODO: 여기에 생성 코드를 추가합니다.
}
CToolBasic00View::~CToolBasic00View()
{
DXUTShutdown();
}
BOOL CToolBasic00View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: CREATESTRUCT cs를 수정하여 여기에서
// Window 클래스 또는 스타일을 수정합니다.
return CView::PreCreateWindow(cs);
}
// CToolBasic00View 그리기
void CToolBasic00View::OnDraw(CDC* /*pDC*/)
{
CToolBasic00Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 여기에 원시 데이터에 대한 그리기 코드를 추가합니다.
}
void CToolBasic00View::OnRButtonUp(UINT /* nFlags */, CPoint point)
{
ClientToScreen(&point);
OnContextMenu(this, point);
}
void CToolBasic00View::OnContextMenu(CWnd* /* pWnd */, CPoint point)
{
#ifndef SHARED_HANDLERS
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE);
#endif
}
// CToolBasic00View 진단
#ifdef _DEBUG
void CToolBasic00View::AssertValid() const
{
CView::AssertValid();
}
void CToolBasic00View::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CToolBasic00Doc* CToolBasic00View::GetDocument() const // 디버그되지 않은 버전은 인라인으로 지정됩니다.
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CToolBasic00Doc)));
return (CToolBasic00Doc*)m_pDocument;
}
#endif //_DEBUG
// CToolBasic00View 메시지 처리기
void CToolBasic00View::OnInitialUpdate()
{
CView::OnInitialUpdate();
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
// Set the callback functions
DXUTSetCallbackD3D9DeviceAcceptable( IsD3D9DeviceAcceptable );
DXUTSetCallbackD3D9DeviceCreated( OnD3D9CreateDevice );
DXUTSetCallbackD3D9DeviceReset( OnD3D9ResetDevice );
DXUTSetCallbackD3D9FrameRender( OnD3D9FrameRender );
DXUTSetCallbackD3D9DeviceLost( OnD3D9LostDevice );
DXUTSetCallbackD3D9DeviceDestroyed( OnD3D9DestroyDevice );
DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
DXUTSetCallbackFrameMove( OnFrameMove );
RECT rect;
DXUTInit( true, true);
DXUTSetWindow(m_hWnd, m_hWnd, m_hWnd, false );
GetClientRect(&rect);
DXUTCreateDevice( true, rect.right - rect.left, rect.bottom - rect.top);
}
LRESULT CToolBasic00View::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
LRESULT Result = CView::WindowProc(message, wParam, lParam);
DXUTStaticWndProc(m_hWnd, message, wParam, lParam );
return Result;
}
| [
"whdgkks12347@naver.com"
] | whdgkks12347@naver.com |
1e9932aa83558565ec790411596111b3a2ea4d27 | 68e02fef410f02124b2d91d159dd13924f9d5f78 | /Build/ncltech/OcTree.cpp | 057116bf1b954afafd2c490a7a160cb77e05ddc6 | [] | no_license | GiannhsHour/GameTechnologies | 8cc7efb5bf74e32a35a393a57ad47e0ed03e37dc | caeff1159b39c8a09c1fe2adbc1dbb952c35270e | refs/heads/master | 2021-09-03T23:30:05.343799 | 2018-01-12T20:45:04 | 2018-01-12T20:45:04 | 112,353,210 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,921 | cpp | #include "OcTree.h"
std::vector<OcTree*> OcTree::leaves = std::vector<OcTree*>();
bool OcTree::isActive = false;
int OcTree::capacity = 5;
bool OcTree::insert(PhysicsNode* p) {
// Ignore objects that do not belong in this OcTree
if (!boundary->containsObject(p))
return false; // object cannot be added
// If there is space in this OcTree, add the object here
if (objectsIn.size() < capacity && isLeaf())
{
objectsIn.push_back(p);
return true;
}
if (isLeaf()) {
this->subdivide();
for (int i = 0; i < objectsIn.size(); i++) {
for (int j = 0; j < 8; j++) {
children[j]->insert(objectsIn[i]);
}
}
}
for (int i = 0; i < 8; i++) {
(children[i]->insert(p));
}
return false;
}
void OcTree::subdivide() {
Vector3 cur_center = boundary->center;
float half_cur_dim = boundary->halfdim / 2.0f;
children.push_back(new OcTree(new AABB(Vector3(cur_center.x - half_cur_dim, cur_center.y - half_cur_dim, cur_center.z - half_cur_dim), half_cur_dim))); //topLeft ( down)
children.push_back(new OcTree(new AABB(Vector3(cur_center.x + half_cur_dim, cur_center.y - half_cur_dim, cur_center.z - half_cur_dim), half_cur_dim))); //topRight (down)
children.push_back(new OcTree(new AABB(Vector3(cur_center.x - half_cur_dim, cur_center.y - half_cur_dim, cur_center.z + half_cur_dim), half_cur_dim))); //botLeft (down)
children.push_back(new OcTree(new AABB(Vector3(cur_center.x + half_cur_dim, cur_center.y - half_cur_dim, cur_center.z + half_cur_dim), half_cur_dim))); //botRight (down)
children.push_back(new OcTree(new AABB(Vector3(cur_center.x - half_cur_dim, cur_center.y + half_cur_dim, cur_center.z - half_cur_dim), half_cur_dim))); //topLeft (up)
children.push_back(new OcTree(new AABB(Vector3(cur_center.x + half_cur_dim, cur_center.y + half_cur_dim, cur_center.z - half_cur_dim), half_cur_dim))); //topRight (up)
children.push_back(new OcTree(new AABB(Vector3(cur_center.x - half_cur_dim, cur_center.y + half_cur_dim, cur_center.z + half_cur_dim), half_cur_dim))); //botLeft (up)
children.push_back(new OcTree(new AABB(Vector3(cur_center.x + half_cur_dim, cur_center.y + half_cur_dim, cur_center.z + half_cur_dim), half_cur_dim))); //botRight (up)
}
void OcTree::populateLeaves(OcTree* root) {
if (root->isLeaf()) {
leaves.push_back(root);
}
else {
for (int i = 0; i < 8; i++) {
populateLeaves(root->children[i]);
}
}
}
void OcTree::deleteTree(OcTree* root) {
if (root) {
for (int i = 0; i < root->children.size(); i++) {
deleteTree(root->children[i]);
}
delete root;
}
}
void OcTree::draw(OcTree* root) {
if (root) {
for (int i = 0; i < root->children.size(); i++) {
draw(root->children[i]);
}
float d = 2 * root->boundary->halfdim;
Vector3 c1 = root->boundary->corner1;
Vector3 c2 = c1 + Vector3(-d, 0, 0);
Vector3 c3 = c2 + Vector3(0, 0, d);
Vector3 c4 = c3 + Vector3(d, 0, 0);
Vector3 c5 = root->boundary->corner2;
Vector3 c6 = c5 + Vector3(d, 0, 0);
Vector3 c7 = c6 + Vector3(0, 0, -d);
Vector3 c8 = c7 + Vector3(-d, 0, 0);
NCLDebug::DrawThickLine(c1, c2, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c2, c3, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c3, c4, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c1, c4, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c5, c6, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c6, c7, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c7, c8, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c5, c8, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c1, c7, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c4, c6, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c2, c8, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
NCLDebug::DrawThickLine(c3, c5, 0.1f, Vector4(0.0f, 1.0f, 0.0f, 1.0f));
}
} | [
"Giannhs@DESKTOP-PAOEACI"
] | Giannhs@DESKTOP-PAOEACI |
fc6708f1e202c0b8df42b6cafc4781ea2c1fc19b | bd0ca7e994dc35b071706231be1cc7177d224d5d | /ch4.3_virtual_constructor/4.3_virtual_constructor/PayOff3.h | ad2ba10884c702b18d85d1fa54d120a18694a59c | [] | no_license | zhongfaliao/C-Plus-Plus-Design-Patterns-and-Derivatives-Pricing | 25ddc33f9ef32cb1ab9bb96606e77e47bd7a0ce9 | 93e08aa50f4743cb96caeb41f7e774e1ae7dca79 | refs/heads/master | 2022-01-23T01:52:05.309181 | 2019-08-07T13:07:16 | 2019-08-07T13:07:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | h | //
// PayOff3.h
// 4.3_virtual_constructor
//
// Created by cheerzzh on 12/6/14.
// Copyright (c) 2014年 Jared Zhou. All rights reserved.
//
#ifndef ____3_virtual_constructor__PayOff3__
#define ____3_virtual_constructor__PayOff3__
#include <iostream>
class PayOff
{
public:
PayOff(){}
virtual double operator()(double Spot) const = 0;
virtual ~PayOff(){}
virtual PayOff* clone() const = 0; // virtual copy constructor
private:
};
class PayOffCall: public PayOff
{
public:
PayOffCall(double Strike_);
virtual double operator()(double Spot) const;
virtual ~PayOffCall(){}
virtual PayOff* clone() const;
private:
double Strike;
};
class PayOffPut: public PayOff
{
public:
PayOffPut(double Strike_);
virtual double operator()(double Spot) const;
virtual ~PayOffPut(){}
virtual PayOff* clone() const;
private:
double Strike;
};
#endif /* defined(____3_virtual_constructor__PayOff3__) */
| [
"cheerzzh@gmail.com"
] | cheerzzh@gmail.com |
1ba040b0dd1c982a257e0be6cd40fc86e57cf1d3 | afe7d19e29a79359b50cdf99ce4599dff1b19744 | /src/test/archiv1.h | 7e39c47280a68f56ec980b6b8fc9d6b62bfcc51a | [] | no_license | maot0341/ODBC-DFW | 0baee4a172b57f243328edd5a61493743da53421 | 6d351ea34667e0b27369d9f46a7d335f8397755b | refs/heads/master | 2021-09-02T10:13:05.522297 | 2012-02-19T09:11:58 | 2018-01-01T19:35:31 | 115,926,318 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 919 | h | // test.cpp : Definiert den Einsprungpunkt für die Konsolenanwendung.
//
#ifndef __ARCHIV1_H__
#define __ARCHIV1_H__
#include <assert.h>
#include <stdio.h>
#include "database.h"
//---------------------------------------------------------------------------
class CArchiv1
{
public:
CArchiv1 (CDatabase* db=0);
void open (CDatabase &);
void close();
void purge();
void create (long tid, const char * knz, long takt, long slots, bool erase=false);
void create (long tid, long slots=0, bool erase=true);
bool select (long tid);
void set (long nTid, time_t t, long slots, double *pValue, char * szMark);
bool get (long nTid, time_t t, long slots, double *pValue, char * szMark);
CDatabase * m_pDatabase;
char m_szTable[256];
HSTMT m_hCtrl;
HSTMT m_hData;
long m_nTid;
long m_nSlots;
time_t m_nTakt;
time_t m_nDate;
};
//---------------------------------------------------------------------------
#endif | [
"juvater@web.de"
] | juvater@web.de |
fc3fe5ddc272caf3e3fbb8e720057208e0f6c6da | b4c9a89b9acf805ba7d6beb43eac29d48d71944d | /tools/rawbufmaker/src/main.cpp | 20cb97c58f28920fb6cd7fb188efcffe916ca99d | [] | no_license | ufaith/mir2x | 5db0b5132c69cf63b4ce8e74b65b062164720feb | 2e08a371794372c346b0cd43934a8785bfedd133 | refs/heads/master | 2022-03-26T01:45:33.209809 | 2022-02-22T21:29:35 | 2022-02-22T21:29:35 | 93,562,935 | 1 | 0 | null | 2017-06-06T20:54:08 | 2017-06-06T20:54:08 | null | UTF-8 | C++ | false | false | 1,682 | cpp | /*
* =====================================================================================
*
* Filename: main.cpp
* Created: 07/20/2017 00:34:13
* Description:
*
* Version: 1.0
* Revision: none
* Compiler: gcc
*
* Author: ANHONG
* Email: anhonghe@gmail.com
*
* =====================================================================================
*/
#include <regex>
#include <cstdio>
#include <fstream>
#include <cinttypes>
#include "rawbuf.hpp"
#include "argparser.hpp"
static int cmd_help()
{
std::printf("--help:\n");
std::printf("--create-bin\n");
std::printf("--create-hex\n");
return 0;
}
static int cmd_create_hex(const argh::parser &cmd)
{
auto szInFileName = [&cmd]() -> std::string
{
if(!cmd(1)){
throw std::invalid_argument("no file provided");
}
return cmd[1];
}();
auto szOutFileName = [&cmd]() -> std::string
{
if(cmd["create-hex"]){
return "out.inc";
}else{
if(cmd("create-hex").str().empty()){
return "out.inc";
}else{
return cmd("create-hex").str();
}
}
}();
Rawbuf::buildHexFile(szInFileName.c_str(), szOutFileName.c_str(), 8);
return 0;
}
int main(int argc, char *argv[])
{
try{
arg_parser cmd(argc, argv);
if(cmd.has_option("help")){
return cmd_help();
}
if(cmd.has_option("create-hex")){
return cmd_create_hex(cmd);
}
}catch(std::exception &e){
std::printf("%s\n", e.what());
return -1;
}
return 0;
}
| [
"anhonghe@gmail.com"
] | anhonghe@gmail.com |
0e80377be7a0d6243461b70bcfe2f9a7980a5e5d | 58f965cbb405ef1c9e1444e4d9bf7061a6c34a85 | /deps/libgraphqlparser/dump_json_ast.cpp | de2402619978279dfdca2f44ac80ecc2bb8bf4f5 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown",
"MIT"
] | permissive | dosten/graphql-parser-php | 2bcae361da6e28c7aeb99d10545d0cef80ae89d1 | 9c9c87266e199524edec8f9a48c0dcb2769418e3 | refs/heads/master | 2021-01-11T00:47:12.778610 | 2019-10-30T11:31:27 | 2019-10-30T11:31:27 | 70,489,448 | 34 | 3 | MIT | 2019-10-30T11:31:28 | 2016-10-10T13:14:19 | PHP | UTF-8 | C++ | false | false | 1,041 | cpp | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "AstNode.h"
#include "GraphQLParser.h"
#include "c/GraphQLAstToJSON.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
using std::fopen;
using std::fclose;
using std::free;
int main(int argc, char **argv) {
const char *error;
FILE * in;
if (argc > 1) {
in = fopen(argv[1], "r");
} else {
in = stdin;
}
auto AST = facebook::graphql::parseFile(in, &error);
if (argc > 1) {
fclose(in);
}
if (!AST) {
cerr << "Parser failed with error: " << error << endl;
free((void *)error);
return 1;
}
const char *json = graphql_ast_to_json((const struct GraphQLAstNode *)AST.get());
puts(json);
free((void *)json);
return 0;
}
| [
"diego@saintesteben.me"
] | diego@saintesteben.me |
735b62524c8329130b3f11ca1275776e27e6ab86 | 61c06c7c2765df4a8ec147aee012301bf023ae2c | /Engine/SoundEngine_SFML/Listener.cpp | 6327dabdd5e0bfad78bfc1a9af3ad5519ec49389 | [] | no_license | swordlegend/ExcessiveTeam | da14ba3471c0357fedcce205e6ed28d537c9f0e7 | 0143301297252ca78d087f2d709e0fc342338289 | refs/heads/master | 2021-01-16T18:07:44.371989 | 2016-05-06T06:49:24 | 2016-05-06T06:49:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,143 | cpp | #include "Listener.h"
#include "SFML/Audio/Listener.hpp"
#include <cmath>
Listener::Listener() : dir(0, 0, -1), upwards(0, 1, 0){
}
void Listener::SetHandedness(sound::eHandedness newHandedness) {
//TODO move handedness to engine class
handedness = handedness;
}
void Listener::SetUpwards(const mm::vec3& newUp) {
upwards = mm::normalize(newUp);
}
void Listener::SetTarget(const mm::vec3& newTargetPos) {
dir = mm::normalize(newTargetPos - this->pos);
}
void Listener::SetDir(const mm::vec3& newDir) {
dir = mm::normalize(newDir);
}
void Listener::SetPos(const mm::vec3& newPos) {
pos = newPos;
}
void Listener::SetVel(const mm::vec3& newVel) {
vel = newVel;
}
sound::eHandedness Listener::GetHandedness() const {
return handedness;
}
mm::vec3 Listener::GetUpwards() const {
return upwards;
}
mm::vec3 Listener::GetDir() const {
return dir;
}
mm::vec3 Listener::GetPos() const {
return pos;
}
mm::vec3 Listener::GetVel() const {
return vel;
}
/*
mm::mat4 Listener::GetSFMLViewTransform() const {
//SFML has a right handed coordinate system where +Y is always up
//lets say that listener is always at origo
mm::mat4 result = mm::create_translation(-pos);
mm::vec3 left = mm::cross(upwards, dir);
mm::vec3 actualUpwards = mm::cross(dir, left);
float angleFromUpToY = std::acos(mm::dot(actualUpwards, mm::vec3(0, 1, 0)));
//rotate everything so that Y will be UP
//TODO check if Create rotation really takes angle in radians
result *= mm::create_rotation(angleFromUpToY, mm::cross(actualUpwards, mm::vec3(0, 1, 0)));
//at this point "listener direction" is on the x z pane, because the actual up direction was used for rotation.
//now rotate everything to make -Z forward (OpenGL style and i dont care)
mm::vec3 currentDir = mm::normalize(mm::vec3(dir.x, 0, dir.z));
float angleFromDirToNegZ = std::acos(mm::dot(currentDir, mm::vec3(0, 0, -1)));
result *= mm::create_rotation(angleFromDirToNegZ, mm::cross(currentDir, mm::vec3(0, 0, -1)));
//TODO handle handedness (what a good pun :D)
return result;
}
*/
| [
"kardospeter1994@hotmail.com"
] | kardospeter1994@hotmail.com |
d7d7ea712812c1c9c4bb9d5931d6c8f99081feac | c50d2b4595dbf6693e7870db6498b98c25b47037 | /main/main.cpp | a2e823780960ee40a9da55f0a59d88e3f42116b2 | [] | no_license | boobhsi/Qt-ParticleWidget | 719346637c4074febd7f05e43a77c68a5e4ecf46 | 3281531037edb328f5bb7486a2de6e8b426be13b | refs/heads/master | 2021-06-25T23:57:55.307239 | 2017-09-06T10:11:15 | 2017-09-06T10:11:15 | 98,858,307 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | cpp | #include "mainwindow.h"
#include <QApplication>
#include <QSurfaceFormat>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSurfaceFormat format;
format.setDepthBufferSize(24);
format.setStencilBufferSize(8);
format.setVersion(3, 2);
format.setProfile(QSurfaceFormat::CoreProfile);
QSurfaceFormat::setDefaultFormat(format);
MainWindow w;
w.show();
return a.exec();
}
| [
"marklinkzelda30609@gmail.com"
] | marklinkzelda30609@gmail.com |
dfe6cf1c8ffdfd2026682c9e531a9a8701ff6f75 | 1cee0bff588dbe579df00d90bc3bd6a0ad37de75 | /Game/GameDll/GameRulesClientServer.cpp | cf573543b660ef940d9a2f579ec9e82f64665158 | [] | no_license | highkings/CryGame | eb22941f9911b6a0319887e8246739a10ae1c7a4 | 6a8e11e06564d34974e3725a4adb99fe82f2e3ba | refs/heads/master | 2021-01-21T05:09:55.418666 | 2013-09-08T07:01:35 | 2013-09-08T07:01:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,333 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2005.
-------------------------------------------------------------------------
$Id$
$DateTime$
-------------------------------------------------------------------------
History:
- 23:5:2006 9:27 : Created by Marcio Martins
*************************************************************************/
#include "StdAfx.h"
#include "ScriptBind_GameRules.h"
#include "GameRules.h"
#include "Game.h"
#include "GameCVars.h"
#include "Actor.h"
#include "Player.h"
#include "IVehicleSystem.h"
#include "IItemSystem.h"
#include "IMaterialEffects.h"
#include "WeaponSystem.h"
#include "Radio.h"
#include "Audio/GameAudio.h"
#include "Audio/SoundMoods.h"
#include "Audio/BattleStatus.h"
#include "IWorldQuery.h"
#include <StlUtils.h>
#include "HUD/UIManager.h"
#include "HUD/UIMultiPlayer.h"
#include "HitDeathReactions.h"
#include "Network/Lobby/GameLobby.h"
#include "PlayerMovementController.h"
//------------------------------------------------------------------------
void CGameRules::ClientSimpleHit(const SimpleHitInfo &simpleHitInfo)
{
if (!simpleHitInfo.remote)
{
if (!gEnv->bServer)
GetGameObject()->InvokeRMI(SvRequestSimpleHit(), simpleHitInfo, eRMI_ToServer);
else
ServerSimpleHit(simpleHitInfo);
}
}
//------------------------------------------------------------------------
void CGameRules::ClientHit(const HitInfo &hitInfo)
{
FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);
IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();
IActor *pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(hitInfo.targetId);
if(pActor == pClientActor)
if (gEnv->pInput) gEnv->pInput->ForceFeedbackEvent( SFFOutputEvent(eDI_XI, eFF_Rumble_Basic, 0.5f * hitInfo.damage * 0.01f, hitInfo.damage * 0.02f, 0.0f));
CreateScriptHitInfo(m_scriptHitInfo, hitInfo);
CallScript(m_clientStateScript, "OnHit", m_scriptHitInfo);
bool backface = hitInfo.dir.Dot(hitInfo.normal)>0;
if (!hitInfo.remote && hitInfo.targetId && !backface)
{
if (!gEnv->bServer)
{
GetGameObject()->InvokeRMI(SvRequestHit(), hitInfo, eRMI_ToServer);
}
else
{
ServerHit(hitInfo);
}
if(gEnv->IsClient())
ProcessLocalHit(hitInfo);
}
}
//------------------------------------------------------------------------
void CGameRules::ServerSimpleHit(const SimpleHitInfo &simpleHitInfo)
{
switch (simpleHitInfo.type)
{
case 0: // tag
{
if (!simpleHitInfo.targetId)
return;
// tagged entities are temporary in MP, not in SP.
bool temp = gEnv->bMultiplayer;
AddTaggedEntity(simpleHitInfo.shooterId, simpleHitInfo.targetId, temp);
}
break;
case 1: // tac
{
if (!simpleHitInfo.targetId)
return;
CActor *pActor = (CActor *)gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(simpleHitInfo.targetId);
if (pActor && pActor->CanSleep())
pActor->Fall(Vec3(0.0f,0.0f,0.0f),simpleHitInfo.value);
}
break;
case 0xe: // freeze
{
if (!simpleHitInfo.targetId)
return;
// call OnFreeze
bool allow=true;
if (m_serverStateScript.GetPtr() && m_serverStateScript->GetValueType("OnFreeze")==svtFunction)
{
HSCRIPTFUNCTION func=0;
m_serverStateScript->GetValue("OnFreeze", func);
Script::CallReturn(m_serverStateScript->GetScriptSystem(), func, m_script, ScriptHandle(simpleHitInfo.targetId), ScriptHandle(simpleHitInfo.shooterId), ScriptHandle(simpleHitInfo.weaponId), simpleHitInfo.value, allow);
gEnv->pScriptSystem->ReleaseFunc(func);
}
if (!allow)
return;
if (IEntity *pEntity=gEnv->pEntitySystem->GetEntity(simpleHitInfo.targetId))
{
IScriptTable *pScriptTable=pEntity->GetScriptTable();
// call OnFrost
if (pScriptTable && pScriptTable->GetValueType("OnFrost")==svtFunction)
{
HSCRIPTFUNCTION func=0;
pScriptTable->GetValue("OnFrost", func);
Script::Call(pScriptTable->GetScriptSystem(), func, pScriptTable, ScriptHandle(simpleHitInfo.shooterId), ScriptHandle(simpleHitInfo.weaponId), simpleHitInfo.value);
gEnv->pScriptSystem->ReleaseFunc(func);
}
FreezeEntity(simpleHitInfo.targetId, true, true, simpleHitInfo.value>0.999f);
}
}
break;
default:
assert(!"Unknown Simple Hit type!");
}
}
//------------------------------------------------------------------------
void CGameRules::ServerHit(const HitInfo &hitInfo)
{
if (m_processingHit)
{
m_queuedHits.push(hitInfo);
return;
}
++m_processingHit;
ProcessServerHit(hitInfo);
while (!m_queuedHits.empty())
{
HitInfo info(m_queuedHits.front());
ProcessServerHit(info);
m_queuedHits.pop();
}
--m_processingHit;
}
//------------------------------------------------------------------------
void CGameRules::ProcessServerHit(const HitInfo &hitInfo)
{
bool ok=true;
// check if shooter is alive
CActor *pShooter = GetActorByEntityId(hitInfo.shooterId);
CActor *pTarget = GetActorByEntityId(hitInfo.targetId);
if (hitInfo.shooterId)
{
if (pShooter && pShooter->GetHealth()<=0)
ok=false;
}
if (hitInfo.targetId)
{
if (pTarget && pTarget->GetSpectatorMode())
ok=false;
}
if (ok)
{
float fTargetHealthBeforeHit = 0.0f;
if(pTarget)
{
fTargetHealthBeforeHit = pTarget->GetHealth();
}
CreateScriptHitInfo(m_scriptHitInfo, hitInfo);
CallScript(m_serverStateScript, "OnHit", m_scriptHitInfo);
if(pTarget && !pTarget->IsDead())
{
const float fCausedDamage = fTargetHealthBeforeHit - pTarget->GetHealth();
ProcessLocalHit(hitInfo, fCausedDamage);
}
// call hit listeners if any
if (m_hitListeners.empty() == false)
{
for (size_t i = 0; i < m_hitListeners.size(); )
{
size_t count = m_hitListeners.size();
m_hitListeners[i]->OnHit(hitInfo);
if (count == m_hitListeners.size())
i++;
else
continue;
}
}
if (pShooter && hitInfo.shooterId!=hitInfo.targetId && hitInfo.weaponId!=hitInfo.shooterId && hitInfo.weaponId!=hitInfo.targetId && hitInfo.damage>=0)
{
EntityId params[2];
params[0] = hitInfo.weaponId;
params[1] = hitInfo.targetId;
m_pGameplayRecorder->Event(pShooter->GetEntity(), GameplayEvent(eGE_WeaponHit, 0, 0, (void *)params));
}
if (pShooter)
m_pGameplayRecorder->Event(pShooter->GetEntity(), GameplayEvent(eGE_Hit, 0, 0, (void *)hitInfo.weaponId));
if (pShooter)
m_pGameplayRecorder->Event(pShooter->GetEntity(), GameplayEvent(eGE_Damage, 0, hitInfo.damage, (void *)hitInfo.weaponId));
}
}
void CGameRules::ProcessLocalHit( const HitInfo& hitInfo, float fCausedDamage /*= 0.0f*/ )
{
//Place the code that should be invoked in both server and client sides here
IActor* pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(hitInfo.targetId);
if (pActor != NULL && (pActor->GetActorClass() == CPlayer::GetActorClassType()))
{
// Clients sometimes want to force a hit death reaction to play (when the victim isnt actually dead.. but will be when the server responds to a hit req)
CHitDeathReactionsPtr pHitDeathReactions = static_cast<CPlayer*>(pActor)->GetHitDeathReactions();
if (pHitDeathReactions)
{
// If the user has requested the player be force killed, then we need to *react* like this was a kill
if(hitInfo.forceLocalKill)
{
// Force the hit death reaction to react as if was a kill
CActor::KillParams params;
params.shooterId = hitInfo.shooterId;
params.targetId = hitInfo.targetId;
params.weaponId = hitInfo.weaponId;
params.projectileId = hitInfo.projectileId;
params.itemIdToDrop = -1;
params.weaponClassId = hitInfo.weaponClassId;
params.damage = hitInfo.damage;
params.material = -1;
params.hit_type = hitInfo.type;
params.hit_joint = hitInfo.partId;
params.projectileClassId = hitInfo.projectileClassId;
params.penetration = hitInfo.penetrationCount;
params.firstKill = false;
params.killViaProxy = hitInfo.hitViaProxy;
params.impulseScale = hitInfo.impulseScale;
params.forceLocalKill = hitInfo.forceLocalKill;
pHitDeathReactions->OnKill(params);
}
else
{
// Proceed as normal
pHitDeathReactions->OnHit(hitInfo, fCausedDamage);
}
}
}
}
//------------------------------------------------------------------------
void CGameRules::ServerExplosion(const ExplosionInfo &explosionInfo)
{
m_queuedExplosions.push(explosionInfo);
}
//------------------------------------------------------------------------
void CGameRules::ProcessServerExplosion(const ExplosionInfo &explosionInfo)
{
//CryLog("[ProcessServerExplosion] (frame %i) shooter %i, damage %.0f, radius %.1f", gEnv->pRenderer->GetFrameID(), explosionInfo.shooterId, explosionInfo.damage, explosionInfo.radius);
GetGameObject()->InvokeRMI(ClExplosion(), explosionInfo, eRMI_ToRemoteClients);
ClientExplosion(explosionInfo);
}
//------------------------------------------------------------------------
void CGameRules::ProcessQueuedExplosions()
{
const static uint8 nMaxExp = 3;
for (uint8 exp=0; !m_queuedExplosions.empty() && exp<nMaxExp; ++exp)
{
ExplosionInfo info(m_queuedExplosions.front());
ProcessServerExplosion(info);
m_queuedExplosions.pop();
}
}
//------------------------------------------------------------------------
void CGameRules::KnockActorDown( EntityId actorEntityId )
{
// Forbid fall and play if the actor is playing a hit/death reaction
CActor* pHitActor = static_cast<CActor*>(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor( actorEntityId ));
if (pHitActor)
{
if (pHitActor->GetActorClass() == CPlayer::GetActorClassType())
{
// Don't trigger Fall and Play if the actor is playing a hit reaction
CPlayer* pHitPlayer = static_cast<CPlayer*>(pHitActor);
CHitDeathReactionsConstPtr pHitDeathReactions = pHitPlayer->GetHitDeathReactions();
if (!pHitDeathReactions || !pHitDeathReactions->IsInReaction())
pHitActor->Fall();
}
else
pHitActor->Fall();
}
}
//------------------------------------------------------------------------
void CGameRules::CullEntitiesInExplosion(const ExplosionInfo &explosionInfo)
{
if (!g_pGameCVars->g_ec_enable || explosionInfo.damage <= 0.1f)
return;
IPhysicalEntity **pents;
float radiusScale = g_pGameCVars->g_ec_radiusScale;
float minVolume = g_pGameCVars->g_ec_volume;
float minExtent = g_pGameCVars->g_ec_extent;
int removeThreshold = max(1, g_pGameCVars->g_ec_removeThreshold);
IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();
Vec3 radiusVec(radiusScale * explosionInfo.physRadius);
int i = gEnv->pPhysicalWorld->GetEntitiesInBox(explosionInfo.pos-radiusVec,explosionInfo.pos+radiusVec,pents, ent_rigid|ent_sleeping_rigid);
int removedCount = 0;
static IEntityClass* s_pInteractiveEntityClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass("InteractiveEntity");
static IEntityClass* s_pDeadBodyClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass("DeadBody");
if (i > removeThreshold)
{
int entitiesToRemove = i - removeThreshold;
for(--i;i>=0;i--)
{
if(removedCount>=entitiesToRemove)
break;
IEntity * pEntity = (IEntity*) pents[i]->GetForeignData(PHYS_FOREIGN_ID_ENTITY);
if (pEntity)
{
// don't remove if entity is held by the player
if (pClientActor && pEntity->GetId()==pClientActor->GetGrabbedEntityId())
continue;
// don't remove items/pickups
if (IItem* pItem = g_pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pEntity->GetId()))
{
continue;
}
// don't remove enemies/ragdolls
if (IActor* pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(pEntity->GetId()))
{
continue;
}
// if there is a flowgraph attached, never remove!
if (pEntity->GetProxy(ENTITY_PROXY_FLOWGRAPH) != 0)
continue;
IEntityClass* pClass = pEntity->GetClass();
if (pClass == s_pInteractiveEntityClass || pClass == s_pDeadBodyClass)
continue;
// get bounding box
if (IEntityPhysicalProxy* pPhysProxy = (IEntityPhysicalProxy*)pEntity->GetProxy(ENTITY_PROXY_PHYSICS))
{
AABB aabb;
pPhysProxy->GetWorldBounds(aabb);
// don't remove objects which are larger than a predefined minimum volume
if (aabb.GetVolume() > minVolume)
continue;
// don't remove objects which are larger than a predefined minimum volume
Vec3 size(aabb.GetSize().abs());
if (size.x > minExtent || size.y > minExtent || size.z > minExtent)
continue;
}
// marcok: somehow editor doesn't handle deleting non-dynamic entities very well
// but craig says, hiding is not synchronized for DX11 breakable MP, so we remove entities only when playing pure game
// alexl: in SinglePlayer, we also currently only hide the object because it could be part of flowgraph logic
// which would break if Entity was removed and could not propagate events anymore
if (gEnv->bMultiplayer == false || gEnv->IsEditor())
{
pEntity->Hide(true);
}
else
{
gEnv->pEntitySystem->RemoveEntity(pEntity->GetId());
}
removedCount++;
}
}
}
}
//------------------------------------------------------------------------
void CGameRules::ClientExplosion(const ExplosionInfo &explosionInfo)
{
// let 3D engine know about explosion (will create holes and remove vegetation)
if (explosionInfo.hole_size > 1.0f && gEnv->p3DEngine->GetIVoxTerrain())
{
gEnv->p3DEngine->OnExplosion(explosionInfo.pos, explosionInfo.hole_size, true);
}
TExplosionAffectedEntities affectedEntities;
if (gEnv->bServer)
{
CullEntitiesInExplosion(explosionInfo);
pe_explosion explosion;
explosion.epicenter = explosionInfo.pos;
explosion.rmin = explosionInfo.minRadius;
explosion.rmax = explosionInfo.radius;
if (explosion.rmax==0)
explosion.rmax=0.0001f;
explosion.r = explosion.rmin;
explosion.impulsivePressureAtR = explosionInfo.pressure;
explosion.epicenterImp = explosionInfo.pos;
explosion.explDir = explosionInfo.dir;
explosion.nGrow = 0;
explosion.rminOcc = 0.07f;
// we separate the calls to SimulateExplosion so that we can define different radii for AI and physics bodies
explosion.holeSize = 0.0f;
explosion.nOccRes = explosion.rmax>50.0f ? 0:16;
gEnv->pPhysicalWorld->SimulateExplosion( &explosion, 0, 0, ent_living);
CreateScriptExplosionInfo(m_scriptExplosionInfo, explosionInfo);
UpdateAffectedEntitiesSet(affectedEntities, &explosion);
// check vehicles
IVehicleSystem *pVehicleSystem = g_pGame->GetIGameFramework()->GetIVehicleSystem();
uint32 vcount = pVehicleSystem->GetVehicleCount();
if (vcount > 0)
{
IVehicleIteratorPtr iter = g_pGame->GetIGameFramework()->GetIVehicleSystem()->CreateVehicleIterator();
while (IVehicle* pVehicle = iter->Next())
{
if(IEntity *pEntity = pVehicle->GetEntity())
{
AABB aabb;
pEntity->GetWorldBounds(aabb);
IPhysicalEntity* pEnt = pEntity->GetPhysics();
if (pEnt && aabb.GetDistanceSqr(explosionInfo.pos) <= explosionInfo.radius*explosionInfo.radius)
{
float affected = gEnv->pPhysicalWorld->CalculateExplosionExposure(&explosion, pEnt);
AddOrUpdateAffectedEntity(affectedEntities, pEntity, affected);
}
}
}
}
explosion.rmin = explosionInfo.minPhysRadius;
explosion.rmax = explosionInfo.physRadius;
if (explosion.rmax==0)
explosion.rmax=0.0001f;
explosion.r = explosion.rmin;
explosion.holeSize = explosionInfo.hole_size;
if (explosion.nOccRes>0)
explosion.nOccRes = -1; // makes second call re-use occlusion info
gEnv->pPhysicalWorld->SimulateExplosion( &explosion, 0, 0, ent_rigid|ent_sleeping_rigid|ent_independent|ent_static | ent_delayed_deformations);
UpdateAffectedEntitiesSet(affectedEntities, &explosion);
CommitAffectedEntitiesSet(m_scriptExplosionInfo, affectedEntities);
float fSuitEnergyBeforeExplosion = 0.0f;
float fHealthBeforeExplosion = 0.0f;
IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();
if(pClientActor)
{
fHealthBeforeExplosion = (float)pClientActor->GetHealth();
}
CallScript(m_serverStateScript, "OnExplosion", m_scriptExplosionInfo);
if(pClientActor)
{
float fDeltaHealth = fHealthBeforeExplosion - static_cast<CPlayer *>(pClientActor)->GetHealth();
if(fDeltaHealth >= 20.0f)
{
SAFE_GAMEAUDIO_SOUNDMOODS_FUNC(AddSoundMood(SOUNDMOOD_EXPLOSION, MIN(fDeltaHealth, 100.0f) ));
}
}
// call hit listeners if any
if (m_hitListeners.empty() == false)
{
for (size_t i = 0; i < m_hitListeners.size(); )
{
size_t count = m_hitListeners.size();
m_hitListeners[i]->OnServerExplosion(explosionInfo);
if (count == m_hitListeners.size())
i++;
else
continue;
}
}
}
if (gEnv->IsClient())
{
if (explosionInfo.pParticleEffect)
explosionInfo.pParticleEffect->Spawn(true, IParticleEffect::ParticleLoc(explosionInfo.pos, explosionInfo.dir, explosionInfo.effect_scale));
if (!gEnv->bServer)
{
CreateScriptExplosionInfo(m_scriptExplosionInfo, explosionInfo);
}
else
{
affectedEntities.clear();
CommitAffectedEntitiesSet(m_scriptExplosionInfo, affectedEntities);
}
CallScript(m_clientStateScript, "OnExplosion", m_scriptExplosionInfo);
// call hit listeners if any
if (m_hitListeners.empty() == false)
{
THitListenerVec::iterator iter = m_hitListeners.begin();
while (iter != m_hitListeners.end())
{
(*iter)->OnExplosion(explosionInfo);
++iter;
}
}
}
ProcessClientExplosionScreenFX(explosionInfo);
ProcessExplosionMaterialFX(explosionInfo);
if (gEnv->pAISystem && !gEnv->bMultiplayer)
{
// Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
EntityId ownerId = explosionInfo.shooterId;
IActor* pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(ownerId);
if (pActor && pActor->GetLinkedVehicle() && pActor->GetLinkedVehicle()->GetEntityId())
ownerId = pActor->GetLinkedVehicle()->GetEntityId();
if (ownerId != 0)
{
SAIStimulus stim(AISTIM_EXPLOSION, 0, ownerId, 0,
explosionInfo.pos, ZERO, explosionInfo.radius);
gEnv->pAISystem->RegisterStimulus(stim);
SAIStimulus stimSound(AISTIM_SOUND, AISOUND_EXPLOSION, ownerId, 0,
explosionInfo.pos, ZERO, explosionInfo.radius * 3.0f, AISTIMPROC_FILTER_LINK_WITH_PREVIOUS);
gEnv->pAISystem->RegisterStimulus(stimSound);
}
}
}
//-------------------------------------------
void CGameRules::ProcessClientExplosionScreenFX(const ExplosionInfo &explosionInfo)
{
IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();
if (pClientActor)
{
//Distance
float dist = (pClientActor->GetEntity()->GetWorldPos() - explosionInfo.pos).len();
//Is the explosion in Player's FOV (let's suppose the FOV a bit higher, like 80)
CActor *pActor = (CActor *)pClientActor;
SMovementState state;
if (IMovementController *pMV = pActor->GetMovementController())
{
pMV->GetMovementState(state);
}
Vec3 eyeToExplosion = explosionInfo.pos - state.eyePosition;
eyeToExplosion.Normalize();
bool inFOV = (state.eyeDirection.Dot(eyeToExplosion) > 0.68f);
// if in a vehicle eyeDirection is wrong
if(pActor && pActor->GetLinkedVehicle())
{
Vec3 eyeDir = static_cast<CPlayer*>(pActor)->GetVehicleViewDir();
inFOV = (eyeDir.Dot(eyeToExplosion) > 0.68f);
}
//All explosions have radial blur (default 30m radius, to make Sean happy =))
float maxBlurDistance = (explosionInfo.maxblurdistance>0.0f)?explosionInfo.maxblurdistance:30.0f;
if (maxBlurDistance>0.0f && g_pGameCVars->g_radialBlur>0.0f && m_explosionScreenFX && explosionInfo.radius>0.5f)
{
if (inFOV && dist < maxBlurDistance)
{
ray_hit hit;
int col = gEnv->pPhysicalWorld->RayWorldIntersection(explosionInfo.pos , -eyeToExplosion*dist, ent_static | ent_terrain, rwi_stop_at_pierceable|rwi_colltype_any, &hit, 1);
//If there was no obstacle between flashbang grenade and player
if(!col)
{
if (CScreenEffects* pSE = pActor->GetScreenEffects())
{
float blurRadius = (-1.0f/maxBlurDistance)*dist + 1.0f;
gEnv->p3DEngine->SetPostEffectParam("FilterRadialBlurring_Radius", blurRadius);
gEnv->p3DEngine->SetPostEffectParam("FilterRadialBlurring_Amount", 1.0f);
IBlendedEffect *pBlur = CBlendedEffect<CPostProcessEffect>::Create(CPostProcessEffect(pClientActor->GetEntityId(),"FilterRadialBlurring_Amount", 0.0f));
IBlendType *pLinear = CBlendType<CLinearBlend>::Create(CLinearBlend(1.0f));
pSE->StartBlend(pBlur, pLinear, 1.0f, CScreenEffects::eSFX_GID_RBlur);
pSE->SetUpdateCoords("FilterRadialBlurring_ScreenPosX","FilterRadialBlurring_ScreenPosY", explosionInfo.pos);
}
float distAmp = 1.0f - (dist / maxBlurDistance);
if (gEnv->pInput)
gEnv->pInput->ForceFeedbackEvent( SFFOutputEvent(eDI_XI, eFF_Rumble_Basic, 0.5f, distAmp*3.0f, 0.0f));
}
}
}
//Flashbang effect
if(dist<explosionInfo.radius && inFOV &&
(!strcmp(explosionInfo.effect_class,"flashbang") || !strcmp(explosionInfo.effect_class,"FlashbangAI")))
{
ray_hit hit;
int col = gEnv->pPhysicalWorld->RayWorldIntersection(explosionInfo.pos , -eyeToExplosion*dist, ent_static | ent_terrain, rwi_stop_at_pierceable|rwi_colltype_any, &hit, 1);
//If there was no obstacle between flashbang grenade and player
if(!col)
{
float power = explosionInfo.flashbangScale;
power *= max(0.0f, 1 - (dist/explosionInfo.radius));
float lookingAt = (eyeToExplosion.Dot(state.eyeDirection.normalize()) + 1)*0.5f;
power *= lookingAt;
SAFE_GAMEAUDIO_SOUNDMOODS_FUNC(AddSoundMood(SOUNDMOOD_EXPLOSION,MIN(power*40.0f,100.0f)));
gEnv->p3DEngine->SetPostEffectParam("Flashbang_Time", 1.0f + (power * 4));
gEnv->p3DEngine->SetPostEffectParam("FlashBang_BlindAmount",explosionInfo.blindAmount);
gEnv->p3DEngine->SetPostEffectParam("Flashbang_DifractionAmount", (power * 2));
gEnv->p3DEngine->SetPostEffectParam("Flashbang_Active", 1);
}
}
else if(inFOV && (dist < explosionInfo.radius))
{
if (explosionInfo.damage>10.0f || explosionInfo.pressure>100.0f)
{
//Add some angular impulse to the client actor depending on distance, direction...
float dt = (1.0f - dist/explosionInfo.radius);
dt = dt * dt;
float angleZ = gf_PI*0.15f*dt;
float angleX = gf_PI*0.15f*dt;
pActor->AddAngularImpulse(Ang3(Random(-angleX*0.5f,angleX),0.0f,Random(-angleZ,angleZ)),0.0f,dt*2.0f);
}
}
float fDist2=(pClientActor->GetEntity()->GetWorldPos()-explosionInfo.pos).len2();
if (fDist2<250.0f*250.0f)
{
if (fDist2<sqr(SAFE_GAMEAUDIO_BATTLESTATUS_FUNC_RET(GetBattleRange())))
SAFE_GAMEAUDIO_BATTLESTATUS_FUNC(TickBattleStatus(1.0f));
}
}
}
//---------------------------------------------------
void CGameRules::UpdateScoreBoardItem(EntityId id, const string name, int kills, int deaths)
{
NOTIFY_UI_MP( UpdateScoreBoardItem(id, name, kills, deaths) );
}
//---------------------------------------------------
void CGameRules::ProcessExplosionMaterialFX(const ExplosionInfo &explosionInfo)
{
// if an effect was specified, don't use MFX
if (explosionInfo.pParticleEffect)
return;
// impact stuff here
SMFXRunTimeEffectParams params;
params.soundSemantic = eSoundSemantic_Explosion;
params.pos = params.decalPos = explosionInfo.pos;
params.trg = 0;
params.trgRenderNode = 0;
Vec3 gravity;
pe_params_buoyancy buoyancy;
gEnv->pPhysicalWorld->CheckAreas(params.pos, gravity, &buoyancy);
// 0 for water, 1 for air
Vec3 pos=params.pos;
params.inWater = (buoyancy.waterPlane.origin.z > params.pos.z) && (gEnv->p3DEngine->GetWaterLevel(&pos)>=params.pos.z);
params.inZeroG = (gravity.len2() < 0.0001f);
params.trgSurfaceId = 0;
static const int objTypes = ent_all;
static const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any;
ray_hit ray;
if (explosionInfo.impact)
{
params.dir[0] = explosionInfo.impact_velocity.normalized();
params.normal = explosionInfo.impact_normal;
if (gEnv->pPhysicalWorld->RayWorldIntersection(params.pos-params.dir[0]*0.0125f, params.dir[0]*0.25f, objTypes, flags, &ray, 1))
{
params.trgSurfaceId = ray.surface_idx;
if (ray.pCollider->GetiForeignData()==PHYS_FOREIGN_ID_STATIC)
params.trgRenderNode = (IRenderNode*)ray.pCollider->GetForeignData(PHYS_FOREIGN_ID_STATIC);
}
}
else
{
params.dir[0] = gravity;
params.normal = -gravity.normalized();
if (gEnv->pPhysicalWorld->RayWorldIntersection(params.pos, gravity, objTypes, flags, &ray, 1))
{
params.trgSurfaceId = ray.surface_idx;
if (ray.pCollider->GetiForeignData()==PHYS_FOREIGN_ID_STATIC)
params.trgRenderNode = (IRenderNode*)ray.pCollider->GetForeignData(PHYS_FOREIGN_ID_STATIC);
}
}
string effectClass = explosionInfo.effect_class;
if (effectClass.empty())
effectClass = "generic";
string query = effectClass + "_explode";
if(gEnv->p3DEngine->GetWaterLevel(&explosionInfo.pos)>explosionInfo.pos.z)
query = query + "_underwater";
if(IMaterialEffects* pMaterialEffects = gEnv->pGame->GetIGameFramework()->GetIMaterialEffects())
{
TMFXEffectId effectId = pMaterialEffects->GetEffectId(query.c_str(), params.trgSurfaceId);
if (effectId == InvalidEffectId)
effectId = pMaterialEffects->GetEffectId(query.c_str(), pMaterialEffects->GetDefaultSurfaceIndex());
if (effectId != InvalidEffectId)
pMaterialEffects->ExecuteEffect(effectId, params);
}
}
//------------------------------------------------------------------------
// RMI
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestRename)
{
CActor *pActor = GetActorByEntityId(params.entityId);
if (!pActor)
return true;
RenamePlayer(pActor, params.name.c_str());
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClRenameEntity)
{
IEntity *pEntity=gEnv->pEntitySystem->GetEntity(params.entityId);
if (pEntity)
{
string old=pEntity->GetName();
pEntity->SetName(params.name.c_str());
CryLogAlways("$8%s$o renamed to $8%s", old.c_str(), params.name.c_str());
NOTIFY_UI_MP( PlayerRenamed( params.entityId, params.name ) );
// if this was a remote player, check we're not spectating them.
// If we are, we need to trigger a spectator hud update for the new name
EntityId clientId = g_pGame->GetIGameFramework()->GetClientActorId();
if(gEnv->bMultiplayer && params.entityId != clientId)
{
CActor* pClientActor = static_cast<CActor *>(g_pGame->GetIGameFramework()->GetClientActor());
}
}
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestChatMessage)
{
SendChatMessage((EChatMessageType)params.type, params.sourceId, params.targetId, params.msg.c_str());
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClChatMessage)
{
OnChatMessage((EChatMessageType)params.type, params.sourceId, params.targetId, params.msg.c_str(), params.onlyTeam);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClForbiddenAreaWarning)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestRadioMessage)
{
SendRadioMessage(params.sourceId,params.msg);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClRadioMessage)
{
OnRadioMessage(params.sourceId,params.msg);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestChangeTeam)
{
CActor *pActor = GetActorByEntityId(params.entityId);
if (!pActor)
return true;
ChangeTeam(pActor, params.teamId);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestSpectatorMode)
{
CActor *pActor = GetActorByEntityId(params.entityId);
if (!pActor)
return true;
ChangeSpectatorMode(pActor, params.mode, params.targetId, params.resetAll);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetTeam)
{
if (!params.entityId) // ignore these for now
return true;
int oldTeam = GetTeam(params.entityId);
if (oldTeam==params.teamId)
return true;
TEntityTeamIdMap::iterator it=m_entityteams.find(params.entityId);
if (it!=m_entityteams.end())
m_entityteams.erase(it);
IActor *pActor=m_pActorSystem->GetActor(params.entityId);
bool isplayer=pActor!=0;
if (isplayer && oldTeam)
{
TPlayerTeamIdMap::iterator pit=m_playerteams.find(oldTeam);
assert(pit!=m_playerteams.end());
stl::find_and_erase(pit->second, params.entityId);
}
if (params.teamId)
{
m_entityteams.insert(TEntityTeamIdMap::value_type(params.entityId, params.teamId));
if (isplayer)
{
TPlayerTeamIdMap::iterator pit=m_playerteams.find(params.teamId);
assert(pit!=m_playerteams.end());
pit->second.push_back(params.entityId);
}
}
if(isplayer)
{
ReconfigureVoiceGroups(params.entityId,oldTeam,params.teamId);
if (pActor->IsClient())
m_pRadio->SetTeam(GetTeamName(params.teamId));
}
ScriptHandle handle(params.entityId);
CallScript(m_clientStateScript, "OnSetTeam", handle, params.teamId);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClTextMessage)
{
OnTextMessage((ETextMessageType)params.type, params.msg.c_str(),
params.params[0].empty()?0:params.params[0].c_str(),
params.params[1].empty()?0:params.params[1].c_str(),
params.params[2].empty()?0:params.params[2].c_str(),
params.params[3].empty()?0:params.params[3].c_str()
);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestSimpleHit)
{
ServerSimpleHit(params);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvRequestHit)
{
HitInfo info(params);
info.remote=true;
ServerHit(info);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClExplosion)
{
ClientExplosion(params);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClFreezeEntity)
{
//IEntity *pEntity=gEnv->pEntitySystem->GetEntity(params.entityId);
//CryLogAlways("ClFreezeEntity: %s %s", pEntity?pEntity->GetName():"<<null>>", params.freeze?"true":"false");
FreezeEntity(params.entityId, params.freeze, 0);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClShatterEntity)
{
ShatterEntity(params.entityId, params.pos, params.impulse);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetGameTime)
{
m_endTime = params.endTime;
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetRoundTime)
{
m_roundEndTime = params.endTime;
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetPreRoundTime)
{
m_preRoundEndTime = params.endTime;
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetReviveCycleTime)
{
m_reviveCycleEndTime = params.endTime;
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetGameStartTimer)
{
m_gameStartTime = params.endTime;
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClTaggedEntity)
{
if (!params.entityId)
return true;
SEntityEvent scriptEvent( ENTITY_EVENT_SCRIPT_EVENT );
scriptEvent.nParam[0] = (INT_PTR)"OnGPSTagged";
scriptEvent.nParam[1] = IEntityClass::EVT_BOOL;
bool bValue = true;
scriptEvent.nParam[2] = (INT_PTR)&bValue;
IEntity *pEntity = gEnv->pEntitySystem->GetEntity(params.entityId);
if (pEntity)
pEntity->SendEvent( scriptEvent );
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClTempRadarEntity)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClAddSpawnGroup)
{
AddSpawnGroup(params.entityId);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClRemoveSpawnGroup)
{
RemoveSpawnGroup(params.entityId);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClAddMinimapEntity)
{
AddMinimapEntity(params.entityId, params.type, params.lifetime);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClRemoveMinimapEntity)
{
RemoveMinimapEntity(params.entityId);
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClResetMinimap)
{
ResetMinimap();
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetObjective)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetObjectiveStatus)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClSetObjectiveEntity)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClResetObjectives)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClHitIndicator)
{
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, ClDamageIndicator)
{
Vec3 dir(ZERO);
bool vehicle=false;
if (IEntity *pEntity=gEnv->pEntitySystem->GetEntity(params.shooterId))
{
if (IActor *pLocal=m_pGameFramework->GetClientActor())
{
dir=(pLocal->GetEntity()->GetWorldPos()-pEntity->GetWorldPos());
dir.NormalizeSafe();
vehicle=(pLocal->GetLinkedVehicle()!=0);
}
}
return true;
}
//------------------------------------------------------------------------
IMPLEMENT_RMI(CGameRules, SvVote)
{
CActor* pActor = GetActorByChannelId(m_pGameFramework->GetGameChannelId(pNetChannel));
if(pActor)
Vote(pActor, true);
return true;
}
IMPLEMENT_RMI(CGameRules, SvVoteNo)
{
CActor* pActor = GetActorByChannelId(m_pGameFramework->GetGameChannelId(pNetChannel));
if(pActor)
Vote(pActor, false);
return true;
}
IMPLEMENT_RMI(CGameRules, SvStartVoting)
{
CActor* pActor = GetActorByChannelId(m_pGameFramework->GetGameChannelId(pNetChannel));
if(pActor)
StartVoting(pActor,params.vote_type,params.entityId,params.param);
return true;
}
IMPLEMENT_RMI(CGameRules, ClVotingStatus)
{
return true;
}
IMPLEMENT_RMI(CGameRules, ClEnteredGame)
{
CPlayer *pClientActor = static_cast<CPlayer*>(m_pGameFramework->GetClientActor());
if (pClientActor)
{
IEntity *pClientEntity = pClientActor->GetEntity();
const EntityId clientEntityId = pClientEntity->GetId();
if(!gEnv->bServer)
{
int status[2];
status[0] = GetTeam(clientEntityId);
status[1] = pClientActor->GetSpectatorMode();
m_pGameplayRecorder->Event(pClientEntity, GameplayEvent(eGE_Connected, 0, 0, (void*)status));
}
if (g_pGame->GetHostMigrationState() != CGame::eHMS_NotMigrating)
{
eHostMigrationState hostMigrationState = g_pGame->GetGameLobby()->GetMatchMakingHostMigrationState();
if (hostMigrationState < eHMS_ReconnectClient)
{
CryLog("CGameRules::ClEnteredGame() received a left over message from previous server, ignoring it");
return true;
}
CryLog("CGameRules::ClEnteredGame() We have our client actor ('%s'), send migration params", pClientEntity->GetName());
// Request various bits
GetGameObject()->InvokeRMI(SvHostMigrationRequestSetup(), *m_pHostMigrationParams, eRMI_ToServer);
SAFE_DELETE(m_pHostMigrationParams);
pClientActor->GetEntity()->SetPos(m_pHostMigrationClientParams->m_position);
pClientActor->SetViewRotation(m_pHostMigrationClientParams->m_viewQuat);
if (m_pHostMigrationClientParams->m_hasValidVelocity)
{
pe_action_set_velocity actionVel;
actionVel.v = m_pHostMigrationClientParams->m_velocity;
actionVel.w.zero();
IPhysicalEntity *pPhysicalEntity = pClientEntity->GetPhysics();
if (pPhysicalEntity)
{
pPhysicalEntity->Action(&actionVel);
}
}
CPlayerMovementController *pPMC = static_cast<CPlayerMovementController *>(pClientActor->GetMovementController());
if (pPMC)
{
// Force an update through so that the aim direction gets set correctly
pPMC->PostUpdate(0.f);
}
if (m_pHostMigrationClientParams->m_pSelectedItemClass)
{
CItem *pItem = pClientActor->GetItemByClass(m_pHostMigrationClientParams->m_pSelectedItemClass);
if (pItem)
{
EntityId itemId = pItem->GetEntityId();
if (pClientActor->GetCurrentItemId() != itemId)
{
pClientActor->SelectItem(itemId, false);
}
}
}
m_pHostMigrationClientParams->m_doneEnteredGame = true;
if (m_pHostMigrationClientParams->IsDone())
{
SAFE_DELETE(m_pHostMigrationClientParams);
}
if (!gEnv->bServer)
{
// todo: ui
}
m_hostMigrationClientHasRejoined = true;
}
else
{
NOTIFY_UI_MP( EnteredGame() );
}
}
return true;
}
IMPLEMENT_RMI(CGameRules, ClPlayerJoined)
{
NOTIFY_UI_MP( PlayerJoined(params.entityId, params.name) );
return true;
}
IMPLEMENT_RMI(CGameRules, ClPlayerLeft)
{
NOTIFY_UI_MP( PlayerLeft(params.entityId, params.name) );
return true;
}
| [
"nomail"
] | nomail |
3a9e7fc511301502a901a307b7522b09983ca796 | 534e2e3d8d8bebd2366c0fee60886d84597ee0ef | /atcoder/Keyence2020_pE.cpp | 2d44042f611ff9977ed2d24cdc7228238492aade | [] | no_license | coldEr66/online-judge | a8844d3f35755adafd4f43a1f08ce56b6b870601 | e85ec0750d92dd00133c93284085a0f5d8a11d36 | refs/heads/master | 2021-09-07T01:58:10.634492 | 2021-07-28T16:31:13 | 2021-07-28T16:31:13 | 128,494,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,254 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double lf;
typedef pair<int,int> ii;
typedef pair<ii,int> iii;
#define REP(i,n) for(int i=0;i<n;i++)
#define REP1(i,n) for(int i=1;i<=n;i++)
#define RST(i,n) memset(i,n,sizeof i)
#define SZ(a) (int)a.size()
#define ALL(a) a.begin(),a.end()
#define X first
#define Y second
#define eb emplace_back
#ifdef cold66
#define debug(...) do{\
fprintf(stderr,"LINE %d: (%s) = ",__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<", ";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#define IOS()
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#endif // cold66
//}
template<class T> inline bool chkmax(T &a, const T &b) { return b > a ? a = b, true : false; }
template<class T> inline bool chkmin(T &a, const T &b) { return b < a ? a = b, true : false; }
const ll MAXn=2e5+5,MAXlg=__lg(MAXn)+2;
const ll MOD=1000000007;
const ll INF=1e9;
vector<ii> e[MAXn];
vector<ii> ne[MAXn];
int d[MAXn];
int col[MAXn];
int w[MAXn];
int chk[MAXn];
vector<ii> edg;
void dfs(int x,int p){
for (auto i:ne[x]) {
int to = i.X;
if (to == p) continue;
col[to] = !col[x];
dfs(to,x);
}
}
int main(){
IOS();
int n,m;
cin >> n >> m;
REP (i,n) cin >> d[i];
REP (i,m) {
int u,v;
cin >> u >> v;
u--, v--;
e[u].eb(v,i);
e[v].eb(u,i);
}
REP (i,m) w[i] = INF;
REP (i,n) {
bool fg = false;
sort(ALL(e[i]));
for (auto it:e[i]) {
int to = it.X;
if (d[i] >= d[to]) fg = true;
}
if (!fg) return cout << -1 << endl,0;
int cur = -1, curid = -1;
for (auto it:e[i]) {
int to = it.X, id = it.Y;
if (cur == -1) {
cur = to, curid = id;
}
else if (d[cur] > d[to]) {
cur = to, curid = id;
}
}
w[curid] = d[i];
ne[i].eb(cur,d[i]);
ne[cur].eb(i,d[i]);
}
REP (i,n) {
sort(ALL(ne[i]));
debug(ne[i]);
}
RST(col,-1);
REP (i,n) {
if (col[i] == -1) {
col[i] = 0;
dfs(i,i);
}
}
REP (i,m) if (w[i] == -1) w[i] = INF;
REP (i,n) {
if (col[i] == 0) cout << 'W';
else cout << 'B';
}
cout << endl;
REP (i,m) cout << w[i] << endl;
}
| [
"seal1000402@gmail.com"
] | seal1000402@gmail.com |
cd1d2a597b8780182ee15ffd84144091a3c093ec | 15ee46e9b15018e2bd66a28f7b9163238727dad2 | /hack.cpp | 32b3cca2d99c0e76094d60428ab1fff86159bfae | [] | no_license | vishwanath1306/Torch-C--Makefile | 0135969711b6805f6469846d3e2216b353ccd006 | 5862479d2e1cb17a9d4b3f8f9c475484f7576727 | refs/heads/main | 2023-03-25T21:01:53.455906 | 2021-03-24T22:12:31 | 2021-03-24T22:12:31 | 351,233,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | cpp | #include <torch/script.h>
#include <iostream>
#include <memory>
int main(int argc, const char* argv[]) {
// if (argc != 2) {
// std::cerr << "usage: example-app <path-to-exported-script-module>\n";
// return -1;
// }
torch::jit::script::Module module;
try {
module = torch::jit::load("./traced_resnet_model.pt");
}
catch (const c10::Error& e) {
std::cerr << "error loading the model\n";
return -1;
}
std::vector<torch::jit::IValue> inputs;
inputs.push_back(torch::ones({1, 3, 224, 224}));
at::Tensor output = module.forward(inputs).toTensor();
std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/5) << '\n';
std::cout << "ok\n";
}
| [
"vishwa.nath@outlook.com"
] | vishwa.nath@outlook.com |
95807692c9d3392ff97ca15c294e1077d7b1068b | bc9d17b9861511792972b46bad7414919dfe6ea8 | /Cpp/chapter3/Arrays.cpp | e53db939a555c7cd4f93d6d533cf828afd372347 | [] | no_license | Liamgettingbetter/Introduction_to_Cpp | 7c0b4549cc231aa0588b74b269846cf57ace801d | 9350f022e0dc4b8fc4a91463aa936a327eca4b6e | refs/heads/master | 2021-01-12T09:44:27.192579 | 2017-09-07T02:13:40 | 2017-09-07T02:13:40 | 76,232,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 193 | cpp | //: C03:Arrays.cpp
#include <iostream>
using namespace std;
int main() {
int a[10];
for(int i = 0; i < 10; i++) {
a[i] = i * 10;
cout << "a[" << i << "] = "
<< a[i] << endl;
}
} | [
"775138281@qq.com"
] | 775138281@qq.com |
d53e101958e9fd731cb9739001a56b1e061711ab | 6a27cae1763e194bbb97f3710bce059a4f97dfae | /include/gameobject.h | ffd032e62ef8a987793aad6daee15813acbc0106 | [
"MIT"
] | permissive | Loddgrimner/test | 78274cee803054ddaf48dc76f5a87bbc79893ca0 | 75e961a0a3dd4fbcb17273687b35afa801d11222 | refs/heads/master | 2021-01-10T16:52:26.756971 | 2015-12-05T18:27:32 | 2015-12-05T18:27:32 | 45,363,304 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | h | #pragma once
#include "ivec2.h"
#include "path.h"
class visitor;
class gameobject
{
public:
gameobject ();
virtual void accept(visitor &v);
int getx();
int gety();
void setx(int x);
void sety(int y);
ivec2 getposition();
ivec2 getdestination();
void setposition(ivec2 v);
void setdestination(ivec2 v);
path getpath();
void move();
private:
ivec2 position;
ivec2 destination;
path currentpath;
};
| [
"loddgrimner@yahoo.com"
] | loddgrimner@yahoo.com |
7c2a68f3cd5ba84e905d62d0da73694e1733b968 | b28f59293318dbcf990c8525af0b0b03026aa4d7 | /include/OpenGL/GLFunction/GLFunction.h | a5199159f8c2a4b4f475bcd0443ae314f101d571 | [] | no_license | Sommy1491/OpenGL | 7a89418d5d3d6d7f0008d93c6bd74626b82ab5a0 | fad40ef5ba66664ae43d0d4e6d04497c1c23b292 | refs/heads/master | 2020-03-14T16:47:21.291033 | 2018-05-01T11:26:54 | 2018-05-01T11:26:54 | 126,367,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,603 | h | #pragma once
#pragma region BufferSpecification
namespace BUFFER
{
enum TYPE
{
VERTEX,
ELEMENT
};
}
#pragma endregion
#pragma region ShaderSpecification
namespace SHADER
{
enum TYPE
{
VERTEX,
FRAGMENT
};
}
#pragma endregion
#include <GL/glew.h>
#include <iostream>
#pragma region BufferObject
class BufferObject
{
public:
BufferObject(BUFFER::TYPE type);
~BufferObject();
void BindBuffer();
void BufferData(GLenum target, GLsizeiptr size, const GLvoid * data, GLenum usage);
void DeleteBuffer();
private:
BUFFER::TYPE type;
GLuint bufferObject;
};
#pragma endregion
#pragma region VertexArrayObject
class VertexArrayObject
{
public:
VertexArrayObject();
~VertexArrayObject();
void BindVertexArrayObject();
void UnbindVertexArrayObject();
void DeleteVertexArrayObject();
private:
GLuint vertexArrayObject;
};
#pragma endregion
#pragma region VertexAttribute
class VertexAttribute
{
public:
GLint GetAttributeLocation(GLuint shaderProgram, const GLchar* name);
void VertexAttributePointer(GLint attribLocation);
void enableVertexAttribArray(GLint attribLocation);
};
#pragma endregion
#pragma region Shader
class Shader
{
public:
Shader(SHADER::TYPE type, const char* program);
~Shader();
GLuint getShader();
private:
SHADER::TYPE type;
GLuint shader;
GLint shaderStatus;
char shaderInfoLog[512];
void CompileShader();
};
#pragma endregion
#pragma region ShaderProgram
class ShaderProgram
{
public:
ShaderProgram(Shader* vertexShader, Shader* fragmentShader);
~ShaderProgram();
GLuint getProgram();
private:
GLuint program;
};
#pragma endregion | [
"mahendrasomesh@gmail.com"
] | mahendrasomesh@gmail.com |
793efed2e157817e2c9458ea2b742ba807d94754 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13756/function13756_schedule_30/function13756_schedule_30.cpp | a211c71295b6514415126673310c192f6a267d47 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,131 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function13756_schedule_30");
constant c0("c0", 64), c1("c1", 2048), c2("c2", 512);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
input input00("input00", {i0, i2}, p_int32);
input input01("input01", {i0, i2}, p_int32);
input input02("input02", {i1}, p_int32);
input input03("input03", {i0, i2}, p_int32);
input input04("input04", {i0}, p_int32);
input input05("input05", {i1}, p_int32);
input input06("input06", {i1}, p_int32);
input input07("input07", {i0, i2}, p_int32);
input input08("input08", {i1, i2}, p_int32);
computation comp0("comp0", {i0, i1, i2}, input00(i0, i2) - input01(i0, i2) + input02(i1) * input03(i0, i2) * input04(i0) * input05(i1) - input06(i1) + input07(i0, i2) * input08(i1, i2));
comp0.tile(i0, i1, i2, 64, 128, 32, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i01);
buffer buf00("buf00", {64, 512}, p_int32, a_input);
buffer buf01("buf01", {64, 512}, p_int32, a_input);
buffer buf02("buf02", {2048}, p_int32, a_input);
buffer buf03("buf03", {64, 512}, p_int32, a_input);
buffer buf04("buf04", {64}, p_int32, a_input);
buffer buf05("buf05", {2048}, p_int32, a_input);
buffer buf06("buf06", {2048}, p_int32, a_input);
buffer buf07("buf07", {64, 512}, p_int32, a_input);
buffer buf08("buf08", {2048, 512}, p_int32, a_input);
buffer buf0("buf0", {64, 2048, 512}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
input03.store_in(&buf03);
input04.store_in(&buf04);
input05.store_in(&buf05);
input06.store_in(&buf06);
input07.store_in(&buf07);
input08.store_in(&buf08);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf05, &buf06, &buf07, &buf08, &buf0}, "../data/programs/function13756/function13756_schedule_30/function13756_schedule_30.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
a8d69107cf981d531bffba9086f3cf1705ace399 | 786de89be635eb21295070a6a3452f3a7fe6712c | /PSHdf5Input/tags/V00-01-04/src/Hdf5RunIter.cpp | 122c5d16d983940a3924762c936188cbb9881645 | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,326 | cpp | //--------------------------------------------------------------------------
// File and Version Information:
// $Id$
//
// Description:
// Class Hdf5RunIter...
//
// Author List:
// Andy Salnikov
//
//------------------------------------------------------------------------
//-----------------------
// This Class's Header --
//-----------------------
#include "PSHdf5Input/Hdf5RunIter.h"
//-----------------
// C/C++ Headers --
//-----------------
#include <boost/make_shared.hpp>
#include <boost/algorithm/string/predicate.hpp>
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "hdf5pp/GroupIter.h"
#include "PSHdf5Input/Exceptions.h"
#include "PSHdf5Input/Hdf5CalibCycleIter.h"
#include "PSHdf5Input/Hdf5EventId.h"
#include "PSHdf5Input/Hdf5Utils.h"
#include "MsgLogger/MsgLogger.h"
//-----------------------------------------------------------------------
// Local Macros, Typedefs, Structures, Unions and Forward Declarations --
//-----------------------------------------------------------------------
namespace {
const char* logger = "Hdf5RunIter";
// comparison operator for groups
struct GroupCmp {
bool operator()(const hdf5pp::Group& lhs, const hdf5pp::Group& rhs) const {
return lhs.name() < rhs.name();
}
};
}
// ----------------------------------------
// -- Public Function Member Definitions --
// ----------------------------------------
namespace PSHdf5Input {
//----------------
// Constructors --
//----------------
Hdf5RunIter::Hdf5RunIter (const hdf5pp::Group& grp, int runNumber,
unsigned schemaVersion, bool fullTsFormat)
: m_grp(grp)
, m_runNumber(runNumber)
, m_schemaVersion(schemaVersion)
, m_fullTsFormat(fullTsFormat)
, m_groups()
, m_ccIter()
{
// get all subgroups which start with 'CalibCycle:'
hdf5pp::GroupIter giter(m_grp);
for (hdf5pp::Group grp = giter.next(); grp.valid(); grp = giter.next()) {
const std::string& grpname = grp.basename();
if (grpname == "CalibCycle" or boost::algorithm::starts_with(grpname, "CalibCycle:")) {
m_groups.push_back(grp);
}
}
// sort them by name
m_groups.sort(GroupCmp());
}
//--------------
// Destructor --
//--------------
Hdf5RunIter::~Hdf5RunIter ()
{
}
// Returns next object
Hdf5RunIter::value_type
Hdf5RunIter::next()
{
Hdf5IterData res;
if (not m_ccIter.get()) {
// no more run groups left - we are done
if (m_groups.empty()) {
MsgLog(logger, debug, "stop iterating in group: " << m_grp.name());
res = value_type(value_type::Stop, boost::shared_ptr<PSEvt::EventId>());
} else {
// open next group
hdf5pp::Group grp = m_groups.front();
m_groups.pop_front();
MsgLog(logger, debug, "switching to group: " << grp.name());
// make iter for this new group
m_ccIter.reset(new Hdf5CalibCycleIter(grp, m_runNumber, m_schemaVersion, m_fullTsFormat));
// make event id
PSTime::Time etime = Hdf5Utils::getTime(m_ccIter->group(), "start");
boost::shared_ptr<PSEvt::EventId> eid;
if (etime != PSTime::Time(0,0)) eid = boost::make_shared<Hdf5EventId>(m_runNumber, etime, 0x1ffff, 0, 0);
res = Hdf5IterData(Hdf5IterData::BeginCalibCycle, eid);
// fill result with the configuration object data locations
hdf5pp::GroupIter giter(grp);
for (hdf5pp::Group grp1 = giter.next(); grp1.valid(); grp1 = giter.next()) {
if (grp1.basename() != "Epics::EpicsPv") {
hdf5pp::GroupIter subgiter(grp1);
for (hdf5pp::Group grp2 = subgiter.next(); grp2.valid(); grp2 = subgiter.next()) {
if (not grp2.hasChild("time")) {
res.add(grp2, -1);
}
}
}
}
}
} else {
// read next event from this iterator
res = m_ccIter->next();
// switch to next group if it sends us Stop
if (res.type() == value_type::Stop) {
PSTime::Time etime = Hdf5Utils::getTime(m_ccIter->group(), "end");
boost::shared_ptr<PSEvt::EventId> eid;
if (etime != PSTime::Time(0,0)) eid = boost::make_shared<Hdf5EventId>(m_runNumber, etime, 0x1ffff, 0, 0);
res = Hdf5IterData(Hdf5IterData::EndCalibCycle, eid);
m_ccIter.reset();
}
}
return res;
}
} // namespace PSHdf5Input
| [
"salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7"
] | salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7 |
75c128b3372edfdc8215b07733a47c8b20e00ba1 | c87127655cf02d9d25b2ee73bd0bf8e9e53c8d20 | /src/common/spawn.h | ae8f6c584fd1d6fbb7bece5947c0630fc4432cb2 | [
"BSD-3-Clause"
] | permissive | nioshares/InitiS-Coin | 8f2c81b90470946abfd6933efbcc040e2c946b7a | 2230331b788bafb659ca3810764c089a60ee3dd9 | refs/heads/master | 2020-09-26T02:08:55.078501 | 2019-12-09T03:53:00 | 2019-12-09T03:53:00 | 226,138,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,743 | h | // Copyright (c) 2018-2019, CUT coin
// Copyright (c) 2018, The Monero Project
//
// 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.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
namespace tools
{
int spawn(const char *filename, const std::vector<std::string>& args, bool wait);
}
| [
"49848701+nioshares@users.noreply.github.com"
] | 49848701+nioshares@users.noreply.github.com |
f36e8959565705dc9099a9b7a138f93a66bd58aa | c4a3dd148338ba98ec404ac5ebc315ceadd2e11a | /sensei/strings/join.h | b437c7484660aaf2db56baa51ad64cf15fd1d1d8 | [
"Apache-2.0"
] | permissive | rbnx/sensei | 53b062bba1c81a044a3555f4dcd0cb84f96b2f46 | 0be283b604c7f0505850fefd880fe9bf985212b5 | refs/heads/master | 2020-05-19T22:53:15.590982 | 2019-05-06T19:14:08 | 2019-05-06T19:14:08 | 185,255,284 | 0 | 0 | Apache-2.0 | 2019-05-06T19:03:11 | 2019-05-06T19:03:11 | null | UTF-8 | C++ | false | false | 11,885 | h | // Copyright 2008 and onwards Google, Inc.
//
// #status: RECOMMENDED
// #category: operations on strings
// #summary: Functions for joining ranges of elements with an element separator.
//
#ifndef SENSEI_STRINGS_JOIN_H_
#define SENSEI_STRINGS_JOIN_H_
#include <stdio.h>
#include <string.h>
#include <unordered_map>
using std::unordered_map;
template<typename K, typename V>
using hash_map = unordered_map<K,V>; // Not used in this file.
#include <unordered_set>
using std::unordered_set;
template<typename K>
using hash_set = unordered_set<K>; // Not used in this file.
#include <iterator>
#include <map>
#include <set>
using std::set;
#include <string>
using std::string;
#include <utility>
using std::pair;
#include <vector>
using std::vector;
#include "sensei/base/integral_types.h"
#include "sensei/base/macros.h"
#include "sensei/base/port.h"
#include "sensei/base/template_util.h"
#include "sensei/strings/join_internal.h"
#include "sensei/strings/numbers.h"
#include "sensei/strings/strcat.h" // For backward compatibility.
#include "sensei/strings/stringpiece.h"
#include "sensei/util/hash.h"
#ifdef LANG_CXX11
#include <initializer_list> // NOLINT(build/include_order)
#include <tuple> // NOLINT(build/include_order)
#endif // LANG_CXX11
namespace strings {
// strings::Join()
//
// The strings::Join() function joins the given range of elements, with each
// element separated by the given separator string, and returns the result as a
// string. Ranges may be specified by passing a container or array compatible
// with std::begin() and std::end(), a brace-initialized std::initializer_list,
// as individual begin and end iterators, or as a std::tuple of heterogeneous
// objects. The separator string is taken as a StringPiece, which means it can
// be specified as a string literal, C-string, C++ string, etc. By default,
// non-string elements are converted to strings using AlphaNum, which yields
// the same behavior as using StrCat(). This means that strings::Join() works
// out-of-the-box on collections of strings, ints, floats, doubles, etc. An
// optional final argument of a "Formatter" (details below) function object
// may be given. This object will be responsible for converting each
// argument in the Range to a string.
//
// Example 1:
// // Joins a collection of strings. This also works with a collection of
// // StringPiece or even const char*.
// vector<string> v = util::gtl::Container("foo", "bar", "baz");
// string s = strings::Join(v, "-");
// EXPECT_EQ("foo-bar-baz", s);
//
// Example 2:
// // Joins the values in the given std::initializer_list<> specified using
// // brace initialization. This also works with an initializer_list of ints
// // or StringPiece--any AlphaNum-compatible type.
// string s = strings::Join({"foo", "bar", "baz"}, "-");
// EXPECT_EQ("foo-bar-baz", s);
//
// Example 3:
// // Joins a collection of ints. This also works with floats, doubles,
// // int64s; any StrCat-compatible type.
// vector<int> v = util::gtl::Container(1, 2, 3, -4);
// string s = strings::Join(v, "-");
// EXPECT_EQ("1-2-3--4", s);
//
// Example 4:
// // Joins a collection of pointer-to-int. By default, pointers are
// // dereferenced and the pointee is formatted using the default format for
// // that type. The upshot of this is that all levels of inderection are
// // collapsed, so this works just as well for vector<int***> as
// // vector<int*>.
// int x = 1, y = 2, z = 3;
// vector<int*> v = util::gtl::Container(&x, &y, &z);
// string s = strings::Join(v, "-");
// EXPECT_EQ("1-2-3", s);
//
// Example 5:
// // In C++11, dereferecing std::unique_ptr is also supported:
// vector<std::unique_ptr<int>> v
// v.emplace_back(new int(1));
// v.emplace_back(new int(2));
// v.emplace_back(new int(3));
// string s = strings::Join(v, "-");
// EXPECT_EQ("1-2-3", s);
//
// Example 6:
// // Joins a map, with each key-value pair separated by an equals sign.
// // This would also work with, say, a vector<pair<>>.
// map<string, int> m = util::gtl::Container(
// std::make_pair("a", 1),
// std::make_pair("b", 2),
// std::make_pair("c", 3));
// string s = strings::Join(m, ",", strings::PairFormatter("="));
// EXPECT_EQ("a=1,b=2,c=3", s);
//
// Example 7:
// // These examples show how strings::Join() handles a few common edge cases.
// vector<string> v_empty;
// EXPECT_EQ("", strings::Join(v_empty, "-"));
//
// vector<string> v_one_item = util::gtl::Container("foo");
// EXPECT_EQ("foo", strings::Join(v_one_item, "-"));
//
// vector<string> v_empty_string = util::gtl::Container("");
// EXPECT_EQ("", strings::Join(v_empty_string, "-"));
//
// vector<string> v_one_item_empty_string = util::gtl::Container("a", "");
// EXPECT_EQ("a-", strings::Join(v_one_item_empty_string, "-"));
//
// vector<string> v_two_empty_string = util::gtl::Container("", "");
// EXPECT_EQ("-", strings::Join(v_two_empty_string, "-"));
//
// Example 8:
// // Join a std::tuple<T...>.
// string s = strings::Join(std::make_tuple(123, "abc", 0.456), "-");
// EXPECT_EQ("123-abc-0.456", s);
//
//
// Formatters
//
// A Formatter is a function object that is responsible for formatting its
// argument as a string and appending it to the given output string. Formatters
// are an extensible part of the Join2 API: They allow callers to provide their
// own conversion function to enable strings::Join() work with arbitrary types.
//
// The following is an example Formatter that simply uses StrAppend to format an
// integer as a string.
//
// struct MyFormatter {
// void operator()(string* out, int i) const {
// StrAppend(out, i);
// }
// };
//
// You would use the above formatter by passing an instance of it as the final
// argument to strings::Join():
//
// vector<int> v = util::gtl::Container(1, 2, 3, 4);
// string s = strings::Join(v, "-", MyFormatter());
// EXPECT_EQ("1-2-3-4", s);
//
// The following standard formatters are provided with the Join2 API.
//
// - AlphaNumFormatter (the default)
// - PairFormatter
// - DereferenceFormatter
//
// AlphaNumFormatter()
//
// Default formatter used if none is specified. Uses AlphaNum to convert numeric
// arguments to strings.
inline internal::AlphaNumFormatterImpl AlphaNumFormatter() {
return internal::AlphaNumFormatterImpl();
}
// PairFormatter()
//
// Formats a std::pair by putting the given separator between the pair's .first
// and .second members. The separator argument is required. By default, the
// first and second members are themselves formatted using AlphaNumFormatter(),
// but the caller may specify other formatters to use for the members.
template <typename FirstFormatter, typename SecondFormatter>
inline internal::PairFormatterImpl<FirstFormatter, SecondFormatter>
PairFormatter(FirstFormatter f1, StringPiece sep, SecondFormatter f2) {
return internal::PairFormatterImpl<FirstFormatter, SecondFormatter>(
f1, sep, f2);
}
inline internal::PairFormatterImpl<
internal::AlphaNumFormatterImpl,
internal::AlphaNumFormatterImpl>
PairFormatter(StringPiece sep) {
return PairFormatter(AlphaNumFormatter(), sep, AlphaNumFormatter());
}
// DereferenceFormatter()
//
// Dereferences its argument then formats it using AlphaNumFormatter (by
// default), or the given formatter if one is explicitly given. This is useful
// for formatting a container of pointer-to-T. This pattern often shows up when
// joining repeated fields in protocol buffers.
template <typename Formatter>
internal::DereferenceFormatterImpl<Formatter>
DereferenceFormatter(Formatter f) {
return internal::DereferenceFormatterImpl<Formatter>(f);
}
inline internal::DereferenceFormatterImpl<internal::AlphaNumFormatterImpl>
DereferenceFormatter() {
return internal::DereferenceFormatterImpl<internal::AlphaNumFormatterImpl>(
AlphaNumFormatter());
}
//
// strings::Join() overloads
//
template <typename Iterator, typename Formatter>
string Join(Iterator start, Iterator end, StringPiece sep, Formatter fmt) {
return internal::JoinAlgorithm(start, end, sep, fmt);
}
template <typename Range, typename Formatter>
string Join(const Range& range, StringPiece separator, Formatter fmt) {
return internal::JoinRange(range, separator, fmt);
}
#ifdef LANG_CXX11
template <typename T, typename Formatter>
string Join(std::initializer_list<T> il, StringPiece separator, Formatter fmt) {
return internal::JoinRange(il, separator, fmt);
}
template <typename... T, typename Formatter>
string Join(const std::tuple<T...>& value, StringPiece separator,
Formatter fmt) {
return internal::JoinAlgorithm(value, separator, fmt);
}
#endif // LANG_CXX11
template <typename Iterator>
string Join(Iterator start, Iterator end, StringPiece separator) {
return internal::JoinRange(start, end, separator);
}
template <typename Range>
string Join(const Range& range, StringPiece separator) {
return internal::JoinRange(range, separator);
}
#ifdef LANG_CXX11
template <typename T>
string Join(std::initializer_list<T> il, StringPiece separator) {
return internal::JoinRange(il, separator);
}
template <typename... T>
string Join(const std::tuple<T...>& value, StringPiece separator) {
return internal::JoinAlgorithm(value, separator, AlphaNumFormatter());
}
#endif // LANG_CXX11
} // namespace strings
// ----------------------------------------------------------------------
// LEGACY(jgm): Utilities provided in util/csv/writer.h are now preferred for
// writing CSV data in google3.
//
// Example for CSV formatting a single record (a sequence container of string,
// char*, or StringPiece values) using the util::csv::WriteRecordToString helper
// function:
// std::vector<string> record = ...;
// string line = util::csv::WriteRecordToString(record);
//
// NOTE: When writing many records, use the util::csv::Writer class directly.
//
// JoinCSVLineWithDelimiter()
// This function is the inverse of SplitCSVLineWithDelimiter() in that the
// string returned by JoinCSVLineWithDelimiter() can be passed to
// SplitCSVLineWithDelimiter() to get the original string vector back.
// Quotes and escapes the elements of original_cols according to CSV quoting
// rules, and the joins the escaped quoted strings with commas using
// JoinStrings(). Note that JoinCSVLineWithDelimiter() will not necessarily
// return the same string originally passed in to
// SplitCSVLineWithDelimiter(), since SplitCSVLineWithDelimiter() can handle
// gratuitous spacing and quoting. 'output' must point to an empty string.
//
// Example:
// [Google], [x], [Buchheit, Paul], [string with " quote in it], [ space ]
// ---> [Google,x,"Buchheit, Paul","string with "" quote in it"," space "]
//
// JoinCSVLine()
// A convenience wrapper around JoinCSVLineWithDelimiter which uses
// ',' as the delimiter.
// ----------------------------------------------------------------------
void JoinCSVLine(const std::vector<string>& original_cols, string* output);
string JoinCSVLine(const std::vector<string>& original_cols);
void JoinCSVLineWithDelimiter(const std::vector<string>& original_cols,
char delimiter,
string* output);
template <class CONTAINER>
GOOGLE_DEPRECATED("Use strings::Join()")
void JoinStrings(const CONTAINER& components,
StringPiece delim,
string* result) {
*result = strings::Join(components, delim);
}
template <class ITERATOR>
GOOGLE_DEPRECATED("Use strings::Join()")
void JoinStringsIterator(const ITERATOR& start,
const ITERATOR& end,
StringPiece delim,
string* result) {
*result = strings::Join(start, end, delim);
}
#endif // SENSEI_STRINGS_JOIN_H_
| [
"wiktork@google.com"
] | wiktork@google.com |
f23c3a688fd85b97fd644744257dc2c6e5c018c8 | c7a277d0072d7029d12b15486d307e3a8edfb4d3 | /Plugins/ARToolkitPlugin/Source/ARToolkitPlugin/Public/IARToolkitPlugin.h | b1f00a4b09b22bfebf0a7933e8183680c0297ffb | [] | no_license | ccc030233/TileReality | 51c3a87afbf62dacde8dd3952d1c3bba4fdd0fe9 | aaccd4e2c45c9b50fb607b9ade9da9a6f152c328 | refs/heads/master | 2021-09-24T12:02:58.680380 | 2018-10-09T17:30:38 | 2018-10-09T17:30:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,883 | h | //
// Copyright 2016 Adam Horvath - WWW.UNREAL4AR.COM - info@unreal4ar.com - All Rights Reserved.
//
#pragma once
#include "ModuleManager.h"
/**
* The public interface to this module. In most cases, this interface is only public to sibling modules
* within this plugin.
*/
class IARToolkitPlugin : public IModuleInterface
{
public:
/**
* Singleton-like access to this module's interface. This is just for convenience!
* Beware of calling this during the shutdown phase, though. Your module might have been unloaded already.
*
* @return Returns singleton instance, loading the module on demand if needed
*/
static inline IARToolkitPlugin& Get()
{
return FModuleManager::LoadModuleChecked< IARToolkitPlugin >( "ARToolkitPlugin" );
}
/**
* Checks to see if this module is loaded and ready. It is only valid to call Get() if IsAvailable() returns true.
*
* @return True if the module is loaded and ready to use
*/
static inline bool IsAvailable()
{
return FModuleManager::Get().IsModuleLoaded( "ARToolkitPlugin" );
}
FORCEINLINE TSharedPtr<class FARToolkitDevice> GetARToolkitDevice() const
{
return ARToolkitDevice;
}
/**
* Simple helper function to get the device currently active.
* @return Pointer to the ARToolkitDevice, or nullptr if Device is not available.
*/
static FARToolkitDevice* GetARToolkitDeviceSafe()
{
#if WITH_EDITOR
FARToolkitDevice* ARToolkitDevice = IARToolkitPlugin::IsAvailable() ? IARToolkitPlugin::Get().GetARToolkitDevice().Get() : nullptr;
#else
FARToolkitDevice* ARToolkitDevice = IARToolkitPlugin::Get().GetARToolkitDevice().Get();
#endif
return ARToolkitDevice;
}
protected:
/**
* Reference to the actual ARToolkitDevice, grabbed through the GetKinectV2Device() interface, and created and destroyed in Startup/ShutdownModule
*/
TSharedPtr<class FARToolkitDevice> ARToolkitDevice;
};
| [
"38584099+jvreinosa@users.noreply.github.com"
] | 38584099+jvreinosa@users.noreply.github.com |
d2455e8581282dae5eef0b607886b34d9d110631 | 872dc783104f2cd00ea15309b615f369637d7e66 | /include/KeyboardInputAction.hpp | 8e9af535d53b65cb8ae9ee54b8ebd0765307c0f2 | [] | no_license | boge90/SpaceSimulator | bdf5bdf624cb1d460558e61185ce21b27de1c716 | 2cc76d975c4e526568fe3350ea430ddb858a4edd | refs/heads/master | 2016-09-06T12:21:49.329611 | 2016-01-24T15:37:35 | 2016-01-24T15:37:35 | 24,286,615 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 152 | hpp | #ifndef KEYBOARD_INPUT_ACTION_H
#define KEYBOARD_INPUT_ACTION_H
class KeyboardInputAction{
public:
virtual void onKeyInput(int key) = 0;
};
#endif
| [
"boge90@gmail.com"
] | boge90@gmail.com |
396c42e69def0348974c0cdd4538beae6288613c | 9160d5980d55c64c2bbc7933337e5e1f4987abb0 | /base/src/sgpp/base/datatypes/DataTensor.cpp | 91af2982d1725c02d80271ff9bba3c4c81f8fb45 | [
"LicenseRef-scancode-generic-exception",
"BSD-3-Clause"
] | permissive | SGpp/SGpp | 55e82ecd95ac98efb8760d6c168b76bc130a4309 | 52f2718e3bbca0208e5e08b3c82ec7c708b5ec06 | refs/heads/master | 2022-08-07T12:43:44.475068 | 2021-10-20T08:50:38 | 2021-10-20T08:50:38 | 123,916,844 | 68 | 44 | NOASSERTION | 2022-06-23T08:28:45 | 2018-03-05T12:33:52 | C++ | UTF-8 | C++ | false | false | 3,465 | cpp | // Copyright (C) 2008-today The SG++ project
// This file is part of the SG++ project. For conditions of distribution and
// use, please see the copyright notice provided with SG++ or at
// sgpp.sparsegrids.org
#include <sgpp/base/datatypes/DataTensor.hpp>
#include <sgpp/base/exception/data_exception.hpp>
namespace sgpp {
namespace base {
DataTensor::DataTensor() : DataTensor(0, 0, 0) {}
DataTensor::DataTensor(size_t ndepth, size_t nrows, size_t ncols)
: DataTensor(ndepth, nrows, ncols, 0.0) {}
DataTensor::DataTensor(size_t ndepth, size_t nrows, size_t ncols, double value)
: ndepth(ndepth), nrows(nrows), ncols(ncols), matrixsize(nrows * ncols) {
this->assign(ndepth * nrows * ncols, value);
}
void DataTensor::resize(size_t ndepth, size_t nrows, size_t ncols) {
this->std::vector<double>::resize(ndepth * nrows * ncols);
}
double DataTensor::get(size_t depth, size_t row, size_t col) {
if ((depth >= ndepth) || (row >= nrows) || (col >= ncols)) {
throw sgpp::base::data_exception("DataTensor::get Entry does not exist");
}
return (*this)[depth * matrixsize + row * ncols + col];
}
void DataTensor::set(size_t depth, size_t row, size_t col, double value) {
if ((depth >= ndepth) || (row >= nrows) || (col >= ncols)) {
throw sgpp::base::data_exception("DataTensor::set Entry does not exist");
}
(*this)[depth * matrixsize + row * ncols + col] = value;
}
void DataTensor::getMatrix(size_t depth, sgpp::base::DataMatrix& matrix) {
if (depth >= ndepth) {
throw sgpp::base::data_exception("DataTensor::getMatrix Entry does not exist");
}
if (matrix.getNcols() != this->ncols) {
matrix.resize(this->nrows, this->ncols);
}
if (matrix.getNrows() != this->nrows) {
matrix.resize(this->nrows, this->ncols);
}
sgpp::base::DataVector row(this->ncols);
for (size_t i = 0; i < this->nrows; i++) {
this->getRow(depth, i, row);
matrix.setRow(i, row);
}
}
void DataTensor::getRow(size_t depth, size_t row, sgpp::base::DataVector& vec) {
if (row >= nrows) {
throw sgpp::base::data_exception("DataTensor::getRow Entry does not exist");
}
vec.clear();
for (size_t i = 0; i < this->ncols; ++i) {
vec.push_back((*this)[depth * matrixsize + row * ncols + i]);
}
}
void DataTensor::getColumn(size_t depth, size_t col, sgpp::base::DataVector& vec) {
if (col >= ncols) {
throw sgpp::base::data_exception("DataTensor::getColumn Entry does not exist");
}
if (vec.getSize() != this->nrows) {
vec.resize(nrows);
}
for (size_t j = 0; j < this->nrows; ++j) {
vec[j] = (*this)[depth * matrixsize + j * ncols + col];
}
}
void DataTensor::toString(std::string& text) const {
std::stringstream str;
str << std::scientific;
str.precision(20);
str << "{";
for (size_t h = 0; h < ndepth; ++h) {
str << "\n[";
for (size_t i = 0; i < nrows; ++i) {
str << "[";
for (size_t j = 0; j < ncols; ++j) {
if (j != 0) {
str << ", ";
// add linebreak for readability
if (j % 20 == 0) {
str << std::endl;
}
}
str << (*this)[h * matrixsize + i * ncols + j];
}
if (i == nrows - 1) {
str << "]";
} else {
str << "]," << std::endl;
}
}
str << "]\n";
}
str << "}";
text = str.str();
}
std::string DataTensor::toString() const {
std::string str;
toString(str);
return str;
}
} // namespace base
} // namespace sgpp
| [
"michael.rehme@ipvs.uni-stuttgart.de"
] | michael.rehme@ipvs.uni-stuttgart.de |
1a3c1268390ad3e986a25c0e8e91e0238037d086 | ce7453e65bc63cfffa334a39a368891eab082f29 | /mediatek/platform/mt6589/hardware/mtkcam/v1/hal/adapter/MtkEng/State/State.h | 55489bd24d291e82d673d6ebb2eba0862e9c2d75 | [] | no_license | AdryV/kernel_w200_kk_4.4.2_3.4.67_mt6589 | 7a65d4c3ca0f4b59e4ad6d7d8a81c28862812f1c | f2b1be8f087cd8216ec1c9439b688df30c1c67d4 | refs/heads/master | 2021-01-13T00:45:17.398354 | 2016-12-04T17:41:24 | 2016-12-04T17:41:24 | 48,487,823 | 7 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 6,382 | h | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
#ifndef _MTK_HAL_CAMADAPTER_MTKENG_STATE_STATE_H_
#define _MTK_HAL_CAMADAPTER_MTKENG_STATE_STATE_H_
//
#include <utils/threads.h>
namespace android {
namespace NSMtkEngCamAdapter {
/*******************************************************************************
*
*******************************************************************************/
class IState;
class IStateHandler;
/*******************************************************************************
*
*******************************************************************************/
class StateBase : public IState
{
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Interfaces.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public: //// Interfaces
virtual status_t onStartPreview(IStateHandler* pHandler) { return op_UnSupport(__FUNCTION__); }
virtual status_t onStopPreview(IStateHandler* pHandler) { return op_UnSupport(__FUNCTION__); }
//
virtual status_t onPreCapture(IStateHandler* pHandler) { return op_UnSupport(__FUNCTION__); }
virtual status_t onCapture(IStateHandler* pHandler) { return op_UnSupport(__FUNCTION__); }
virtual status_t onCaptureDone(IStateHandler* pHandler) { return op_UnSupport(__FUNCTION__); }
virtual status_t onCancelCapture(IStateHandler* pHandler){ return op_UnSupport(__FUNCTION__); }
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Implementation.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public: //// Operations.
StateBase(char const*const pcszName, ENState const eState);
virtual char const* getName() const { return m_pcszName; }
virtual ENState getEnum() const { return m_eState; }
IStateManager* getStateManager() const { return m_pStateManager; }
protected: //// Data Members.
char const*const m_pcszName;
ENState const m_eState;
IStateManager*const m_pStateManager;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected: //// Operations.
status_t waitState(ENState const eState, nsecs_t const timeout = -1);
status_t op_UnSupport(char const*const pcszDbgText = "");
};
/*******************************************************************************
*
*******************************************************************************/
struct StateIdle : public StateBase
{
StateIdle(ENState const eState);
//
virtual status_t onStartPreview(IStateHandler* pHandler);
virtual status_t onCapture(IStateHandler* pHandler);
};
/*******************************************************************************
*
*******************************************************************************/
struct StatePreview : public StateBase
{
StatePreview(ENState const eState);
//
virtual status_t onStopPreview(IStateHandler* pHandler);
virtual status_t onPreCapture(IStateHandler* pHandler);
};
/*******************************************************************************
*
*******************************************************************************/
struct StatePreCapture : public StateBase
{
StatePreCapture(ENState const eState);
//
virtual status_t onStopPreview(IStateHandler* pHandler);
};
/*******************************************************************************
*
*******************************************************************************/
struct StateCapture : public StateBase
{
StateCapture(ENState const eState);
//
virtual status_t onCaptureDone(IStateHandler* pHandler);
virtual status_t onCancelCapture(IStateHandler* pHandler);
};
/*******************************************************************************
*
*******************************************************************************/
};
}; // namespace android
#endif // _MTK_HAL_CAMADAPTER_MTKENG_STATE_STATE_H_
| [
"vetaxa.manchyk@gmail.com"
] | vetaxa.manchyk@gmail.com |
0a7e776a15255160eb548852c4829542d8c2f06c | 01d83afc1877977c042faf185afb8debe38f946d | /Lib/Widgets.cpp | c70b85b7fd0f7651c453d26d0407ba608e6513f4 | [] | no_license | lkorsman/GraphicDemoApp | 8437c7001763d6b24544b54943b1c89b117af959 | 34da71c04799a93f03a5dc5205d7657e247a8346 | refs/heads/master | 2023-01-15T22:01:51.114132 | 2020-11-19T14:12:27 | 2020-11-19T14:12:27 | 313,784,678 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,395 | cpp | // Widgets.cpp, Copyright (c) Jules Bloomenthal, Seattle, 2018, All rights reserved.
#include <glad.h>
#include <glfw3.h>
#include <gl/glu.h>
#include "Draw.h"
#include "GLXtras.h"
#include "Misc.h"
#include "Widgets.h"
#include <stdio.h>
#include <string.h>
// #define USE_TEXT
#ifdef USE_TEXT
#include "Text.h"
#endif
// Mouse
bool MouseOver(int x, int y, vec2 &p, int xoff, int yoff, int proximity) {
vec2 m(x+xoff, y+yoff);
return length(m-p) < proximity;
}
bool MouseOver(int x, int y, vec3 &p, mat4 &view, int xoff, int yoff, int proximity) {
return ScreenDistSq(x+xoff, y+yoff, p, view) < proximity*proximity;
}
// Mover
float DotProduct(float a[], float b[]) { return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]; }
/* deprecated
void SetPlane(vec3 &p, int x, int y, mat4 &modelview, mat4 &persp, float *plane) {
vec3 p1, p2; // two points that transform to pixel x,y
ScreenLine((float) x, (float) y, modelview, persp, (float *) &p1, (float *) &p2);
for (int i = 0; i < 3; i++)
plane[i] = p2[i]-p1[i]; // set plane normal (not unitized) to that of line p1p2
plane[3] = -plane[0]*p.x-plane[1]*p.y-plane[2]*p.z; // pass plane through point
} */
void Mover::Set(vec3 *p, int x, int y, mat4 modelview, mat4 persp) {
vec2 s = ScreenPoint(*p, persp*modelview);
mouseOffset = vec2(s.x-x, s.y-y);
point = p;
// SetPlane(*p, x, y, modelview, persp, plane);
for (int i = 0; i < 3; i++)
plane[i] = modelview[2][i]; // zrow (which is product of modelview matrix with untransformed z-axis)
plane[3] = -plane[0]*p->x-plane[1]*p->y-plane[2]*p->z; // pass plane through point
}
void Mover::Drag(int xMouse, int yMouse, mat4 modelview, mat4 persp) {
if (!point)
return;
float p1[3], p2[3], axis[3];
float x = xMouse+mouseOffset.x, y = yMouse+mouseOffset.y;
ScreenLine(static_cast<float>(x), static_cast<float>(y), modelview, persp, p1, p2);
// get two points that transform to pixel x,y
for (int i = 0; i < 3; i++)
axis[i] = p2[i]-p1[i];
// direction of line through p1
float pdDot = DotProduct(axis, plane);
// project onto plane normal
float a = (-plane[3]-DotProduct(p1, plane))/pdDot;
// intersection of line with plane
for (int j = 0; j < 3; j++)
(*point)[j] = p1[j]+a*axis[j];
}
bool Mover::Hit(int x, int y, mat4 &view, int xoff, int yoff, int proximity) {
return MouseOver(x, y, *point, view, xoff, yoff, proximity);
}
bool Mover::IsSet() {
return point != NULL;
}
void Mover::Unset() {
point = NULL;
}
// Toggler
Toggler::Toggler(bool *on, const char *name, int x, int y, float dia, vec3 onCol, vec3 offCol, vec3 ringCol)
: on(on), name(name), x(x), y(y), dia(dia), onCol(onCol), offCol(offCol), ringCol(ringCol) { };
void Toggler::Draw() {
// assume ScreenMode and no depth-test
vec3 p((float)x, (float)y, 0);
Disk(p, dia, ringCol);
Disk(p, dia-6, *on? onCol : offCol);
#ifdef USE_TEXT
Text(x+15, y-5, vec3(0,0,0), 1, name.c_str());
#endif
}
bool Toggler::Hit(int xMouse, int yMouse, int xoff, int yoff, int proximity) {
vec2 p((float)x, (float)y);
return MouseOver(xMouse, yMouse, p, xoff, yoff, proximity);
}
bool Toggler::UpHit(int xMouse, int yMouse, int state, int xoff, int yoff, int proximity) {
bool hit = Hit(xMouse, yMouse, xoff, yoff, proximity);
if (state == GLFW_RELEASE && hit)
*on = *on? false : true;
return hit;
}
bool Toggler::On() {
return *on;
}
const char *Toggler::Name() {
return name.c_str();
}
| [
"lukekorsman@gmail.com"
] | lukekorsman@gmail.com |
1190b452ea449bd30e4e346d0ac4905b21580cbc | da86d9f9cf875db42fd912e3366cfe9e0aa392c6 | /2020/solutions/C/AIP-Ruse/strip.cpp | e645bec86e91e554a7d28e4fc6563f1e24c37061 | [] | no_license | Alaxe/noi2-ranking | 0c98ea9af9fc3bd22798cab523f38fd75ed97634 | bb671bacd369b0924a1bfa313acb259f97947d05 | refs/heads/master | 2021-01-22T23:33:43.481107 | 2020-02-15T17:33:25 | 2020-02-15T17:33:25 | 85,631,202 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 513 | cpp | #include<iostream>
using namespace std;
long long a[55][55];
long long rez(long long n, long long k)
{
if(n <= k || k == 1)
{
return 1;
}
if(a[n - 1][k] == 0)
{
a[n - 1][k] = rez(n - 1, k);
}
if(a[n - 1][k - 1] == 0)
{
a[n - 1][k - 1] = rez(n - 1, k - 1);
}
return a[n - 1][k] + a[n - 1][k - 1];
}
int main()
{
long long n,k;
cin>>n>>k;
cout<<rez(n,k)<<endl;
return 0;
} | [
"aleks.tcr@gmail.com"
] | aleks.tcr@gmail.com |
9c9f6774604717b333da55bcf9db29dc273bdc17 | e4ca86fa4166ac425c725a6ede7a069896f6dfb9 | /library/flowNetwork/minCutMaxFlow.h | b6d1752e8667f617180a56bb36a598c4993b52e2 | [
"Unlicense"
] | permissive | kkafar/algorithm_study | 12d60ad6e2f918604be801f77508aee7e7857774 | 47b5deeff9197ea7dac415e72baedddf8eae67c2 | refs/heads/master | 2022-02-01T07:13:17.410488 | 2019-07-20T16:21:57 | 2019-07-20T16:21:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,998 | h | #pragma once
// Edmonds-Karp Algorithm (Ford-Fulkerson method)
template <typename T, const T INF = 0x3f3f3f3f>
struct MinCutMaxFlow {
struct Edge {
int to; // v
int revIndex; // for (v -> u)
T flow;
T capacity;
};
int N; // the number of vertices
vector<vector<Edge>> edges;
vector<pair<int, int>> parent; // (u, edge index in u's edges)
MinCutMaxFlow() : N(0) {
}
explicit MinCutMaxFlow(int n) : N(n), edges(N), parent(N, make_pair(-1, -1)) {
}
void init(int n) {
N = n;
edges = vector<vector<Edge>>(N);
parent = vector<pair<int, int>>(N, make_pair(-1, -1));
}
// add edges to a directed graph
void addEdge(int u, int v, T capacity, T capacityRev = 0) {
int uN = int(edges[u].size());
int vN = int(edges[v].size());
edges[u].push_back(Edge{ v, vN, 0, capacity });
edges[v].push_back(Edge{ u, uN, 0, capacityRev });
}
void clearFlow() {
for (auto& vec : edges) {
for (auto& e : vec)
e.flow = 0;
}
}
// O(V * E^2)
T findMinCut(int s, int t, vector<pair<int, int>>& minCutEdges) {
clearFlow();
minCutEdges.clear();
while (bfs(s, t)) {
T amount = INF;
for (int i = t; i != s; i = parent[i].first) {
int u = parent[i].first;
auto& e = edges[u][parent[i].second];
amount = min(amount, e.capacity - e.flow);
}
for (int i = t; i != s; i = parent[i].first) {
int u = parent[i].first;
auto& e = edges[u][parent[i].second];
e.flow += amount;
edges[e.to][e.revIndex].flow -= amount;
}
}
T res = 0;
for (int u = 0; u < int(N); u++) {
for (int j = 0; j < int(edges[u].size()); j++) {
auto& e = edges[u][j];
if (e.capacity > 0 && ((parent[u].first != -1) && (parent[e.to].first == -1))) {
res += e.flow;
minCutEdges.push_back(make_pair(u, e.to));
}
}
}
return res;
}
private:
bool bfs(int s, int t) {
fill(parent.begin(), parent.end(), make_pair(-1, -1));
//memset(&parent[0], -1, sizeof(parent[0]) * parent.size());
queue<int> q;
q.push(s);
parent[s] = make_pair(s, -1);
while (!q.empty() && parent[t].first == -1) {
int u = q.front();
q.pop();
for (int i = 0; i < int(edges[u].size()); i++) {
auto& e = edges[u][i];
if (parent[e.to].first == -1 && (e.capacity - e.flow) > 0) {
q.push(e.to);
parent[e.to] = make_pair(u, i);
}
}
}
return parent[t].first != -1;
}
};
| [
"youngman.ro@gmail.com"
] | youngman.ro@gmail.com |
8862f984f0c68c24fc0ce0dca9133fe3dcf5e755 | 022405262652cad4e130b81ac89e9c38383b4036 | /qt 2/new_user.cpp | 794321082c1e9dd353c8aabd3f91cd58da9c9a65 | [] | no_license | kartikeyagup/COP290-Anupam | c0a1aefc6ce46396e855da4648ddd7172bd3449f | 48ee59377c12eb36fdc5d86e2fac2fb3a44734f6 | refs/heads/master | 2021-01-20T01:03:27.756492 | 2015-04-06T18:49:11 | 2015-04-06T18:49:11 | 29,173,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,608 | cpp | #include "new_user.h"
#include "ui_new_user.h"
#include "secondwindow.h"
#include <qlineedit.h>
#include <fstream>
#include <vector>
#include <iostream>
#include <qmessagebox.h>
using namespace std;
New_User::New_User(QWidget *parent) :
QDialog(parent),
ui(new Ui::New_User)
{
ui->setupUi(this);
ui->name_lineedit->setPlaceholderText("Enter Name");
ui->surname_lineedit->setPlaceholderText("Enter Surname");
ui->securityquestion->setPlaceholderText("Enter Security Question");
ui->answer->setPlaceholderText("Enter Answer");
}
New_User::~New_User()
{
delete ui;
}
void New_User::on_createaccount_clicked()
{
vector<pair<string,QString> > newuserinfo;
vector<string> newuserinfostring;
// if(ui->name_lineedit->text()==""){
//
// }
// }
newuserinfo.push_back(make_pair("First name",ui->name_lineedit->text()));
newuserinfo.push_back(make_pair("Surname",ui->surname_lineedit->text()));
newuserinfo.push_back(make_pair("Username",ui->username1_lineedit->text()));
newuserinfo.push_back(make_pair("password",ui->password1_lineedit->text()));
newuserinfo.push_back(make_pair("security",ui->securityquestion->text()));
newuserinfo.push_back(make_pair("answer",ui->answer->text()));
for(int i=0;i<newuserinfo.size();i++){
QByteArray ba = newuserinfo[i].second.toLocal8Bit();
const char *c = ba.data();
newuserinfostring.push_back(string(c));
}
int count=0;
string a="";
for(int i=0;i<newuserinfostring.size();i++){
if(newuserinfostring[i]==""){
a+=newuserinfo[i].first;
a= a+ ","+ " ";
}
}
if(a!=""){
a=a.substr(0,a.size()-2);
a=a+":"+"not provided";
QMessageBox::information(this,"Unable to create account","please provide all information");
}
else if(ui->password1_lineedit->text()!=ui->repassword_lineedit->text()){
QMessageBox::information(this,"Unable to create account","Passwords do not match");
}
else{
ofstream newuserfile;
newuserfile.open("/home/ronak8/Desktop/Untitled Folder 2/newuserfile.txt");
for(int i=0;i<newuserinfostring.size();i++){
if(i==0){
newuserfile<<newuserinfostring[i]<<" ";
}
else{
newuserfile<<newuserinfostring[i]<<"\n";
}
}
QMessageBox::information(this,"Account Created","Account successfully Created");
this->hide();
Secondwindow secnew;
secnew.exec();
secnew.show();
newuserfile.close();
}
}
| [
"khandelwalronak1995@gmail.com"
] | khandelwalronak1995@gmail.com |
1ea50d2aa0c3cd905ebe57b38083efe8687743c1 | a815edcd3c7dcbb79d7fc20801c0170f3408b1d6 | /content/renderer/media/stream/user_media_processor.cc | f88184f6c0878b7cc8e77229552e53bfa5cb8e9a | [
"BSD-3-Clause"
] | permissive | oguzzkilic/chromium | 06be90df9f2e7f218bff6eee94235b6e684e2b40 | 1de71b638f99c15a3f97ec7b25b0c6dc920fbee0 | refs/heads/master | 2023-03-04T00:01:27.864257 | 2018-07-17T10:33:19 | 2018-07-17T10:33:19 | 141,275,697 | 1 | 0 | null | 2018-07-17T10:48:53 | 2018-07-17T10:48:52 | null | UTF-8 | C++ | false | false | 53,477 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/media/stream/user_media_processor.h"
#include <stddef.h>
#include <algorithm>
#include <map>
#include <utility>
#include "base/location.h"
#include "base/logging.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/stringprintf.h"
#include "base/task_runner.h"
#include "base/task_runner_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/common/media/media_stream_controls.h"
#include "content/renderer/media/stream/local_media_stream_audio_source.h"
#include "content/renderer/media/stream/media_stream_audio_processor.h"
#include "content/renderer/media/stream/media_stream_audio_source.h"
#include "content/renderer/media/stream/media_stream_constraints_util.h"
#include "content/renderer/media/stream/media_stream_constraints_util_audio.h"
#include "content/renderer/media/stream/media_stream_constraints_util_video_content.h"
#include "content/renderer/media/stream/media_stream_constraints_util_video_device.h"
#include "content/renderer/media/stream/media_stream_device_observer.h"
#include "content/renderer/media/stream/media_stream_video_capturer_source.h"
#include "content/renderer/media/stream/media_stream_video_track.h"
#include "content/renderer/media/stream/processed_local_audio_source.h"
#include "content/renderer/media/stream/user_media_client_impl.h"
#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
#include "content/renderer/media/webrtc/webrtc_uma_histograms.h"
#include "content/renderer/media/webrtc_logging.h"
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_widget.h"
#include "media/base/audio_parameters.h"
#include "media/capture/video_capture_types.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/platform/web_media_constraints.h"
#include "third_party/blink/public/platform/web_media_stream.h"
#include "third_party/blink/public/platform/web_media_stream_source.h"
#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/blink/public/platform/web_string.h"
#include "ui/gfx/geometry/size.h"
#include "url/origin.h"
namespace content {
namespace {
void CopyFirstString(const blink::StringConstraint& constraint,
std::string* destination) {
if (!constraint.Exact().IsEmpty())
*destination = constraint.Exact()[0].Utf8();
}
bool IsDeviceSource(const std::string& source) {
return source.empty();
}
void InitializeTrackControls(const blink::WebMediaConstraints& constraints,
TrackControls* track_controls) {
DCHECK(!constraints.IsNull());
track_controls->requested = true;
CopyFirstString(constraints.Basic().media_stream_source,
&track_controls->stream_source);
}
bool IsSameDevice(const MediaStreamDevice& device,
const MediaStreamDevice& other_device) {
return device.id == other_device.id && device.type == other_device.type &&
device.session_id == other_device.session_id;
}
bool IsSameSource(const blink::WebMediaStreamSource& source,
const blink::WebMediaStreamSource& other_source) {
MediaStreamSource* const source_extra_data =
static_cast<MediaStreamSource*>(source.GetExtraData());
const MediaStreamDevice& device = source_extra_data->device();
MediaStreamSource* const other_source_extra_data =
static_cast<MediaStreamSource*>(other_source.GetExtraData());
const MediaStreamDevice& other_device = other_source_extra_data->device();
return IsSameDevice(device, other_device);
}
bool IsValidAudioContentSource(const std::string& source) {
return source == kMediaStreamSourceTab ||
source == kMediaStreamSourceDesktop ||
source == kMediaStreamSourceSystem;
}
bool IsValidVideoContentSource(const std::string& source) {
return source == kMediaStreamSourceTab ||
source == kMediaStreamSourceDesktop ||
source == kMediaStreamSourceScreen;
}
void SurfaceAudioProcessingSettings(blink::WebMediaStreamSource* source) {
MediaStreamAudioSource* source_impl =
static_cast<MediaStreamAudioSource*>(source->GetExtraData());
bool sw_echo_cancellation = false, auto_gain_control = false,
noise_supression = false, system_echo_cancellation = false;
if (ProcessedLocalAudioSource* processed_source =
ProcessedLocalAudioSource::From(source_impl)) {
AudioProcessingProperties properties =
processed_source->audio_processing_properties();
sw_echo_cancellation = properties.EchoCancellationIsWebRtcProvided();
auto_gain_control = properties.goog_auto_gain_control;
noise_supression = properties.goog_noise_suppression;
// The ECHO_CANCELLER flag will be set if either:
// - The device advertises the ECHO_CANCELLER flag and
// echo_cancellation_type is kEchoCancellationDisabled or
// kEchoCancellationAec2 (that is, system ec is disabled);
// or if
// - The device advertises the EXPERIMENTAL_ECHO_CANCELLER flag and
// echo_cancellation_type is kEchoCancellationSystem.
// See: ProcessedLocalAudioSource::EnsureSourceIsStarted().
const media::AudioParameters& params = processed_source->device().input;
system_echo_cancellation =
params.IsValid() &&
(params.effects() & media::AudioParameters::ECHO_CANCELLER);
}
using blink::WebMediaStreamSource;
const WebMediaStreamSource::EchoCancellationMode echo_cancellation_mode =
system_echo_cancellation
? WebMediaStreamSource::EchoCancellationMode::kHardware
: sw_echo_cancellation
? WebMediaStreamSource::EchoCancellationMode::kSoftware
: WebMediaStreamSource::EchoCancellationMode::kDisabled;
source->SetAudioProcessingProperties(echo_cancellation_mode,
auto_gain_control, noise_supression);
}
} // namespace
UserMediaRequest::UserMediaRequest(
int request_id,
const blink::WebUserMediaRequest& web_request,
bool is_processing_user_gesture)
: request_id(request_id),
web_request(web_request),
is_processing_user_gesture(is_processing_user_gesture) {}
// Class for storing state of the the processing of getUserMedia requests.
class UserMediaProcessor::RequestInfo
: public base::SupportsWeakPtr<RequestInfo> {
public:
using ResourcesReady =
base::Callback<void(RequestInfo* request_info,
MediaStreamRequestResult result,
const blink::WebString& result_name)>;
enum class State {
NOT_SENT_FOR_GENERATION,
SENT_FOR_GENERATION,
GENERATED,
};
explicit RequestInfo(std::unique_ptr<UserMediaRequest> request);
void StartAudioTrack(const blink::WebMediaStreamTrack& track,
bool is_pending);
blink::WebMediaStreamTrack CreateAndStartVideoTrack(
const blink::WebMediaStreamSource& source);
// Triggers |callback| when all sources used in this request have either
// successfully started, or a source has failed to start.
void CallbackOnTracksStarted(const ResourcesReady& callback);
// Called when a local audio source has finished (or failed) initializing.
void OnAudioSourceStarted(MediaStreamSource* source,
MediaStreamRequestResult result,
const blink::WebString& result_name);
UserMediaRequest* request() { return request_.get(); }
int request_id() const { return request_->request_id; }
State state() const { return state_; }
void set_state(State state) { state_ = state; }
const AudioCaptureSettings& audio_capture_settings() const {
return audio_capture_settings_;
}
void SetAudioCaptureSettings(const AudioCaptureSettings& settings,
bool is_content_capture) {
DCHECK(settings.HasValue());
is_audio_content_capture_ = is_content_capture;
audio_capture_settings_ = settings;
}
const VideoCaptureSettings& video_capture_settings() const {
return video_capture_settings_;
}
bool is_video_content_capture() const {
return video_capture_settings_.HasValue() && is_video_content_capture_;
}
bool is_video_device_capture() const {
return video_capture_settings_.HasValue() && !is_video_content_capture_;
}
void SetVideoCaptureSettings(const VideoCaptureSettings& settings,
bool is_content_capture) {
DCHECK(settings.HasValue());
is_video_content_capture_ = is_content_capture;
video_capture_settings_ = settings;
}
void SetDevices(MediaStreamDevices audio_devices,
MediaStreamDevices video_devices) {
audio_devices_ = std::move(audio_devices);
video_devices_ = std::move(video_devices);
}
void AddNativeVideoFormats(const std::string& device_id,
media::VideoCaptureFormats formats) {
video_formats_map_[device_id] = std::move(formats);
}
// Do not store or delete the returned pointer.
media::VideoCaptureFormats* GetNativeVideoFormats(
const std::string& device_id) {
auto it = video_formats_map_.find(device_id);
CHECK(it != video_formats_map_.end());
return &it->second;
}
const MediaStreamDevices& audio_devices() const { return audio_devices_; }
const MediaStreamDevices& video_devices() const { return video_devices_; }
bool CanStartTracks() const {
return video_formats_map_.size() == video_devices_.size();
}
blink::WebMediaStream* web_stream() { return &web_stream_; }
const blink::WebUserMediaRequest& web_request() const {
return request_->web_request;
}
StreamControls* stream_controls() { return &stream_controls_; }
bool is_processing_user_gesture() const {
return request_->is_processing_user_gesture;
}
const url::Origin& security_origin() const { return security_origin_; }
private:
void OnTrackStarted(MediaStreamSource* source,
MediaStreamRequestResult result,
const blink::WebString& result_name);
// Cheks if the sources for all tracks have been started and if so,
// invoke the |ready_callback_|. Note that the caller should expect
// that |this| might be deleted when the function returns.
void CheckAllTracksStarted();
std::unique_ptr<UserMediaRequest> request_;
State state_ = State::NOT_SENT_FOR_GENERATION;
AudioCaptureSettings audio_capture_settings_;
bool is_audio_content_capture_ = false;
VideoCaptureSettings video_capture_settings_;
bool is_video_content_capture_ = false;
blink::WebMediaStream web_stream_;
StreamControls stream_controls_;
const url::Origin security_origin_;
ResourcesReady ready_callback_;
MediaStreamRequestResult request_result_ = MEDIA_DEVICE_OK;
blink::WebString request_result_name_;
// Sources used in this request.
std::vector<blink::WebMediaStreamSource> sources_;
std::vector<MediaStreamSource*> sources_waiting_for_callback_;
std::map<std::string, media::VideoCaptureFormats> video_formats_map_;
MediaStreamDevices audio_devices_;
MediaStreamDevices video_devices_;
};
// TODO(guidou): Initialize request_result_name_ as a null blink::WebString.
// http://crbug.com/764293
UserMediaProcessor::RequestInfo::RequestInfo(
std::unique_ptr<UserMediaRequest> request)
: request_(std::move(request)),
security_origin_(url::Origin(request_->web_request.GetSecurityOrigin())),
request_result_name_("") {}
void UserMediaProcessor::RequestInfo::StartAudioTrack(
const blink::WebMediaStreamTrack& track,
bool is_pending) {
DCHECK(track.Source().GetType() == blink::WebMediaStreamSource::kTypeAudio);
DCHECK(web_request().Audio());
#if DCHECK_IS_ON()
DCHECK(audio_capture_settings_.HasValue());
#endif
MediaStreamAudioSource* native_source =
MediaStreamAudioSource::From(track.Source());
// Add the source as pending since OnTrackStarted will expect it to be there.
sources_waiting_for_callback_.push_back(native_source);
sources_.push_back(track.Source());
bool connected = native_source->ConnectToTrack(track);
if (!is_pending) {
OnTrackStarted(
native_source,
connected ? MEDIA_DEVICE_OK : MEDIA_DEVICE_TRACK_START_FAILURE_AUDIO,
"");
}
}
blink::WebMediaStreamTrack
UserMediaProcessor::RequestInfo::CreateAndStartVideoTrack(
const blink::WebMediaStreamSource& source) {
DCHECK(source.GetType() == blink::WebMediaStreamSource::kTypeVideo);
DCHECK(web_request().Video());
DCHECK(video_capture_settings_.HasValue());
MediaStreamVideoSource* native_source =
MediaStreamVideoSource::GetVideoSource(source);
DCHECK(native_source);
sources_.push_back(source);
sources_waiting_for_callback_.push_back(native_source);
return MediaStreamVideoTrack::CreateVideoTrack(
native_source, video_capture_settings_.track_adapter_settings(),
video_capture_settings_.noise_reduction(), is_video_content_capture_,
video_capture_settings_.min_frame_rate(),
base::Bind(&UserMediaProcessor::RequestInfo::OnTrackStarted, AsWeakPtr()),
true);
}
void UserMediaProcessor::RequestInfo::CallbackOnTracksStarted(
const ResourcesReady& callback) {
DCHECK(ready_callback_.is_null());
ready_callback_ = callback;
CheckAllTracksStarted();
}
void UserMediaProcessor::RequestInfo::OnTrackStarted(
MediaStreamSource* source,
MediaStreamRequestResult result,
const blink::WebString& result_name) {
DVLOG(1) << "OnTrackStarted result " << result;
auto it = std::find(sources_waiting_for_callback_.begin(),
sources_waiting_for_callback_.end(), source);
DCHECK(it != sources_waiting_for_callback_.end());
sources_waiting_for_callback_.erase(it);
// All tracks must be started successfully. Otherwise the request is a
// failure.
if (result != MEDIA_DEVICE_OK) {
request_result_ = result;
request_result_name_ = result_name;
}
CheckAllTracksStarted();
}
void UserMediaProcessor::RequestInfo::CheckAllTracksStarted() {
if (!ready_callback_.is_null() && sources_waiting_for_callback_.empty()) {
ready_callback_.Run(this, request_result_, request_result_name_);
// NOTE: |this| might now be deleted.
}
}
void UserMediaProcessor::RequestInfo::OnAudioSourceStarted(
MediaStreamSource* source,
MediaStreamRequestResult result,
const blink::WebString& result_name) {
// Check if we're waiting to be notified of this source. If not, then we'll
// ignore the notification.
auto found = std::find(sources_waiting_for_callback_.begin(),
sources_waiting_for_callback_.end(), source);
if (found != sources_waiting_for_callback_.end())
OnTrackStarted(source, result, result_name);
}
UserMediaProcessor::UserMediaProcessor(
RenderFrameImpl* render_frame,
PeerConnectionDependencyFactory* dependency_factory,
std::unique_ptr<MediaStreamDeviceObserver> media_stream_device_observer,
MediaDevicesDispatcherCallback media_devices_dispatcher_cb)
: dependency_factory_(dependency_factory),
media_stream_device_observer_(std::move(media_stream_device_observer)),
media_devices_dispatcher_cb_(std::move(media_devices_dispatcher_cb)),
render_frame_(render_frame),
weak_factory_(this) {
DCHECK(dependency_factory_);
DCHECK(media_stream_device_observer_.get());
}
UserMediaProcessor::~UserMediaProcessor() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Force-close all outstanding user media requests and local sources here,
// before the outstanding WeakPtrs are invalidated, to ensure a clean
// shutdown.
StopAllProcessing();
}
UserMediaRequest* UserMediaProcessor::CurrentRequest() {
return current_request_info_ ? current_request_info_->request() : nullptr;
}
void UserMediaProcessor::ProcessRequest(
std::unique_ptr<UserMediaRequest> request,
base::OnceClosure callback) {
DCHECK(!request_completed_cb_);
DCHECK(!current_request_info_);
request_completed_cb_ = std::move(callback);
current_request_info_ = std::make_unique<RequestInfo>(std::move(request));
// TODO(guidou): Set up audio and video in parallel.
if (current_request_info_->web_request().Audio()) {
SetupAudioInput();
return;
}
SetupVideoInput();
}
void UserMediaProcessor::SetupAudioInput() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
DCHECK(current_request_info_->web_request().Audio());
auto& audio_controls = current_request_info_->stream_controls()->audio;
InitializeTrackControls(
current_request_info_->web_request().AudioConstraints(), &audio_controls);
if (IsDeviceSource(audio_controls.stream_source)) {
GetMediaDevicesDispatcher()->GetAudioInputCapabilities(base::BindOnce(
&UserMediaProcessor::SelectAudioDeviceSettings,
weak_factory_.GetWeakPtr(), current_request_info_->web_request()));
} else {
if (!IsValidAudioContentSource(audio_controls.stream_source)) {
blink::WebString failed_constraint_name =
blink::WebString::FromASCII(current_request_info_->web_request()
.AudioConstraints()
.Basic()
.media_stream_source.GetName());
MediaStreamRequestResult result = MEDIA_DEVICE_CONSTRAINT_NOT_SATISFIED;
GetUserMediaRequestFailed(result, failed_constraint_name);
return;
}
SelectAudioSettings(current_request_info_->web_request(),
{AudioDeviceCaptureCapability()});
}
}
void UserMediaProcessor::SelectAudioDeviceSettings(
const blink::WebUserMediaRequest& web_request,
std::vector<blink::mojom::AudioInputDeviceCapabilitiesPtr>
audio_input_capabilities) {
AudioDeviceCaptureCapabilities capabilities;
for (const auto& device : audio_input_capabilities) {
MediaStreamAudioSource* audio_source = nullptr;
auto it =
std::find_if(local_sources_.begin(), local_sources_.end(),
[&device](const blink::WebMediaStreamSource& web_source) {
DCHECK(!web_source.IsNull());
return web_source.Id().Utf8() == device->device_id;
});
if (it != local_sources_.end()) {
MediaStreamSource* const source =
static_cast<MediaStreamSource*>(it->GetExtraData());
if (source->device().type == MEDIA_DEVICE_AUDIO_CAPTURE)
audio_source = static_cast<MediaStreamAudioSource*>(source);
}
if (audio_source) {
capabilities.emplace_back(audio_source);
} else {
capabilities.emplace_back(device->device_id, device->group_id,
device->parameters);
}
}
SelectAudioSettings(web_request, capabilities);
}
void UserMediaProcessor::SelectAudioSettings(
const blink::WebUserMediaRequest& web_request,
const std::vector<AudioDeviceCaptureCapability>& capabilities) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// The frame might reload or |web_request| might be cancelled while
// capabilities are queried. Do nothing if a different request is being
// processed at this point.
if (!IsCurrentRequestInfo(web_request))
return;
DCHECK(current_request_info_->stream_controls()->audio.requested);
auto settings = SelectSettingsAudioCapture(
capabilities, web_request.AudioConstraints(),
web_request.ShouldDisableHardwareNoiseSuppression());
if (!settings.HasValue()) {
blink::WebString failed_constraint_name =
blink::WebString::FromASCII(settings.failed_constraint_name());
MediaStreamRequestResult result =
failed_constraint_name.IsEmpty()
? MEDIA_DEVICE_NO_HARDWARE
: MEDIA_DEVICE_CONSTRAINT_NOT_SATISFIED;
GetUserMediaRequestFailed(result, failed_constraint_name);
return;
}
current_request_info_->stream_controls()->audio.device_id =
settings.device_id();
current_request_info_->stream_controls()->disable_local_echo =
settings.disable_local_echo();
current_request_info_->stream_controls()->hotword_enabled =
settings.hotword_enabled();
current_request_info_->SetAudioCaptureSettings(
settings,
!IsDeviceSource(
current_request_info_->stream_controls()->audio.stream_source));
// No further audio setup required. Continue with video.
SetupVideoInput();
}
void UserMediaProcessor::SetupVideoInput() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
if (!current_request_info_->web_request().Video()) {
GenerateStreamForCurrentRequestInfo();
return;
}
auto& video_controls = current_request_info_->stream_controls()->video;
InitializeTrackControls(
current_request_info_->web_request().VideoConstraints(), &video_controls);
if (IsDeviceSource(video_controls.stream_source)) {
GetMediaDevicesDispatcher()->GetVideoInputCapabilities(base::BindOnce(
&UserMediaProcessor::SelectVideoDeviceSettings,
weak_factory_.GetWeakPtr(), current_request_info_->web_request()));
} else {
if (!IsValidVideoContentSource(video_controls.stream_source)) {
blink::WebString failed_constraint_name =
blink::WebString::FromASCII(current_request_info_->web_request()
.VideoConstraints()
.Basic()
.media_stream_source.GetName());
MediaStreamRequestResult result = MEDIA_DEVICE_CONSTRAINT_NOT_SATISFIED;
GetUserMediaRequestFailed(result, failed_constraint_name);
return;
}
SelectVideoContentSettings();
}
}
void UserMediaProcessor::SelectVideoDeviceSettings(
const blink::WebUserMediaRequest& web_request,
std::vector<blink::mojom::VideoInputDeviceCapabilitiesPtr>
video_input_capabilities) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// The frame might reload or |web_request| might be cancelled while
// capabilities are queried. Do nothing if a different request is being
// processed at this point.
if (!IsCurrentRequestInfo(web_request))
return;
DCHECK(current_request_info_->stream_controls()->video.requested);
DCHECK(IsDeviceSource(
current_request_info_->stream_controls()->video.stream_source));
VideoDeviceCaptureCapabilities capabilities;
capabilities.device_capabilities = std::move(video_input_capabilities);
capabilities.power_line_capabilities = {
media::PowerLineFrequency::FREQUENCY_DEFAULT,
media::PowerLineFrequency::FREQUENCY_50HZ,
media::PowerLineFrequency::FREQUENCY_60HZ};
capabilities.noise_reduction_capabilities = {base::Optional<bool>(),
base::Optional<bool>(true),
base::Optional<bool>(false)};
VideoCaptureSettings settings = SelectSettingsVideoDeviceCapture(
std::move(capabilities), web_request.VideoConstraints(),
MediaStreamVideoSource::kDefaultWidth,
MediaStreamVideoSource::kDefaultHeight,
MediaStreamVideoSource::kDefaultFrameRate);
if (!settings.HasValue()) {
blink::WebString failed_constraint_name =
blink::WebString::FromASCII(settings.failed_constraint_name());
MediaStreamRequestResult result =
failed_constraint_name.IsEmpty()
? MEDIA_DEVICE_NO_HARDWARE
: MEDIA_DEVICE_CONSTRAINT_NOT_SATISFIED;
GetUserMediaRequestFailed(result, failed_constraint_name);
return;
}
current_request_info_->stream_controls()->video.device_id =
settings.device_id();
current_request_info_->SetVideoCaptureSettings(
settings, false /* is_content_capture */);
GenerateStreamForCurrentRequestInfo();
}
void UserMediaProcessor::SelectVideoContentSettings() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
gfx::Size screen_size = GetScreenSize();
VideoCaptureSettings settings = SelectSettingsVideoContentCapture(
current_request_info_->web_request().VideoConstraints(),
current_request_info_->stream_controls()->video.stream_source,
screen_size.width(), screen_size.height());
if (!settings.HasValue()) {
blink::WebString failed_constraint_name =
blink::WebString::FromASCII(settings.failed_constraint_name());
DCHECK(!failed_constraint_name.IsEmpty());
GetUserMediaRequestFailed(MEDIA_DEVICE_CONSTRAINT_NOT_SATISFIED,
failed_constraint_name);
return;
}
current_request_info_->stream_controls()->video.device_id =
settings.device_id();
current_request_info_->SetVideoCaptureSettings(settings,
true /* is_content_capture */);
GenerateStreamForCurrentRequestInfo();
}
void UserMediaProcessor::GenerateStreamForCurrentRequestInfo() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
WebRtcLogMessage(base::StringPrintf(
"UMCI::GenerateStreamForCurrentRequestInfo. request_id=%d, "
"audio device id=\"%s\", video device id=\"%s\"",
current_request_info_->request_id(),
current_request_info_->stream_controls()->audio.device_id.c_str(),
current_request_info_->stream_controls()->video.device_id.c_str()));
current_request_info_->set_state(RequestInfo::State::SENT_FOR_GENERATION);
// The browser replies to this request by invoking OnStreamGenerated().
GetMediaStreamDispatcherHost()->GenerateStream(
current_request_info_->request_id(),
*current_request_info_->stream_controls(),
current_request_info_->is_processing_user_gesture(),
base::BindOnce(&UserMediaProcessor::OnStreamGenerated,
weak_factory_.GetWeakPtr(),
current_request_info_->request_id()));
}
void UserMediaProcessor::OnStreamGenerated(
int request_id,
MediaStreamRequestResult result,
const std::string& label,
const MediaStreamDevices& audio_devices,
const MediaStreamDevices& video_devices) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (result != MEDIA_DEVICE_OK) {
OnStreamGenerationFailed(request_id, result);
return;
}
if (!IsCurrentRequestInfo(request_id)) {
// This can happen if the request is cancelled or the frame reloads while
// MediaStreamDispatcherHost is processing the request.
DVLOG(1) << "Request ID not found";
OnStreamGeneratedForCancelledRequest(audio_devices, video_devices);
return;
}
current_request_info_->set_state(RequestInfo::State::GENERATED);
for (const auto* devices : {&audio_devices, &video_devices}) {
for (const auto& device : *devices) {
WebRtcLogMessage(base::StringPrintf(
"UMCI::OnStreamGenerated. request_id=%d, device id=\"%s\", "
"device name=\"%s\"",
request_id, device.id.c_str(), device.name.c_str()));
}
}
current_request_info_->SetDevices(audio_devices, video_devices);
if (video_devices.empty()) {
StartTracks(label);
return;
}
if (current_request_info_->is_video_content_capture()) {
media::VideoCaptureFormat format =
current_request_info_->video_capture_settings().Format();
for (const auto& video_device : video_devices) {
current_request_info_->AddNativeVideoFormats(
video_device.id,
{media::VideoCaptureFormat(GetScreenSize(), format.frame_rate,
format.pixel_format)});
}
StartTracks(label);
return;
}
for (const auto& video_device : video_devices) {
GetMediaDevicesDispatcher()->GetAllVideoInputDeviceFormats(
video_device.id,
base::BindOnce(&UserMediaProcessor::GotAllVideoInputFormatsForDevice,
weak_factory_.GetWeakPtr(),
current_request_info_->web_request(), label,
video_device.id));
}
}
void UserMediaProcessor::GotAllVideoInputFormatsForDevice(
const blink::WebUserMediaRequest& web_request,
const std::string& label,
const std::string& device_id,
const media::VideoCaptureFormats& formats) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// The frame might reload or |web_request| might be cancelled while video
// formats are queried. Do nothing if a different request is being processed
// at this point.
if (!IsCurrentRequestInfo(web_request))
return;
current_request_info_->AddNativeVideoFormats(device_id, formats);
if (current_request_info_->CanStartTracks())
StartTracks(label);
}
gfx::Size UserMediaProcessor::GetScreenSize() {
gfx::Size screen_size(kDefaultScreenCastWidth, kDefaultScreenCastHeight);
if (render_frame_) { // Can be null in tests.
blink::WebScreenInfo info =
render_frame_->GetRenderWidget()->GetScreenInfo();
screen_size = gfx::Size(info.rect.width, info.rect.height);
}
return screen_size;
}
void UserMediaProcessor::OnStreamGeneratedForCancelledRequest(
const MediaStreamDevices& audio_devices,
const MediaStreamDevices& video_devices) {
// Only stop the device if the device is not used in another MediaStream.
for (auto it = audio_devices.begin(); it != audio_devices.end(); ++it) {
if (!FindLocalSource(*it)) {
GetMediaStreamDispatcherHost()->StopStreamDevice(it->id, it->session_id);
}
}
for (auto it = video_devices.begin(); it != video_devices.end(); ++it) {
if (!FindLocalSource(*it)) {
GetMediaStreamDispatcherHost()->StopStreamDevice(it->id, it->session_id);
}
}
}
// static
void UserMediaProcessor::OnAudioSourceStartedOnAudioThread(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
base::WeakPtr<UserMediaProcessor> weak_ptr,
MediaStreamSource* source,
MediaStreamRequestResult result,
const blink::WebString& result_name) {
task_runner->PostTask(
FROM_HERE, base::BindOnce(&UserMediaProcessor::OnAudioSourceStarted,
weak_ptr, source, result, result_name));
}
void UserMediaProcessor::OnAudioSourceStarted(
MediaStreamSource* source,
MediaStreamRequestResult result,
const blink::WebString& result_name) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
for (auto it = pending_local_sources_.begin();
it != pending_local_sources_.end(); ++it) {
MediaStreamSource* const source_extra_data =
static_cast<MediaStreamSource*>((*it).GetExtraData());
if (source_extra_data != source)
continue;
if (result == MEDIA_DEVICE_OK)
local_sources_.push_back((*it));
pending_local_sources_.erase(it);
NotifyCurrentRequestInfoOfAudioSourceStarted(source, result, result_name);
return;
}
NOTREACHED();
}
void UserMediaProcessor::NotifyCurrentRequestInfoOfAudioSourceStarted(
MediaStreamSource* source,
MediaStreamRequestResult result,
const blink::WebString& result_name) {
// The only request possibly being processed is |current_request_info_|.
if (current_request_info_)
current_request_info_->OnAudioSourceStarted(source, result, result_name);
}
void UserMediaProcessor::OnStreamGenerationFailed(
int request_id,
MediaStreamRequestResult result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!IsCurrentRequestInfo(request_id)) {
// This can happen if the request is cancelled or the frame reloads while
// MediaStreamDispatcherHost is processing the request.
return;
}
GetUserMediaRequestFailed(result);
DeleteWebRequest(current_request_info_->web_request());
}
void UserMediaProcessor::OnDeviceStopped(const MediaStreamDevice& device) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DVLOG(1) << "UserMediaClientImpl::OnDeviceStopped("
<< "{device_id = " << device.id << "})";
const blink::WebMediaStreamSource* source_ptr = FindLocalSource(device);
if (!source_ptr) {
// This happens if the same device is used in several guM requests or
// if a user happen stop a track from JS at the same time
// as the underlying media device is unplugged from the system.
return;
}
// By creating |source| it is guaranteed that the blink::WebMediaStreamSource
// object is valid during the cleanup.
blink::WebMediaStreamSource source(*source_ptr);
StopLocalSource(source, false);
RemoveLocalSource(source);
}
blink::WebMediaStreamSource UserMediaProcessor::InitializeVideoSourceObject(
const MediaStreamDevice& device) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
blink::WebMediaStreamSource source = FindOrInitializeSourceObject(device);
if (!source.GetExtraData()) {
source.SetExtraData(CreateVideoSource(
device, base::Bind(&UserMediaProcessor::OnLocalSourceStopped,
weak_factory_.GetWeakPtr())));
source.SetCapabilities(ComputeCapabilitiesForVideoSource(
blink::WebString::FromUTF8(device.id),
*current_request_info_->GetNativeVideoFormats(device.id),
device.video_facing, current_request_info_->is_video_device_capture(),
device.group_id));
local_sources_.push_back(source);
}
return source;
}
blink::WebMediaStreamSource UserMediaProcessor::InitializeAudioSourceObject(
const MediaStreamDevice& device,
bool* is_pending) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
*is_pending = true;
// See if the source is already being initialized.
auto* pending = FindPendingLocalSource(device);
if (pending)
return *pending;
blink::WebMediaStreamSource source = FindOrInitializeSourceObject(device);
if (source.GetExtraData()) {
// The only return point for non-pending sources.
*is_pending = false;
return source;
}
// While sources are being initialized, keep them in a separate array.
// Once they've finished initialized, they'll be moved over to local_sources_.
// See OnAudioSourceStarted for more details.
pending_local_sources_.push_back(source);
MediaStreamSource::ConstraintsCallback source_ready = base::Bind(
&UserMediaProcessor::OnAudioSourceStartedOnAudioThread,
base::ThreadTaskRunnerHandle::Get(), weak_factory_.GetWeakPtr());
MediaStreamAudioSource* const audio_source =
CreateAudioSource(device, std::move(source_ready));
audio_source->SetStopCallback(base::Bind(
&UserMediaProcessor::OnLocalSourceStopped, weak_factory_.GetWeakPtr()));
blink::WebMediaStreamSource::Capabilities capabilities;
capabilities.echo_cancellation = {true, false};
capabilities.echo_cancellation_type.reserve(2);
capabilities.echo_cancellation_type.emplace_back(
blink::WebString::FromASCII(blink::kEchoCancellationTypeBrowser));
if (device.input.effects() &
(media::AudioParameters::ECHO_CANCELLER |
media::AudioParameters::EXPERIMENTAL_ECHO_CANCELLER)) {
capabilities.echo_cancellation_type.emplace_back(
blink::WebString::FromASCII(blink::kEchoCancellationTypeSystem));
}
capabilities.auto_gain_control = {true, false};
capabilities.noise_suppression = {true, false};
capabilities.device_id = blink::WebString::FromUTF8(device.id);
if (device.group_id)
capabilities.group_id = blink::WebString::FromUTF8(*device.group_id);
source.SetExtraData(audio_source); // Takes ownership.
source.SetCapabilities(capabilities);
return source;
}
MediaStreamAudioSource* UserMediaProcessor::CreateAudioSource(
const MediaStreamDevice& device,
const MediaStreamSource::ConstraintsCallback& source_ready) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
StreamControls* stream_controls = current_request_info_->stream_controls();
// If the audio device is a loopback device (for screen capture), or if the
// constraints/effects parameters indicate no audio processing is needed,
// create an efficient, direct-path MediaStreamAudioSource instance.
AudioProcessingProperties audio_processing_properties =
current_request_info_->audio_capture_settings()
.audio_processing_properties();
if (IsScreenCaptureMediaType(device.type) ||
!MediaStreamAudioProcessor::WouldModifyAudio(
audio_processing_properties)) {
return new LocalMediaStreamAudioSource(
render_frame_->GetRoutingID(), device, stream_controls->hotword_enabled,
stream_controls->disable_local_echo, source_ready);
}
// The audio device is not associated with screen capture and also requires
// processing.
return new ProcessedLocalAudioSource(
render_frame_->GetRoutingID(), device, stream_controls->hotword_enabled,
stream_controls->disable_local_echo, audio_processing_properties,
source_ready, dependency_factory_);
}
MediaStreamVideoSource* UserMediaProcessor::CreateVideoSource(
const MediaStreamDevice& device,
const MediaStreamSource::SourceStoppedCallback& stop_callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
DCHECK(current_request_info_->video_capture_settings().HasValue());
return new MediaStreamVideoCapturerSource(
render_frame_->GetRoutingID(), stop_callback, device,
current_request_info_->video_capture_settings().capture_params());
}
void UserMediaProcessor::StartTracks(const std::string& label) {
DCHECK(!current_request_info_->web_request().IsNull());
media_stream_device_observer_->AddStream(
label, current_request_info_->audio_devices(),
current_request_info_->video_devices(), weak_factory_.GetWeakPtr());
blink::WebVector<blink::WebMediaStreamTrack> audio_tracks(
current_request_info_->audio_devices().size());
CreateAudioTracks(current_request_info_->audio_devices(), &audio_tracks);
blink::WebVector<blink::WebMediaStreamTrack> video_tracks(
current_request_info_->video_devices().size());
CreateVideoTracks(current_request_info_->video_devices(), &video_tracks);
blink::WebString blink_id = blink::WebString::FromUTF8(label);
current_request_info_->web_stream()->Initialize(blink_id, audio_tracks,
video_tracks);
// Wait for the tracks to be started successfully or to fail.
current_request_info_->CallbackOnTracksStarted(
base::BindRepeating(&UserMediaProcessor::OnCreateNativeTracksCompleted,
weak_factory_.GetWeakPtr(), label));
}
void UserMediaProcessor::CreateVideoTracks(
const MediaStreamDevices& devices,
blink::WebVector<blink::WebMediaStreamTrack>* webkit_tracks) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
DCHECK_EQ(devices.size(), webkit_tracks->size());
for (size_t i = 0; i < devices.size(); ++i) {
blink::WebMediaStreamSource source =
InitializeVideoSourceObject(devices[i]);
(*webkit_tracks)[i] =
current_request_info_->CreateAndStartVideoTrack(source);
}
}
void UserMediaProcessor::CreateAudioTracks(
const MediaStreamDevices& devices,
blink::WebVector<blink::WebMediaStreamTrack>* webkit_tracks) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(current_request_info_);
DCHECK_EQ(devices.size(), webkit_tracks->size());
MediaStreamDevices overridden_audio_devices = devices;
bool render_to_associated_sink =
current_request_info_->audio_capture_settings().HasValue() &&
current_request_info_->audio_capture_settings()
.render_to_associated_sink();
if (!render_to_associated_sink) {
// If the GetUserMedia request did not explicitly set the constraint
// kMediaStreamRenderToAssociatedSink, the output device id must
// be removed.
for (auto& device : overridden_audio_devices)
device.matched_output_device_id.reset();
}
for (size_t i = 0; i < overridden_audio_devices.size(); ++i) {
bool is_pending = false;
blink::WebMediaStreamSource source =
InitializeAudioSourceObject(overridden_audio_devices[i], &is_pending);
(*webkit_tracks)[i].Initialize(source);
current_request_info_->StartAudioTrack((*webkit_tracks)[i], is_pending);
// At this point the source has started, and its audio parameters have been
// set. Thus, all audio processing properties are known and can be surfaced
// to |source|.
SurfaceAudioProcessingSettings(&source);
}
}
void UserMediaProcessor::OnCreateNativeTracksCompleted(
const std::string& label,
RequestInfo* request_info,
MediaStreamRequestResult result,
const blink::WebString& constraint_name) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (result == MEDIA_DEVICE_OK) {
GetUserMediaRequestSucceeded(*request_info->web_stream(),
request_info->web_request());
GetMediaStreamDispatcherHost()->OnStreamStarted(label);
} else {
GetUserMediaRequestFailed(result, constraint_name);
for (auto& web_track : request_info->web_stream()->AudioTracks()) {
MediaStreamTrack* track = MediaStreamTrack::GetTrack(web_track);
if (track)
track->Stop();
}
for (auto& web_track : request_info->web_stream()->VideoTracks()) {
MediaStreamTrack* track = MediaStreamTrack::GetTrack(web_track);
if (track)
track->Stop();
}
}
DeleteWebRequest(request_info->web_request());
}
void UserMediaProcessor::GetUserMediaRequestSucceeded(
const blink::WebMediaStream& stream,
blink::WebUserMediaRequest web_request) {
DCHECK(IsCurrentRequestInfo(web_request));
WebRtcLogMessage(
base::StringPrintf("UMCI::GetUserMediaRequestSucceeded. request_id=%d",
current_request_info_->request_id()));
// Completing the getUserMedia request can lead to that the RenderFrame and
// the UserMediaClientImpl/UserMediaProcessor are destroyed if the JavaScript
// code request the frame to be destroyed within the scope of the callback.
// Therefore, post a task to complete the request with a clean stack.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&UserMediaProcessor::DelayedGetUserMediaRequestSucceeded,
weak_factory_.GetWeakPtr(), stream, web_request));
}
void UserMediaProcessor::DelayedGetUserMediaRequestSucceeded(
const blink::WebMediaStream& stream,
blink::WebUserMediaRequest web_request) {
DVLOG(1) << "UserMediaProcessor::DelayedGetUserMediaRequestSucceeded";
LogUserMediaRequestResult(MEDIA_DEVICE_OK);
DeleteWebRequest(web_request);
web_request.RequestSucceeded(stream);
}
void UserMediaProcessor::GetUserMediaRequestFailed(
MediaStreamRequestResult result,
const blink::WebString& constraint_name) {
DCHECK(current_request_info_);
WebRtcLogMessage(
base::StringPrintf("UMCI::GetUserMediaRequestFailed. request_id=%d",
current_request_info_->request_id()));
// Completing the getUserMedia request can lead to that the RenderFrame and
// the UserMediaClientImpl/UserMediaProcessor are destroyed if the JavaScript
// code request the frame to be destroyed within the scope of the callback.
// Therefore, post a task to complete the request with a clean stack.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&UserMediaProcessor::DelayedGetUserMediaRequestFailed,
weak_factory_.GetWeakPtr(),
current_request_info_->web_request(), result,
constraint_name));
}
void UserMediaProcessor::DelayedGetUserMediaRequestFailed(
blink::WebUserMediaRequest web_request,
MediaStreamRequestResult result,
const blink::WebString& constraint_name) {
LogUserMediaRequestResult(result);
DeleteWebRequest(web_request);
switch (result) {
case MEDIA_DEVICE_OK:
case NUM_MEDIA_REQUEST_RESULTS:
NOTREACHED();
return;
case MEDIA_DEVICE_PERMISSION_DENIED:
web_request.RequestFailed(
blink::WebUserMediaRequest::Error::kPermissionDenied,
"Permission denied");
return;
case MEDIA_DEVICE_PERMISSION_DISMISSED:
web_request.RequestFailed(
blink::WebUserMediaRequest::Error::kPermissionDismissed,
"Permission dismissed");
return;
case MEDIA_DEVICE_INVALID_STATE:
web_request.RequestFailed(
blink::WebUserMediaRequest::Error::kInvalidState, "Invalid state");
return;
case MEDIA_DEVICE_NO_HARDWARE:
web_request.RequestFailed(
blink::WebUserMediaRequest::Error::kDevicesNotFound,
"Requested device not found");
return;
case MEDIA_DEVICE_INVALID_SECURITY_ORIGIN:
web_request.RequestFailed(
blink::WebUserMediaRequest::Error::kSecurityError,
"Invalid security origin");
return;
case MEDIA_DEVICE_TAB_CAPTURE_FAILURE:
web_request.RequestFailed(blink::WebUserMediaRequest::Error::kTabCapture,
"Error starting tab capture");
return;
case MEDIA_DEVICE_SCREEN_CAPTURE_FAILURE:
web_request.RequestFailed(
blink::WebUserMediaRequest::Error::kScreenCapture,
"Error starting screen capture");
return;
case MEDIA_DEVICE_CAPTURE_FAILURE:
web_request.RequestFailed(blink::WebUserMediaRequest::Error::kCapture,
"Error starting capture");
return;
case MEDIA_DEVICE_CONSTRAINT_NOT_SATISFIED:
web_request.RequestFailedConstraint(constraint_name);
return;
case MEDIA_DEVICE_TRACK_START_FAILURE_AUDIO:
web_request.RequestFailed(blink::WebUserMediaRequest::Error::kTrackStart,
"Could not start audio source");
return;
case MEDIA_DEVICE_TRACK_START_FAILURE_VIDEO:
web_request.RequestFailed(blink::WebUserMediaRequest::Error::kTrackStart,
"Could not start video source");
return;
case MEDIA_DEVICE_NOT_SUPPORTED:
web_request.RequestFailed(
blink::WebUserMediaRequest::Error::kNotSupported, "Not supported");
return;
case MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN:
web_request.RequestFailed(
blink::WebUserMediaRequest::Error::kFailedDueToShutdown,
"Failed due to shutdown");
return;
case MEDIA_DEVICE_KILL_SWITCH_ON:
web_request.RequestFailed(
blink::WebUserMediaRequest::Error::kKillSwitchOn);
return;
}
NOTREACHED();
web_request.RequestFailed(
blink::WebUserMediaRequest::Error::kPermissionDenied);
}
const blink::WebMediaStreamSource* UserMediaProcessor::FindLocalSource(
const LocalStreamSources& sources,
const MediaStreamDevice& device) const {
for (const auto& local_source : sources) {
MediaStreamSource* const source =
static_cast<MediaStreamSource*>(local_source.GetExtraData());
const MediaStreamDevice& active_device = source->device();
if (IsSameDevice(active_device, device))
return &local_source;
}
return nullptr;
}
blink::WebMediaStreamSource UserMediaProcessor::FindOrInitializeSourceObject(
const MediaStreamDevice& device) {
const blink::WebMediaStreamSource* existing_source = FindLocalSource(device);
if (existing_source) {
DVLOG(1) << "Source already exists. Reusing source with id "
<< existing_source->Id().Utf8();
return *existing_source;
}
blink::WebMediaStreamSource::Type type =
IsAudioInputMediaType(device.type)
? blink::WebMediaStreamSource::kTypeAudio
: blink::WebMediaStreamSource::kTypeVideo;
blink::WebMediaStreamSource source;
source.Initialize(blink::WebString::FromUTF8(device.id), type,
blink::WebString::FromUTF8(device.name),
false /* remote */);
if (device.group_id)
source.SetGroupId(blink::WebString::FromUTF8(*device.group_id));
DVLOG(1) << "Initialize source object :"
<< "id = " << source.Id().Utf8()
<< ", name = " << source.GetName().Utf8();
return source;
}
bool UserMediaProcessor::RemoveLocalSource(
const blink::WebMediaStreamSource& source) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
for (LocalStreamSources::iterator device_it = local_sources_.begin();
device_it != local_sources_.end(); ++device_it) {
if (IsSameSource(*device_it, source)) {
local_sources_.erase(device_it);
return true;
}
}
// Check if the source was pending.
for (LocalStreamSources::iterator device_it = pending_local_sources_.begin();
device_it != pending_local_sources_.end(); ++device_it) {
if (IsSameSource(*device_it, source)) {
MediaStreamSource* const source_extra_data =
static_cast<MediaStreamSource*>(source.GetExtraData());
const bool is_audio_source =
source.GetType() == blink::WebMediaStreamSource::kTypeAudio;
NotifyCurrentRequestInfoOfAudioSourceStarted(
source_extra_data,
is_audio_source ? MEDIA_DEVICE_TRACK_START_FAILURE_AUDIO
: MEDIA_DEVICE_TRACK_START_FAILURE_VIDEO,
blink::WebString::FromUTF8(
is_audio_source ? "Failed to access audio capture device"
: "Failed to access video capture device"));
pending_local_sources_.erase(device_it);
return true;
}
}
return false;
}
bool UserMediaProcessor::IsCurrentRequestInfo(int request_id) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return current_request_info_ &&
current_request_info_->request_id() == request_id;
}
bool UserMediaProcessor::IsCurrentRequestInfo(
const blink::WebUserMediaRequest& web_request) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return current_request_info_ &&
current_request_info_->web_request() == web_request;
}
bool UserMediaProcessor::DeleteWebRequest(
const blink::WebUserMediaRequest& web_request) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (current_request_info_ &&
current_request_info_->web_request() == web_request) {
current_request_info_.reset();
base::ResetAndReturn(&request_completed_cb_).Run();
return true;
}
return false;
}
void UserMediaProcessor::StopAllProcessing() {
if (current_request_info_) {
switch (current_request_info_->state()) {
case RequestInfo::State::SENT_FOR_GENERATION:
// Let the browser process know that the previously sent request must be
// canceled.
GetMediaStreamDispatcherHost()->CancelRequest(
current_request_info_->request_id());
FALLTHROUGH;
case RequestInfo::State::NOT_SENT_FOR_GENERATION:
LogUserMediaRequestWithNoResult(MEDIA_STREAM_REQUEST_NOT_GENERATED);
break;
case RequestInfo::State::GENERATED:
LogUserMediaRequestWithNoResult(
MEDIA_STREAM_REQUEST_PENDING_MEDIA_TRACKS);
break;
}
current_request_info_.reset();
}
request_completed_cb_.Reset();
// Loop through all current local sources and stop the sources.
auto it = local_sources_.begin();
while (it != local_sources_.end()) {
StopLocalSource(*it, true);
it = local_sources_.erase(it);
}
}
void UserMediaProcessor::OnLocalSourceStopped(
const blink::WebMediaStreamSource& source) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DVLOG(1) << "UserMediaProcessor::OnLocalSourceStopped";
const bool some_source_removed = RemoveLocalSource(source);
CHECK(some_source_removed);
MediaStreamSource* source_impl =
static_cast<MediaStreamSource*>(source.GetExtraData());
media_stream_device_observer_->RemoveStreamDevice(source_impl->device());
GetMediaStreamDispatcherHost()->StopStreamDevice(
source_impl->device().id, source_impl->device().session_id);
}
void UserMediaProcessor::StopLocalSource(
const blink::WebMediaStreamSource& source,
bool notify_dispatcher) {
MediaStreamSource* source_impl =
static_cast<MediaStreamSource*>(source.GetExtraData());
DVLOG(1) << "UserMediaProcessor::StopLocalSource("
<< "{device_id = " << source_impl->device().id << "})";
if (notify_dispatcher) {
media_stream_device_observer_->RemoveStreamDevice(source_impl->device());
GetMediaStreamDispatcherHost()->StopStreamDevice(
source_impl->device().id, source_impl->device().session_id);
}
source_impl->ResetSourceStoppedCallback();
source_impl->StopSource();
}
const mojom::MediaStreamDispatcherHostPtr&
UserMediaProcessor::GetMediaStreamDispatcherHost() {
if (!dispatcher_host_) {
render_frame_->GetRemoteInterfaces()->GetInterface(
mojo::MakeRequest(&dispatcher_host_));
}
return dispatcher_host_;
}
const blink::mojom::MediaDevicesDispatcherHostPtr&
UserMediaProcessor::GetMediaDevicesDispatcher() {
return media_devices_dispatcher_cb_.Run();
}
const AudioCaptureSettings& UserMediaProcessor::AudioCaptureSettingsForTesting()
const {
DCHECK(current_request_info_);
return current_request_info_->audio_capture_settings();
}
const VideoCaptureSettings& UserMediaProcessor::VideoCaptureSettingsForTesting()
const {
DCHECK(current_request_info_);
return current_request_info_->video_capture_settings();
}
} // namespace content
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
235553d312af682a53bc4ee9caae18dcf662bf76 | 02d26702ff6b0b4d8129efc5f890ace2eae848db | /Knight_Test.cpp | 42b5f1be3edb62052201876cb4989463fdc3ab40 | [] | no_license | tongzhi1998/Knight_in_Chessboard | 555af99443fa35c45ed04bdb004cedb88a8701b9 | 3dbb61980e4c8fcbe4dadcf23a6006b6723476c1 | refs/heads/master | 2020-04-19T22:37:30.539301 | 2019-01-31T06:42:19 | 2019-01-31T06:42:19 | 168,473,949 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | cpp | #include "Board.h"
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
double average = 0;
for (int i=0;i<10000;i++)
{
Board* gameBoard = new Board(8,8,1);
gameBoard->Guess();
//cout << gameBoard->getAttempts() << endl;
average+=gameBoard->getAttempts();
delete gameBoard;
}
cout << endl;
average = average/10000.0;
cout << average << endl;
return 0;
} | [
"tongzhi@usc.edu"
] | tongzhi@usc.edu |
bd9dfc28663ab92a3b8ae85336cb0d143fb3c2f9 | 158a0e9e44eaffd724c441160443225a396cdbb6 | /andbot_pkg/andbot/src/mybot_base_controller_v1.cpp | d25cbec4e2cf8a6a53cd948266918e4a6b6d08e2 | [] | no_license | ChingHengWang/andbot_tool | dbd8366fc5dcf57ea78d2f06c5b2925166fd1f63 | aa9a5492b42405f4d77cc617d6e0db88b173f06c | refs/heads/master | 2020-12-24T05:22:15.738595 | 2016-06-08T04:27:34 | 2016-06-08T04:27:34 | 60,668,125 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,517 | cpp | #include <ros/ros.h>
//#include <sensor_msgs/JointState.h>
#include <tf/transform_broadcaster.h>
#include <andbot/WheelCmd.h>
//#include <nav_msgs/Odometry.h>
#include <iostream>
using namespace std;
//double wheelSeparation = 0.22; for small lambo
double wheelSeparation = 0.393;
//double wheelSeparation = 0.3996;
double wheelRadius = 0.078;
//double wheelRadius = 0.0637; for small lambo
//double wheelRadius = 0.0625;
double vl = 0.0;
double vr = 0.0;
ros::Publisher cmd_wheel_angularVel_pub;
ros::Subscriber cmd_vel_sub;
void cmd_velCallback(const geometry_msgs::Twist &twist_aux)
{
andbot::WheelCmd wheel;
geometry_msgs::Twist twist = twist_aux;
double vel_x = twist_aux.linear.x;
double vel_th = twist_aux.angular.z;
double right_vel = 0.0;
double left_vel = 0.0;
// (vel_x, vel_th) --> (vl, vr)
left_vel = (2*vel_x - vel_th * wheelSeparation) / 2 / wheelRadius;
right_vel =(2*vel_x + vel_th * wheelSeparation) / 2 / wheelRadius;
// publish to /cmd_wheel_angularVel
wheel.speed1 = left_vel;
wheel.speed2 = right_vel;
wheel.mode1 = true;
wheel.mode2 = true;
cmd_wheel_angularVel_pub.publish(wheel);
}
int main(int argc, char** argv){
ros::init(argc, argv, "mybot_base_controller");
ros::NodeHandle n1, n2;
cmd_vel_sub = n1.subscribe("/andbot/cmd_vel", 10, cmd_velCallback);
cmd_wheel_angularVel_pub = n2.advertise<andbot::WheelCmd>("cmd_wheel_angularVel", 50);
ros::Rate loop_rate(10);
while(ros::ok())
{
ros::spinOnce();
loop_rate.sleep();
}
}
| [
"qoogood1234@gmail.com"
] | qoogood1234@gmail.com |
8203da7bcda3087e3fa65fafad6ed5f0b9f78c29 | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/chrome/browser/ui/views/frame/system_menu_model_builder.cc | 9216a24015d514dd6cc2500d7a5611ec6880fb15 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 7,695 | cc | // Copyright (c) 2013 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 "chrome/browser/ui/views/frame/system_menu_model_builder.h"
#include "base/command_line.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/toolbar/app_menu_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "grit/components_strings.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/models/simple_menu_model.h"
#if defined(OS_CHROMEOS)
#include "ash/common/session/session_state_delegate.h"
#include "ash/common/wm_shell.h"
#include "chrome/browser/ui/ash/multi_user/multi_user_util.h"
#include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h"
#include "chrome/browser/ui/browser_window.h"
#include "components/signin/core/account_id/account_id.h"
#include "components/user_manager/user_info.h"
#include "ui/base/l10n/l10n_util.h"
#endif
namespace {
// Given a |browser| that's an app or popup window, checks if it's hosting the
// settings page.
bool IsChromeSettingsAppOrPopupWindow(Browser* browser) {
DCHECK(browser);
TabStripModel* tab_strip = browser->tab_strip_model();
DCHECK_EQ(1, tab_strip->count());
const GURL gurl(tab_strip->GetWebContentsAt(0)->GetURL());
if (gurl.SchemeIs(content::kChromeUIScheme) &&
gurl.host().find(chrome::kChromeUISettingsHost) != std::string::npos) {
return true;
}
return false;
}
} // namespace
SystemMenuModelBuilder::SystemMenuModelBuilder(
ui::AcceleratorProvider* provider,
Browser* browser)
: menu_delegate_(provider, browser) {
}
SystemMenuModelBuilder::~SystemMenuModelBuilder() {
}
void SystemMenuModelBuilder::Init() {
ui::SimpleMenuModel* model = new ui::SimpleMenuModel(&menu_delegate_);
menu_model_.reset(model);
BuildMenu(model);
#if defined(OS_WIN)
// On Windows we put the menu items in the system menu (not at the end). Doing
// this necessitates adding a trailing separator.
model->AddSeparator(ui::NORMAL_SEPARATOR);
#endif
}
void SystemMenuModelBuilder::BuildMenu(ui::SimpleMenuModel* model) {
// We add the menu items in reverse order so that insertion_index never needs
// to change.
if (browser()->is_type_tabbed())
BuildSystemMenuForBrowserWindow(model);
else
BuildSystemMenuForAppOrPopupWindow(model);
AddFrameToggleItems(model);
}
void SystemMenuModelBuilder::BuildSystemMenuForBrowserWindow(
ui::SimpleMenuModel* model) {
model->AddItemWithStringId(IDC_NEW_TAB, IDS_NEW_TAB);
model->AddItemWithStringId(IDC_RESTORE_TAB, IDS_RESTORE_TAB);
if (chrome::CanOpenTaskManager()) {
model->AddSeparator(ui::NORMAL_SEPARATOR);
model->AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER);
}
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
model->AddSeparator(ui::NORMAL_SEPARATOR);
model->AddCheckItemWithStringId(IDC_USE_SYSTEM_TITLE_BAR,
IDS_SHOW_WINDOW_DECORATIONS_MENU);
#endif
AppendTeleportMenu(model);
// If it's a regular browser window with tabs, we don't add any more items,
// since it already has menus (Page, Chrome).
}
void SystemMenuModelBuilder::BuildSystemMenuForAppOrPopupWindow(
ui::SimpleMenuModel* model) {
model->AddItemWithStringId(IDC_BACK, IDS_CONTENT_CONTEXT_BACK);
model->AddItemWithStringId(IDC_FORWARD, IDS_CONTENT_CONTEXT_FORWARD);
model->AddItemWithStringId(IDC_RELOAD, IDS_APP_MENU_RELOAD);
model->AddSeparator(ui::NORMAL_SEPARATOR);
if (browser()->is_app())
model->AddItemWithStringId(IDC_NEW_TAB, IDS_APP_MENU_NEW_WEB_PAGE);
else
model->AddItemWithStringId(IDC_SHOW_AS_TAB, IDS_SHOW_AS_TAB);
model->AddSeparator(ui::NORMAL_SEPARATOR);
model->AddItemWithStringId(IDC_CUT, IDS_CUT);
model->AddItemWithStringId(IDC_COPY, IDS_COPY);
model->AddItemWithStringId(IDC_PASTE, IDS_PASTE);
model->AddSeparator(ui::NORMAL_SEPARATOR);
model->AddItemWithStringId(IDC_FIND, IDS_FIND);
model->AddItemWithStringId(IDC_PRINT, IDS_PRINT);
zoom_menu_contents_.reset(new ZoomMenuModel(&menu_delegate_));
model->AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU,
zoom_menu_contents_.get());
encoding_menu_contents_.reset(new EncodingMenuModel(browser()));
model->AddSubMenuWithStringId(IDC_ENCODING_MENU,
IDS_ENCODING_MENU,
encoding_menu_contents_.get());
if (browser()->is_app() && chrome::CanOpenTaskManager()) {
model->AddSeparator(ui::NORMAL_SEPARATOR);
model->AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER);
}
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
model->AddSeparator(ui::NORMAL_SEPARATOR);
model->AddItemWithStringId(IDC_CLOSE_WINDOW, IDS_CLOSE);
#endif
// Avoid appending the teleport menu for the settings window. This window's
// presentation is unique: it's a normal browser window with an app-like
// frame, which doesn't have a user icon badge. Thus if teleported it's not
// clear what user it applies to. Rather than bother to implement badging just
// for this rare case, simply prevent the user from teleporting the window.
if (!IsChromeSettingsAppOrPopupWindow(browser()))
AppendTeleportMenu(model);
}
void SystemMenuModelBuilder::AddFrameToggleItems(ui::SimpleMenuModel* model) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDebugEnableFrameToggle)) {
model->AddSeparator(ui::NORMAL_SEPARATOR);
model->AddItem(IDC_DEBUG_FRAME_TOGGLE,
base::ASCIIToUTF16("Toggle Frame Type"));
}
}
void SystemMenuModelBuilder::AppendTeleportMenu(ui::SimpleMenuModel* model) {
#if defined(OS_CHROMEOS)
DCHECK(browser()->window());
// If there is no manager, we are not in the proper multi user mode.
if (chrome::MultiUserWindowManager::GetMultiProfileMode() !=
chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_SEPARATED)
return;
// Don't show the menu for incognito windows.
if (browser()->profile()->IsOffTheRecord())
return;
// To show the menu we need at least two logged in users.
ash::SessionStateDelegate* delegate =
ash::WmShell::Get()->GetSessionStateDelegate();
int logged_in_users = delegate->NumberOfLoggedInUsers();
if (logged_in_users <= 1)
return;
// If this does not belong to a profile or there is no window, or the window
// is not owned by anyone, we don't show the menu addition.
chrome::MultiUserWindowManager* manager =
chrome::MultiUserWindowManager::GetInstance();
const AccountId account_id =
multi_user_util::GetAccountIdFromProfile(browser()->profile());
aura::Window* window = browser()->window()->GetNativeWindow();
if (!account_id.is_valid() || !window ||
!manager->GetWindowOwner(window).is_valid())
return;
model->AddSeparator(ui::NORMAL_SEPARATOR);
DCHECK(logged_in_users <= 3);
for (int user_index = 1; user_index < logged_in_users; ++user_index) {
const user_manager::UserInfo* user_info = delegate->GetUserInfo(user_index);
model->AddItem(
user_index == 1 ? IDC_VISIT_DESKTOP_OF_LRU_USER_2
: IDC_VISIT_DESKTOP_OF_LRU_USER_3,
l10n_util::GetStringFUTF16(IDS_VISIT_DESKTOP_OF_LRU_USER,
user_info->GetDisplayName(),
base::ASCIIToUTF16(user_info->GetEmail())));
}
#endif
}
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
7842848db51af09f22958ce3d3842055bfcee467 | 851d12adffa6dcdc85816c2ee6f6af129c5542b6 | /TDEngine2/include/ecs/CBoundsUpdatingSystem.h | 2258c1c284ec883d09d781da832de8ca5a881711 | [
"Apache-2.0"
] | permissive | bnoazx005/TDEngine2 | 775c018e1aebfe4a42f727e132780e52a80f6a96 | ecc1683aac5df5b1581a56b6d240893f5c79161b | refs/heads/master | 2023-08-31T08:07:19.288783 | 2022-05-12T16:41:06 | 2022-05-12T16:45:02 | 149,013,665 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,528 | h | /*!
\file CBoundsUpdatingSystem.h
\date 28.04.2020
\authors Kasimov Ildar
*/
#pragma once
#include "./../utils/Types.h"
#include "./../utils/Utils.h"
#include "CBaseSystem.h"
#include <vector>
#include <functional>
namespace TDEngine2
{
class CTransform;
class CEntity;
class IDebugUtility;
class IResourceManager;
class ISceneManager;
class CQuadSprite;
class CStaticMeshContainer;
class CSkinnedMeshContainer;
class CBoundsComponent;
/*!
\brief A factory function for creation objects of CBoundsUpdatingSystem's type.
\param[in, out] pResourceManager A pointer to IResourceManager implementation
\param[in, out] pDebugUtility A pointer to IDebugUtility implementation
\param[in, out] pSceneManager A pointer to ISceneManager implementation
\param[out] result Contains RC_OK if everything went ok, or some other code, which describes an error
\return A pointer to CBoundsUpdatingSystem's implementation
*/
TDE2_API ISystem* CreateBoundsUpdatingSystem(IResourceManager* pResourceManager, IDebugUtility* pDebugUtility, ISceneManager* pSceneManager, E_RESULT_CODE& result);
/*!
class CBoundsUpdatingSystem
\brief The class represents a system that updates boundaries of renderable objects
*/
class CBoundsUpdatingSystem : public CBaseSystem
{
public:
friend TDE2_API ISystem* CreateBoundsUpdatingSystem(IResourceManager*, IDebugUtility*, ISceneManager*, E_RESULT_CODE&);
public:
template <typename T>
struct TSystemContext
{
std::vector<CBoundsComponent*> mpBounds;
std::vector<CTransform*> mpTransforms;
std::vector<T*> mpElements;
};
typedef TSystemContext<CQuadSprite> TSpritesBoundsContext;
typedef TSystemContext<CStaticMeshContainer> TStaticMeshesBoundsContext;
typedef TSystemContext<CSkinnedMeshContainer> TSkinnedMeshesBoundsContext;
public:
TDE2_SYSTEM(CBoundsUpdatingSystem);
/*!
\brief The method initializes an inner state of a system
\param[in, out] pResourceManager A pointer to IResourceManager implementation
\param[in, out] pDebugUtility A pointer to IDebugUtility implementation
\param[in, out] pSceneManager A pointer to ISceneManager implementation
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE Init(IResourceManager* pResourceManager, IDebugUtility* pDebugUtility, ISceneManager* pSceneManager);
/*!
\brief The method inject components array into a system
\param[in] pWorld A pointer to a main scene's object
*/
TDE2_API void InjectBindings(IWorld* pWorld) override;
/*!
\brief The main method that should be implemented in all derived classes.
It contains all the logic that the system will execute during engine's work.
\param[in] pWorld A pointer to a main scene's object
\param[in] dt A delta time's value
*/
TDE2_API void Update(IWorld* pWorld, F32 dt) override;
protected:
DECLARE_INTERFACE_IMPL_PROTECTED_MEMBERS(CBoundsUpdatingSystem)
TDE2_API void _processScenesEntities(IWorld* pWorld);
protected:
TStaticMeshesBoundsContext mStaticMeshesContext;
TSkinnedMeshesBoundsContext mSkinnedMeshesContext;
TSpritesBoundsContext mSpritesContext;
TEntitiesArray mScenesBoundariesEntities;
IResourceManager* mpResourceManager;
IDebugUtility* mpDebugUtility;
ISceneManager* mpSceneManager;
F32 mCurrTimer = 0.0f;
};
} | [
"ildar2571@yandex.ru"
] | ildar2571@yandex.ru |
c0c1f3b872cb4ba3fb946c6bc759d6fca51733c6 | a8d5963e589c524721cafb633ce3e6ccf254b9ab | /libs/src/package.cpp | fe44807191bf37fae025dfb458496ea9ccfffcdd | [] | no_license | AnatoliiShablov/FireFly | 25883240d9d9014ca7476557117160230efe75d2 | 0917b9c37cfc251c602fc345fcac19145154a120 | refs/heads/master | 2020-08-10T18:29:24.031243 | 2020-06-15T13:24:55 | 2020-06-15T13:24:55 | 214,396,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,361 | cpp | #include "../include/package.h"
#ifdef DEBUG_OUTPUT
#define debug_fprintf(...) fprintf(...)
#else
#define debug_fprintf(...) \
do { \
} while (0)
#endif
uint32_t hash(std::string const &str) noexcept {
uint32_t hash_ = 0;
uint32_t mult = 1;
uint32_t alphabet_size = 257;
for (char c : str) {
hash_ += static_cast<uint32_t>(c) * mult;
mult *= alphabet_size;
}
return hash_;
}
constexpr size_t header_size_after_serializer() noexcept {
return sizeof(header::size) + sizeof(header::type);
}
size_t header_serializer(std::byte *output, header const &head) {
output[0] = static_cast<std::byte>((head.size & UINT32_C(0xff000000)) >> UINT32_C(24));
output[1] = static_cast<std::byte>((head.size & UINT32_C(0x00ff0000)) >> UINT32_C(16));
output[2] = static_cast<std::byte>((head.size & UINT32_C(0x0000ff00)) >> UINT32_C(8));
output[3] = static_cast<std::byte>((head.size & UINT32_C(0x000000ff)) >> UINT32_C(0));
output[4] = static_cast<std::byte>(head.type);
return header_size_after_serializer();
}
size_t header_deserializer(std::byte *input, header &head) {
head.size = static_cast<uint32_t>(input[0]) << UINT32_C(24) | static_cast<uint32_t>(input[1]) << UINT32_C(16) |
static_cast<uint32_t>(input[2]) << UINT32_C(8) | static_cast<uint32_t>(input[3]) << UINT32_C(0);
auto type = static_cast<uint8_t>(input[4]);
if (type >= static_cast<uint8_t>(package_type::types_amount)) {
return 0;
}
head.type = static_cast<package_type>(type);
return header_size_after_serializer();
}
uint32_t message_hash(message const &package) noexcept {
return hash(package.name) ^ hash(package.text);
}
size_t message_size_after_serializer(message const &package) noexcept {
return 3 * sizeof(uint32_t) + package.name.length() + package.text.length();
}
size_t message_serializer(std::byte *output, message const &package) {
uint32_t name_length = static_cast<uint32_t>(package.name.length());
uint32_t text_length = static_cast<uint32_t>(package.text.length());
uint32_t hash = message_hash(package);
output[0] = static_cast<std::byte>((name_length & UINT32_C(0xff000000)) >> UINT32_C(24));
output[1] = static_cast<std::byte>((name_length & UINT32_C(0x00ff0000)) >> UINT32_C(16));
output[2] = static_cast<std::byte>((name_length & UINT32_C(0x0000ff00)) >> UINT32_C(8));
output[3] = static_cast<std::byte>((name_length & UINT32_C(0x000000ff)) >> UINT32_C(0));
output[4] = static_cast<std::byte>((text_length & UINT32_C(0xff000000)) >> UINT32_C(24));
output[5] = static_cast<std::byte>((text_length & UINT32_C(0x00ff0000)) >> UINT32_C(16));
output[6] = static_cast<std::byte>((text_length & UINT32_C(0x0000ff00)) >> UINT32_C(8));
output[7] = static_cast<std::byte>((text_length & UINT32_C(0x000000ff)) >> UINT32_C(0));
output[8] = static_cast<std::byte>((hash & UINT32_C(0xff000000)) >> UINT32_C(24));
output[9] = static_cast<std::byte>((hash & UINT32_C(0x00ff0000)) >> UINT32_C(16));
output[10] = static_cast<std::byte>((hash & UINT32_C(0x0000ff00)) >> UINT32_C(8));
output[11] = static_cast<std::byte>((hash & UINT32_C(0x000000ff)) >> UINT32_C(0));
size_t offset = 12;
for (char c : package.name) {
output[offset++] = static_cast<std::byte>(c);
}
for (char c : package.text) {
output[offset++] = static_cast<std::byte>(c);
}
return offset;
}
size_t message_deserializer(std::byte *input, message &package) {
uint32_t name_length = static_cast<uint32_t>(input[0]) << UINT32_C(24) | static_cast<uint32_t>(input[1]) << UINT32_C(16) |
static_cast<uint32_t>(input[2]) << UINT32_C(8) | static_cast<uint32_t>(input[3]) << UINT32_C(0);
uint32_t text_length = static_cast<uint32_t>(input[4]) << UINT32_C(24) | static_cast<uint32_t>(input[5]) << UINT32_C(16) |
static_cast<uint32_t>(input[6]) << UINT32_C(8) | static_cast<uint32_t>(input[7]) << UINT32_C(0);
uint32_t hash = static_cast<uint32_t>(input[8]) << UINT32_C(24) | static_cast<uint32_t>(input[9]) << UINT32_C(16) |
static_cast<uint32_t>(input[10]) << UINT32_C(8) | static_cast<uint32_t>(input[11]) << UINT32_C(0);
package.name.resize(name_length);
package.text.resize(text_length);
size_t offset = 12;
for (size_t i = 0; i < name_length; ++i) {
package.name[i] = static_cast<char>(input[offset++]);
}
for (size_t i = 0; i < text_length; ++i) {
package.text[i] = static_cast<char>(input[offset++]);
}
return hash == message_hash(package) ? offset : 0;
}
size_t sign_in_size_after_serializer(sign_in const &package) noexcept {
return 2 * sizeof(uint32_t) + package.name.length() + package.password.length();
}
size_t sign_in_serializer(std::byte *output, sign_in const &package) {
uint32_t name_length = static_cast<uint32_t>(package.name.length());
uint32_t password_length = static_cast<uint32_t>(package.password.length());
output[0] = static_cast<std::byte>((name_length & UINT32_C(0xff000000)) >> UINT32_C(24));
output[1] = static_cast<std::byte>((name_length & UINT32_C(0x00ff0000)) >> UINT32_C(16));
output[2] = static_cast<std::byte>((name_length & UINT32_C(0x0000ff00)) >> UINT32_C(8));
output[3] = static_cast<std::byte>((name_length & UINT32_C(0x000000ff)) >> UINT32_C(0));
output[4] = static_cast<std::byte>((password_length & UINT32_C(0xff000000)) >> UINT32_C(24));
output[5] = static_cast<std::byte>((password_length & UINT32_C(0x00ff0000)) >> UINT32_C(16));
output[6] = static_cast<std::byte>((password_length & UINT32_C(0x0000ff00)) >> UINT32_C(8));
output[7] = static_cast<std::byte>((password_length & UINT32_C(0x000000ff)) >> UINT32_C(0));
size_t offset = 8;
for (char c : package.name) {
output[offset++] = static_cast<std::byte>(c);
}
for (char c : package.password) {
output[offset++] = static_cast<std::byte>(c);
}
return offset;
}
size_t sign_in_deserializer(std::byte *input, sign_in &package) {
uint32_t name_length = static_cast<uint32_t>(input[0]) << UINT32_C(24) | static_cast<uint32_t>(input[1]) << UINT32_C(16) |
static_cast<uint32_t>(input[2]) << UINT32_C(8) | static_cast<uint32_t>(input[3]) << UINT32_C(0);
uint32_t password_length = static_cast<uint32_t>(input[4]) << UINT32_C(24) |
static_cast<uint32_t>(input[5]) << UINT32_C(16) |
static_cast<uint32_t>(input[6]) << UINT32_C(8) | static_cast<uint32_t>(input[7]) << UINT32_C(0);
package.name.resize(name_length);
package.password.resize(password_length);
size_t offset = 8;
for (size_t i = 0; i < name_length; ++i) {
package.name[i] = static_cast<char>(input[offset++]);
}
for (size_t i = 0; i < password_length; ++i) {
package.password[i] = static_cast<char>(input[offset++]);
}
return offset;
}
size_t sign_up_size_after_serializer(sign_up const &package) noexcept {
return 2 * sizeof(uint32_t) + package.name.length() + package.password.length();
}
size_t sign_up_serializer(std::byte *output, sign_up const &package) {
uint32_t name_length = static_cast<uint32_t>(package.name.length());
uint32_t password_length = static_cast<uint32_t>(package.password.length());
output[0] = static_cast<std::byte>((name_length & UINT32_C(0xff000000)) >> UINT32_C(24));
output[1] = static_cast<std::byte>((name_length & UINT32_C(0x00ff0000)) >> UINT32_C(16));
output[2] = static_cast<std::byte>((name_length & UINT32_C(0x0000ff00)) >> UINT32_C(8));
output[3] = static_cast<std::byte>((name_length & UINT32_C(0x000000ff)) >> UINT32_C(0));
output[4] = static_cast<std::byte>((password_length & UINT32_C(0xff000000)) >> UINT32_C(24));
output[5] = static_cast<std::byte>((password_length & UINT32_C(0x00ff0000)) >> UINT32_C(16));
output[6] = static_cast<std::byte>((password_length & UINT32_C(0x0000ff00)) >> UINT32_C(8));
output[7] = static_cast<std::byte>((password_length & UINT32_C(0x000000ff)) >> UINT32_C(0));
size_t offset = 8;
for (char c : package.name) {
output[offset++] = static_cast<std::byte>(c);
}
for (char c : package.password) {
output[offset++] = static_cast<std::byte>(c);
}
return offset;
}
size_t sign_up_deserializer(std::byte *input, sign_up &package) {
uint32_t name_length = static_cast<uint32_t>(input[0]) << UINT32_C(24) | static_cast<uint32_t>(input[1]) << UINT32_C(16) |
static_cast<uint32_t>(input[2]) << UINT32_C(8) | static_cast<uint32_t>(input[3]) << UINT32_C(0);
uint32_t password_length = static_cast<uint32_t>(input[4]) << UINT32_C(24) |
static_cast<uint32_t>(input[5]) << UINT32_C(16) |
static_cast<uint32_t>(input[6]) << UINT32_C(8) | static_cast<uint32_t>(input[7]) << UINT32_C(0);
package.name.resize(name_length);
package.password.resize(password_length);
size_t offset = 8;
for (size_t i = 0; i < name_length; ++i) {
package.name[i] = static_cast<char>(input[offset++]);
}
for (size_t i = 0; i < password_length; ++i) {
package.password[i] = static_cast<char>(input[offset++]);
}
return offset;
}
special_signal::special_signal(special_signal::types type) : type{type} {}
constexpr size_t special_signal_size_after_serializer() noexcept {
return sizeof(special_signal::type);
}
size_t special_signal_serializer(std::byte *output, special_signal const &package) {
output[0] = static_cast<std::byte>(package.type);
return special_signal_size_after_serializer();
}
size_t special_signal_deserializer(std::byte *input, special_signal &package) {
auto type = static_cast<uint8_t>(input[0]);
if (type >= static_cast<uint8_t>(special_signal::special_signals_amount)) {
return 0;
}
package.type = static_cast<special_signal::types>(type);
return special_signal_size_after_serializer();
}
package_sender::package_sender() : success_{}, error_{}, buffer_{}, offset_{0}, header_{}, state_{package_state::ready} {}
void package_sender::on_success(std::function<void()> success) noexcept {
success_ = std::move(success);
}
void package_sender::on_error(std::function<void(std::string_view)> error) noexcept {
error_ = std::move(error);
}
void package_sender::send_error(std::string_view error) {
error_(error);
}
int package_sender::set_package(std::variant<message, sign_in, sign_up, special_signal> const &package) {
if (state_ != package_state::ready) {
error_("Sender is busy");
return -1;
}
switch (package.index()) {
case 0: {
header_.type = package_type::MESSAGE;
header_.size = static_cast<uint32_t>(message_size_after_serializer(std::get<message>(package)));
break;
}
case 1: {
header_.type = package_type::SIGN_IN;
header_.size = static_cast<uint32_t>(sign_in_size_after_serializer(std::get<sign_in>(package)));
break;
}
case 2: {
header_.type = package_type::SIGN_UP;
header_.size = static_cast<uint32_t>(sign_up_size_after_serializer(std::get<sign_up>(package)));
break;
}
case 3: {
header_.type = package_type::SPECIAL_SIGNAL;
header_.size = static_cast<uint32_t>(special_signal_size_after_serializer());
break;
}
}
debug_fprintf(stdout, "set_package:\n header.size=%u\n header.type=%hhu\n", header_.size, header_.type);
if (header_.size > BUFFER_SIZE) {
error_("Package is too big");
return -2;
}
offset_ = header_serializer(buffer_.data(), header_);
switch (package.index()) {
case 0: {
message_serializer(buffer_.data() + offset_, std::get<message>(package));
break;
}
case 1: {
sign_in_serializer(buffer_.data() + offset_, std::get<sign_in>(package));
break;
}
case 2: {
sign_up_serializer(buffer_.data() + offset_, std::get<sign_up>(package));
break;
}
case 3: {
special_signal_serializer(buffer_.data() + offset_, std::get<special_signal>(package));
break;
}
}
offset_ = 0;
state_ = package_state::header_transfering;
return 0;
}
package_state package_sender::get_state() const noexcept {
return state_;
}
package_sender::buffer_t package_sender::buffer() noexcept {
return asio::buffer(buffer_.data() + offset_, left_to_write());
}
void package_sender::data_transferred(size_t bytes_transferred) {
debug_fprintf(stdout, "data_transfered(send):\n bytes_transfered=%zu\n", bytes_transferred);
offset_ += bytes_transferred;
if (state_ == package_state::header_transfering && offset_ >= header_size_after_serializer()) {
state_ = package_state::body_transfering;
}
if (state_ == package_state::body_transfering && offset_ == header_size_after_serializer() + header_.size) {
state_ = package_state::ready;
success_();
}
}
size_t package_sender::left_to_write() const noexcept {
switch (state_) {
case package_state::header_transfering:
case package_state::body_transfering:
return header_size_after_serializer() + header_.size - offset_;
case package_state::ready:
return 0;
}
return 0;
}
package_reciever::package_reciever()
: success_{}, error_{}, buffer_{}, offset_{0}, header_{}, state_{package_state::header_transfering} {}
void package_reciever::on_success(
std::function<void(std::variant<message, sign_in, sign_up, special_signal> &&)> success) noexcept {
success_ = std::move(success);
}
void package_reciever::on_error(std::function<void(std::string_view)> error) noexcept {
error_ = std::move(error);
}
void package_reciever::send_error(std::string_view error) {
error_(error);
}
package_reciever::buffer_t package_reciever::buffer() noexcept {
return asio::buffer(buffer_.data() + offset_, std::min(left_to_read(), BUFFER_SIZE - offset_));
}
void package_reciever::data_transferred(size_t bytes_transferred) noexcept {
debug_fprintf(stdout, "data_transfered(recieve):\n bytes_transfered=%zu\n", bytes_transferred);
offset_ += bytes_transferred;
size_t offset_new = 0;
while (true) {
if (state_ == package_state::header_transfering) {
if (offset_ - offset_new >= header_size_after_serializer()) {
{
size_t add = header_deserializer(buffer_.data() + offset_new, header_);
debug_fprintf(stdout, "data_transfered(recieve):\n header.size=%u\n header.type=%hhu\n", header_.size,
header_.type);
if (add == 0) {
error_("Unknown type");
return;
} else {
offset_new += add;
}
}
if (header_.size > BUFFER_SIZE) {
error_("Package is too big");
return;
}
state_ = package_state::body_transfering;
} else {
break;
}
}
if (state_ == package_state::body_transfering && offset_ - offset_new >= header_.size) {
switch (header_.type) {
case MESSAGE: {
message tmp;
if (size_t add = message_deserializer(buffer_.data() + offset_new, tmp); add == 0) {
error_("Wrong Hash");
return;
} else {
offset_new += add;
debug_fprintf(stdout, "message recieved:\n %s: %s\n", tmp.name.c_str(), tmp.text.c_str());
}
success_(std::move(tmp));
break;
}
case SIGN_IN: {
sign_in tmp;
offset_new += sign_in_deserializer(buffer_.data() + offset_new, tmp);
success_(std::move(tmp));
break;
}
case SIGN_UP: {
sign_up tmp;
offset_new += sign_up_deserializer(buffer_.data() + offset_new, tmp);
success_(std::move(tmp));
break;
}
case SPECIAL_SIGNAL: {
special_signal tmp;
offset_new += special_signal_deserializer(buffer_.data() + offset_new, tmp);
success_(std::move(tmp));
break;
}
default:
break;
}
state_ = package_state::header_transfering;
} else {
break;
}
}
if (offset_new != 0) {
for (size_t i = offset_new, j = 0; i < offset_; ++i, ++j) {
buffer_[j] = buffer_[i];
}
offset_ -= offset_new;
}
}
size_t package_reciever::left_to_read() const noexcept {
switch (state_) {
case package_state::header_transfering:
return header_size_after_serializer() - offset_;
case package_state::body_transfering:
return header_.size - offset_;
case package_state::ready:
return 0;
}
return 0;
}
| [
"anatoliishablov@gmail.com"
] | anatoliishablov@gmail.com |
9e9a8059e97e14f9d6f356673fe4054a9910c4fc | 845b453fd5f0a3093f4683979c74bf9bac5f839a | /src/msg_router/msg_router.cpp | c5f84d80172918b217936239a86bb69703ffdc1f | [] | no_license | csc301lei/msgproject | 894ca50eaa00a3601da532a44e733030e0618c47 | 8b0b3e74bca22d8a8a8f20ee61fde5e067ace631 | refs/heads/master | 2020-04-01T00:10:50.414474 | 2018-09-28T10:48:26 | 2018-09-28T10:48:26 | 152,685,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,500 | cpp | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
//#include "router.h"
#include <nn.h>
#include <reqrep.h>
#include <pubsub.h>
#include <pipeline.h>
#include <pthread.h>
#include "fatal.h"
#define CLIENT "client"
#define ROUTER "router"
#define CLIENT_ADDR "ipc:///tmp/pubsub_client.ipc"
#define CHECK_NAME "ipc:///tmp/checkname.ipc"
//#define ROUTER_ADDR "ipc:///tmp/pubsub_router.ipc"
#define ROUTER_ADDR "tcp://*:19001"
char topic_name[1000];
void * checkname(void * a)
{
int sock;
int rv;
if ((sock = nn_socket(AF_SP, NN_REP)) < 0) {
fatal("nn_socket");
}
if ((rv = nn_bind(sock, CHECK_NAME)) < 0) {
fatal("nn_bind");
}
for (;;)
{
char *buf = NULL;
int bytes;
if ((bytes = nn_recv(sock, &buf, NN_MSG, 0)) < 0)
{
fatal("nn_recv");
}
if(strstr(topic_name, buf) == NULL)
{
strcat(topic_name, buf);
strcat(topic_name, "|");
printf("topic_name: %s\n", topic_name);
nn_send(sock, "new", 3, 0);
}
else{
nn_send(sock, "exist", 5, 0);
}
}
}
void * router(void * a)
{
int frontend;
if ((frontend = nn_socket(AF_SP, NN_SUB)) < 0)
{
fatal("nn_socket");
}
if (nn_setsockopt(frontend, NN_SUB, NN_SUB_SUBSCRIBE, "", 0) < 0)
{
fatal("nn_setsockopt");
}
if (nn_bind(frontend, ROUTER_ADDR) < 0)
{
fatal("nn_bind");
}
int backend;
if ((backend = nn_socket(AF_SP, NN_PUB)) < 0)
{
fatal("nn_socket");
}
if (nn_bind(backend, CLIENT_ADDR) < 0)
{
fatal("nn_bind");
}
for(;;)
{
char *buf = NULL;
nn_recv(frontend, &buf, NN_MSG, 0);
printf("frontend: %s\n", buf);
int sz_buf = strlen(buf) + 1;
nn_send(backend, buf, sz_buf, 0);
printf("backend: %s\n", buf);
nn_freemsg(buf);
}
nn_close(frontend);
nn_close(backend);
}
int main(const int argc, const char **argv)
{
pthread_t router1;
pthread_t checkname1;
if( pthread_create (&checkname1, NULL, checkname, NULL) !=0 )
{
printf("thread getaddr failede\n");
exit(1);
}
if(pthread_create (&router1, NULL, router, NULL) != 0 )
{
printf("thread router failede\n");
exit(1);
}
pthread_join (checkname1, NULL);
pthread_join (router1, NULL);
return 1;
} | [
"guolei@zerozero.cn"
] | guolei@zerozero.cn |
39d41511ed3d46398e1eec2bb248f7d6929bb707 | e8f008fdea4f8dc2b4a2a3828991ab34ef26048f | /pat/甲级/1070.cpp | b504f1b9c018791305752d9533d0a87e4ca6b06b | [] | no_license | vlluvia/algorithm | a46f52dc5b4e60993290fbf4b51d827b201acbf9 | 40b999aca041c67ee8627dfece04ec4995e3e5ec | refs/heads/master | 2023-08-06T09:16:01.276191 | 2023-07-31T14:15:47 | 2023-07-31T14:15:47 | 216,355,179 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | cpp | #include<bits/stdc++.h>
#define INF 1<<29
using namespace std;
struct mooncake{
float mount, price, unit;
};
bool cmp(mooncake m1, mooncake m2) {
return m1.unit > m2.unit;
}
void pat1070() {
int n, need;
cin >> n >> need;
vector<mooncake> a(n);
for (int i = 0; i < n; i++) scanf("%f", &a[i].mount);
for (int i = 0; i < n; i++) scanf("%f", &a[i].price);
for (int i = 0; i < n; i++) a[i].unit = a[i].price / a[i].mount;
sort(a.begin(), a.end(), cmp);
float result = 0.0;
for (int i = 0; i < n; i++) {
if (a[i].mount <= need) {
result = result + a[i].price;
} else {
result = result + a[i].unit * need;
break;
}
need = need - a[i].mount;
}
printf("%.2f",result);
}
//int main() {
// pat1070();
// return 0;
//} | [
"925716329@qq.com"
] | 925716329@qq.com |
769fe00023cb85dd00a5e4d69297803cc676c65b | cf9d7a083b91378aee2c54ef63011536108d6552 | /chapter_02/04_DesignersNetwork_logicalOperators/DesignersNetwork.cpp | cd9c7c8ac469c6910b405ce853055df9239f2c05 | [] | no_license | AselK/Beginning-cpp-through-game-programming | 3a86f70c8cb99480dafce68c2b7865d9e68e652d | adb9f762a942be66ba58607f93478f5da9d5441f | refs/heads/master | 2021-05-05T13:10:45.143894 | 2018-05-29T21:02:02 | 2018-05-29T21:02:02 | 118,325,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cpp | #include <iostream>
#include <string>
int main()
{
std::string username;
std::string password;
bool success;
std::cout <<"\tGame Designer's Network\n";
do
{
std::cout <<"\nUsername: ";
std::cin >> username;
std::cout <<"Password: ";
std::cin >> password;
if (username == "S.Meier" && password == "civilization")
{
std::cout <<"\nHey, Sid.";
success = true;
}
else if (username == "S.Miyamoto" && password == "mariobros")
{
std::cout <<"\nWhat's up. Shigeru?";
success = true;
}
else if (username == "W.Wright" && password == "thesims")
{
std::cout <<"\nHow goes it, Will?";
success = true;
}
else if (username == "guest" || password == "guest")
{
std::cout <<"\nWelcome, guest.";
success = true;
}
else
{
std::cout <<"\nYour login failed.";
success = false;
}
}
while (!success);
}
| [
"asel.nurmuhanbetova@gmail.com"
] | asel.nurmuhanbetova@gmail.com |
41545fef7d96c16f47515492cd663f588a0562a2 | 13924dddc9c16b38de80536f082d8fee0281a437 | /project_20_1/project_20_1.ino | 7409c29b8c52372fa7fc03050bebb142688b2598 | [] | no_license | AndreyMarkinPPC/ArduinoExamples | 37ef08fc7877e6bdc8b05e5e188ad1c12f6c410a | d00ea348d6e18cea67b660c70bdda55cd6c5d2e4 | refs/heads/master | 2022-07-05T19:23:20.042034 | 2020-05-10T11:45:03 | 2020-05-10T11:45:03 | 262,774,963 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,198 | ino | /*
LiquidCrystal Library - Hello World
Demonstrates the use a 16x2 LCD display. The LiquidCrystal
library works with all LCD displays that are compatible with the
Hitachi HD44780 driver. There are many of them out there, and you
can usually tell them by the 16-pin interface.
This sketch prints "Hello World!" to the LCD
and shows the time.
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* LCD VSS pin to ground
* LCD VCC pin to 5V
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe
modified 7 Nov 2016
by Arturo Guadalupi
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/LiquidCrystalHelloWorld
*/
// include the library code:
#include <LiquidCrystal.h>
// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, rw = 11, en = 2, d0 = 3, d1 = 4, d2 = 5, d3 = 6, d4 = 7, d5 = 8, d6 = 9, d7 = 10;
LiquidCrystal lcd(rs, rw, en, d0, d1, d2, d3, d4, d5, d6, d7);
//byte heart[8] = {
// 0b00000,
// 0b01010,
// 0b11111,
// 0b11111,
// 0b11111,
// 0b01110,
// 0b00100,
// 0b00000
//};
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// lcd.createChar(0, heart);
lcd.setCursor(0, 0);
// Print a message to the LCD.
lcd.print(" Sama monstr");
// lcd.write(byte(0));
// lcd.write(byte(0));
// lcd.write(byte(0));
// lcd.write(byte(0));
// lcd.write(byte(0));
lcd.setCursor(0, 1);
lcd.print("Very-very-very loooong texttttt");
//lcd.print("<------Eto ty!)");
}
void loop() {
for (int i = 0; i < 5; i++) {
lcd.scrollDisplayLeft();
delay(1050);
}
// Turn off the blinking cursor:
// lcd.noBlink();
// delay(3000);
// // Turn on the blinking cursor:
// lcd.blink();
// delay(3000);
}
| [
"andrey.markin.ppc@gmail.com"
] | andrey.markin.ppc@gmail.com |
68451b864176b8ae83446aac7edf0ec3c7bae693 | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/third_party/WebKit/Source/core/events/EventPath.h | 6f771758a24dab1d2a3ccdd393ffff74fa8eb7b1 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"Apache-2.0",
"MIT"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 4,290 | h | /*
* Copyright (C) 2013 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.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef EventPath_h
#define EventPath_h
#include "core/CoreExport.h"
#include "core/events/NodeEventContext.h"
#include "core/events/TreeScopeEventContext.h"
#include "core/events/WindowEventContext.h"
#include "platform/heap/Handle.h"
#include "wtf/HashMap.h"
#include "wtf/Vector.h"
namespace blink {
class Event;
class EventTarget;
class Node;
class TouchEvent;
class TouchList;
class TreeScope;
class CORE_EXPORT EventPath final : public GarbageCollected<EventPath> {
WTF_MAKE_NONCOPYABLE(EventPath);
public:
explicit EventPath(Node&, Event* = nullptr);
void initializeWith(Node&, Event*);
NodeEventContext& operator[](size_t index) { return m_nodeEventContexts[index]; }
const NodeEventContext& operator[](size_t index) const { return m_nodeEventContexts[index]; }
NodeEventContext& at(size_t index) { return m_nodeEventContexts[index]; }
NodeEventContext& last() { return m_nodeEventContexts[size() - 1]; }
WindowEventContext& windowEventContext() { ASSERT(m_windowEventContext); return *m_windowEventContext; }
void ensureWindowEventContext();
bool isEmpty() const { return m_nodeEventContexts.isEmpty(); }
size_t size() const { return m_nodeEventContexts.size(); }
void adjustForRelatedTarget(Node&, EventTarget* relatedTarget);
void adjustForTouchEvent(TouchEvent&);
static EventTarget* eventTargetRespectingTargetRules(Node&);
DECLARE_TRACE();
void clear()
{
m_nodeEventContexts.clear();
m_treeScopeEventContexts.clear();
}
private:
EventPath();
void initialize();
void calculatePath();
void calculateAdjustedTargets();
void calculateTreeOrderAndSetNearestAncestorClosedTree();
void shrink(size_t newSize) { ASSERT(!m_windowEventContext); m_nodeEventContexts.shrink(newSize); }
void retargetRelatedTarget(const Node& relatedTargetNode);
void shrinkForRelatedTarget(const Node& target, const Node& relatedTarget);
void adjustTouchList(const TouchList*, HeapVector<Member<TouchList>> adjustedTouchList, const HeapVector<Member<TreeScope>>& treeScopes);
using TreeScopeEventContextMap = HeapHashMap<Member<TreeScope>, Member<TreeScopeEventContext>>;
TreeScopeEventContext* ensureTreeScopeEventContext(Node* currentTarget, TreeScope*, TreeScopeEventContextMap&);
using RelatedTargetMap = HeapHashMap<Member<TreeScope>, Member<EventTarget>>;
static void buildRelatedNodeMap(const Node&, RelatedTargetMap&);
static EventTarget* findRelatedNode(TreeScope&, RelatedTargetMap&);
#if ENABLE(ASSERT)
static void checkReachability(TreeScope&, TouchList&);
#endif
const NodeEventContext& topNodeEventContext();
HeapVector<NodeEventContext> m_nodeEventContexts;
Member<Node> m_node;
Member<Event> m_event;
HeapVector<Member<TreeScopeEventContext>> m_treeScopeEventContexts;
Member<WindowEventContext> m_windowEventContext;
};
} // namespace blink
#endif
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
2441683448000f9ffd7ce4723b23b41eaff445e8 | c4a66686285857e441d05420f970a9b72bc8d5d5 | /testHulk.cpp | 1557cea37f4680ba39b4726cff23c6f1a4e8809d | [] | no_license | himanshu-rawat/CBcplusplus | 99140cb25a96b66c6160f6689b02d278ac8ba66d | fbb5de2e4945457eed604fc11fb2093da4258ecc | refs/heads/master | 2020-05-03T20:38:32.174661 | 2019-07-24T13:13:06 | 2019-07-24T13:13:06 | 178,807,210 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 421 | cpp | #include<iostream>
using namespace std;
int HulkSteps(int steps,int value,int i){
int count=0;
if(i>=value){
return count;
}
if(value%2==0){
count =1;
return count;
}
else{
count++;
return count+1;
}
}
int main(){
int n;
cin>>n;
int steps[100000];
for(int i=0;i<n;i++){
cin>>steps[i];
}
for(int i=0;i<n;i++){
int value=steps[i];
cout<<HulkSteps(steps[i],value,0);
cout<<endl;
}
}
| [
"himanshurawatrit@gmail.com"
] | himanshurawatrit@gmail.com |
c76cc2c944c4fd68240b1e0370e2257d54a46757 | 7abbbef9590f9c4b9469adcbae5ea8907478bf03 | /chromium_git/chromium/src/content/browser/compositor/buffer_queue.cc | cb6bd7933ab58cfc33001e475457518795ec7419 | [
"BSD-3-Clause"
] | permissive | GiorgiGagnidze/CEF | 845bdc2f54833254b3454ba8f6c61449431c7884 | fbfc30b5d60f1ea7157da449e34dd9ba9c50f360 | refs/heads/master | 2021-01-10T17:32:27.640882 | 2016-03-23T07:43:04 | 2016-03-23T07:43:04 | 54,463,340 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,015 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/compositor/buffer_queue.h"
#include "base/containers/adapters.h"
#include "build/build_config.h"
#include "content/browser/compositor/image_transport_factory.h"
#include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
#include "content/common/gpu/client/context_provider_command_buffer.h"
#include "content/common/gpu/client/gl_helper.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "gpu/command_buffer/service/image_factory.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/gfx/gpu_memory_buffer.h"
#include "ui/gfx/skia_util.h"
namespace content {
BufferQueue::BufferQueue(
scoped_refptr<cc::ContextProvider> context_provider,
unsigned int texture_target,
unsigned int internalformat,
GLHelper* gl_helper,
BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager,
int surface_id)
: context_provider_(context_provider),
fbo_(0),
allocated_count_(0),
texture_target_(texture_target),
internal_format_(internalformat),
gl_helper_(gl_helper),
gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
surface_id_(surface_id) {}
BufferQueue::~BufferQueue() {
FreeAllSurfaces();
gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL();
if (fbo_)
gl->DeleteFramebuffers(1, &fbo_);
}
void BufferQueue::Initialize() {
gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL();
gl->GenFramebuffers(1, &fbo_);
}
void BufferQueue::BindFramebuffer() {
gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL();
gl->BindFramebuffer(GL_FRAMEBUFFER, fbo_);
if (!current_surface_)
current_surface_ = GetNextSurface();
if (current_surface_) {
gl->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
texture_target_, current_surface_->texture, 0);
}
}
void BufferQueue::CopyBufferDamage(int texture,
int source_texture,
const gfx::Rect& new_damage,
const gfx::Rect& old_damage) {
gl_helper_->CopySubBufferDamage(
texture_target_, texture, source_texture,
SkRegion(gfx::RectToSkIRect(new_damage)),
SkRegion(gfx::RectToSkIRect(old_damage)));
}
void BufferQueue::UpdateBufferDamage(const gfx::Rect& damage) {
if (displayed_surface_)
displayed_surface_->damage.Union(damage);
for (auto& surface : available_surfaces_)
surface->damage.Union(damage);
for (auto& surface : in_flight_surfaces_) {
if (surface)
surface->damage.Union(damage);
}
}
void BufferQueue::SwapBuffers(const gfx::Rect& damage) {
if (current_surface_) {
if (!damage.IsEmpty() && damage != gfx::Rect(size_)) {
// Copy damage from the most recently swapped buffer. In the event that
// the buffer was destroyed and failed to recreate, pick from the most
// recently available buffer.
unsigned int texture_id = 0;
for (auto& surface : base::Reversed(in_flight_surfaces_)) {
if (surface) {
texture_id = surface->texture;
break;
}
}
if (!texture_id && displayed_surface_)
texture_id = displayed_surface_->texture;
if (texture_id) {
CopyBufferDamage(current_surface_->texture, texture_id, damage,
current_surface_->damage);
}
}
current_surface_->damage = gfx::Rect();
}
UpdateBufferDamage(damage);
in_flight_surfaces_.push_back(std::move(current_surface_));
// Some things reset the framebuffer (CopySubBufferDamage, some GLRenderer
// paths), so ensure we restore it here.
context_provider_->ContextGL()->BindFramebuffer(GL_FRAMEBUFFER, fbo_);
}
void BufferQueue::Reshape(const gfx::Size& size, float scale_factor) {
if (size == size_)
return;
// TODO(ccameron): This assert is being hit on Mac try jobs. Determine if that
// is cause for concern or if it is benign.
// http://crbug.com/524624
#if !defined(OS_MACOSX)
DCHECK(!current_surface_);
#endif
size_ = size;
// TODO: add stencil buffer when needed.
gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL();
gl->BindFramebuffer(GL_FRAMEBUFFER, fbo_);
gl->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
texture_target_, 0, 0);
FreeAllSurfaces();
}
void BufferQueue::RecreateBuffers() {
// We need to recreate the buffers, for whatever reason the old ones are not
// presentable on the device anymore.
// Unused buffers can be freed directly, they will be re-allocated as needed.
// Any in flight, current or displayed surface must be replaced.
available_surfaces_.clear();
// Recreate all in-flight surfaces and put the recreated copies in the queue.
for (auto& surface : in_flight_surfaces_)
surface = RecreateBuffer(std::move(surface));
current_surface_ = RecreateBuffer(std::move(current_surface_));
displayed_surface_ = RecreateBuffer(std::move(displayed_surface_));
if (current_surface_) {
// If we have a texture bound, we will need to re-bind it.
gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL();
gl->BindFramebuffer(GL_FRAMEBUFFER, fbo_);
gl->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
texture_target_, current_surface_->texture, 0);
}
}
scoped_ptr<BufferQueue::AllocatedSurface> BufferQueue::RecreateBuffer(
scoped_ptr<AllocatedSurface> surface) {
if (!surface)
return nullptr;
scoped_ptr<AllocatedSurface> new_surface(GetNextSurface());
if (!new_surface)
return nullptr;
new_surface->damage = surface->damage;
// Copy the entire texture.
CopyBufferDamage(new_surface->texture, surface->texture, gfx::Rect(),
gfx::Rect(size_));
return new_surface;
}
void BufferQueue::PageFlipComplete() {
DCHECK(!in_flight_surfaces_.empty());
if (displayed_surface_)
available_surfaces_.push_back(std::move(displayed_surface_));
displayed_surface_ = std::move(in_flight_surfaces_.front());
in_flight_surfaces_.pop_front();
}
void BufferQueue::FreeAllSurfaces() {
displayed_surface_.reset();
current_surface_.reset();
// This is intentionally not emptied since the swap buffers acks are still
// expected to arrive.
for (auto& surface : in_flight_surfaces_)
surface = nullptr;
available_surfaces_.clear();
}
void BufferQueue::FreeSurfaceResources(AllocatedSurface* surface) {
if (!surface->texture)
return;
gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL();
gl->BindTexture(texture_target_, surface->texture);
gl->ReleaseTexImage2DCHROMIUM(texture_target_, surface->image);
gl->DeleteTextures(1, &surface->texture);
gl->DestroyImageCHROMIUM(surface->image);
surface->buffer.reset();
allocated_count_--;
}
scoped_ptr<BufferQueue::AllocatedSurface> BufferQueue::GetNextSurface() {
if (!available_surfaces_.empty()) {
scoped_ptr<AllocatedSurface> surface =
std::move(available_surfaces_.back());
available_surfaces_.pop_back();
return surface;
}
unsigned int texture = 0;
gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL();
gl->GenTextures(1, &texture);
if (!texture)
return nullptr;
// We don't want to allow anything more than triple buffering.
DCHECK_LT(allocated_count_, 4U);
scoped_ptr<gfx::GpuMemoryBuffer> buffer(
gpu_memory_buffer_manager_->AllocateGpuMemoryBufferForScanout(
size_, gpu::ImageFactory::DefaultBufferFormatForImageFormat(
internal_format_),
surface_id_));
if (!buffer.get()) {
gl->DeleteTextures(1, &texture);
DLOG(ERROR) << "Failed to allocate GPU memory buffer";
return nullptr;
}
unsigned int id = gl->CreateImageCHROMIUM(
buffer->AsClientBuffer(), size_.width(), size_.height(),
internal_format_);
if (!id) {
LOG(ERROR) << "Failed to allocate backing image surface";
gl->DeleteTextures(1, &texture);
return nullptr;
}
allocated_count_++;
gl->BindTexture(texture_target_, texture);
gl->BindTexImage2DCHROMIUM(texture_target_, id);
return make_scoped_ptr(new AllocatedSurface(this, std::move(buffer), texture,
id, gfx::Rect(size_)));
}
BufferQueue::AllocatedSurface::AllocatedSurface(
BufferQueue* buffer_queue,
scoped_ptr<gfx::GpuMemoryBuffer> buffer,
unsigned int texture,
unsigned int image,
const gfx::Rect& rect)
: buffer_queue(buffer_queue),
buffer(buffer.release()),
texture(texture),
image(image),
damage(rect) {}
BufferQueue::AllocatedSurface::~AllocatedSurface() {
buffer_queue->FreeSurfaceResources(this);
}
} // namespace content
| [
"ggagn12@freeuni.edu.ge"
] | ggagn12@freeuni.edu.ge |
012144a2a0f80339b62fe72a979f5e9145a493dd | e3cee45fbe869a5239de195027bce663aca55020 | /w9/7.cpp | 3eec82797db1682f157a26cfbfbff6561c34a85f | [] | no_license | bobur554396/PPI2020FALL | dd354724c9b530652d81436791d8e2526a5fb478 | 8e55ec56a899ceb94ca9d9cc247f67c189110bf3 | refs/heads/master | 2023-01-20T04:58:30.129991 | 2020-12-05T09:23:01 | 2020-12-05T09:23:01 | 294,113,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | cpp | #include <iostream>
using namespace std;
int f1(int n){
int k = 0;
for(int i = 1; i <= n; i++)
k += i;
return k;
}
int f2(int n){
if(n == 1)
return 1;
return n + f2(n - 1);
}
/*
f(n) = 1, if n < 2
n + f(n - 1), if n >= 2
1) f2(4) => 4 + f2(3) => 4 + 3 + 2 + 1
2) f2(3) => 3 + f2(2) => 3 + 2 + 1
3) f2(2) => 2 + f2(1) => 2 + 1
4) f2(1) => 1
*/
int main(){
int n; // 4 = 1 + 2 + 3 + 4 = 10
cin >> n;
cout << f1(n) << endl << f2(n) << endl;
return 0;
} | [
"bobur.muhsimbaev@gmail.com"
] | bobur.muhsimbaev@gmail.com |
403ba565e5904d3eb4202849308f8f0e39791f22 | 7a8e6dbdfdda889eb759fbef398b996b2a08f968 | /CookieRunAndRun/CookieRunAndRun/InputHandler.h | 08169dfc18d30e08f42f3f42068df93a7bcbc71d | [] | no_license | Parkms2/CookieRun-Run | d5dba0a9b71a88288912a2ae7e7da37c75872b99 | 54c80f36dc6a4ac0ed9f1f4bd0e6c9f55409d7e8 | refs/heads/master | 2020-04-05T07:24:07.304051 | 2018-12-30T16:14:33 | 2018-12-30T16:14:33 | 156,674,214 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 952 | h | #pragma once
#include "SDL.h"
#include"Vector2D.h"
#include"Game.h"
class InputHandler {
public:
static InputHandler* Instance()
{
if (s_pInstance == 0) {
s_pInstance = new InputHandler();
return s_pInstance;
}
return s_pInstance;
}
void update();
void clean(); // 디바이스 관련 초기화된 부분을 clear
bool isKeyDown(SDL_Scancode key);
Vector2D* m_mousePosition;
bool getMouseButtonState(int buttonNumber);
Vector2D* getMousePosition();
void onMouseMove(SDL_Event event);
void onMouseButtonDown(SDL_Event event);
void onMouseButtonUp(SDL_Event event);
void onKeyDown();
void onKeyUp();
const Uint8* m_keystates;
enum mouse_buttons
{
LEFT = 0,
MIDDLE = 1,
RIGHT = 2
};
std::vector<bool> m_mouseButtonStates;
bool jump = false;
bool slide = false;
bool doubleJump = false;
private:
InputHandler();
~InputHandler() {}
static InputHandler* s_pInstance;
};
typedef InputHandler TheInputHandler;
| [
"20171153@vision.hoseo.edu"
] | 20171153@vision.hoseo.edu |
da7dbd64b367fa296a06a029f5701f7fa3925601 | fca68c5fec6df6f999408571315c2b8e7c4b8ce9 | /service/supersialign_home/src/Suez/Suez/UserApplication.h | e33cbffc347d206625a8c8bf639b42d05915eaea | [] | no_license | jpivarski-talks/1999-2006_gradschool-3 | 8b2ea0b6babef104b0281c069994fc9894a05b14 | 57e80d601c0519f9e01a07ecb53d367846e8306e | refs/heads/master | 2022-11-19T12:01:42.959599 | 2020-07-25T01:19:59 | 2020-07-25T01:19:59 | 282,235,559 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,198 | h | #if !defined(JOBCONTROL_USERAPPLICATION_H)
#define JOBCONTROL_USERAPPLICATION_H
// -*- C++ -*-
//
// Package: JobControl
// Module: UserApplication
//
// Description: This class must be provided by the user of
// in order to build an application. It must define
// the modules that are to form the basis of the application.
///
// Usage:
// <usage>
//
// Author: Martin Lohner
// Created: Thu Mar 20 15:13:08 EST 1997
// $Id: UserApplication.h,v 1.2 2000/03/14 23:26:04 mkl Exp $
//
// Revision history (at end of file)
//
// system include files
// user include files
// forward declarations
class JobControl;
class Interpreter;
class UserApplication
{
// friend classses and functions
public:
// constants, enums and typedefs
// Constructors and destructor
UserApplication( JobControl* jobControl );
virtual ~UserApplication();
// member functions
DABoolean runEmbeddedCommands( Interpreter& interpreter );
// const member functions
virtual DABoolean interactiveMode() const;
// static member functions
protected:
// protected member functions
// protected const member functions
private:
// Constructors and destructor
UserApplication( const UserApplication& );
// assignment operator(s)
const UserApplication& operator=( const UserApplication& );
// private member functions
// private const member functions
// data members
// static data members
};
// inline function definitions
// ------------------------------------------------------
// Revision history
//
// $Log: UserApplication.h,v $
// Revision 1.2 2000/03/14 23:26:04 mkl
// make OSF1 compiler happy (such a better compiler)
//
// Revision 1.1 2000/03/14 20:55:23 mkl
// new UserApplication functionality: new embeddedCommand and interactiveMode methods for running Suez in standalone mode in online
//
// Revision 1.2 1997/07/11 06:55:57 mkl
// // New <Package>/<File>.h structure
// // Modified so can also compile under cxx v5.5
//
// Revision 1.1 1997/03/27 06:53:57 mkl
// imported sources.
//
#endif /* JOBCONTROL_USERAPPLICATION_H */
| [
"jpivarski@gmail.com"
] | jpivarski@gmail.com |
ae495c0c1f6f066afe27b8f7b8c581220abe0028 | e8c23a3bec1ba3eb3856b373788e08b6dbffa7de | /Source/GDKShooter/Private/Controllers/Components/ControllerEventsComponent.cpp | f37de71bd2f38d74cbca467a3c2aae7e38c943a8 | [] | no_license | iomeone/NG-FPS | 67703ed8d4847845d64d25b9da37855b63a628ff | 8d58ad977c6ac191caa7df416c5e241f81245661 | refs/heads/master | 2023-07-23T22:12:40.599733 | 2021-09-06T13:10:08 | 2021-09-06T13:10:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,781 | cpp | // Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#include "Controllers/Components/ControllerEventsComponent.h"
#include "GameFramework/Controller.h"
#include "GameFramework/PlayerState.h"
#include "Runtime/Launch/Resources/Version.h"
UControllerEventsComponent::UControllerEventsComponent()
{
PrimaryComponentTick.bCanEverTick = false;
}
void UControllerEventsComponent::Death_Implementation(const AController* Killer)
{
DeathEvent.Broadcast(Killer);
if (Killer != nullptr)
{
APlayerState* KillerPlayerState = Killer->PlayerState;
if (KillerPlayerState != nullptr)
{
#if ENGINE_MINOR_VERSION <= 24
ClientInformOfDeath(KillerPlayerState->GetPlayerName(), KillerPlayerState->PlayerId);
#else
ClientInformOfDeath(KillerPlayerState->GetPlayerName(), KillerPlayerState->GetPlayerId());
#endif
}
else
{
ClientInformOfDeath(TEXT("") /*PlayerName*/, -1 /*PlayerID*/);
}
}
else //Offloaded NPC
{
ClientInformOfDeath(TEXT(""), -1);
}
}
void UControllerEventsComponent::Kill_Implementation(const AController* Victim)
{
KillEvent.Broadcast(Victim);
if (Victim != nullptr)
{
APlayerState* VictimPlayerState = Victim->PlayerState;
if (VictimPlayerState != nullptr)
{
#if ENGINE_MINOR_VERSION <= 24
ClientInformOfKill(VictimPlayerState->GetPlayerName(), VictimPlayerState->PlayerId);
#else
ClientInformOfKill(VictimPlayerState->GetPlayerName(), VictimPlayerState->GetPlayerId());
#endif
}
}
}
void UControllerEventsComponent::ClientInformOfKill_Implementation(const FString& VictimName, int32 VictimId)
{
KillDetailsEvent.Broadcast(VictimName, VictimId);
}
void UControllerEventsComponent::ClientInformOfDeath_Implementation(const FString& KillerName, int32 KillerId)
{
DeathDetailsEvent.Broadcast(KillerName, KillerId);
}
| [
"jpetanjek@foi.hr"
] | jpetanjek@foi.hr |
e6c29918bf0ca9a0b192b9cc44185c7be183e7c3 | f6f0f87647e23507dca538760ab70e26415b8313 | /6.1.0/msvc2019_64/include/QtCore/qtextstream.h | 70326b68c77054ca17fc124e2bb66a1d2cc4d62a | [] | no_license | stenzek/duckstation-ext-qt-minimal | a942c62adc5654c03d90731a8266dc711546b268 | e5c412efffa3926f7a4d5bf0ae0333e1d6784f30 | refs/heads/master | 2023-08-17T16:50:21.478373 | 2023-08-15T14:53:43 | 2023-08-15T14:53:43 | 233,179,313 | 3 | 1 | null | 2021-11-16T15:34:28 | 2020-01-11T05:05:34 | C++ | UTF-8 | C++ | false | false | 9,933 | h | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QTEXTSTREAM_H
#define QTEXTSTREAM_H
#include <QtCore/qiodevicebase.h>
#include <QtCore/qstring.h>
#include <QtCore/qchar.h>
#include <QtCore/qscopedpointer.h>
#include <QtCore/qstringconverter.h>
#include <stdio.h>
#ifdef Status
#error qtextstream.h must be included before any header file that defines Status
#endif
QT_BEGIN_NAMESPACE
class QIODevice;
class QLocale;
class QTextStreamPrivate;
class Q_CORE_EXPORT QTextStream : public QIODeviceBase
{
Q_DECLARE_PRIVATE(QTextStream)
public:
enum RealNumberNotation {
SmartNotation,
FixedNotation,
ScientificNotation
};
enum FieldAlignment {
AlignLeft,
AlignRight,
AlignCenter,
AlignAccountingStyle
};
enum Status {
Ok,
ReadPastEnd,
ReadCorruptData,
WriteFailed
};
enum NumberFlag {
ShowBase = 0x1,
ForcePoint = 0x2,
ForceSign = 0x4,
UppercaseBase = 0x8,
UppercaseDigits = 0x10
};
Q_DECLARE_FLAGS(NumberFlags, NumberFlag)
QTextStream();
explicit QTextStream(QIODevice *device);
explicit QTextStream(FILE *fileHandle, OpenMode openMode = ReadWrite);
explicit QTextStream(QString *string, OpenMode openMode = ReadWrite);
explicit QTextStream(QByteArray *array, OpenMode openMode = ReadWrite);
explicit QTextStream(const QByteArray &array, OpenMode openMode = ReadOnly);
virtual ~QTextStream();
void setEncoding(QStringConverter::Encoding encoding);
QStringConverter::Encoding encoding() const;
void setAutoDetectUnicode(bool enabled);
bool autoDetectUnicode() const;
void setGenerateByteOrderMark(bool generate);
bool generateByteOrderMark() const;
void setLocale(const QLocale &locale);
QLocale locale() const;
void setDevice(QIODevice *device);
QIODevice *device() const;
void setString(QString *string, OpenMode openMode = ReadWrite);
QString *string() const;
Status status() const;
void setStatus(Status status);
void resetStatus();
bool atEnd() const;
void reset();
void flush();
bool seek(qint64 pos);
qint64 pos() const;
void skipWhiteSpace();
QString readLine(qint64 maxlen = 0);
bool readLineInto(QString *line, qint64 maxlen = 0);
QString readAll();
QString read(qint64 maxlen);
void setFieldAlignment(FieldAlignment alignment);
FieldAlignment fieldAlignment() const;
void setPadChar(QChar ch);
QChar padChar() const;
void setFieldWidth(int width);
int fieldWidth() const;
void setNumberFlags(NumberFlags flags);
NumberFlags numberFlags() const;
void setIntegerBase(int base);
int integerBase() const;
void setRealNumberNotation(RealNumberNotation notation);
RealNumberNotation realNumberNotation() const;
void setRealNumberPrecision(int precision);
int realNumberPrecision() const;
QTextStream &operator>>(QChar &ch);
QTextStream &operator>>(char &ch);
QTextStream &operator>>(signed short &i);
QTextStream &operator>>(unsigned short &i);
QTextStream &operator>>(signed int &i);
QTextStream &operator>>(unsigned int &i);
QTextStream &operator>>(signed long &i);
QTextStream &operator>>(unsigned long &i);
QTextStream &operator>>(qlonglong &i);
QTextStream &operator>>(qulonglong &i);
QTextStream &operator>>(float &f);
QTextStream &operator>>(double &f);
QTextStream &operator>>(QString &s);
QTextStream &operator>>(QByteArray &array);
QTextStream &operator>>(char *c);
QTextStream &operator<<(QChar ch);
QTextStream &operator<<(char ch);
QTextStream &operator<<(signed short i);
QTextStream &operator<<(unsigned short i);
QTextStream &operator<<(signed int i);
QTextStream &operator<<(unsigned int i);
QTextStream &operator<<(signed long i);
QTextStream &operator<<(unsigned long i);
QTextStream &operator<<(qlonglong i);
QTextStream &operator<<(qulonglong i);
QTextStream &operator<<(float f);
QTextStream &operator<<(double f);
QTextStream &operator<<(const QString &s);
QTextStream &operator<<(QStringView s);
QTextStream &operator<<(QLatin1String s);
QTextStream &operator<<(const QByteArray &array);
QTextStream &operator<<(const char *c);
QTextStream &operator<<(const void *ptr);
private:
Q_DISABLE_COPY(QTextStream)
friend class QDebugStateSaverPrivate;
friend class QDebug;
QScopedPointer<QTextStreamPrivate> d_ptr;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QTextStream::NumberFlags)
/*****************************************************************************
QTextStream manipulators
*****************************************************************************/
typedef QTextStream & (*QTextStreamFunction)(QTextStream &);// manipulator function
typedef void (QTextStream::*QTSMFI)(int); // manipulator w/int argument
typedef void (QTextStream::*QTSMFC)(QChar); // manipulator w/QChar argument
class Q_CORE_EXPORT QTextStreamManipulator
{
public:
constexpr QTextStreamManipulator(QTSMFI m, int a) noexcept : mf(m), mc(nullptr), arg(a), ch() {}
constexpr QTextStreamManipulator(QTSMFC m, QChar c) noexcept : mf(nullptr), mc(m), arg(-1), ch(c) {}
void exec(QTextStream &s) { if (mf) { (s.*mf)(arg); } else { (s.*mc)(ch); } }
private:
QTSMFI mf; // QTextStream member function
QTSMFC mc; // QTextStream member function
int arg; // member function argument
QChar ch;
};
inline QTextStream &operator>>(QTextStream &s, QTextStreamFunction f)
{ return (*f)(s); }
inline QTextStream &operator<<(QTextStream &s, QTextStreamFunction f)
{ return (*f)(s); }
inline QTextStream &operator<<(QTextStream &s, QTextStreamManipulator m)
{ m.exec(s); return s; }
namespace Qt {
Q_CORE_EXPORT QTextStream &bin(QTextStream &s);
Q_CORE_EXPORT QTextStream &oct(QTextStream &s);
Q_CORE_EXPORT QTextStream &dec(QTextStream &s);
Q_CORE_EXPORT QTextStream &hex(QTextStream &s);
Q_CORE_EXPORT QTextStream &showbase(QTextStream &s);
Q_CORE_EXPORT QTextStream &forcesign(QTextStream &s);
Q_CORE_EXPORT QTextStream &forcepoint(QTextStream &s);
Q_CORE_EXPORT QTextStream &noshowbase(QTextStream &s);
Q_CORE_EXPORT QTextStream &noforcesign(QTextStream &s);
Q_CORE_EXPORT QTextStream &noforcepoint(QTextStream &s);
Q_CORE_EXPORT QTextStream &uppercasebase(QTextStream &s);
Q_CORE_EXPORT QTextStream &uppercasedigits(QTextStream &s);
Q_CORE_EXPORT QTextStream &lowercasebase(QTextStream &s);
Q_CORE_EXPORT QTextStream &lowercasedigits(QTextStream &s);
Q_CORE_EXPORT QTextStream &fixed(QTextStream &s);
Q_CORE_EXPORT QTextStream &scientific(QTextStream &s);
Q_CORE_EXPORT QTextStream &left(QTextStream &s);
Q_CORE_EXPORT QTextStream &right(QTextStream &s);
Q_CORE_EXPORT QTextStream ¢er(QTextStream &s);
Q_CORE_EXPORT QTextStream &endl(QTextStream &s);
Q_CORE_EXPORT QTextStream &flush(QTextStream &s);
Q_CORE_EXPORT QTextStream &reset(QTextStream &s);
Q_CORE_EXPORT QTextStream &bom(QTextStream &s);
Q_CORE_EXPORT QTextStream &ws(QTextStream &s);
} // namespace Qt
inline QTextStreamManipulator qSetFieldWidth(int width)
{
QTSMFI func = &QTextStream::setFieldWidth;
return QTextStreamManipulator(func,width);
}
inline QTextStreamManipulator qSetPadChar(QChar ch)
{
QTSMFC func = &QTextStream::setPadChar;
return QTextStreamManipulator(func, ch);
}
inline QTextStreamManipulator qSetRealNumberPrecision(int precision)
{
QTSMFI func = &QTextStream::setRealNumberPrecision;
return QTextStreamManipulator(func, precision);
}
QT_END_NAMESPACE
#endif // QTEXTSTREAM_H
| [
"stenzek@gmail.com"
] | stenzek@gmail.com |
0356b0066c00fdf97ffaec623a12520f0477a9d0 | ab981cd119c4695edc6e9a588f18984eded96bbc | /device/test/mainTest/mainTest.ino | 8d85d5674eaa8f7533cb7333fe3c29aba26d0f87 | [
"MIT"
] | permissive | rafaeljimenez01/iot-trashcan-tracking | ceb8f456ae1a0e8add4d801e52016648d4414601 | 31e4ee5dedba8db3c5e8c539687a46a8118442dc | refs/heads/master | 2023-04-01T11:15:25.241756 | 2021-04-08T20:46:43 | 2021-04-08T20:46:43 | 356,013,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,071 | ino | #include <ArduinoJson.h>
//------------------------------------------
#include <FirebaseESP8266.h>
#include <FirebaseESP8266HTTPClient.h>
#include <FirebaseFS.h>
#include <FirebaseJson.h>
#define FIREBASE_HOST "iot-trashcan-app.firebaseio.com/"
#define FIREBASE_AUTH "sdv5W0uduPp3BdFo1dUCpEuRqVLaMuQm619lgUaA"
//------------------------------------------
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
//------------------------------------------
#include <DHT.h>
#include <DHT_U.h>
#define DHTTYPE DHT11 //Definimos el tipo de sensor de humedad (DHT11 o DHT22)
//------------------------------------------
#define Trig D0
#define Echo D1
#define DHTPin D3
#define LED D5
#define TiltS D8
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
//Define humidity/temperature sensor object.
DHT dht(DHTPin, DHTTYPE);
//Define FirebaseESP8266 data object for data sending and receiving
FirebaseData firebaseData;
void blinkLed(uint8_t pin, int frecuency);
int getTiltVal(uint8_t pin);
float getDistanceUS(uint8_t trigPin, uint8_t echoPin);
float getUsedCapacity(uint8_t trigPin, uint8_t echoPin, float heigh_cm);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(Trig, OUTPUT);
pinMode(Echo, INPUT);
pinMode(LED, OUTPUT);
pinMode(TiltS, INPUT);
wifiConnect();
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
delay(10);
}
void loop() {
// put your main code here, to run repeatedly:
float h = dht.readHumidity(); //Lectura de Humedad
float t = dht.readTemperature(); //Lectura de Temperatura
Serial.print("Temperature = ");
Serial.println(t);
Serial.print("Humidity = ");
Serial.println(h);
// Demostración de inclinación y ultrasónico:
Serial.print("Used storage: ");
Serial.print(getUsedCapacity(Trig, Echo, 50));
Serial.println("%");
Serial.print("Tilt value: ");
Serial.println(getTiltVal(TiltS));
Firebase.pushFloat(firebaseData, "DHT/2/temperatura", t);
Firebase.pushFloat(firebaseData, "DHT/2/humedad", h);
if(WiFi.status() != WL_CONNECTED) {
wifiConnect();
}
delay(1000);
}
void blinkLed(uint8_t pin, int frecuency){
digitalWrite(pin, HIGH);
delay(frecuency);
digitalWrite(pin, LOW);
delay(frecuency);
}
void wifiConnect(){
digitalWrite(LED, HIGH);
// Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
// Uncomment and run it once, if you want to erase all the stored information
wifiManager.resetSettings();
// set custom ip for portal
//wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
// fetches ssid and pass from eeprom and tries to connect
// if it does not connect it starts an access point with generated name (ESP + ChipID)
// and goes into a blocking loop awaiting configuration
wifiManager.autoConnect();
digitalWrite(LED, LOW);
} //End wifiConnect()
/*
getTiltVal
Sensor: tilt switch
Returns 0 if trashcan is in vertical position, 1 if it's horizontal.
*/
int getTiltVal(uint8_t pin) {
return (digitalRead(pin) == 0);
}
/*
getDistanceUS
Sensor: ultrasonic distance sensor
Returns distance (in cm) from the trashcan's top to the trash level.
*/
float getDistanceUS(uint8_t trigPin, uint8_t echoPin) {
digitalWrite(trigPin, HIGH);
delay(10);
digitalWrite(trigPin, LOW);
float duration_us = pulseIn(echoPin, HIGH);
float distance_cm = 0.017 * duration_us;
return distance_cm;
}
/*
getUsedCapacity
Sensor: ultrasonic distance sensor
Returns percentage of capacity in trashcan that is being used based on height
*/
float getUsedCapacity(uint8_t trigPin, uint8_t echoPin, float height_cm) {
float distance = getDistanceUS(trigPin, echoPin);
return (1 - distance / height_cm) * 100;
}
| [
"oscar-me@outlook.com"
] | oscar-me@outlook.com |
2d76c26d95191c8ca6540ead0fb4c97cdaa917f9 | af69bd57934f3daf5299194f354a15f5eac32468 | /stackIT.cpp | 358ed6d0106bdb019093884174b2457191854416 | [] | no_license | Memhir-Yasue/cpp-tutorial | 05c530f8090d59abac6c55d73b0ed7efac4130a5 | d61d92c7ec468791281e58ac32c95a7e15653351 | refs/heads/master | 2020-04-27T03:15:26.289813 | 2019-03-06T05:37:06 | 2019-03-06T05:37:06 | 174,019,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,297 | cpp | #include <iostream>
#include <cassert>
class Stack
{
static const int capacity = 10; //
int stack[capacity];
int size = 0;
public:
bool push(int element)
{
if (size < capacity - 1)
{
stack[size] = element;
size++;
return true;
}
std::cout <<"The stack is full!\n";
return false;
}
int pop()
{
assert(size != 0);
int toBeRemoved = stack[size];
size --;
return toBeRemoved;
}
void reset() {
size = 0;
}
void print() {
if(size == 0)
{
std::cout <<"( )"<<std::endl;
}
else if(size == 1)
{
std::cout << "( " << stack[size]<< ") "<<std::endl;
}
else
{
std::cout << "( ";
for (int i = 0; i <= size - 1; i++)
{
std::cout << stack[i] << " ";
}
std::cout << ")\n";
}
}
void returnFirstElem(){
std::cout << stack[0]<<"\n";
}
};
int main()
{
Stack stack;
stack.reset();
stack.print();
stack.push(5);
stack.push(3);
stack.push(8);
stack.print();
stack.pop();
stack.print();
//
stack.pop();
stack.pop();
stack.print();
return 0;
}
| [
"eyasu.woldu@temple.edu"
] | eyasu.woldu@temple.edu |
d2c759a7c44c3ce8da533ff6a1185dbd44499f3a | f13b002a27c4b6d89151b3c925b4a5a97607f39a | /SOUI_gn/src/third-part/7z/CPP/7zip/Compress/BZip2Crc.h | c16bcad72600e938a0fe00c90ad9fa91a3549219 | [
"MIT"
] | permissive | lehoon/soui_gn | 007c2b0f00e5f0f036cbaeee98526eaa445bd541 | 0d3196eca8bddc0c2c9a694e06fb544965079b77 | refs/heads/master | 2020-05-23T13:15:54.091119 | 2018-05-04T02:46:34 | 2018-05-04T02:46:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | h | // BZip2Crc.h
#ifndef __BZIP2_CRC_H
#define __BZIP2_CRC_H
#include "../../Common/MyTypes.h"
class CBZip2Crc
{
UInt32 _value;
static UInt32 Table[256];
public:
static void InitTable();
CBZip2Crc(): _value(0xFFFFFFFF) {};
void Init() { _value = 0xFFFFFFFF; }
void UpdateByte(Byte b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); }
void UpdateByte(unsigned int b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); }
UInt32 GetDigest() const { return _value ^ 0xFFFFFFFF; }
};
class CBZip2CombinedCrc
{
UInt32 _value;
public:
CBZip2CombinedCrc(): _value(0){};
void Init() { _value = 0; }
void Update(UInt32 v) { _value = ((_value << 1) | (_value >> 31)) ^ v; }
UInt32 GetDigest() const { return _value ; }
};
#endif
| [
"24015500@qq.com"
] | 24015500@qq.com |
31174613de158ceb6b0e09bd7d3584a29c9e68e4 | c5843992e233b92e90b53bd8a90a9e68bfc1f6d6 | /gcwrap/apps/harvestrn/harvestrn.cc | 033919e48e68ab324761d02d9b0a92b3589bf92d | [] | no_license | pkgw/casa | 17662807d3f9b5c6b57bf3e36de3b804e202c8d3 | 0f676fa7b080a9815a0b57567fd4e16cfb69782d | refs/heads/master | 2021-09-25T18:06:54.510905 | 2017-08-16T21:53:54 | 2017-08-16T21:53:54 | 100,752,745 | 2 | 1 | null | 2020-02-24T18:50:59 | 2017-08-18T21:51:10 | C++ | UTF-8 | C++ | false | false | 2,403 | cc | //
// harvestrn - a wee program to scan the output of svn log and
// if the log contains a notation to include the text in the
// release notes it will spit that out to stdout.
//
//# Copyright (C) 2007
//# Associated Universities, Inc. Washington DC, USA.
//#
//# 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.,
//# 675 Massachusetts Ave, Cambridge, MA 02139, USA.
//#
//# Correspondence concerning AIPS++ should be addressed as follows:
//# Internet email: aips2-request@nrao.edu.
//# Postal address: AIPS++ Project Office
//# National Radio Astronomy Observatory
//# 520 Edgemont Road
//# Charlottesville, VA 22903-2475 USA
//#
//# $Id$
//
//# Includes
//
//
#include <iostream>
#include <fstream>
#include <fstream>
#include <casa/BasicSL/String.h>
#include <casa/Utilities/Regex.h>
using namespace std;
int main(int argc, char **argv)
{
bool inRelNotes(false);
istream *ifs;
if(argc > 1)
ifs = new ifstream(argv[1]);
else
ifs = &cin;
//
//
//
casa::String jiraLine;
while(!ifs->eof()){
char buffer[1025];
ifs->getline(buffer, 1024);
casa::String theLine(buffer);
if(theLine.contains("JIRA Issue:")){
jiraLine = casa::String(theLine);
}
if(theLine.contains(casa::Regex("Put in Release Notes:.*[Yy][Ee][Ss]"))){
if(!theLine.contains(casa::Regex("Put in Release Notes:.*[yY][Ee][Ss]/[Nn][oO]"))){
inRelNotes = true;
cout << "--------------------" << endl;
cout << jiraLine << endl;
}
}
if(theLine.contains("---------------------")){
inRelNotes = false;
}
if(inRelNotes)
cout << theLine << endl;
}
cout << "--------------------" << endl;
return 0;
}
| [
"srankin@nrao.edu"
] | srankin@nrao.edu |
a62e05df2d6d45d5f71f6355da36c0a08f7a01e2 | 31e4715ec439da3eee1ca4fd8abfc9c425311c89 | /_PC/babecheck2/src/babe_a1.cpp | 0f07c32c4a06fba5ed131da595b641618bdbd7ed | [] | no_license | justdanpo/elfpack-se | 41f036b9add3799e1a63c16599d008ce5d2c009f | d0c0cee1385f70046439ba46630d41675f559db8 | refs/heads/master | 2022-07-05T00:22:58.656282 | 2022-03-06T21:23:55 | 2022-03-06T21:23:55 | 32,311,965 | 20 | 7 | null | 2022-03-09T15:30:39 | 2015-03-16T08:46:02 | C | UTF-8 | C++ | false | false | 11,071 | cpp | #include "stdafx.h"
#include <stdint.h>
#include "babeheaders\babe_a1.h"
#include "openssl/sha.h"
#include "certs\certz.h"
#include "rsadecode.h"
#include <string>
typedef std::basic_string<unsigned char> ucbuffer;
#pragma pack(push,1)
struct A1CERT
{
uint32_t keysize;//1
char name[0x40];
uint8_t cert0[0x80];
uint8_t cert80[0x80];
uint32_t e;//5
uint32_t serviceflag;//0000=blue , 01=red/brown
uint32_t C1;//C1 00 00 00
uint32_t color;//color: FFFF=blue , 62=brown , 04=red
uint32_t FF;//FF 00 00 00
uint32_t cid;
uint32_t unk0;
uint16_t year;
uint8_t month;
uint8_t day;
uint32_t FFFFFFFF;//FF FF FF FF
uint8_t cert124[0x80];
};
#pragma pack(pop)
int isbabe_a1(TCHAR* infilename)
{
int retvalue=0;
BABEHDR hdr;
FILE* f;
if(_tfopen_s(&f,infilename,_T("rb")) == 0)
{
if(sizeof(hdr)==fread(&hdr,1,sizeof(hdr),f))
{
if(hdr.sig == 0xBEBA)
{
if(hdr.ver>=2 && hdr.ver<=4)
{
if(hdr.color ==COLOR_RED || hdr.color==COLOR_BROWN || hdr.color==COLOR_BLUE)
{
if(hdr.platform ==DB2000
||hdr.platform == DB2001
||hdr.platform == DB2010
||hdr.platform == DB2012
||hdr.platform == PNX5230
||hdr.platform == DB2020
)
{
retvalue = 1;
}
}
}
}
}
fclose(f);
}else
{
retvalue = -1;
}
return retvalue;
}
A1CERT* findcert(int platform, int cid=0, int color=0)
{
for(int i=0;i<sizeof(certz)/sizeof(certz[0]);i++)
{
if( (platform & certz[i].platform) && (certz[i].cid==cid) /*&& certz[i].color == color*/ )
{
if( (!cid && !color) || color == certz[i].color )
return (A1CERT*)&certz[i].cert;
}
}
return NULL;
}
A1CERT* findcert(int platform, char* name)
{
for(int i=0;i<sizeof(certz)/sizeof(certz[0]);i++)
{
if( (platform & certz[i].platform) )
{
A1CERT* ptr=(A1CERT*)&certz[i].cert;
if(strncmp(name, ptr->name, sizeof(ptr->name))==0)
return ptr;
}
}
return NULL;
}
int shaupdatefile(SHA_CTX& sha,FILE* f, int pos, int size)
{
fseek(f,pos,SEEK_SET);
while(size)
{
uint8_t tmp[64];
int tmpsize=size>sizeof(tmp) ? sizeof(tmp): size;
if(fread(tmp,1,tmpsize,f) !=tmpsize)
return -1;
SHA1_Update(&sha, &tmp[0],tmpsize);
size-=tmpsize;
}
return 0;
}
static TCHAR* getplatformname(int platform)
{
struct PN
{
int platform;
TCHAR* name;
} static const pn[]={
DB2000 ,_T("DB2000")
,DB2001 ,_T("DB2001")
,DB2010 ,_T("DB2010")
,DB2012 ,_T("DB2012")
,PNX5230 ,_T("PNX5230")
,DB2020 ,_T("DB2020")
};
for(int i=0;i<sizeof(pn)/sizeof(pn[0]);i++)
if(pn[i].platform & platform)
return pn[i].name;
return _T("unknown");
}
static TCHAR* getcolorname(int color)
{
struct PN
{
int color;
TCHAR* name;
} static const pn[]={
COLOR_RED ,_T("RED")
,COLOR_BROWN,_T("BROWN")
,COLOR_BLUE ,_T("BLUE")
,COLOR_BLACK,_T("BLACK")
};
for(int i=0;i<sizeof(pn)/sizeof(pn[0]);i++)
if(pn[i].color == color)
return pn[i].name;
return _T("unknown");
}
int decodehashes(BABEHDR* hdr,FILE* f,unsigned char* hashes1,unsigned char* hashes2,A1CERT* &cer)
{
A1CERT* emproot = findcert(hdr->platform, hdr->z1 & 0x0F, COLOR_BLUE);//emp root
if(!emproot)
{
_tprintf(_T("can't find root cert\n"));
return -1;
}
if( (hdr->z1 & 0xF0) == 0 )
cer= findcert(hdr->platform, ((A1CERT*)&hdr->certplace)->name);
else
cer = findcert(hdr->platform, hdr->cid, hdr->color);
if(!cer)
{
_tprintf(_T("can't find cert\n"));
return -1;
}
if(decodeblock( hashes1, 0x80, hdr->hash1, emproot->cert0 ))
{
_tprintf(_T("can't decrypt hashtab1\n"));
// return -1;
}
if(decodeblock( hashes2, 0x80, hdr->hash2, cer->cert0 ))
{
_tprintf(_T("can't decrypt hashtab2\n"));
return -1;
}
return 0;
}
int checka1loader(BABEHDR* hdr,FILE* f)
{
uint8_t hashes1[0x80];
uint8_t hashes2[0x80];
A1CERT* cer;
if(decodehashes(hdr,f,hashes1,hashes2,cer)<0)
return -1;
//--------------------------
unsigned char hash[20];
SHA_CTX sha;
SHA1_Init(&sha);
SHA1_Update(&sha, (unsigned char*)hdr, 0x3C);
SHA1_Update(&sha, (unsigned char*)cer, 0x1E8);
SHA1_Update(&sha, (unsigned char*)&hdr->prologuestart, 0x1C);
SHA1_Final(hash, &sha);
if(memcmp(hash,&hashes1[0],20))
{
_tprintf(_T("bad hash1 (header)\n"));
// return -1;
}
//--------------------------
SHA1_Init(&sha);
SHA1_Update(&sha, (unsigned char*)hdr,0x3C);
SHA1_Update(&sha, (unsigned char*)cer,0x1E8);
SHA1_Update(&sha, (unsigned char*)&hdr->prologuestart,0x1C);
if(shaupdatefile(sha,f,0x380,hdr->prologuesize1))
{
_tprintf(_T("error while processing prologue\n"));
return -1;
}
SHA1_Final(hash, &sha);
if(memcmp(hash,&hashes1[20],20))
{
_tprintf(_T("bad hash2 (header + prologue)\n"));
// return -1;
}
//--------------------------
SHA1_Init(&sha);
SHA1_Update(&sha, (unsigned char*)hdr,0x3C);
SHA1_Update(&sha, (unsigned char*)cer,0x1E8);
SHA1_Update(&sha, (unsigned char*)&hdr->prologuestart,0x1C);
SHA1_Update(&sha, (unsigned char*)&hdr->hash1,0xC0);
SHA1_Final(hash, &sha);
if(memcmp(hash,&hashes2[2],20))
{
_tprintf(_T("bad hash3 (header full)\n"));
return -1;
}
//--------------------------
SHA1_Init(&sha);
SHA1_Update(&sha, (unsigned char*)hdr,0x3C);
SHA1_Update(&sha, (unsigned char*)cer,0x1E8);
SHA1_Update(&sha, (unsigned char*)&hdr->prologuestart,0x1C);
SHA1_Update(&sha, (unsigned char*)&hdr->hash1,0xC0);
if(shaupdatefile(sha,f,0x380+hdr->prologuesize1,hdr->payloadsize1))
{
_tprintf(_T("error while processing payload\n"));
return -1;
}
SHA1_Final(hash, &sha);
if(memcmp(hash,&hashes2[22],20))
{
_tprintf(_T("bad hash4 (header full + payload)\n"));
return -1;
}
return 0;
}
int checka1ssw(BABEHDR* hdr,FILE* f)
{
unsigned char hashes1[0x80];
unsigned char hashes2[0x80];
A1CERT* cer;
if(decodehashes(hdr,f,hashes1,hashes2,cer)<0)
return -1;
//--------------------------
unsigned char hash[20];
SHA_CTX sha;
SHA1_Init(&sha);
SHA1_Update(&sha, (unsigned char*)hdr,0x3C);
SHA1_Update(&sha, (unsigned char*)cer,0x1E8);
SHA1_Update(&sha, (unsigned char*)&hdr->prologuestart,0x1C);
SHA1_Final(hash, &sha);
if(memcmp(hash,&hashes1[0],20))
{
_tprintf(_T("bad hash1 (header)\n"));
// return -1;
}
//--------------------------
SHA1_Init(&sha);
SHA1_Update(&sha, (unsigned char*)hdr,0x3C);
SHA1_Update(&sha, (unsigned char*)cer,0x1E8);
SHA1_Update(&sha, (unsigned char*)&hdr->prologuestart,0x1C);
SHA1_Update(&sha, (unsigned char*)&hdr->hash1,0xC0);
SHA1_Final(hash, &sha);
if(memcmp(hash,&hashes2[2],20))
{
_tprintf(_T("bad hash3 (header full)\n"));
return -1;
}
int hashsize=1;
int blocks = hdr->payloadsize1;
int sbsize = hdr->payloadsize2;
unsigned long hptr=0x380;
unsigned long hashtablesize;
switch(hdr->ver)
{
case 2:
hashtablesize = 0x100;
_tprintf(_T("static hash\n"));
break;
case 3:
hashtablesize = hashsize*blocks;
_tprintf(_T("dynamic hash\n"));
break;
case 4:
hashsize=20;
hashtablesize = hashsize*blocks;
_tprintf(_T("full hash\n"));
break;
default:
_tprintf(_T("error! unknown header version %x\n"),hdr->ver);
}
_tprintf(_T("number of blocks: %d (0x%X)\n"),blocks,blocks);
ucbuffer hashes;
hashes.resize(hashtablesize);
fseek(f, hptr, SEEK_SET);
if(hashtablesize != fread(&hashes[0],1,hashtablesize,f))
{
_tprintf(_T("can't read hashtable\n"));
return -1;
}
SHA1_Init(&sha);
SHA1_Update(&sha, (unsigned char*)hdr,0x3C);
SHA1_Update(&sha, (unsigned char*)cer,0x1E8);
SHA1_Update(&sha, (unsigned char*)&hdr->prologuestart,0x1C);
SHA1_Update(&sha, (unsigned char*)&hdr->hash1,0xC0);
for(int curblock=1;curblock<=blocks;curblock++)
{
uint32_t offset;
uint32_t addresssize[2];
if( sizeof(addresssize) != fread(addresssize,1,sizeof(addresssize),f))
{
_tprintf(_T("error! block %d out of file!\n"),curblock);
return 1;
}
if(curblock==1)
{
offset = addresssize[0];
switch(offset & 0x00FFFFFF)
{
case 0x00000000:
case 0x00020000:
case 0x000A0000:
_tprintf(_T("superblock addr: 0x%X\n"),offset);
_tprintf(_T("superblock size: 0x%X\n"),sbsize);
break;
case 0x00140000:
default:
_tprintf(_T("1st block addr: 0x%X\n"),offset);
_tprintf(_T("1st block size: 0x%X\n"),sbsize);
break;
}
}
//memleak
ucbuffer block;
block.resize(addresssize[1]);
if(addresssize[1]!=fread(&block[0],1,addresssize[1],f))
{
_tprintf(_T("error! block %d out of file!\n"),curblock);
return -1;
}
if(curblock>2)
{
if(addresssize[0]!=offset)
_tprintf(_T("warning! block %d addr %08X size %08X, expected address: %08X\n")
,curblock,addresssize[0],addresssize[1],offset);
}
SHA1_Update(&sha, (unsigned char*)addresssize,sizeof(addresssize));
SHA1_Update(&sha, block.data(),block.size());
SHA_CTX shacopy;
memcpy(&shacopy, &sha, sizeof(sha));
SHA1_Final(hash, &shacopy);
if(memcmp(&hash[20-hashsize],&hashes[hashsize*(curblock-1)],hashsize))
{
_tprintf(_T("error! %dst block's hash doesn't match a hdr value\n"),curblock);
return -1;
}
offset = (addresssize[0] + addresssize[1] + 3) &~3;
}
SHA1_Final(hash, &sha);
if(memcmp( &hashes2[22],hash,20 ))
{
_tprintf(_T("bad hash4 (final hash)\n"));
return -1;
}
_tprintf(_T("//2do: hash2+hash5\n"));//hashes1[20], hashes2[42]
return 0;
}
int checka1sfa(BABEHDR* hdr,FILE* f)
{
/*
unsigned char hashes1[0x80];
unsigned char hashes2[0x80];
A1CERT* cer;
if(decodehashes(hdr,f,hashes1,hashes2,cer)<0)
return -1;
//--------------------------
unsigned char hash[20];
CSHA1 sha;
sha.Reset();
sha.Update((unsigned char*)hdr,0x3C);
sha.Update((unsigned char*)cer,0x1E8);
sha.Update((unsigned char*)&hdr->prologuestart,0x1C);
sha.Final();
sha.GetHash(hash);
if(memcmp(hash,&hashes1[0],20))
{
_tprintf(_T("bad hash1 (header)\n"));
// return -1;
}
//--------------------------
sha.Reset();
sha.Update((unsigned char*)hdr,0x3C);
sha.Update((unsigned char*)cer,0x1E8);
sha.Update((unsigned char*)&hdr->prologuestart,0x1C);
sha.Update((unsigned char*)&hdr->hash1,0xC0);
sha.Final();
sha.GetHash(hash);
if(memcmp(hash,&hashes2[2],20))
{
_tprintf(_T("bad hash3 (header full)\n"));
return -1;
}
*/
_tprintf(_T("sfa unsupported\n"));
return -1;
}
static TCHAR* getfiletypename(BABEHDR* hdr)
{
switch(hdr->flags & 0x210)
{
case 0:
return _T("LOADER");
case 0x200:
return _T("SFA");
case 0x210:
return _T("SSW");
}
return _T("unknown");
}
int checkbabe_a1(TCHAR* infilename)
{
int retvalue=0;
FILE* f;
if(_tfopen_s(&f,infilename,_T("rb")) == 0)
{
BABEHDR hdr;
if(sizeof(hdr)==fread(&hdr,1,sizeof(hdr),f))
{
_tprintf(_T("platform %s, cid %d, color %s, filetype %s\n"),getplatformname(hdr.platform),hdr.cid,
getcolorname(hdr.color),getfiletypename(&hdr));
switch(hdr.flags & 0x210)
{
case 0:
retvalue = checka1loader(&hdr,f);
break;
case 0x200:
retvalue = checka1sfa(&hdr,f);
break;
case 0x210:
retvalue = checka1ssw(&hdr,f);
break;
}
}
fclose(f);
}else
{
retvalue = -1;
}
return retvalue;
} | [
"jdp@bk.ru"
] | jdp@bk.ru |
0c5cdb3f148b8ed92af92603d21d9d96cdaf7686 | 82b37d52d5be853fafb313a239de697ff690d69a | /ch17/bk/bk04_vector_element_access_array.cpp | 787def9cf2e2d96ca1a1c2e189721ba4ea8efda8 | [] | no_license | sinedanat/teach_yourself_cpp_in_one_hour_a_day_rao_2017 | d8b918aabccbd4e37cb81ac346b17d3c254f204b | a82d62c1310c4dc48c6cb1f022f0a1fd9ece98ba | refs/heads/master | 2023-09-05T11:01:21.140910 | 2021-11-22T13:36:47 | 2021-11-22T13:36:47 | 426,196,251 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 572 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> integers{50, 1, 987, 1001};
for (size_t index = 0; index < integers.size(); ++index)
{
cout << "Element[" << index << "] = " ;
cout << integers[index] << endl;
}
integers[2] = 2011; // change value of 3rd element
cout << "After replacement: " << endl;
cout << "Element[2] = " << integers[2] << endl;
return 0;
}
// Element[0] = 50
// Element[1] = 1
// Element[2] = 987
// Element[3] = 1001
// After replacement:
// Element[2] = 2011
| [
""
] | |
9a3184f6872ecc25173506e25ec15634ebe6dc85 | dfb0baf3c8ddf2470386c261a2aa322666c1b667 | /Others/Boggle_Game/boggle.cpp | da4947f47d92ce0084b049163436bb1f49388458 | [] | no_license | zhenglu0/Miscellaneous_Projects | 70bdee241ffa061f36bd198fd994887ce7545876 | c26229052a55124fcd511f118de3030841f66004 | refs/heads/master | 2021-08-26T07:08:33.539242 | 2017-11-22T04:07:54 | 2017-11-22T04:07:54 | 83,157,418 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,299 | cpp | #include "boggle.h"
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <cmath>
using std::string;
using std::ifstream;
template <typename T>
inline T square(T x) {
return x*x;
}
void Boggle::read_dictionary(const char *filename) {
ifstream f(filename);
if (!f.is_open())
throw std::runtime_error("failed to open dictionary file");
while(f.good()) {
string s;
getline(f,s);
if (s.size()>0)
dict.addWord(s);
}
}
void Boggle::read_board(const char *filename) {
ifstream f(filename);
if (!f.is_open())
throw std::runtime_error("Failed to open board file");
std::vector<char> letters;
char c;
while (f >> c) {
letters.push_back(c);
}
n = std::sqrt(letters.size());
if (square(n) != letters.size())
throw std::runtime_error("board file is not NxN");
board result;
for (unsigned int i=0;i<n;++i) {
row r;
for (unsigned int j=0;j<n;++j) {
r.push_back(letters[(i*n)+j]);
}
result.push_back(r);
}
boggle_board=result;
}
void Boggle::show_board()
{
print_board(boggle_board);
}
void Boggle::solve_board()
{
set_visited_board();
for (unsigned int i = 0; i < n; ++i)
for (unsigned int j = 0; j < n; ++j)
do_solve_board(i, j);
}
void Boggle::print_result()
{
for (std::set<std::string>::iterator it=result.begin(); it!=result.end(); ++it)
std::cout << *it << std::endl;
std::cout << std::endl;
}
void Boggle::do_solve_board(int x, int y)
{
word.push_back(boggle_board[x][y]);
if (!dict.searchPrefix(word)) {
word.erase(word.size()-1, 1);
return;
}
visited_board[x][y] = 'T';
if (word.length()>= 3 && dict.searchWord(word))
result.insert(word);
int d = static_cast<int>(n);
if (x-1>=0 && x-1<d && y-1>=0 && y-1<d &&
visited_board[x-1][y-1] == 'F')
do_solve_board(x-1, y-1);
if (x-1>=0 && x-1<d && y>=0 && y<d &&
visited_board[x-1][y] == 'F')
do_solve_board(x-1, y);
if (x-1>=0 && x-1<d && y+1>=0 && y+1<d &&
visited_board[x-1][y+1] == 'F')
do_solve_board(x-1, y+1);
if (x>=0 && x<d && y-1>=0 && y-1<d &&
visited_board[x][y-1] == 'F')
do_solve_board(x, y-1);
if (x>=0 && x<d && y+1>=0 && y+1<d &&
visited_board[x][y+1] == 'F')
do_solve_board(x, y+1);
if (x+1>=0 && x+1<d && y-1>=0 && y-1<d &&
visited_board[x+1][y-1] == 'F')
do_solve_board(x+1, y-1);
if (x+1>=0 && x+1<d && y>=0 && y<d &&
visited_board[x+1][y] == 'F')
do_solve_board(x+1, y);
if (x+1>=0 && x+1<d && y+1>=0 && y+1<d &&
visited_board[x+1][y+1] == 'F')
do_solve_board(x+1, y+1);
word.erase(word.size()-1, 1);
visited_board[x][y] = 'F';
}
void Boggle::print_board(const board &b)
{
board::const_iterator i = b.begin();
board::const_iterator e = b.end();
while (i != e) {
row::const_iterator j = i->begin();
while (j != i->end())
std::cout<<*j++<<" ";
++i;
std::cout<<std::endl;
}
}
// 'T' means the position is visited
// 'F' means the position is not visited
void Boggle::set_visited_board()
{
for (unsigned int i=0;i<n;++i) {
row r;
for (unsigned int j=0;j<n;++j) {
r.push_back('F');
}
visited_board.push_back(r);
}
}
void Boggle::show_visited_board()
{
print_board(visited_board);
}
| [
"luozheng03@gmail.com"
] | luozheng03@gmail.com |
26950f9fa4c18e3301406267bb545a6f79d9a21c | 193aacd05d997604655a0872bbe1604f4585dc29 | /sachin codes/laboratories.cpp | f5ff06429877bef7cc9c40e0ca685ff1911a9973 | [] | no_license | NEERAJISM/codes | b27e375313b1c1c8c002f76159cb1160706c9eea | 9f770d7b2dbfbe0f12f235089dcdac7dfe370887 | refs/heads/master | 2021-01-19T11:10:31.721972 | 2016-07-30T05:27:41 | 2016-07-30T05:27:41 | 60,888,241 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 320 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i;
string s;
map<string, int> m;
map<string, int> :: iterator it;
cin>>n;
for(i=0;i<n;i++)
{
cin>>s;
m[s]++;
}
for(it = (m).begin(); it != (m).end(); it++)
{
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
| [
"8patidarneeraj@gmail.com"
] | 8patidarneeraj@gmail.com |
14180f87b9417e89d94e827b4fd8f3767e60431d | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/make/hunk_596.cpp | 89f4d206116a1e99bbc12edba859980d82681e77 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,735 | cpp | file->cmds = default_file->cmds;
}
- /* Update all non-intermediate files we depend on, if necessary,
- and see whether any of them is more recent than this file. */
+ /* Update all non-intermediate files we depend on, if necessary, and see
+ whether any of them is more recent than this file. We need to walk our
+ deps, AND the deps of any also_make targets to ensure everything happens
+ in the correct order. */
- lastd = 0;
- d = file->deps;
- while (d != 0)
+ amake.file = file;
+ amake.next = file->also_make;
+ ad = &amake;
+ while (ad)
{
- FILE_TIMESTAMP mtime;
- int maybe_make;
- int dontcare = 0;
+ struct dep *lastd = 0;
- check_renamed (d->file);
+ /* Find the deps we're scanning */
+ d = ad->file->deps;
+ ad = ad->next;
- mtime = file_mtime (d->file);
- check_renamed (d->file);
+ while (d)
+ {
+ FILE_TIMESTAMP mtime;
+ int maybe_make;
+ int dontcare = 0;
- if (is_updating (d->file))
- {
- error (NILF, _("Circular %s <- %s dependency dropped."),
- file->name, d->file->name);
- /* We cannot free D here because our the caller will still have
- a reference to it when we were called recursively via
- check_dep below. */
- if (lastd == 0)
- file->deps = d->next;
- else
- lastd->next = d->next;
- d = d->next;
- continue;
- }
+ check_renamed (d->file);
- d->file->parent = file;
- maybe_make = must_make;
+ mtime = file_mtime (d->file);
+ check_renamed (d->file);
- /* Inherit dontcare flag from our parent. */
- if (rebuilding_makefiles)
- {
- dontcare = d->file->dontcare;
- d->file->dontcare = file->dontcare;
- }
+ if (is_updating (d->file))
+ {
+ error (NILF, _("Circular %s <- %s dependency dropped."),
+ file->name, d->file->name);
+ /* We cannot free D here because our the caller will still have
+ a reference to it when we were called recursively via
+ check_dep below. */
+ if (lastd == 0)
+ file->deps = d->next;
+ else
+ lastd->next = d->next;
+ d = d->next;
+ continue;
+ }
+ d->file->parent = file;
+ maybe_make = must_make;
- dep_status |= check_dep (d->file, depth, this_mtime, &maybe_make);
+ /* Inherit dontcare flag from our parent. */
+ if (rebuilding_makefiles)
+ {
+ dontcare = d->file->dontcare;
+ d->file->dontcare = file->dontcare;
+ }
- /* Restore original dontcare flag. */
- if (rebuilding_makefiles)
- d->file->dontcare = dontcare;
+ dep_status |= check_dep (d->file, depth, this_mtime, &maybe_make);
- if (! d->ignore_mtime)
- must_make = maybe_make;
+ /* Restore original dontcare flag. */
+ if (rebuilding_makefiles)
+ d->file->dontcare = dontcare;
- check_renamed (d->file);
+ if (! d->ignore_mtime)
+ must_make = maybe_make;
- {
- register struct file *f = d->file;
- if (f->double_colon)
- f = f->double_colon;
- do
- {
- running |= (f->command_state == cs_running
- || f->command_state == cs_deps_running);
- f = f->prev;
- }
- while (f != 0);
- }
+ check_renamed (d->file);
+
+ {
+ register struct file *f = d->file;
+ if (f->double_colon)
+ f = f->double_colon;
+ do
+ {
+ running |= (f->command_state == cs_running
+ || f->command_state == cs_deps_running);
+ f = f->prev;
+ }
+ while (f != 0);
+ }
- if (dep_status != 0 && !keep_going_flag)
- break;
+ if (dep_status != 0 && !keep_going_flag)
+ break;
- if (!running)
- /* The prereq is considered changed if the timestamp has changed while
- it was built, OR it doesn't exist. */
- d->changed = ((file_mtime (d->file) != mtime)
- || (mtime == NONEXISTENT_MTIME));
+ if (!running)
+ /* The prereq is considered changed if the timestamp has changed while
+ it was built, OR it doesn't exist. */
+ d->changed = ((file_mtime (d->file) != mtime)
+ || (mtime == NONEXISTENT_MTIME));
- lastd = d;
- d = d->next;
+ lastd = d;
+ d = d->next;
+ }
}
/* Now we know whether this target needs updating.
| [
"993273596@qq.com"
] | 993273596@qq.com |
6cadf63c580304aeab4267a041aad06bd85adad5 | fbfde6a2ef2b4683e892fa170d38d099cb0f7106 | /4.CPP | ffba097e845a29468e8a3d612db7782e6a6f4660 | [] | no_license | niks3497/Data-structures-in-C | 739fdce6aeef33386ff0b7639310818a3a24c367 | 1f80b2e77451ab1632db33399c578939f3023026 | refs/heads/master | 2021-05-03T06:42:24.658428 | 2018-02-07T10:35:37 | 2018-02-07T10:35:37 | 120,600,541 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | #include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node* next;
};
void addatend(struct node** q,int num);
void display(struct node* q);
void deletion(struct node** q);
void main()
{
struct node* p=NULL;
clrscr();
addatend(&p,1);
addatend(&p,2);
addatend(&p,3);
addatend(&p,4);
addatend(&p,5);
display(p);
deletion(&p);
display(p);
getch();
}
void addatend(struct node** q,int num)
{
struct node *temp, *s;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=num;
if((*q)==NULL)
(*q)=temp;
else
{
for(s=*q;s->next!=NULL;s=s->next)
s->next=temp;}
temp->next=NULL;
}
void display(struct node* p)
{
int i;
for(i=1;p!=NULL;p=p->next,i++)
printf("%d ",p->data);
}
void deletion(struct node** q)
{
struct node* s;
s=*q;
(*q)=(*q)->next;
free(s);
}
/*
1 2 3 4 5
2 3 4 5
*/
| [
"nik0108@icloud.com"
] | nik0108@icloud.com |
a983df4baf909bf6521c035fecae4352665080a0 | bbae77457dba713cd8e0e01d71f4cbe66634dad4 | /ext/one_signal/capn_proto/malloc_message_builder.cc | 9d236d042f4680b9a45d2c153243ecd76fa587b1 | [
"MIT"
] | permissive | OneSignal/capnp-ruby | b0603417c70d830e98534e6ed4b87a793f164fd3 | 7e4cc69d7c8f51faf433aea8069d10dd52ea3923 | refs/heads/main | 2022-08-09T22:27:11.750010 | 2022-07-28T10:40:34 | 2022-07-28T10:40:34 | 124,286,070 | 2 | 1 | MIT | 2022-07-28T10:40:34 | 2018-03-07T19:45:46 | C++ | UTF-8 | C++ | false | false | 1,515 | cc | #include "ruby_capn_proto.h"
#include "malloc_message_builder.h"
#include "message_builder.h"
#include "struct_schema.h"
#include "dynamic_struct_builder.h"
#include "class_builder.h"
namespace ruby_capn_proto {
using WrappedType = capnp::MallocMessageBuilder;
VALUE MallocMessageBuilder::Class;
void MallocMessageBuilder::Init() {
ClassBuilder("MallocMessageBuilder", MessageBuilder::Class).
defineAlloc(&alloc).
defineMethod("initialize", &initialize).
defineMethod("init_root", &init_root).
// defineMethod("get_root", &get_root).
store(&Class);
}
VALUE MallocMessageBuilder::alloc(VALUE klass) {
return Data_Wrap_Struct(klass, NULL, free, ruby_xmalloc(sizeof(WrappedType)));
}
VALUE MallocMessageBuilder::initialize(VALUE self) {
WrappedType* p = unwrap(self);
new (p) WrappedType();
return Qnil;
}
void MallocMessageBuilder::free(WrappedType* p) {
p->~MallocMessageBuilder();
ruby_xfree(p);
}
WrappedType* MallocMessageBuilder::unwrap(VALUE self) {
WrappedType* p;
Data_Get_Struct(self, WrappedType, p);
return p;
}
VALUE MallocMessageBuilder::init_root(VALUE self, VALUE rb_schema) {
if (rb_respond_to(rb_schema, rb_intern("schema"))) {
rb_schema = rb_funcall(rb_schema, rb_intern("schema"), 0);
}
auto schema = *StructSchema::unwrap(rb_schema);
auto builder = unwrap(self)->initRoot<capnp::DynamicStruct>(schema);
return DynamicStructBuilder::create(builder, self, true);
}
}
| [
"charles.c.strahan@gmail.com"
] | charles.c.strahan@gmail.com |
d5a982e9b6eda3135d11379b1aab6c58c5d53619 | 6fd072757f7f9ceeff1832513b7393bcef91d4dc | /framework/tarscpp/unittest/testcode/source/testcase/StressTest.cpp | 9189e3463dd63f59a42aae9d6efc8e09c3d4b278 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | hfcrwx/Tars-v2.4.20 | 2d6a5f84df434c293cef301d978d38f691d9227f | b0782b3fad556582470cddaa4416874126bd105c | refs/heads/master | 2023-07-16T06:02:01.278347 | 2021-08-28T16:08:40 | 2021-08-28T16:08:40 | 400,194,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,653 | cpp | /**
* Tencent is pleased to support the open source community by making Tars
* available.
*
* Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the
* License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
#include <iostream>
#include "TarsServantName.h"
#include "TarsTest/UnitTest/AServant.h"
#include "gtest/gtest.h"
#include "servant/Application.h"
#include "servant/Communicator.h"
#include "util/tc_thread_pool.h"
using namespace std;
using namespace TarsTest;
using namespace tars;
/****************************************************
压力测试用例
利用TC_ThreadPool启用多个线程进行压力测试
****************************************************/
/**
* @brief 请求执行方法
* @param pprx
* @param excut_num
* @param size
*/
void dohandle(AServantPrx pprx, int excut_num, int size) {
string s(size, 'a');
for (int i = 0; i < excut_num; i++) {
try {
string ret = "";
pprx->tars_set_timeout(15000)->saySomething(s, ret);
} catch (TC_Exception &e) {
cout << "pthread id: " << std::this_thread::get_id() << "id: " << i
<< "exception: " << e.what() << endl;
} catch (...) {
cout << "pthread id: " << std::this_thread::get_id() << "id: " << i
<< "unknown exception." << endl;
}
}
}
TEST(StressTest, stress_test_when_call_multi_times) {
int64_t tBegin = TC_TimeProvider::getInstance()->getNowMs();
CommunicatorPtr _comm = Application::getCommunicator();
AServantPrx prx = _comm->stringToProxy<AServantPrx>(ASERVANT_ENDPOINT);
try {
tars::Int32 threads = 10;
TC_ThreadPool tp;
tp.init(threads);
tp.start();
TLOGDEBUG("init tp succ" << endl);
int times = 10;
int size = 100;
for (int i = 0; i < threads; i++) {
auto fw = std::bind(&dohandle, prx, times, size);
tp.exec(fw);
TLOGDEBUG("********************" << endl);
}
tp.waitForAllDone();
} catch (exception &e) {
cout << e.what() << endl;
} catch (...) {
}
TLOGDEBUG("StressTest time cost: "
<< " | " << TC_TimeProvider::getInstance()->getNowMs() - tBegin
<< "(ms)" << endl);
}
| [
"hfcrwx@163.com"
] | hfcrwx@163.com |
63a9008ca9e896a9e8793b4e1a6c9ae174f8f2d0 | 8896488231f2b3699ccc59fa5111129bfa87d184 | /xygine/src/physics/PhysicsCollisionCircleShape.cpp | b8402b65487caba7012197357aa3d0f127c0f69b | [
"LicenseRef-scancode-warranty-disclaimer",
"Zlib"
] | permissive | brucelevis/xygine | b42c677629a3b4827781fa4a1a981114ccdc8bfe | fa88196456741fff9e4d8403861c6ad30fa2ee00 | refs/heads/master | 2020-12-02T17:48:04.584058 | 2017-04-15T12:01:50 | 2017-04-15T12:01:50 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,987 | cpp | /*********************************************************************
© Matt Marchant 2014 - 2017
http://trederia.blogspot.com
xygine - Zlib license.
This software is provided 'as-is', without any express or
implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
*********************************************************************/
#include <xygine/physics/CollisionCircleShape.hpp>
#include <xygine/physics/World.hpp>
#include <cstring>
using namespace xy;
using namespace xy::Physics;
CollisionCircleShape::CollisionCircleShape(float radius)
{
m_circleShape.m_radius = World::sfToBoxFloat(radius);
setShape(m_circleShape);
}
CollisionCircleShape::CollisionCircleShape(const CollisionCircleShape& other)
: CollisionShape(other)
{
m_circleShape = other.m_circleShape;
setShape(m_circleShape);
}
//public
void CollisionCircleShape::setPosition(const sf::Vector2f& position)
{
m_circleShape.m_p = World::sfToBoxVec(position);
}
sf::Vector2f CollisionCircleShape::getPosition() const
{
return World::boxToSfVec(m_circleShape.m_p);
}
void CollisionCircleShape::setRadius(float radius)
{
m_circleShape.m_radius = World::sfToBoxFloat(radius);
}
float CollisionCircleShape::getRadius() const
{
return World::boxToSfFloat(m_circleShape.m_radius);
}
| [
"matty_styles@hotmail.com"
] | matty_styles@hotmail.com |
df489a91bb84fd27b59ee2a01f49b85e1c467a11 | 62e581f41cd19dbae209219cf69992332380d2ab | /Unity course/Cube modding/Library/Bee/artifacts/WebGL/il2cpp/release_WebGL_wasm/96cfl8wj1y0g2.lump.cpp | 6e80db3a3a9ef99fc250b08a0a5e19b0c01414c8 | [] | no_license | Robinthatdoesnotsuck/Unity | c6eca9767ceb347c89a262a7351eea061af26ec0 | 6c48e0c43dfa3da0eca19b5a7b398f12df3e58c3 | refs/heads/main | 2023-07-08T02:07:03.309688 | 2023-07-02T19:57:29 | 2023-07-02T19:57:29 | 332,323,138 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,493 | cpp | //Generated lump file. generated by Bee.NativeProgramSupport.Lumping
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/COM.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/Cryptography.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/Debug.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/Directory.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/DllMain.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/FileSystemWatcher.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/Initialize.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/MemoryMappedFile.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/NativeMethods.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/Process.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/SystemCertificates.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/Thread.cpp"
#include "C:/Program Files/Unity/Hub/Editor/2022.3.2f1/Editor/Data/il2cpp/libil2cpp/os/Win32/WindowsHelpers.cpp"
| [
"iram24y@gmail.com"
] | iram24y@gmail.com |
9aea7299893a109569a0d83acceaa317d364f65b | ac5ba22660c9eb6d5797a289a2ce18295867cc73 | /RenderWindow/stdafx.h | ea60bdb85fba9c1f64fcf19b94b6252d52888210 | [] | no_license | myronyliu/Inverse-Kinematics | c60f2c6f143d357adcd61a070e9f1ab587f86506 | fc8019ba6ae5ea1f00da72f01e58c3f74cc0eea6 | refs/heads/master | 2021-05-29T17:05:09.425092 | 2015-08-01T00:23:39 | 2015-08-01T00:23:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#ifdef __WIN32__
#include <Windows.h>
#endif
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>
#include <tuple>
#include <unordered_map>
#include <string>
#include <algorithm>
#include <functional>
#include <map>
#include <set>
#include <list>
#include <queue>
//#define _USE_MATH_DEFINES
//#include <cmath>
#define M_PI 3.1415926535897932384626433832795f
#include <GL/glew.h>
#include <GL/glut.h>
#include <glm/glm.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <armadillo>
static GLfloat red[] = { 1, 0, 0, 1 };
static GLfloat green[] = { 0, 1, 0, 1 };
static GLfloat blue[] = { 0, 0, 1, 1 };
static GLfloat white[] = { 1, 1, 1, 1 }; | [
"myronyliu@gmail.com"
] | myronyliu@gmail.com |
52a65596ad032b9ffd04316957ead49015705921 | 5f2fc8048cbdaca72a3bc682015e791e4ac63f01 | /SFND_Unscented_Kalman_Filter/src/ukf.h | 93436cb08428b19d9c263a16e9b3dab94683f165 | [] | no_license | songshan0321/SFND | ded1f06590eebb102c51d6d7c96f19aa226f121d | 4e56176c6ae46613c885224cf0a060717d1f3f02 | refs/heads/master | 2022-12-05T05:28:21.616206 | 2020-08-29T18:00:35 | 2020-08-29T18:00:35 | 277,309,956 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,574 | h | #ifndef UKF_H
#define UKF_H
#include <iostream>
#include "Eigen/Dense"
#include "measurement_package.h"
class UKF {
public:
/**
* Constructor
*/
UKF();
/**
* Destructor
*/
virtual ~UKF();
/**
* ProcessMeasurement
* @param meas_package The latest measurement data of either radar or laser
*/
void ProcessMeasurement(MeasurementPackage meas_package);
/**
* Prediction Predicts sigma points, the state, and the state covariance
* matrix
* @param delta_t Time between k and k+1 in s
*/
void Prediction(double delta_t);
/**
* Updates the state and the state covariance matrix using a laser measurement
* @param meas_package The measurement at k+1
*/
void UpdateLidar(MeasurementPackage meas_package);
/**
* Updates the state and the state covariance matrix using a radar measurement
* @param meas_package The measurement at k+1
*/
void UpdateRadar(MeasurementPackage meas_package);
// initially set to false, set to true in first call of ProcessMeasurement
bool is_initialized_;
// if this is false, laser measurements will be ignored (except for init)
bool use_laser_;
// if this is false, radar measurements will be ignored (except for init)
bool use_radar_;
// state vector: [pos1 pos2 vel_abs yaw_angle yaw_rate] in SI units and rad
Eigen::VectorXd x_;
// state covariance matrix
Eigen::MatrixXd P_;
// predicted sigma points matrix
Eigen::MatrixXd Xsig_pred_;
// time when the state is true, in us
long long time_us_;
// Process noise standard deviation longitudinal acceleration in m/s^2
double std_a_;
// Process noise standard deviation yaw acceleration in rad/s^2
double std_yawdd_;
// Laser measurement noise standard deviation position1 in m
double std_laspx_;
// Laser measurement noise standard deviation position2 in m
double std_laspy_;
// Radar measurement noise standard deviation radius in m
double std_radr_;
// Radar measurement noise standard deviation angle in rad
double std_radphi_;
// Radar measurement noise standard deviation radius change in m/s
double std_radrd_ ;
// Weights of sigma points
Eigen::VectorXd weights_;
// State dimension
int n_x_;
// Augmented state dimension
int n_aug_;
// Sigma point spreading parameter
double lambda_;
// NIS for laser
double NIS_laser_;
// NIS for radar
double NIS_radar_;
// counters for NIS calculation
int radar_count_;
int radar_over_;
int laser_count_;
int laser_over_;
int step_count_;
};
#endif // UKF_H | [
"songshan_you@hotmail.com"
] | songshan_you@hotmail.com |
d1f52f9d78df3ba88462152977d602e5b6d4d967 | ad8271700e52ec93bc62a6fa3ee52ef080e320f2 | /CatalystRichPresence/CatalystSDK/CompositeMeshAsset.h | 7e4cfbc0b20c8a80b5fc9b0e472be73dcbb07aa3 | [] | no_license | RubberDuckShobe/CatalystRPC | 6b0cd4482d514a8be3b992b55ec143273b3ada7b | 92d0e2723e600d03c33f9f027c3980d0f087c6bf | refs/heads/master | 2022-07-29T20:50:50.640653 | 2021-03-25T06:21:35 | 2021-03-25T06:21:35 | 351,097,185 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | h | //
// Generated with FrostbiteGen by Chod
// File: SDK\CompositeMeshAsset.h
// Created: Wed Mar 10 19:07:36 2021
//
#ifndef FBGEN_CompositeMeshAsset_H
#define FBGEN_CompositeMeshAsset_H
#include "MeshAsset.h"
class CompositeMeshAsset :
public MeshAsset // size = 0x78
{
public:
static void* GetTypeInfo()
{
return (void*)0x0000000142834370;
}
}; // size = 0x78
#endif // FBGEN_CompositeMeshAsset_H
| [
"dog@dog.dog"
] | dog@dog.dog |
45f94e01c1dc92ee039af0f20234506082b94262 | 053309314b081dcb3fca08fc5ea15e6e8596141d | /day8/source/xtbl/end.cpp | 387f6d8c080a27801a6e413be1d4c5a26e9d3dac | [] | no_license | cppascalinux/jinanjixun | a6283e1bbdc4cac938131e8061a8b5290f6bb1dc | 555a95c7baf940c38236ac559f0a2c11a34edd0c | refs/heads/master | 2020-05-29T14:46:31.982813 | 2019-06-14T07:14:19 | 2019-06-14T07:14:19 | 189,192,981 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,277 | cpp | #include<cmath>
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int INF=1000000007;
int n;
int f[2][1010][9][2][3][2],h[1010][3];
int a[10],g[10][4],b[10];
char aa[10101];
struct Node
{
int a[130][130];
int h,l;
}A,F;
Node mul(Node x,Node y)
{
Node z;
int i,j,k;
for(i=0;i<=x.h;i++)
for(j=0;j<=y.l;j++)
{
z.a[i][j]=0;
for(k=0;k<=x.l;k++)
z.a[i][j]=(z.a[i][j]+(long long)x.a[i][k]*y.a[k][j])%INF;
}
z.h=x.h,z.l=y.l;
return z;
}
Node ksm(Node a,Node f,int x)
{
while(x>0)
{
if(x%2==1)
a=mul(a,f);
x/=2;
f=mul(f,f);
}
return a;
}
void add(int &x,int y)
{
x+=y;
if(x>=INF)
x-=INF;
}
int solve(int x,int y)
{
int l,i,tmp;
for(l=1;l<n;l++)
b[l]=!!((1<<l-1)&x);
tmp=y;
for(l=1;l<n;l++)
{
a[l]=tmp%3;
tmp/=3;
}
tmp=0;
for(i=1;i<n;i++)
{
// printf("%d %d %d()\n",i,a[i],b[i]);
if(b[i]==0)
{
if(a[i]==2)
return -1;
else
tmp+=(1<<i-1)*a[i];
}
else
tmp+=(1<<i-1)*b[i];
}
return tmp;
}
int calc(int x,int y)
{
if(!y) return x;
return x+(1<<n-1);
}
int main()
{
int K,len,all,i,j,k,l,x,y,nj,nx,tmp,X,Y,ans;
freopen("end.in","r",stdin);
freopen("end.out","w",stdout);
scanf("%d%d",&n,&K);
scanf("%s",aa+1);
len=strlen(aa+1);
all=1;
for(i=1;i<n;i++)
{
for(j=1;j<=2;j++)
g[i][j]=all*j;
all*=3;
}
// cerr<<all<<endl;
// printf("%d %d\n",g[2][2]);
f[0][0][n][0][1][0]=1;
for(i=1;i<=len;i++)
{
// if(i%1000==0)
// cerr<<i<<endl;
memset(f[i&1],0,sizeof(f[i&1]));
for(j=0;j<all;j++)
{
for(l=0;l<=2;l++)
f[i&1][j][1][0][l][0]=f[i&1][j][1][1][l][1]=(f[i-1&1][j][n][0][l][1]+f[i-1&1][j][n][0][l][0])%INF;
}
for(k=1;k<n;k++)
{
for(j=0;j<all;j++)
{
tmp=j;
for(l=1;l<n;l++)
{
a[l]=tmp%3;
tmp/=3;
}
for(l=0;l<=1;l++)
{
if(k==n-1)
{
for(y=0;y<=1;y++)
{
if(y==0)
nj=j;
else if(a[k]==0)
nj=j-g[k][a[k]]+g[k][2];
add(f[i&1][nj][k+1][l][0][0],f[i&1][j][k][l][0][y]);
if(aa[i]=='1')
nx=0;
else
nx=1;
add(f[i&1][nj][k+1][l][nx][0],f[i&1][j][k][l][1][y]);
add(f[i&1][nj][k+1][l][2][0],f[i&1][j][k][l][2][y]);
if(y==1)
nj=j;
else if(a[k]==0)
nj=j-g[k][a[k]]+g[k][1];
add(f[i&1][nj][k+1][l^1][0][1],f[i&1][j][k][l][0][y]);
if(aa[i]=='1')
add(f[i&1][nj][k+1][l^1][1][1],f[i&1][j][k][l][1][y]);
else
add(f[i&1][nj][k+1][l^1][2][1],f[i&1][j][k][l][1][y]);
add(f[i&1][nj][k+1][l^1][2][1],f[i&1][j][k][l][2][y]);
}
}
else
{
for(x=0;x<=2;x++)
{
for(y=0;y<=1;y++)
{
// if(f[i&1][j][k][l][x][y]!=0)
// {
if(y==0)
nj=j;
else if(a[k]==0)
nj=j-g[k][a[k]]+g[k][2];
add(f[i&1][nj][k+1][l][x][0],f[i&1][j][k][l][x][y]);
if(y==1)
nj=j;
else if(a[k]==0)
nj=j-g[k][a[k]]+g[k][1];
add(f[i&1][nj][k+1][l^1][x][1],f[i&1][j][k][l][x][y]);
// }
}
}
}
}
}
}
}
// printf("%d|||\n",f[1][0][1][1][1][1]);
// printf("%d|||\n",f[len&1][8][2][1][0][0]);
// printf("%d\n",g[2][2]);
for(i=0;i<all;i++)
for(j=0;j<=2;j++)
{
for(k=0;k<=1;k++)
{
// printf("%d %d %d %d\n",i,j,k,f[len&1][i][n][0][j][k]);
add(h[i][j],f[len&1][i][n][0][j][k]);
}
// printf("%d %d %d\n",i,j,h[i][j]);
}
for(i=0;i<(1<<n-1);i++)
for(j=0;j<all;j++)
for(k=0;k<=1;k++)
for(l=0;l<=2;l++)
{
tmp=solve(i,j);
if(tmp==-1)
continue;
X=calc(i,k);
if(l<=1)
Y=calc(tmp,k&l);
else if(k==1)
continue;
else
Y=calc(tmp,0);
// printf("%d\n",solve(3,2));
// if(X==3&&Y==3&&h[j][l])
// printf("%d %d %d %d %d %d %d %d\n",i,j,tmp,X,Y,h[j][l],k,l);
add(F.a[X][Y],h[j][l]);
}
F.h=F.l=(1<<n-1)*2-1;
// cerr<<F.l;
A.a[1][1<<n-1]=1;
A.h=1,A.l=F.l;
// printf("%d %d\n",F.h,F.l);
// for(i=0;i<=F.h;i++)
// {
// for(j=0;j<=F.l;j++)
// printf("%d ",F.a[i][j]);
// puts("");
// }
A=ksm(A,F,K);
ans=0;
add(ans,A.a[1][(1<<n-1)-1]);
printf("%d\n",ans);
return 0;
}
| [
"cppascalinux@gmail.com"
] | cppascalinux@gmail.com |
a718e145c3eae6383f0d0e77f54fe1158250abb4 | af73773ca57ae3f09d6109c265942f6b3100925a | /PCNN+ONE/init.h | c6766c68de0aaf648b06bba55f619891a15ef317 | [] | no_license | xiashaxiaoxue/NRE | 745db36a49aa106fd8248eb6b58db4999e582346 | 9ab40cc1e053d04b21f8383d3cd4268bf61495e2 | refs/heads/master | 2021-01-13T10:28:48.978948 | 2016-09-20T05:12:28 | 2016-09-20T05:12:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,144 | h | #ifndef INIT_H
#define INIT_H
#include <cstring>
#include <cstdlib>
#include <vector>
#include <map>
#include <string>
#include <cstdio>
#include <float.h>
#include <cmath>
using namespace std;
string version = "";
int output_model = 0;
int num_threads = 10;
int trainTimes = 25;
float alpha = 0.02;
float reduce = 0.98;
int tt,tt1;
int dimensionC = 230;//1000;
int dimensionWPE = 5;//25;
int window = 3;
int limit = 30;
float marginPositive = 2.5;
float marginNegative = 0.5;
float margin = 2;
float Belt = 0.001;
float *matrixB1, *matrixRelation, *matrixW1, *matrixRelationDao, *matrixRelationPr, *matrixRelationPrDao;
float *matrixB1_egs, *matrixRelation_egs, *matrixW1_egs, *matrixRelationPr_egs;
float *matrixB1_exs, *matrixRelation_exs, *matrixW1_exs, *matrixRelationPr_exs;
float *wordVecDao,*wordVec_egs,*wordVec_exs;
float *positionVecE1, *positionVecE2, *matrixW1PositionE1, *matrixW1PositionE2;
float *positionVecE1_egs, *positionVecE2_egs, *matrixW1PositionE1_egs, *matrixW1PositionE2_egs, *positionVecE1_exs, *positionVecE2_exs, *matrixW1PositionE1_exs, *matrixW1PositionE2_exs;
float *matrixW1PositionE1Dao;
float *matrixW1PositionE2Dao;
float *positionVecDaoE1;
float *positionVecDaoE2;
float *matrixW1Dao;
float *matrixB1Dao;
double mx = 0;
int batch = 16;
int npoch;
int len;
float rate = 1;
FILE *logg;
float *wordVec;
int wordTotal, dimension, relationTotal;
int PositionMinE1, PositionMaxE1, PositionTotalE1,PositionMinE2, PositionMaxE2, PositionTotalE2;
map<string,int> wordMapping;
vector<string> wordList;
map<string,int> relationMapping;
vector<int *> trainLists, trainPositionE1, trainPositionE2;
vector<int> trainLength;
vector<int> headList, tailList, relationList;
vector<int *> testtrainLists, testPositionE1, testPositionE2;
vector<int> testtrainLength;
vector<int> testheadList, testtailList, testrelationList;
vector<std::string> nam;
map<string,vector<int> > bags_train, bags_test;
void init() {
FILE *f = fopen("../data/vec.bin", "rb");
fscanf(f, "%d", &wordTotal);
fscanf(f, "%d", &dimension);
cout<<"wordTotal=\t"<<wordTotal<<endl;
cout<<"Word dimension=\t"<<dimension<<endl;
PositionMinE1 = 0;
PositionMaxE1 = 0;
PositionMinE2 = 0;
PositionMaxE2 = 0;
wordVec = (float *)malloc((wordTotal+1) * dimension * sizeof(float));
wordList.resize(wordTotal+1);
wordList[0] = "UNK";
for (int b = 1; b <= wordTotal; b++) {
string name = "";
while (1) {
char ch = fgetc(f);
if (feof(f) || ch == ' ') break;
if (ch != '\n') name = name + ch;
}
int last = b * dimension;
float smp = 0;
for (int a = 0; a < dimension; a++) {
fread(&wordVec[a + last], sizeof(float), 1, f);
smp += wordVec[a + last]*wordVec[a + last];
}
smp = sqrt(smp);
for (int a = 0; a< dimension; a++)
wordVec[a+last] = wordVec[a+last] / smp;
wordMapping[name] = b;
wordList[b] = name;
}
wordTotal+=1;
fclose(f);
char buffer[1000];
f = fopen("../data/RE/relation2id.txt", "r");
while (fscanf(f,"%s",buffer)==1) {
int id;
fscanf(f,"%d",&id);
relationMapping[(string)(buffer)] = id;
relationTotal++;
nam.push_back((std::string)(buffer));
}
fclose(f);
cout<<"relationTotal:\t"<<relationTotal<<endl;
f = fopen("../data/RE/train.txt", "r");
while (fscanf(f,"%s",buffer)==1) {
string e1 = buffer;
fscanf(f,"%s",buffer);
string e2 = buffer;
fscanf(f,"%s",buffer);
string head_s = (string)(buffer);
int head = wordMapping[(string)(buffer)];
fscanf(f,"%s",buffer);
int tail = wordMapping[(string)(buffer)];
string tail_s = (string)(buffer);
fscanf(f,"%s",buffer);
bags_train[e1+"\t"+e2+"\t"+(string)(buffer)].push_back(headList.size());
int num = relationMapping[(string)(buffer)];
int len = 0, lefnum = 0, rignum = 0;
std::vector<int> tmpp;
while (fscanf(f,"%s", buffer)==1) {
std::string con = buffer;
if (con=="###END###") break;
int gg = wordMapping[con];
if (con == head_s) lefnum = len;
if (con == tail_s) rignum = len;
len++;
tmpp.push_back(gg);
}
headList.push_back(head);
tailList.push_back(tail);
relationList.push_back(num);
trainLength.push_back(len);
int *con=(int *)calloc(len,sizeof(int));
int *conl=(int *)calloc(len,sizeof(int));
int *conr=(int *)calloc(len,sizeof(int));
for (int i = 0; i < len; i++) {
con[i] = tmpp[i];
conl[i] = lefnum - i;
conr[i] = rignum - i;
if (conl[i] >= limit) conl[i] = limit;
if (conr[i] >= limit) conr[i] = limit;
if (conl[i] <= -limit) conl[i] = -limit;
if (conr[i] <= -limit) conr[i] = -limit;
if (conl[i] > PositionMaxE1) PositionMaxE1 = conl[i];
if (conr[i] > PositionMaxE2) PositionMaxE2 = conr[i];
if (conl[i] < PositionMinE1) PositionMinE1 = conl[i];
if (conr[i] < PositionMinE2) PositionMinE2 = conr[i];
}
trainLists.push_back(con);
trainPositionE1.push_back(conl);
trainPositionE2.push_back(conr);
}
fclose(f);
f = fopen("../data/RE/test.txt", "r");
while (fscanf(f,"%s",buffer)==1) {
string e1 = buffer;
fscanf(f,"%s",buffer);
string e2 = buffer;
bags_test[e1+"\t"+e2].push_back(testheadList.size());
fscanf(f,"%s",buffer);
string head_s = (string)(buffer);
int head = wordMapping[(string)(buffer)];
fscanf(f,"%s",buffer);
string tail_s = (string)(buffer);
int tail = wordMapping[(string)(buffer)];
fscanf(f,"%s",buffer);
int num = relationMapping[(string)(buffer)];
int len = 0 , lefnum = 0, rignum = 0;
std::vector<int> tmpp;
while (fscanf(f,"%s", buffer)==1) {
std::string con = buffer;
if (con=="###END###") break;
int gg = wordMapping[con];
if (head_s == con) lefnum = len;
if (tail_s == con) rignum = len;
len++;
tmpp.push_back(gg);
}
testheadList.push_back(head);
testtailList.push_back(tail);
testrelationList.push_back(num);
testtrainLength.push_back(len);
int *con=(int *)calloc(len,sizeof(int));
int *conl=(int *)calloc(len,sizeof(int));
int *conr=(int *)calloc(len,sizeof(int));
for (int i = 0; i < len; i++) {
con[i] = tmpp[i];
conl[i] = lefnum - i;
conr[i] = rignum - i;
if (conl[i] >= limit) conl[i] = limit;
if (conr[i] >= limit) conr[i] = limit;
if (conl[i] <= -limit) conl[i] = -limit;
if (conr[i] <= -limit) conr[i] = -limit;
if (conl[i] > PositionMaxE1) PositionMaxE1 = conl[i];
if (conr[i] > PositionMaxE2) PositionMaxE2 = conr[i];
if (conl[i] < PositionMinE1) PositionMinE1 = conl[i];
if (conr[i] < PositionMinE2) PositionMinE2 = conr[i];
}
testtrainLists.push_back(con);
testPositionE1.push_back(conl);
testPositionE2.push_back(conr);
}
fclose(f);
cout<<PositionMinE1<<' '<<PositionMaxE1<<' '<<PositionMinE2<<' '<<PositionMaxE2<<endl;
for (int i = 0; i < trainPositionE1.size(); i++) {
int len = trainLength[i];
int *work1 = trainPositionE1[i];
for (int j = 0; j < len; j++)
work1[j] = work1[j] - PositionMinE1;
int *work2 = trainPositionE2[i];
for (int j = 0; j < len; j++)
work2[j] = work2[j] - PositionMinE2;
}
for (int i = 0; i < testPositionE1.size(); i++) {
int len = testtrainLength[i];
int *work1 = testPositionE1[i];
for (int j = 0; j < len; j++)
work1[j] = work1[j] - PositionMinE1;
int *work2 = testPositionE2[i];
for (int j = 0; j < len; j++)
work2[j] = work2[j] - PositionMinE2;
}
PositionTotalE1 = PositionMaxE1 - PositionMinE1 + 1;
PositionTotalE2 = PositionMaxE2 - PositionMinE2 + 1;
}
float CalcTanh(float con) {
if (con > 20) return 1.0;
if (con < -20) return -1.0;
float sinhx = exp(con) - exp(-con);
float coshx = exp(con) + exp(-con);
return sinhx / coshx;
}
float tanhDao(float con) {
float res = CalcTanh(con);
return 1 - res * res;
}
float sigmod(float con) {
if (con > 20) return 1.0;
if (con < -20) return 0.0;
con = exp(con);
return con / (1 + con);
}
int getRand(int l,int r) {
int len = r - l;
int res = rand()*rand() % len;
if (res < 0)
res+=len;
return res + l;
}
float getRandU(float l, float r) {
float len = r - l;
float res = (float)(rand()) / RAND_MAX;
return res * len + l;
}
void norm(float* a, int ll, int rr)
{
float tmp = 0;
for (int i=ll; i<rr; i++)
tmp+=a[i]*a[i];
if (tmp>1)
{
tmp = sqrt(tmp);
for (int i=ll; i<rr; i++)
a[i]/=tmp;
}
}
#endif
| [
"mrlyk423@gmail.com"
] | mrlyk423@gmail.com |
febff45b8ca405ad5a2c538b8ec5d0bbd39df7ce | 54f66275a407b849b1682db5ba3e3c347d7242a8 | /UvA/CJ2017QD.cpp | f39ecad67c98da01fef7afd9d2f959282971425f | [
"MIT"
] | permissive | fvannee/competitive-coding | b4f6aa30a162fb2813ba8671fa7a3abe79ae5543 | 92bc383c482b55f3e48a583cddc50d92474eb488 | refs/heads/master | 2021-01-20T17:50:34.300462 | 2017-05-10T18:28:14 | 2017-05-10T18:28:14 | 90,893,696 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,264 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <assert.h>
#include <boost/lexical_cast.hpp>
#define INF 1023123123
#define EPS 1e-11
#define LSOne(S) (S & (-S))
#define FORN(X,Y) for (int (X) = 0;(X) < (Y);++(X))
#define FORB(X,Y) for (int (X) = (Y);(X) >= 0;--(X))
#define REP(X,Y,Z) for (int (X) = (Y);(X) < (Z);++(X))
#define REPB(X,Y,Z) for (int (X) = (Y);(X) >= (Z);--(X))
#define SZ(Z) ((int)(Z).size())
#define ALL(W) (W).begin(), (W).end()
#define PB push_back
#define MP make_pair
#define A first
#define B second
#define FORIT(X,Y) for(typeof((Y).begin()) X = (Y).begin();X!=(Y).end();X++)
using namespace std;
typedef long long ll;
typedef double db;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
void print_case(int i)
{
cout << "Case #" << i + 1 << ": ";
}
void fill_ps(vector<vector<char>>& ps)
{
int r = 0;
for (int c = 0; c < ps.size(); c++)
{
if (ps[r][c] == '.')
{
ps[r][c] = '+';
}
}
r = ps.size() - 1;
for (int c = 1; c < ps.size() - 1; c++)
{
if (ps[r][c] == '.')
{
ps[r][c] = '+';
}
}
}
void fill_xs(vector<vector<char>>& xs)
{
int r = 0;
int fc = 0;
for (int c = 0; c < xs.size(); c++)
{
if (xs[r][c] == 'x')
{
fc = c;
break;
}
}
for (r = 0; r < xs.size(); r++)
{
if (xs[r][fc] == '.')
{
xs[r][fc] = 'x';
}
fc = (fc + 1) % xs.size();
}
}
bool can_place_x(vector<vector<char>>& xs, int r1, int c1)
{
bool valid = true;
FORN(c, xs.size())
{
if ((xs[r1][c] == 'o' || xs[r1][c] == 'x'))
{
valid = false;
}
}
FORN(r, xs.size())
{
if ((xs[r][c1] == 'o' || xs[r][c1] == 'x'))
{
valid = false;
}
}
return valid;
}
bool can_place_p(vector<vector<char>>& ps, int r1, int c1)
{
int lr = r1 - min(r1, c1);
int lc = c1 - min(r1, c1);
bool valid = true;
while (lr < ps.size() && lc < ps.size())
{
valid &= ps[lr][lc] != 'o' && ps[lr][lc] != '+';
lr++;
lc++;
}
int rr = r1 - min(r1, (int)ps.size() - c1 - 1);
int rc = c1 + min(r1, (int)ps.size() - c1 - 1);
while (rr < ps.size() && rc >= 0)
{
valid &= ps[rr][rc] != 'o' && ps[rr][rc] != '+';
rr++;
rc--;
}
return valid;
}
void fill_ps2(vector<vector<char>>& ps)
{
int r = 0;
for (int c = 0; c < ps.size(); c++)
{
if (ps[r][c] == '.' && can_place_p(ps, r, c))
{
ps[r][c] = '+';
}
}
r = ps.size() - 1;
for (int c = 0; c < ps.size(); c++)
{
if (ps[r][c] == '.' && can_place_p(ps, r, c))
{
ps[r][c] = '+';
}
}
int c = 0;
for (int r = 0; r < ps.size(); r++)
{
if (ps[r][c] == '.' && can_place_p(ps, r, c))
{
ps[r][c] = '+';
}
}
c = ps.size() - 1;
for (int r = 0; r < ps.size(); r++)
{
if (ps[r][c] == '.' && can_place_p(ps, r, c))
{
ps[r][c] = '+';
}
}
}
void fill_xs2(vector<vector<char>>& xs)
{
FORN(r, xs.size())
{
FORN(c, xs.size())
{
if (xs[r][c] == '.' && can_place_x(xs, r, c))
{
xs[r][c] = 'x';
}
}
}
}
vector<vector<char>> merge_diffs(vector<vector<char>>& ps, vector<vector<char>>& xs)
{
auto ret = vector<vector<char>>(ps.size(), vector<char>(ps.size(), '.'));
FORN(r, ps.size())
{
FORN(c, ps.size())
{
if (ps[r][c] == '+' && xs[r][c] == '.')
ret[r][c] = '+';
else if (ps[r][c] == '+' && xs[r][c] == 'x')
ret[r][c] = 'o';
else if (ps[r][c] == '.' && xs[r][c] == 'x')
ret[r][c] = 'x';
}
}
return ret;
}
bool validate(vector<vector<char>>& all)
{
bool valid = true;
FORN(r, all.size())
{
bool cross = false;
FORN(c, all.size())
{
if (cross && (all[r][c] == 'o' || all[r][c] == 'x'))
{
valid = false;
}
cross |= (all[r][c] == 'o' || all[r][c] == 'x');
}
}
FORN(c, all.size())
{
bool cross = false;
FORN(r, all.size())
{
if (cross && (all[r][c] == 'o' || all[r][c] == 'x'))
{
valid = false;
}
cross |= (all[r][c] == 'o' || all[r][c] == 'x');
}
}
return valid;
}
void print_diffs(vector<vector<char>>& old, vector<vector<char>>& new_)
{
int beauty = 0;
vector<string> out;
FORN(r, old.size())
{
FORN(c, old.size())
{
if (new_[r][c] == 'x')
beauty++;
if (new_[r][c] == '+')
beauty++;
if (new_[r][c] == 'o')
beauty += 2;
if (old[r][c] != new_[r][c])
{
out.push_back(boost::lexical_cast<string>(new_[r][c]) + " " + boost::lexical_cast<string>(r + 1) + " " + boost::lexical_cast<string>(c + 1));
}
}
}
cout << beauty << ' ' << out.size() << endl;
FORN(i, out.size())
{
cout << out[i] << endl;
}
}
int main()
{
int ntc;
cin >> ntc;
FORN(kk, ntc)
{
print_case(kk);
int n, m;
cin >> n >> m;
vector<vector<char>> xs(n, vector<char>(n, '.'));
vector<vector<char>> ps(n, vector<char>(n, '.'));
vector<vector<char>> all(n, vector<char>(n, '.'));
FORN(i, m)
{
char p;
int r, c;
cin >> p >> r >> c;
r--;
c--;
if (p == 'o')
{
xs[r][c] = 'x';
ps[r][c] = '+';
all[r][c] = p;
}
else if (p == 'x')
{
xs[r][c] = p;
all[r][c] = p;
}
else
{
ps[r][c] = '+';
all[r][c] = p;
}
}
fill_ps2(ps);
fill_xs2(xs);
auto res = merge_diffs(ps, xs);
print_diffs(all, res);
}
}
| [
"floris.vannee@gmail.com"
] | floris.vannee@gmail.com |
cf338225e1600cd14bac721d39f95385537fcaf2 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /cdn/src/v20180606/model/ListClsTopicDomainsRequest.cpp | 21924c5d3e48213a63fd949204dc4b1ef404609f | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 3,208 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cdn/v20180606/model/ListClsTopicDomainsRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Cdn::V20180606::Model;
using namespace std;
ListClsTopicDomainsRequest::ListClsTopicDomainsRequest() :
m_logsetIdHasBeenSet(false),
m_topicIdHasBeenSet(false),
m_channelHasBeenSet(false)
{
}
string ListClsTopicDomainsRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_logsetIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LogsetId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_logsetId.c_str(), allocator).Move(), allocator);
}
if (m_topicIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TopicId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_topicId.c_str(), allocator).Move(), allocator);
}
if (m_channelHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Channel";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_channel.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string ListClsTopicDomainsRequest::GetLogsetId() const
{
return m_logsetId;
}
void ListClsTopicDomainsRequest::SetLogsetId(const string& _logsetId)
{
m_logsetId = _logsetId;
m_logsetIdHasBeenSet = true;
}
bool ListClsTopicDomainsRequest::LogsetIdHasBeenSet() const
{
return m_logsetIdHasBeenSet;
}
string ListClsTopicDomainsRequest::GetTopicId() const
{
return m_topicId;
}
void ListClsTopicDomainsRequest::SetTopicId(const string& _topicId)
{
m_topicId = _topicId;
m_topicIdHasBeenSet = true;
}
bool ListClsTopicDomainsRequest::TopicIdHasBeenSet() const
{
return m_topicIdHasBeenSet;
}
string ListClsTopicDomainsRequest::GetChannel() const
{
return m_channel;
}
void ListClsTopicDomainsRequest::SetChannel(const string& _channel)
{
m_channel = _channel;
m_channelHasBeenSet = true;
}
bool ListClsTopicDomainsRequest::ChannelHasBeenSet() const
{
return m_channelHasBeenSet;
}
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
efe456a71bdfb340f16f822955c5391ba724b3ee | 137a843a0ff19d47dfa0419d7897b5079b990bdc | /test/helpers.cpp | b6c5bd9451fc9d4498c3ec45ce99fc68b6a9c00a | [
"Apache-2.0"
] | permissive | mniesluchow/cynara | 61a0f8ae0ee3c7da31ffd0b62eb1d92dd64049db | 4347dc3d030aa488ea7d9b7b245ea5d4ee0bbe14 | refs/heads/master | 2020-12-25T09:58:24.304612 | 2014-07-09T07:59:14 | 2014-07-09T08:01:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | cpp | /*
* Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @file helpers.cpp
* @author Aleksander Zdyb <a.zdyb@partner.samsung.com>
* @version 1.0
* @brief Helper functions for tests
*/
#include "helpers.h"
#include "types/PolicyKey.h"
namespace Cynara {
namespace Helpers {
PolicyKey generatePolicyKey(const PolicyKeyFeature::ValueType &sufix) {
auto createPKF = [&sufix](const PolicyKeyFeature::ValueType &value) -> PolicyKeyFeature {
return PolicyKeyFeature::create(value + sufix);
};
return PolicyKey(createPKF("c"), createPKF("u"), createPKF("p"));
}
PolicyBucketId generateBucketId(const PolicyBucketId &sufix) {
return "bucket" + sufix;
}
} // namespace Helpers
} // namespace Cynara
| [
"r.krypa@samsung.com"
] | r.krypa@samsung.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.