blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a18900ff60b49e9dc118fceaec8b133b3593b69b | d5b7ae5e5f6d7e379040514c10f1f2aa715348bd | /ProcessLib/ThermoMechanics/ThermoMechanicsProcess-impl.h | 25fc9223234b694adda3952887e932355f1f6486 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | mahg/ogs | fa27c04633d095fa551654779bfced6df925257a | 6409f0f4682c037ba8313cfc9af5925d4bc849e8 | refs/heads/master | 2021-08-15T15:29:43.977208 | 2017-11-17T21:47:43 | 2017-11-17T21:47:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,554 | h | /**
* \file
*
* \copyright
* Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#pragma once
#include <cassert>
#include "BaseLib/Functional.h"
#include "ProcessLib/SmallDeformation/CreateLocalAssemblers.h"
#include "ThermoMechanicsFEM.h"
namespace ProcessLib
{
namespace ThermoMechanics
{
template <int DisplacementDim>
ThermoMechanicsProcess<DisplacementDim>::ThermoMechanicsProcess(
MeshLib::Mesh& mesh,
std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler,
std::vector<std::unique_ptr<ParameterBase>> const& parameters,
unsigned const integration_order,
std::vector<std::reference_wrapper<ProcessVariable>>&& process_variables,
ThermoMechanicsProcessData<DisplacementDim>&& process_data,
SecondaryVariableCollection&& secondary_variables,
NumLib::NamedFunctionCaller&& named_function_caller)
: Process(mesh, std::move(jacobian_assembler), parameters,
integration_order, std::move(process_variables),
std::move(secondary_variables), std::move(named_function_caller)),
_process_data(std::move(process_data))
{
}
template <int DisplacementDim>
bool ThermoMechanicsProcess<DisplacementDim>::isLinear() const
{
return false;
}
template <int DisplacementDim>
void ThermoMechanicsProcess<DisplacementDim>::initializeConcreteProcess(
NumLib::LocalToGlobalIndexMap const& dof_table,
MeshLib::Mesh const& mesh,
unsigned const integration_order)
{
ProcessLib::SmallDeformation::createLocalAssemblers<
DisplacementDim, ThermoMechanicsLocalAssembler>(
mesh.getElements(), dof_table, _local_assemblers,
mesh.isAxiallySymmetric(), integration_order, _process_data);
// TODO move the two data members somewhere else.
// for extrapolation of secondary variables
std::vector<MeshLib::MeshSubsets> all_mesh_subsets_single_component;
all_mesh_subsets_single_component.emplace_back(
_mesh_subset_all_nodes.get());
_local_to_global_index_map_single_component.reset(
new NumLib::LocalToGlobalIndexMap(
std::move(all_mesh_subsets_single_component),
// by location order is needed for output
NumLib::ComponentOrder::BY_LOCATION));
Base::_secondary_variables.addSecondaryVariable(
"sigma_xx",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaXX));
Base::_secondary_variables.addSecondaryVariable(
"sigma_yy",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaYY));
Base::_secondary_variables.addSecondaryVariable(
"sigma_zz",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaZZ));
Base::_secondary_variables.addSecondaryVariable(
"sigma_xy",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaXY));
if (DisplacementDim == 3)
{
Base::_secondary_variables.addSecondaryVariable(
"sigma_xz",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaXZ));
Base::_secondary_variables.addSecondaryVariable(
"sigma_yz",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaYZ));
}
Base::_secondary_variables.addSecondaryVariable(
"epsilon_xx",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonXX));
Base::_secondary_variables.addSecondaryVariable(
"epsilon_yy",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonYY));
Base::_secondary_variables.addSecondaryVariable(
"epsilon_zz",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonZZ));
Base::_secondary_variables.addSecondaryVariable(
"epsilon_xy",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonXY));
if (DisplacementDim == 3)
{
Base::_secondary_variables.addSecondaryVariable(
"epsilon_yz",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonYZ));
Base::_secondary_variables.addSecondaryVariable(
"epsilon_xz",
makeExtrapolator(
1, getExtrapolator(), _local_assemblers,
&ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonXZ));
}
}
template <int DisplacementDim>
void ThermoMechanicsProcess<DisplacementDim>::assembleConcreteProcess(
const double t, GlobalVector const& x, GlobalMatrix& M, GlobalMatrix& K,
GlobalVector& b)
{
DBUG("Assemble ThermoMechanicsProcess.");
// Call global assembler for each local assembly item.
GlobalExecutor::executeMemberDereferenced(
_global_assembler, &VectorMatrixAssembler::assemble, _local_assemblers,
*_local_to_global_index_map, t, x, M, K, b, _coupling_term);
}
template <int DisplacementDim>
void ThermoMechanicsProcess<DisplacementDim>::
assembleWithJacobianConcreteProcess(const double t, GlobalVector const& x,
GlobalVector const& xdot,
const double dxdot_dx,
const double dx_dx, GlobalMatrix& M,
GlobalMatrix& K, GlobalVector& b,
GlobalMatrix& Jac)
{
DBUG("AssembleJacobian ThermoMechanicsProcess.");
// Call global assembler for each local assembly item.
GlobalExecutor::executeMemberDereferenced(
_global_assembler, &VectorMatrixAssembler::assembleWithJacobian,
_local_assemblers, *_local_to_global_index_map, t, x, xdot, dxdot_dx,
dx_dx, M, K, b, Jac, _coupling_term);
}
template <int DisplacementDim>
void ThermoMechanicsProcess<DisplacementDim>::preTimestepConcreteProcess(
GlobalVector const& x, double const t, double const dt)
{
DBUG("PreTimestep ThermoMechanicsProcess.");
_process_data.dt = dt;
_process_data.t = t;
GlobalExecutor::executeMemberOnDereferenced(
&ThermoMechanicsLocalAssemblerInterface::preTimestep, _local_assemblers,
*_local_to_global_index_map, x, t, dt);
}
template <int DisplacementDim>
void ThermoMechanicsProcess<DisplacementDim>::postTimestepConcreteProcess(
GlobalVector const& x)
{
DBUG("PostTimestep ThermoMechanicsProcess.");
GlobalExecutor::executeMemberOnDereferenced(
&ThermoMechanicsLocalAssemblerInterface::postTimestep,
_local_assemblers, *_local_to_global_index_map, x);
}
} // namespace ThermoMechanics
} // namespace ProcessLib
| [
"dmitri.naumov@ufz.de"
] | dmitri.naumov@ufz.de |
7387368f142152a7eb86cf2e026adda251929d8e | 11372f47584ed7154697ac3b139bf298cdc10675 | /CF练习/CF1238/A.cpp | c373d311b2a7cfb84572878c468adeb80b6cf25e | [] | no_license | strategist614/ACM-Code | b5d893103e4d2ea0134fbaeb0cbd18c0fec06d12 | d1e0f36dab47f649e2fade5e7ff23cfd0e8c8e56 | refs/heads/master | 2020-12-20T04:21:50.750182 | 2020-01-24T07:43:50 | 2020-01-24T07:45:08 | 235,958,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 260 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
long long x, y;
cin >> x >> y;
if (x - y > 1)
puts("YES");
else
puts("NO");
}
return 0;
} | [
"syf981002@gmail.com"
] | syf981002@gmail.com |
eba666c5e540ea9a66766b5743cbf574b5bd8cb1 | 8b7ccd22aa258b016e4317d222dce9eac0709f36 | /example-advanced-servo/src/Servo.h | d4f2d0a0c0d40b5f3d497ab449f1867f9026b5b4 | [
"BSD-2-Clause"
] | permissive | WatershedArts/ofxAdafruitPWMBonnet | c0145a77959f90d1ef9c7950c28734eb4e618341 | 5e6b827e34d207273b108c3e428e5e76b80fde27 | refs/heads/master | 2020-03-29T19:26:53.235730 | 2018-09-27T16:27:45 | 2018-09-27T16:27:45 | 150,263,686 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,744 | h | //
// Servo.h
//
// Created by David Haylock on 26/09/2018.
//
#include "ofMain.h"
#ifndef Servo_h
#define Servo_h
class Servo
{
public:
/**
Default Constructor
*/
//--------------------------------------------------------------
Servo()
{
}
/**
Deconstructor
*/
//--------------------------------------------------------------
~Servo() {}
/**
Init Constructor
*/
//--------------------------------------------------------------
Servo(u_int16_t ctrlAddress, u_int16_t pinNo, glm::vec2 pos, glm::vec2 size, float initAngle)
{
init(ctrlAddress, pinNo, pos, size, initAngle);
}
/**
Initialize
*/
//--------------------------------------------------------------
void init(u_int16_t ctrlAddress, u_int16_t pinNo, glm::vec2 pos, glm::vec2 size, float initAngle)
{
this->ctrlAddress = ctrlAddress;
this->pinNo = pinNo;
this->pos = pos;
this->size = size;
this->currentAngle = initAngle;
}
/**
Returns the Current Angle of the Servo
@return Servo Angle
*/
//--------------------------------------------------------------
int getCurrentAngle()
{
return currentAngle;
}
/**
Get the Connected Pin Number
@return pin no
*/
//--------------------------------------------------------------
u_int16_t getCtrlAddress()
{
return ctrlAddress;
}
/**
Get the Connected Pin Number
@return pin no
*/
//--------------------------------------------------------------
u_int16_t getPin()
{
return pinNo;
}
/**
Returns the Size of the Servo
@return size
*/
//--------------------------------------------------------------
glm::vec2 getSize()
{
return size;
}
/**
Returns the Position of the Servo
@return pos
*/
//--------------------------------------------------------------
glm::vec2 getPosition()
{
return pos;
}
/**
Set the New Angle
@param angle angle
*/
//--------------------------------------------------------------
void setAngle(float angle)
{
this->currentAngle = angle;
}
/**
Draw Servo
*/
//--------------------------------------------------------------
void drawServo()
{
ofPushMatrix();
{
ofTranslate(pos.x,pos.y);
ofPushStyle();
ofNoFill();
ofSetColor(255);
ofDrawRectangle(-(size.x/2),-(size.y/2),size.x,size.y);
ofPushMatrix();
ofTranslate(0,-(size.y/3));
{
ofPushMatrix();
{
ofTranslate(0,0);
ofRotateZDeg(currentAngle);
ofPushMatrix();
{
ofDrawCircle(0,0,(size.y/3));
ofDrawCircle(0,0,5);
ofDrawLine(0,0,0,-(size.y/3));
}
ofPopMatrix();
}
ofPopMatrix();
}
ofPopMatrix();
ofPopStyle();
}
ofPopMatrix();
ofSetColor(255,255,0);
stringstream ss;
ss << "Servo " << pinNo << endl;
ss << "CTRL " << ctrlAddress << endl;
ofDrawBitmapString(ss.str(),pos.x-(size.x/2)-7,pos.y+size.y/2+15);
}
private:
u_int16_t ctrlAddress;
u_int16_t pinNo;
glm::vec2 pos;
glm::vec2 size;
float currentAngle;
};
#endif /* Servo_h */
| [
"david.haylock@watershed.co.uk"
] | david.haylock@watershed.co.uk |
f1ae548e75bfdc9b7540b0924912a22c253c837b | 1c95ed635171fc5d65984da1b7792c7b18a5a0af | /Graph.h | 37c5e2ca2924dfa8dd3567fba42f9b4b08529554 | [] | no_license | DallinKooyman/DatalogProgram | 5f120b5a728d360c4becd7d59f9e61a062778a89 | 5ef03022518c252926ab6c314106d8979679d20d | refs/heads/master | 2022-11-05T16:37:57.093994 | 2020-06-13T03:35:35 | 2020-06-13T03:35:35 | 271,926,660 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 800 | h | #pragma once
#include "DatalogProgram.h"
#include "Relation.h"
class Graph
{
public:
Graph(vector<Rule> RuleList);
Graph(map<unsigned int, set<int>> EdgesToReverse);
string EdgesToString();
vector<int> dfsPostOrder(); //Return normal Post order, need to reverse before using dfsSCC
void dfsSCC(vector<int> reversePostOrder); //Depth First Search to get Strongly Connected Components
void dfs(int CurrNode); //Depth First Search on one node
bool HasLoop(int Node);
map<unsigned int, set<int>> GetEdges();
vector<bool> GetVisited();
vector<int> GetPostOrder();
vector<set<int>> GetSCCs();
private:
map<unsigned int, set<int>> GraphEdges;
vector<bool> RuleVisited;
vector<int> PostOrder;
vector<set<int>> SCCs; //Strongly connected commponents
};
| [
"noreply@github.com"
] | DallinKooyman.noreply@github.com |
dcec21da638b1dd7b38921c5d38e9b3f5daf6d1b | f5d3a2db357c4ce5f34bfdb0866c058182e30b72 | /src/imagemanip.cpp | 270aa3555d7990b3b2ab3c45ab02764bc6eacae4 | [] | no_license | JoaquimGuerra/fingerPrint | 40f56fd0d033aa745a33d21ad6fe1c7e02a2167c | 73264a2c2c3506dd13afdfd39e31b5f25013b9fa | refs/heads/master | 2021-01-18T16:21:45.383654 | 2016-02-08T22:37:14 | 2016-02-08T22:37:14 | 51,331,792 | 0 | 0 | null | 2016-02-08T22:25:55 | 2016-02-08T22:25:55 | null | GB18030 | C++ | false | false | 41,045 | cpp |
/*#############################################################################
* 文件名:imagemanip.cpp
* 功能: 实现了主要的图像处理操作
#############################################################################*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "imagemanip.h"
#ifndef min
#define min(a,b) (((a)<(b))?(a):(b))
#endif
/* 宏定义 */
#define PIJKL p[i+k + (j+l)*nSizeX]
/******************************************************************************
* 功能:图像缩放操作
* 参数:image 指纹图像
* size 缩放的图像块大小
* tolerance 消去直方图的边界
* 返回:错误编号
******************************************************************************/
FvsError_t ImageLocalStretch(FvsImage_t image, const FvsInt_t size,
const FvsInt_t tolerance) {
/* 定义一些变量 */
int nSizeX = ImageGetWidth(image) - size + 1;
int nSizeY = ImageGetHeight(image) - size + 1;
FvsInt_t i, j, t, l;
FvsInt_t sum, denom;
FvsByte_t a = 0;
FvsInt_t k = 0;
FvsByte_t b = 255;
int hist[256];
FvsByte_t* p = ImageGetBuffer(image);
if (p == NULL)
return FvsMemory;
for (j = 0; j < nSizeY; j += size) {
for (i = 0; i < nSizeX; i += size) {
/* 计算直方图 */
memset(hist, 0, 256 * sizeof(int));
for (l = 0; l < size; l++)
for (k = 0; k < size; k++)
hist[PIJKL]++;
/* 伸缩 */
for (k = 0, sum = 0; k < 256; k++) {
sum += hist[k];
a = (FvsByte_t)k;
if (sum > tolerance) break;
}
for (k = 255, sum = 0; k >= 0; k--) {
sum += hist[k];
b = (FvsByte_t)k;
if (sum > tolerance) break;
}
denom = (FvsInt_t)(b - a);
if (denom != 0) {
for (l = 0; l < size; l++) {
for (k = 0; k < size; k++) {
if (PIJKL < a) PIJKL = a;
if (PIJKL > b) PIJKL = b;
t = (FvsInt_t)((((PIJKL) - a) * 255) / denom);
PIJKL = (FvsByte_t)(t);
}
}
}
}
}
return FvsOK;
}
#define P(x,y) ((int32_t)p[(x)+(y)*pitch])
/******************************************************************************
** 估算脊线的方向
** 给定一个归一化的指纹图像,算法的主要步骤如下:
**
** 1 - 将G分成大小为 w x w - (15 x 15) 的块;
**
** 2 - 计算每个象素 (i,j)的梯度 dx(i,j) 和 dy(i,j) ,
** 根据计算的需求,梯度算子可以从简单的Sobel算子到复杂的Marr-Hildreth 算子。
**
** 3 - 估算优势方向(i,j), 使用如下的操作:
**
** i+w/2 j+w/2
** --- ---
** \ \
** Nx(i,j) = -- -- 2 dx(u,v) dy(u,v)
** / /
** --- ---
** u=i-w/2 v=j-w/2
**
** i+w/2 j+w/2
** --- ---
** \ \
** Ny(i,j) = -- -- dx(u,v) - dy(u,v)
** / /
** --- ---
** u=i-w/2 v=j-w/2
**
** 1 -1 / Nx(i,j) \
** Theta(i,j) = - tan | ------- |
** 2 \ Ny(i,j) /
**
** 这里,Theta(i,j)是局部脊线方向的最小方差估计,以像素 (i,j) 为中心。
** 从数学的角度看,它代表傅立叶频谱中直角占有时的方向。
**
** 4 - 由于有噪声,脊线的中断,细节点等等的存在,在输入图像中,对局部脊线
** 方向的估计并不总是正确的。由于局部脊线方向变化缓慢,所以可以用低通
** 滤波器来修正不正确的脊线方向。为了运用低通滤波器,方向图必须转换成
** 连续的矢量域,定义如下:
** Phi_x(i,j) = cos( 2 x theta(i,j) )
** Phi_y(i,j) = sin( 2 x theta(i,j) )
** 在矢量域,可以用如下的卷积低通滤波:
** Phi2_x(i,j) = (W @ Phi_x) (i,j)
** Phi2_y(i,j) = (W @ Phi_y) (i,j)
** W是一个二维的低通滤波器。
**
** 5 - 用如下公式计算 (i,j) 处的方向:
**
** 1 -1 / Phi2_y(i,j) \
** O(i,j) = - tan | ----------- |
** 2 \ Phi2_x(i,j) /
**
** 用这个算法可以得到相当平滑的方向图
**
*/
static FvsError_t FingerprintDirectionLowPass(FvsFloat_t* theta,
FvsFloat_t* out, FvsInt_t nFilterSize,
FvsInt_t w, FvsInt_t h) {
FvsError_t nRet = FvsOK;
FvsFloat_t* filter = NULL;
FvsFloat_t* phix = NULL;
FvsFloat_t* phiy = NULL;
FvsFloat_t* phi2x = NULL;
FvsFloat_t* phi2y = NULL;
FvsInt_t fsize = nFilterSize * 2 + 1;
size_t nbytes = (size_t)(w * h * sizeof(FvsFloat_t));
FvsFloat_t nx, ny;
FvsInt_t val;
FvsInt_t i, j, x, y;
filter = (FvsFloat_t*)malloc((size_t)fsize * fsize * sizeof(FvsFloat_t));
phix = (FvsFloat_t*)malloc(nbytes);
phiy = (FvsFloat_t*)malloc(nbytes);
phi2x = (FvsFloat_t*)malloc(nbytes);
phi2y = (FvsFloat_t*)malloc(nbytes);
if (filter == NULL || phi2x == NULL || phi2y == NULL || phix == NULL || phiy == NULL)
nRet = FvsMemory;
else {
/* 置 0 */
memset(filter, 0, (size_t)fsize * fsize * sizeof(FvsFloat_t));
memset(phix, 0, nbytes);
memset(phiy, 0, nbytes);
memset(phi2x, 0, nbytes);
memset(phi2y, 0, nbytes);
/* 步骤4 */
for (y = 0; y < h; y++)
for (x = 0; x < w; x++) {
val = x + y * w;
phix[val] = cos(theta[val]);
phiy[val] = sin(theta[val]);
}
/* 构造低通滤波器 */
nx = 0.0;
for (j = 0; j < fsize; j++)
for (i = 0; i < fsize; i++) {
filter[j * fsize + i] = 1.0;
nx += filter[j * fsize + i]; /* 系数和 */
}
if (nx > 1.0) {
for (j = 0; j < fsize; j++)
for (i = 0; i < fsize; i++)
/* 归一化结果 */
filter[j * fsize + i] /= nx;
}
/* 低通滤波 */
for (y = 0; y < h - fsize; y++)
for (x = 0; x < w - fsize; x++) {
nx = 0.0;
ny = 0.0;
for (j = 0; j < fsize; j++)
for (i = 0; i < fsize; i++) {
val = (x + i) + (j + y) * w;
nx += filter[j * fsize + i] * phix[val];
ny += filter[j * fsize + i] * phiy[val];
}
val = x + y * w;
phi2x[val] = nx;
phi2y[val] = ny;
}
/* 销毁 phix, phiy */
if (phix != NULL) {
free(phix);
phix = NULL;
}
if (phiy != NULL) {
free(phiy);
phiy = NULL;
}
/* 步骤5 */
for (y = 0; y < h - fsize; y++)
for (x = 0; x < w - fsize; x++) {
val = x + y * w;
out[val] = atan2(phi2y[val], phi2x[val]) * 0.5;
}
}
if (phix != NULL) free(phix);
if (phiy != NULL) free(phiy);
if (phi2x != NULL) free(phi2x);
if (phi2y != NULL) free(phi2y);
if (filter != NULL)free(filter);
return nRet;
}
/******************************************************************************
* 功能:计算指纹图像脊线的方向。
该算法在许多论文中都有描述,如果图像做了归一化,并且对比度较高,
则最后的处理效果也较好。
方向的值在-PI/2和PI/2之间,弧度和脊并不相同。
选取的块越大,分析的效果也越好,但所需的处理计算时间也越长。
由于指纹图像中脊线方向的变化比较缓慢,所以低通滤波器可以较好的
过虑掉方向中的噪声和错误。
* 参数:image 指向图像对象的指针
* field 指向浮点域对象的指针,保存结果
* nBlockSize 块大小
* nFilterSize 滤波器大小
* 返回:错误编号
******************************************************************************/
FvsError_t FingerprintGetDirection(const FvsImage_t image,
FvsFloatField_t field, const FvsInt_t nBlockSize,
const FvsInt_t nFilterSize) {
/* 输入图像的宽度和高度 */
FvsInt_t w = ImageGetWidth (image);
FvsInt_t h = ImageGetHeight(image);
FvsInt_t pitch = ImageGetPitch (image);
FvsByte_t* p = ImageGetBuffer(image);
FvsInt_t i, j, u, v, x, y;
FvsFloat_t dx[16][16];
FvsFloat_t dy[16][16];
// FvsFloat_t dx[(nBlockSize*2+1)][(nBlockSize*2+1)];
// FvsFloat_t dy[(nBlockSize*2+1)][(nBlockSize*2+1)];
FvsFloat_t nx, ny;
FvsFloat_t* out;
FvsFloat_t* theta = NULL;
FvsError_t nRet = FvsOK;
/* 输出图像 */
nRet = FloatFieldSetSize(field, w, h);
if (nRet != FvsOK) return nRet;
nRet = FloatFieldClear(field);
if (nRet != FvsOK) return nRet;
out = FloatFieldGetBuffer(field);
/* 为方向数组申请内存 */
if (nFilterSize > 0) {
theta = (FvsFloat_t*)malloc(w * h * sizeof(FvsFloat_t));
if (theta != NULL)
memset(theta, 0, (w * h * sizeof(FvsFloat_t)));
}
/* 内存错误,返回 */
if (out == NULL || (nFilterSize > 0 && theta == NULL))
nRet = FvsMemory;
else {
/* 1 - 图像分块 */
for (y = nBlockSize + 1; y < h - nBlockSize - 1; y++)
for (x = nBlockSize + 1; x < w - nBlockSize - 1; x++) {
/* 2 - 计算梯度 */
for (j = 0; j < (nBlockSize * 2 + 1); j++)
for (i = 0; i < (nBlockSize * 2 + 1); i++) {
dx[i][j] = (FvsFloat_t)
(P(x + i - nBlockSize, y + j - nBlockSize) -
P(x + i - nBlockSize - 1, y + j - nBlockSize));
dy[i][j] = (FvsFloat_t)
(P(x + i - nBlockSize, y + j - nBlockSize) -
P(x + i - nBlockSize, y + j - nBlockSize - 1));
}
/* 3 - 计算方向 */
nx = 0.0;
ny = 0.0;
for (v = 0; v < (nBlockSize * 2 + 1); v++)
for (u = 0; u < (nBlockSize * 2 + 1); u++) {
nx += 2 * dx[u][v] * dy[u][v];
ny += dx[u][v] * dx[u][v] - dy[u][v] * dy[u][v];
}
/* 计算角度 (-pi/2 .. pi/2) */
if (nFilterSize > 0)
theta[x + y * w] = atan2(nx, ny);
else
out[x + y * w] = atan2(nx, ny) * 0.5;
}
if (nFilterSize > 0)
nRet = FingerprintDirectionLowPass(theta, out, nFilterSize, w, h);
}
if (theta != NULL) free(theta);
return nRet;
}
/* 指纹频率域 */
/******************************************************************************
** 这个步骤里,我们估计指纹脊线的频率。在局部邻域里,没有凸现的细节点或者孤点,
** 沿着脊线和谷底,可以用一个正弦曲线波形作为模型,因此,局部脊线频率是指纹图
** 像的另一个本质的特征。对指纹图像G进行归一化,O是其方向图,估算局部脊线频率
** 的步骤如下:
**
** 1 - 图像分块 w x w - (16 x 16)
**
** 2 - 对每块,计算大小为l x w (32 x 16)的方向图窗口
**
** 3 - 对中心在 (i,j) 的每块, 计算脊线和谷底的 x-signature
** X[0], X[1], ... X[l-1] 采用如下公式:
**
** --- w-1
** 1 \
** X[k] = - -- G (u, v), k = 0, 1, ..., l-1
** w /
** --- d=0
**
** u = i + (d - w/2).cos O(i,j) + (k - l/2).sin O(i,j)
**
** v = j + (d - w/2).sin O(i,j) - (k - l/2).cos O(i,j)
**
** 如果方向图窗口中没有细节点和孤立的点,则x-signature形成了一个离散
** 的正弦曲线波,与方向图中脊线和谷底的频率一样。因此,脊线和谷底的
** 频率可以由x-signature来估计。设T(i,j)是两个峰顶的平均距离,则频率
** OHM(i,j)可以这样计算:OHM(i,j) = 1 / T(i,j)。
**
** 如果没有两个连续的峰顶,则频率置为-1,说明其无效。
**
** 4 - 对于一个指纹图像而言,脊线频率的值在一个范围之内变动,比如说对于500
** dpi的图像,变动范围为[1/3, 1/25],因此,如果估计出的频率不在这个范
** 围内,说明频率估计无效,同意置为-1。
**
** 5 - 如果某块有断点或者细节点,则不会有正弦曲线,其频率可以由邻块的频率
** 插值估计(比如说高斯函数,均值为0,方差为9,宽度为7)。
**
** 6 - 脊线内部距离变化缓慢,可以用低通滤波器
**
*/
/* 宽度 */
#define BLOCK_W 16
#define BLOCK_W2 8
/* 长度 */
#define BLOCK_L 32
#define BLOCK_L2 16
#define EPSILON 0.0001
#define LPSIZE 3
#define LPFACTOR (1.0/((LPSIZE*2+1)*(LPSIZE*2+1)))
FvsError_t FingerprintGetFrequency(const FvsImage_t image, const FvsFloatField_t direction,
FvsFloatField_t frequency) {
/* 输入图像的宽度和高度 */
FvsError_t nRet = FvsOK;
FvsInt_t w = ImageGetWidth (image);
FvsInt_t h = ImageGetHeight(image);
FvsInt_t pitchi = ImageGetPitch (image);
FvsByte_t* p = ImageGetBuffer(image);
FvsFloat_t* out;
FvsFloat_t* freq;
FvsFloat_t* orientation = FloatFieldGetBuffer(direction);
FvsInt_t x, y, u, v, d, k;
size_t size;
if (p == NULL)
return FvsMemory;
/* 输出图像的内存申请 */
nRet = FloatFieldSetSize(frequency, w, h);
if (nRet != FvsOK) return nRet;
(void)FloatFieldClear(frequency);
freq = FloatFieldGetBuffer(frequency);
if (freq == NULL)
return FvsMemory;
/* 输出的内存申请 */
size = w * h * sizeof(FvsFloat_t);
out = (FvsFloat_t*)malloc(size);
if (out != NULL) {
FvsFloat_t dir = 0.0;
FvsFloat_t cosdir = 0.0;
FvsFloat_t sindir = 0.0;
FvsInt_t peak_pos[BLOCK_L]; /* 顶点 */
FvsInt_t peak_cnt; /* 顶点数目 */
FvsFloat_t peak_freq; /* 顶点频率 */
FvsFloat_t Xsig[BLOCK_L]; /* x signature */
FvsFloat_t pmin, pmax;
memset(out, 0, size);
memset(freq, 0, size);
/* 1 - 图像分块 BLOCK_W x BLOCK_W - (16 x 16) */
for (y = BLOCK_L2; y < h - BLOCK_L2; y++)
for (x = BLOCK_L2; x < w - BLOCK_L2; x++) {
/* 2 - 脊线方向的窗口 l x w (32 x 16) */
// dir = orientation[(x+BLOCK_W2) + (y+BLOCK_W2)*w];
dir = orientation[(x) + (y) * w];
cosdir = cos(dir);
sindir = sin(dir);
/* 3 - 计算 x-signature X[0], X[1], ... X[l-1] */
for (k = 0; k < BLOCK_L; k++) {
Xsig[k] = 0.0;
for (d = 0; d < BLOCK_W; d++) {
u = (FvsInt_t)(x + (k - BLOCK_L2) * cosdir - (d - BLOCK_W2) * sindir);
v = (FvsInt_t)(y + (k - BLOCK_L2) * sindir + (d - BLOCK_W2) * cosdir);
/* clipping */
if (u < 0) u = 0;
else if (u > w - 1) u = w - 1;
if (v < 0) v = 0;
else if (v > h - 1) v = h - 1;
Xsig[k] += p[u + (v * pitchi)];
}
Xsig[k] /= BLOCK_W;
}
/* 计算 T(i,j) */
/* 寻找 x signature 中的顶点 */
peak_cnt = 0;
pmax = pmin = Xsig[0];
for (k = 1; k < BLOCK_L; k++) {
if (pmin > Xsig[k]) pmin = Xsig[k];
if (pmax < Xsig[k]) pmax = Xsig[k];
}
if ((pmax - pmin) > 64.0) {
for (k = 1; k < BLOCK_L - 1; k++)
if ((Xsig[k - 1] < Xsig[k]) && (Xsig[k] >= Xsig[k + 1])) {
peak_pos[peak_cnt++] = k;
}
}
/* 计算均值 */
peak_freq = 0.0;
if (peak_cnt >= 2) {
for (k = 0; k < peak_cnt - 1; k++)
peak_freq += peak_pos[k + 1] - peak_pos[k];
peak_freq /= peak_cnt - 1;
}
/* 4 - 验证频率范围 [1/25-1/3] */
/* 可以扩大到 [1/30-1/2] */
if (peak_freq > 30.0)
out[x + y * w] = 0.0;
else if (peak_freq < 2.0)
out[x + y * w] = 0.0;
else
out[x + y * w] = 1.0 / peak_freq;
}
/* 5 - 未知点 */
for (y = BLOCK_L2; y < h - BLOCK_L2; y++)
for (x = BLOCK_L2; x < w - BLOCK_L2; x++) {
if (out[x + y * w] < EPSILON) {
if (out[x + (y - 1)*w] > EPSILON) {
out[x + (y * w)] = out[x + (y - 1) * w];
}
else {
if (out[x - 1 + (y * w)] > EPSILON)
out[x + (y * w)] = out[x - 1 + (y * w)];
}
}
}
/* 6 - 频率插值 */
for (y = BLOCK_L2; y < h - BLOCK_L2; y++)
for (x = BLOCK_L2; x < w - BLOCK_L2; x++) {
k = x + y * w;
peak_freq = 0.0;
for ( v = -LPSIZE; v <= LPSIZE; v++)
for ( u = -LPSIZE; u <= LPSIZE; u++)
peak_freq += out[(x + u) + (y + v) * w];
freq[k] = peak_freq * LPFACTOR;
}
free(out);
}
return nRet;
}
/******************************************************************************
* 功能:获取指纹图像的有效区域,以进行进一步的处理。
* 如果某个区域不可用用,则掩码置为0,包括如下区域:
* 边界,背景点,图像质量很差的区域。
* 有效区域的掩码置为255。
* 参数:image 指纹图像
* direction 脊线方向
* frequency 脊线频率
* mask 输出的掩码
* 返回:错误编号
******************************************************************************/
FvsError_t FingerprintGetMask(const FvsImage_t image,
const FvsFloatField_t direction,
const FvsFloatField_t frequency, FvsImage_t mask) {
FvsError_t nRet = FvsOK;
FvsFloat_t freqmin = 1.0 / 25;
FvsFloat_t freqmax = 1.0 / 3;
/* 输入图像的宽度高度 */
FvsInt_t w = ImageGetWidth (image);
FvsInt_t h = ImageGetHeight(image);
FvsByte_t* out;
FvsInt_t pitchout;
FvsInt_t pos, posout, x, y;
FvsFloat_t* freq = FloatFieldGetBuffer(frequency);
if (freq == NULL)
return FvsMemory;
/* 需要做改进:检查 */
nRet = ImageSetSize(mask, w, h);
if (nRet == FvsOK)
nRet = ImageClear(mask);
out = ImageGetBuffer(mask);
if (out == NULL)
return FvsMemory;
if (nRet == FvsOK) {
pitchout = ImageGetPitch(mask);
for (y = 0; y < h; y++)
for (x = 0; x < w; x++) {
pos = x + y * w;
posout = x + y * pitchout;
out[posout] = 0;
if (freq[pos] >= freqmin && freq[pos] <= freqmax) {
out[posout] = 255;
}
}
/* 补洞 */
for (y = 0; y < 4; y++)
(void)ImageDilate(mask);
/* 去除边界 */
for (y = 0; y < 12; y++)
(void)ImageErode(mask);
}
return nRet;
}
/* 细化算法 */
#undef P
#define P(x,y) ((x)+(y)*pitch)
#define REMOVE_P { p[P(x,y)]=0x80; changed = FvsTrue; }
/******************************************************************************
** 邻域点定义如下:
** 9 2 3
** 8 1 4
** 7 6 5
******************************************************************************/
/* 宏定义 */
#define P1 p[P(x ,y )]
#define P2 p[P(x ,y-1)]
#define P3 p[P(x+1,y-1)]
#define P4 p[P(x+1,y )]
#define P5 p[P(x+1,y+1)]
#define P6 p[P(x ,y+1)]
#define P7 p[P(x-1,y+1)]
#define P8 p[P(x-1,y )]
#define P9 p[P(x-1,y-1)]
FvsError_t ImageRemoveSpurs(FvsImage_t image) {
FvsInt_t w = ImageGetWidth(image);
FvsInt_t h = ImageGetHeight(image);
FvsInt_t pitch = ImageGetPitch(image);
FvsByte_t* p = ImageGetBuffer(image);
FvsInt_t x, y, n, t, c;
c = 0;
do {
n = 0;
for (y = 1; y < h - 1; y++)
for (x = 1; x < w - 1; x++) {
if( p[P(x, y)] == 0xFF) {
t = 0;
if (P3 == 0 && P2 != 0 && P4 == 0) t++;
if (P5 == 0 && P4 != 0 && P6 == 0) t++;
if (P7 == 0 && P6 != 0 && P8 == 0) t++;
if (P9 == 0 && P8 != 0 && P2 == 0) t++;
if (P3 != 0 && P4 == 0) t++;
if (P5 != 0 && P6 == 0) t++;
if (P7 != 0 && P8 == 0) t++;
if (P9 != 0 && P2 == 0) t++;
if (t == 1) {
p[P(x, y)] = 0x80;
n++;
}
}
}
for (y = 1; y < h - 1; y++)
for (x = 1; x < w - 1; x++) {
if( p[P(x, y)] == 0x80)
p[P(x, y)] = 0;
}
}
while (n > 0 && ++c < 5);
return FvsOK;
}
/* a) 验证其有2-6个邻点 */
#define STEP_A n = 0; /* 邻点个数 */ \
if (P2!=0) n++; if (P3!=0) n++; if (P4!=0) n++; if (P5!=0) n++; \
if (P6!=0) n++; if (P7!=0) n++; if (P8!=0) n++; if (P9!=0) n++; \
if (n>=2 && n<=6)
/* b) 统计由0变1的个数 */
#define STEP_B t = 0; /* 变化的数目 */ \
if (P9==0 && P2!=0) t++; if (P2==0 && P3!=0) t++; \
if (P3==0 && P4!=0) t++; if (P4==0 && P5!=0) t++; \
if (P5==0 && P6!=0) t++; if (P6==0 && P7!=0) t++; \
if (P7==0 && P8!=0) t++; if (P8==0 && P9!=0) t++; \
if (t==1)
/******************************************************************************
* 功能:细化指纹图像
* 图像必须是二值化过的(只包含0x00或oxFF)
* 该算法基于领域的判断,决定某个象素该移去还是保留
* 参数:image 指纹图像
* 返回:错误编号
******************************************************************************/
FvsError_t ImageThinConnectivity(FvsImage_t image) {
FvsInt_t w = ImageGetWidth(image);
FvsInt_t h = ImageGetHeight(image);
FvsInt_t pitch = ImageGetPitch(image);
FvsByte_t* p = ImageGetBuffer(image);
FvsInt_t x, y, n, t;
FvsBool_t changed = FvsTrue;
if (p == NULL)
return FvsMemory;
if (ImageGetFlag(image) != FvsImageBinarized)
return FvsBadParameter;
while (changed == FvsTrue) {
changed = FvsFalse;
for (y = 1; y < h - 1; y++)
for (x = 1; x < w - 1; x++) {
if (p[P(x, y)] == 0xFF) {
STEP_A {
STEP_B
{
/*
c) 2*4*6=0 (2,4 ,or 6 为0)
d) 4*6*8=0
*/
if (P2*P4 * P6 == 0 && P4*P6 * P8 == 0)
REMOVE_P;
}
}
}
}
for (y = 1; y < h - 1; y++)
for (x = 1; x < w - 1; x++)
if (p[P(x, y)] == 0x80)
p[P(x, y)] = 0;
for (y = 1; y < h - 1; y++)
for (x = 1; x < w - 1; x++) {
if (p[P(x, y)] == 0xFF) {
STEP_A {
STEP_B
{
/*
c) 2*6*8=0
d) 2*4*8=0
*/
if (P2*P6 * P8 == 0 && P2*P4 * P8 == 0)
REMOVE_P;
}
}
}
}
for (y = 1; y < h - 1; y++)
for (x = 1; x < w - 1; x++)
if (p[P(x, y)] == 0x80)
p[P(x, y)] = 0;
}
ImageRemoveSpurs(image);
return ImageSetFlag(image, FvsImageThinned);
}
/* 重新定义 REMOVE_P */
#undef REMOVE_P
#define REMOVE_P { p[P(x,y)]=0x00; changed = FvsTrue; }
/******************************************************************************
* 功能:细化指纹图像,使用“Hit and Miss”结构元素。
* 图像必须是二值化过的(只包含0x00或oxFF)
* 该算法的缺点是产生很多伪造的线条(伪特征),
* 必须由另外的算法来消除,后处理非常必要。
* 参数:image 指纹图像
* 返回:错误编号
******************************************************************************/
FvsError_t ImageThinHitMiss(FvsImage_t image) {
FvsInt_t w = ImageGetWidth(image);
FvsInt_t h = ImageGetHeight(image);
FvsInt_t pitch = ImageGetPitch(image);
FvsByte_t* p = ImageGetBuffer(image);
/*
//
// 0 0 0 0 0
// 1 1 1 0
// 1 1 1 1
//
*/
FvsInt_t x, y;
FvsBool_t changed = FvsTrue;
if (p == NULL)
return FvsMemory;
if (ImageGetFlag(image) != FvsImageBinarized)
return FvsBadParameter;
while (changed == FvsTrue) {
changed = FvsFalse;
for (y = 1; y < h - 1; y++)
for (x = 1; x < w - 1; x++) {
if (p[P(x, y)] == 0xFF) {
/*
// 0 0 0 0 1 1 1 1 1 0
// 1 0 1 1 1 1 1 0
// 1 1 1 0 1 0 0 0 1 0
*/
if (p[P(x - 1, y - 1)] == 0 && p[P(x, y - 1)] == 0 && p[P(x + 1, y - 1)] == 0 &&
p[P(x - 1, y + 1)] != 0 && p[P(x, y + 1)] != 0 && p[P(x + 1, y + 1)] != 0)
REMOVE_P;
if (p[P(x - 1, y - 1)] != 0 && p[P(x, y - 1)] != 0 && p[P(x + 1, y - 1)] != 0 &&
p[P(x - 1, y + 1)] == 0 && p[P(x, y + 1)] == 0 && p[P(x + 1, y + 1)] == 0)
REMOVE_P;
if (p[P(x - 1, y - 1)] == 0 && p[P(x - 1, y)] == 0 && p[P(x - 1, y + 1)] == 0 &&
p[P(x + 1, y - 1)] != 0 && p[P(x + 1, y)] != 0 && p[P(x + 1, y + 1)] != 0)
REMOVE_P;
if (p[P(x - 1, y - 1)] != 0 && p[P(x - 1, y)] != 0 && p[P(x - 1, y + 1)] != 0 &&
p[P(x + 1, y - 1)] == 0 && p[P(x + 1, y)] == 0 && p[P(x + 1, y + 1)] == 0)
REMOVE_P;
/*
// 0 0 0 0 1 1
// 1 1 0 0 1 1 0 1 1 1 1 0
// 1 1 0 0 0 0
*/
if (p[P(x, y - 1)] == 0 && p[P(x + 1, y - 1)] == 0 && p[P(x + 1, y)] == 0 &&
p[P(x - 1, y)] != 0 && p[P(x, y + 1)] != 0)
REMOVE_P;
if (p[P(x - 1, y - 1)] == 0 && p[P(x, y - 1)] == 0 && p[P(x - 1, y)] == 0 &&
p[P(x + 1, y)] != 0 && p[P(x, y + 1)] != 0)
REMOVE_P;
if (p[P(x - 1, y + 1)] == 0 && p[P(x - 1, y)] == 0 && p[P(x, y + 1)] == 0 &&
p[P(x + 1, y)] != 0 && p[P(x, y - 1)] != 0)
REMOVE_P;
if (p[P(x + 1, y + 1)] == 0 && p[P(x + 1, y)] == 0 && p[P(x, y + 1)] == 0 &&
p[P(x - 1, y)] != 0 && p[P(x, y - 1)] != 0)
REMOVE_P;
}
}
}
ImageRemoveSpurs(image);
return ImageSetFlag(image, FvsImageThinned);
}
/* modified
*/
FvsError_t FingerprintGetFrequency1(const FvsImage_t image, const FvsFloatField_t direction,
FvsFloatField_t frequency) {
/* 输入图像的宽度和高度 */
FvsError_t nRet = FvsOK;
FvsInt_t w = ImageGetWidth (image);
FvsInt_t h = ImageGetHeight(image);
FvsInt_t pitchi = ImageGetPitch (image);
FvsByte_t* p = ImageGetBuffer(image);
FvsFloat_t* out;
FvsFloat_t* freq;
FvsFloat_t* orientation = FloatFieldGetBuffer(direction);
FvsFloat_t dir, dir1, dir2;
FvsFloat_t cosdir, sindir, cosdir1, sindir1, cosdir2, sindir2;
FvsInt_t x, y, u, v, d, k;
size_t size;
if (p == NULL)
return FvsMemory;
/* 输出图像的内存申请 */
nRet = FloatFieldSetSize(frequency, w, h);
if (nRet != FvsOK) return nRet;
(void)FloatFieldClear(frequency);
freq = FloatFieldGetBuffer(frequency);
if (freq == NULL)
return FvsMemory;
/* 输出的内存申请 */
size = w * h * sizeof(FvsFloat_t);
out = (FvsFloat_t*)malloc(size);
if (out != NULL) {
FvsInt_t peak_pos[BLOCK_L]; /* 顶点 */
FvsInt_t peak_cnt; /* 顶点数目 */
FvsFloat_t peak_freq, save[50]; /* 顶点频率 */
FvsFloat_t Xsig[BLOCK_L]; /* x signature */
FvsFloat_t pmin, pmax;
memset(out, 0, size);
memset(freq, 0, size);
/* 1 - 图像分块 BLOCK_W x BLOCK_W - (16 x 16) */
for (y = BLOCK_L2; y < h - BLOCK_L2; y++)
for (x = BLOCK_L2; x < w - BLOCK_L2; x++) {
/* 2 - 脊线方向的窗口 l x w (32 x 16) */
dir = orientation[x + y * w];
cosdir = cos(dir);
sindir = sin(dir);
u = (FvsInt_t)(-sindir * BLOCK_L2 / 2) + x;
v = (FvsInt_t)(cosdir * BLOCK_L2 / 2) + y;
dir1 = orientation[u + v * w];
cosdir1 = cos(dir1);
sindir1 = sin(dir1);
u = (FvsInt_t)(sindir * BLOCK_L2 / 2) + x;
v = (FvsInt_t)(-cosdir * BLOCK_L2 / 2) + y;
dir2 = orientation[u + v * w];
cosdir2 = cos(dir2);
sindir2 = sin(dir2);
/* 3 - 计算 x-signature X[0], X[1], ... X[l-1] */
for (k = 0; k < BLOCK_L; k++) {
Xsig[k] = 0.0;
for (d = 0; d < BLOCK_W; d++) {
if(d - BLOCK_W2 > 0) {
u = (FvsInt_t)(x + (k - BLOCK_L2) * cosdir1 - (d - BLOCK_W2) * sindir1);
v = (FvsInt_t)(y + (k - BLOCK_L2) * sindir1 + (d - BLOCK_W2) * cosdir1);
}
else {
u = (FvsInt_t)(x + (k - BLOCK_L2) * cosdir2 - (d - BLOCK_W2) * sindir2);
v = (FvsInt_t)(y + (k - BLOCK_L2) * sindir2 + (d - BLOCK_W2) * cosdir2);
}
/* clipping */
if (u < 0) u = 0;
else if (u > w - 1) u = w - 1;
if (v < 0) v = 0;
else if (v > h - 1) v = h - 1;
Xsig[k] += p[u + (v * pitchi)];
}
Xsig[k] /= BLOCK_W;
}
/* 计算 T(i,j) */
/* 寻找 x signature 中的顶点 */
peak_cnt = 0;
pmax = pmin = Xsig[0];
for (k = 1; k < BLOCK_L; k++) {
if (pmin > Xsig[k]) pmin = Xsig[k];
if (pmax < Xsig[k]) pmax = Xsig[k];
}
if ((pmax - pmin) > 64.0) {
for (k = 1; k < BLOCK_L - 1; k++)
if ((Xsig[k - 1] < Xsig[k]) && (Xsig[k] >= Xsig[k + 1])) {
peak_pos[peak_cnt++] = k;
}
}
/* 计算均值 */
peak_freq = 0.0;
if (peak_cnt > 2) {
for (k = 0; k < peak_cnt - 1; k++)
peak_freq += peak_pos[k + 1] - peak_pos[k];
peak_freq /= peak_cnt - 1;
}
/* 4 - 验证频率范围 [1/25-1/3] */
/* 可以扩大到 [1/30-1/2] */
if (peak_freq > 25.0 && peak_freq < 3.0)
peak_freq = 0.0;
if (peak_freq == 0.0)
out[x + y * w] = 0.0;
else
out[x + y * w] = 1.0 / peak_freq;
if(x < 230 && x > 220 && y == 46)
x = x;
}
/* 5 - 未知点 */
/* for (y = BLOCK_L2; y < h-BLOCK_L2; y++)
for (x = BLOCK_L2; x < w-BLOCK_L2; x++)
{
if (out[x+y*w]<EPSILON)
{
if (out[x+(y-1)*w]>EPSILON)
{
out[x+(y*w)] = out[x+(y-1)*w];
}
else
{
if (out[x-1+(y*w)]>EPSILON)
out[x+(y*w)] = out[x-1+(y*w)];
}
}
}
/* 6 - 频率插值 */
for (y = BLOCK_L2; y < h - BLOCK_L2; y++)
for (x = BLOCK_L2; x < w - BLOCK_L2; x++) {
k = x + y * w;
peak_freq = 0.0;
for ( v = -LPSIZE; v <= LPSIZE; v++)
for ( u = -LPSIZE; u <= LPSIZE; u++) {
save[(v + LPSIZE) * (LPSIZE * 2 + 1) + u + LPSIZE] = out[(x + u) + (y + v) * w];
peak_freq += out[(x + u) + (y + v) * w];
}
freq[k] = peak_freq * LPFACTOR;
if(x < 230 && x > 220 && y == 46)
x = x;
}
free(out);
}
return nRet;
}
/* modified
*/
struct mycomplex {
FvsFloat_t real;
FvsFloat_t imag;
};
static void fft(FvsFloat_t data[32]) {
FvsInt_t i, j, k, bfsize, p, count, r = 5;
FvsFloat_t angle;
struct mycomplex *w, *x1, *x2, *x;
count = 1 << r;
w = (struct mycomplex*)malloc(sizeof(struct mycomplex) * count / 2);
x1 = (struct mycomplex*)malloc(sizeof(struct mycomplex) * count);
x2 = (struct mycomplex*)malloc(sizeof(struct mycomplex) * count);
for(i = 0; i < count / 2; i++) {
angle = -i * M_PI * 2 / count;
w[i].real = cos(angle);
w[i].imag = sin(angle);
}
for(j = 0; j < count; j++) {
p = 0;
for(i = 0; i < r; i++) {
if(j & (1 << i)) {
p += 1 << (r - i - 1);
}
}
x1[p].real = data[j];
x1[p].imag = 0;
}
for(k = 0; k < r; k++) {
bfsize = 1 << (k + 1);
for(j = 0; j < 1 << (r - k - 1); j++) {
for(i = 0; i < bfsize / 2; i++) {
p = j * bfsize;
x2[i + p].real = x1[i + p].real + x1[i + p + bfsize / 2].real * w[i * 1 << (r - k - 1)].real \
-x1[i + p + bfsize / 2].imag * w[i * 1 << (r - k - 1)].imag;
x2[i + p].imag = x1[i + p].imag + x1[i + p + bfsize / 2].imag * w[i * 1 << (r - k - 1)].real \
+x1[i + p + bfsize / 2].real * w[i * 1 << (r - k - 1)].imag;
x2[i + p + bfsize / 2].real = x1[i + p].real - x1[i + p + bfsize / 2].real * w[i * 1 << (r - k - 1)].real \
+x1[i + p + bfsize / 2].imag * w[i * 1 << (r - k - 1)].imag;
x2[i + p + bfsize / 2].imag = x1[i + p].imag - x1[i + p + bfsize / 2].imag * w[i * 1 << (r - k - 1)].real \
-x1[i + p + bfsize / 2].real * w[i * 1 << (r - k - 1)].imag;
}
}
x = x1;
x1 = x2;
x2 = x;
}
for(j = 0; j < count; j++) {
data[j] = sqrt(x1[j].real * x1[j].real + x1[j].imag * x1[j].imag) / 10;
}
free(w);
free(x1);
free(x2);
}
FvsError_t FingerprintGetFrequency2(const FvsImage_t image, const FvsFloatField_t direction,
FvsFloatField_t frequency) {
/* 输入图像的宽度和高度 */
FvsError_t nRet = FvsOK;
FvsInt_t w = ImageGetWidth (image);
FvsInt_t h = ImageGetHeight(image);
FvsInt_t pitchi = ImageGetPitch (image);
FvsByte_t* p = ImageGetBuffer(image);
FvsFloat_t* out;
FvsFloat_t* freq;
FvsFloat_t* orientation = FloatFieldGetBuffer(direction);
FvsInt_t x, y, u, v, d, k;
size_t size;
if (p == NULL)
return FvsMemory;
/* 输出图像的内存申请 */
nRet = FloatFieldSetSize(frequency, w, h);
if (nRet != FvsOK) return nRet;
(void)FloatFieldClear(frequency);
freq = FloatFieldGetBuffer(frequency);
if (freq == NULL)
return FvsMemory;
/* 输出的内存申请 */
size = w * h * sizeof(FvsFloat_t);
out = (FvsFloat_t*)malloc(size);
if (out != NULL) {
FvsFloat_t dir = 0.0;
FvsFloat_t cosdir = 0.0;
FvsFloat_t sindir = 0.0;
FvsInt_t peak_pos[BLOCK_L]; /* 顶点 */
FvsInt_t peak_cnt; /* 顶点数目 */
FvsFloat_t peak_freq; /* 顶点频率 */
FvsFloat_t Xsig[BLOCK_L]; /* x signature */
FvsFloat_t pmin, pmax;
memset(out, 0, size);
memset(freq, 0, size);
/* 1 - 图像分块 BLOCK_W x BLOCK_W - (16 x 16) */
for (y = BLOCK_L2; y < h - BLOCK_L2; y++)
for (x = BLOCK_L2; x < w - BLOCK_L2; x++) {
/* 2 - 脊线方向的窗口 l x w (32 x 16) */
// dir = orientation[(x+BLOCK_W2) + (y+BLOCK_W2)*w];
dir = orientation[(x) + (y) * w];
cosdir = cos(dir);
sindir = sin(dir);
/* 3 - 计算 x-signature X[0], X[1], ... X[l-1] */
for (k = 0; k < BLOCK_L; k++) {
Xsig[k] = 0.0;
for (d = 0; d < BLOCK_W; d++) {
u = (FvsInt_t)(x + (k - BLOCK_L2) * cosdir - (d - BLOCK_W2) * sindir);
v = (FvsInt_t)(y + (k - BLOCK_L2) * sindir + (d - BLOCK_W2) * cosdir);
/* clipping */
if (u < 0) u = 0;
else if (u > w - 1) u = w - 1;
if (v < 0) v = 0;
else if (v > h - 1) v = h - 1;
Xsig[k] += p[u + (v * pitchi)];
}
Xsig[k] /= BLOCK_W;
}
if(x == 130 && y == 100)
x = x;
// for(k=0;k<32;k++)
// Xsig[k]=cos(2*M_PI*7*k/32)+cos(2*M_PI*3*k/32);
fft(Xsig);
if (peak_freq > 30.0)
out[x + y * w] = 0.0;
else if (peak_freq < 2.0)
out[x + y * w] = 0.0;
else
out[x + y * w] = 1.0 / peak_freq;
}
/* 5 - 未知点 */
for (y = BLOCK_L2; y < h - BLOCK_L2; y++)
for (x = BLOCK_L2; x < w - BLOCK_L2; x++) {
if (out[x + y * w] < EPSILON) {
if (out[x + (y - 1)*w] > EPSILON) {
out[x + (y * w)] = out[x + (y - 1) * w];
}
else {
if (out[x - 1 + (y * w)] > EPSILON)
out[x + (y * w)] = out[x - 1 + (y * w)];
}
}
}
/* 6 - 频率插值 */
for (y = BLOCK_L2; y < h - BLOCK_L2; y++)
for (x = BLOCK_L2; x < w - BLOCK_L2; x++) {
k = x + y * w;
peak_freq = 0.0;
for ( v = -LPSIZE; v <= LPSIZE; v++)
for ( u = -LPSIZE; u <= LPSIZE; u++)
peak_freq += out[(x + u) + (y + v) * w];
freq[k] = peak_freq * LPFACTOR;
}
free(out);
}
return nRet;
}
| [
"chenke625@gmail.com"
] | chenke625@gmail.com |
b2eb5e3914c4af86dc26dfd5de0cc55e9162472f | fae45a23a885b72cd27c0ad1b918ad754b5de9fd | /benchmarks/shenango/shenango/apps/bench/netbench.cc | cfc41f6514646da5d5f97e02c776a891ebcaf9f0 | [
"MIT",
"Apache-2.0"
] | permissive | bitslab/CompilerInterrupts | 6678700651c7c83fd06451c94188716e37e258f0 | 053a105eaf176b85b4c0d5e796ac1d6ee02ad41b | refs/heads/main | 2023-06-24T18:09:43.148845 | 2021-07-26T17:32:28 | 2021-07-26T17:32:28 | 342,868,949 | 3 | 3 | MIT | 2021-07-19T15:38:30 | 2021-02-27T13:57:16 | C | UTF-8 | C++ | false | false | 9,073 | cc | extern "C" {
#include <base/log.h>
#include <net/ip.h>
}
#undef min
#undef max
#include "thread.h"
#include "sync.h"
#include "timer.h"
#include "net.h"
#include "fake_worker.h"
#include "proto.h"
#include <iostream>
#include <iomanip>
#include <utility>
#include <memory>
#include <chrono>
#include <vector>
#include <algorithm>
#include <numeric>
#include <random>
namespace {
using sec = std::chrono::duration<double, std::micro>;
// The number of samples to discard from the start and end.
constexpr uint64_t kDiscardSamples = 1000;
// The maximum lateness to tolerate before dropping egress samples.
constexpr uint64_t kMaxCatchUpUS = 10;
// the number of worker threads to spawn.
int threads;
// the remote UDP address of the server.
netaddr raddr;
// the number of samples to gather.
uint64_t n;
// the mean service time in us.
double st;
void ServerWorker(std::unique_ptr<rt::TcpConn> c) {
payload p;
std::unique_ptr<FakeWorker> w(FakeWorkerFactory("stridedmem:3200:64"));
if (w == nullptr) panic("couldn't create worker");
while (true) {
// Receive a network response.
ssize_t ret = c->ReadFull(&p, sizeof(p));
if (ret <= 0 || ret > static_cast<ssize_t>(sizeof(p))) {
if (ret == 0 || ret == -ECONNRESET) break;
panic("read failed, ret = %ld", ret);
}
// Perform fake work if requested.
if (p.workn != 0) w->Work(p.workn * 82.0);
// Send a network request.
ssize_t sret = c->WriteFull(&p, ret);
if (sret != ret) {
if (sret == -EPIPE || sret == -ECONNRESET) break;
panic("write failed, ret = %ld", sret);
}
}
}
void ServerHandler(void *arg) {
std::unique_ptr<rt::TcpQueue> q(rt::TcpQueue::Listen({0, kNetbenchPort},
4096));
if (q == nullptr) panic("couldn't listen for connections");
while (true) {
rt::TcpConn *c = q->Accept();
if (c == nullptr) panic("couldn't accept a connection");
rt::Thread([=]{ServerWorker(std::unique_ptr<rt::TcpConn>(c));}).Detach();
}
}
std::vector<double> PoissonWorker(rt::TcpConn *c, double req_rate,
double service_time, rt::WaitGroup *starter)
{
constexpr int kBatchSize = 32;
// Seed the random generator.
std::mt19937 g(microtime());
// Create a packet transmit schedule.
std::vector<double> sched;
std::exponential_distribution<double> rd(1.0 / (1000000.0 / req_rate));
std::vector<double> tmp(n);
std::generate(tmp.begin(), tmp.end(), std::bind(rd, g));
sched.push_back(tmp[0]);
for (std::vector<double>::size_type j = 1; j < tmp.size(); ++j) {
tmp[j] += tmp[j - 1];
sched.push_back(static_cast<uint64_t>(tmp[j]));
}
// Create a fake work schedule.
std::vector<double> work(n);
std::exponential_distribution<double> wd(1.0 / service_time);
std::generate(work.begin(), work.end(), std::bind(wd, g));
// Reserve space to record results.
auto n = sched.size();
std::vector<double> timings;
timings.reserve(n);
std::vector<uint64_t> start_us(n);
// Start the receiver thread.
auto th = rt::Thread([&]{
payload rp;
while (true) {
ssize_t ret = c->ReadFull(&rp, sizeof(rp));
if (ret != static_cast<ssize_t>(sizeof(rp))) {
if (ret == 0 || ret < 0) break;
panic("read failed, ret = %ld", ret);
}
barrier();
uint64_t ts = microtime();
barrier();
timings.push_back(ts - start_us[rp.idx]);
}
});
// Initialize timing measurement data structures.
payload p[kBatchSize];
int j = 0;
// Synchronized start of load generation.
starter->Done();
starter->Wait();
barrier();
uint64_t expstart = microtime();
barrier();
for (unsigned int i = 0; i < n; ++i) {
barrier();
uint64_t now = microtime();
barrier();
if (now - expstart < sched[i]) {
ssize_t ret = c->WriteFull(p, sizeof(payload) * j);
if (ret != static_cast<ssize_t>(sizeof(payload) * j))
panic("write failed, ret = %ld", ret);
j = 0;
rt::Sleep(sched[i] - (microtime() - expstart));
now = microtime();
}
if (now - expstart - sched[i] > kMaxCatchUpUS)
continue;
barrier();
start_us[i] = microtime();
barrier();
// Enqueue a network request.
p[j].idx = i;
p[j].workn = work[i];
p[j].tag = 0;
j++;
if (j >= kBatchSize || i == n - 1) {
ssize_t ret = c->WriteFull(p, sizeof(payload) * j);
if (ret != static_cast<ssize_t>(sizeof(payload) * j))
panic("write failed, ret = %ld", ret);
j = 0;
}
}
c->Shutdown(SHUT_RD);
th.Join();
return timings;
}
std::vector<double> RunExperiment(double req_rate, double *reqs_per_sec) {
// Create one TCP connection per thread.
std::vector<std::unique_ptr<rt::TcpConn>> conns;
for (int i = 0; i < threads; ++i) {
std::unique_ptr<rt::TcpConn> outc(rt::TcpConn::Dial({0, 0}, raddr));
if (unlikely(outc == nullptr)) panic("couldn't connect to raddr.");
conns.emplace_back(std::move(outc));
}
// Launch a worker thread for each connection.
rt::WaitGroup starter(threads + 1);
std::vector<rt::Thread> th;
std::unique_ptr<std::vector<double>> samples[threads];
for (int i = 0; i < threads; ++i) {
th.emplace_back(rt::Thread([&, i]{
auto v = PoissonWorker(conns[i].get(), req_rate / threads, st,
&starter);
samples[i].reset(new std::vector<double>(std::move(v)));
}));
}
// Give the workers time to initialize, then start recording.
starter.Done();
starter.Wait();
// |--- start experiment duration timing ---|
barrier();
auto start = std::chrono::steady_clock::now();
barrier();
// Wait for the workers to finish.
for (auto& t: th)
t.Join();
// |--- end experiment duration timing ---|
barrier();
auto finish = std::chrono::steady_clock::now();
barrier();
// Close the connections.
for (auto& c: conns)
c->Abort();
// Aggregate all the latency timings together.
uint64_t total = 0;
std::vector<double> timings;
for (int i = 0; i < threads; ++i) {
auto &v = *samples[i];
total += v.size();
if (v.size() <= kDiscardSamples * 2) panic("not enough samples");
v.erase(v.begin(), v.begin() + kDiscardSamples);
v.erase(v.end() - kDiscardSamples, v.end());
timings.insert(timings.end(), v.begin(), v.end());
}
// Report results.
double elapsed = std::chrono::duration_cast<sec>(finish - start).count();
*reqs_per_sec = static_cast<double>(total) / elapsed * 1000000;
return timings;
}
void DoExperiment(double req_rate) {
constexpr int kRounds = 1;
std::vector<double> timings;
double reqs_per_sec = 0;
for (int i = 0; i < kRounds; i++) {
double tmp;
auto t = RunExperiment(req_rate, &tmp);
timings.insert(timings.end(), t.begin(), t.end());
reqs_per_sec += tmp;
rt::Sleep(500 * rt::kMilliseconds);
}
reqs_per_sec /= kRounds;
std::sort(timings.begin(), timings.end());
double sum = std::accumulate(timings.begin(), timings.end(), 0.0);
double mean = sum / timings.size();
double count = static_cast<double>(timings.size());
double p9 = timings[count * 0.9];
double p99 = timings[count * 0.99];
double p999 = timings[count * 0.999];
double p9999 = timings[count * 0.9999];
double min = timings[0];
double max = timings[timings.size() - 1];
std::cout << std::setprecision(2) << std::fixed
<< "t: " << threads
<< " rps: " << reqs_per_sec
<< " n: " << timings.size()
<< " min: " << min
<< " mean: " << mean
<< " 90%: " << p9
<< " 99%: " << p99
<< " 99.9%: " << p999
<< " 99.99%: " << p9999
<< " max: " << max << std::endl;
}
void ClientHandler(void *arg) {
for (double i = 500000; i <= 5000000; i += 500000)
DoExperiment(i);
}
int StringToAddr(const char *str, uint32_t *addr) {
uint8_t a, b, c, d;
if(sscanf(str, "%hhu.%hhu.%hhu.%hhu", &a, &b, &c, &d) != 4)
return -EINVAL;
*addr = MAKE_IP_ADDR(a, b, c, d);
return 0;
}
} // anonymous namespace
int main(int argc, char *argv[]) {
int ret;
if (argc < 3) {
std::cerr << "usage: [cfg_file] [cmd] ..." << std::endl;
return -EINVAL;
}
std::string cmd = argv[2];
if (cmd.compare("server") == 0) {
ret = runtime_init(argv[1], ServerHandler, NULL);
if (ret) {
printf("failed to start runtime\n");
return ret;
}
} else if (cmd.compare("client") != 0) {
std::cerr << "invalid command: " << cmd << std::endl;
return -EINVAL;
}
if (argc != 7) {
std::cerr << "usage: [cfg_file] client [#threads] [remote_ip] [n] [service_us]"
<< std::endl;
return -EINVAL;
}
threads = std::stoi(argv[3], nullptr, 0);
ret = StringToAddr(argv[4], &raddr.ip);
if (ret) return -EINVAL;
raddr.port = kNetbenchPort;
n = std::stoll(argv[5], nullptr, 0);
st = std::stod(argv[6], nullptr);
ret = runtime_init(argv[1], ClientHandler, NULL);
if (ret) {
printf("failed to start runtime\n");
return ret;
}
return 0;
}
| [
"nilanjana.basu87@gmail.com"
] | nilanjana.basu87@gmail.com |
178c93cd235149f23668e02cfba704a73e3cad94 | 71c8e39d9d849a2e4ec94ff8c3f0120d9da47686 | /arduino/blink_isr/sketch_jan23d/sketch_jan23d.ino | e36018e7fcb5ef398fd1ed975439798136d492e9 | [
"MIT"
] | permissive | joshcol9232/AL-FanControl | d588ba3e619037d02a53b5d82a0b8cd2dec51a5b | ea01a3318bf07deeb78df5eab99e7cef3bf8fcc2 | refs/heads/master | 2023-05-31T22:04:14.712753 | 2021-06-09T18:09:16 | 2021-06-09T18:09:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 816 | ino | /* Arduino 101: timer and interrupts
1: Timer1 compare match interrupt example
more infos: http://www.letmakerobots.com/node/28278
created by RobotFreak
*/
#define ledPin 17
void setup()
{
pinMode(ledPin, OUTPUT);
// initialize timer1
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 31250; // compare match register 16MHz/256/2Hz
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable all interrupts
}
ISR(TIMER1_COMPA_vect) // timer compare interrupt service routine
{
digitalWrite(ledPin, digitalRead(ledPin) ^ 1); // toggle LED pin
}
void loop()
{
// your program here...
}
| [
"bengt.lueers@gmail.com"
] | bengt.lueers@gmail.com |
e4b98049621db95dde767a8ad87a44c4aa4effde | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/MuonSpectrometer/MuonCnv/MuonByteStreamCnvTest/MuonByteStreamCnvTest/MuonRdoToMuonDigit.h | 2695a1de11a7e17f20a29b9f816b3b34146ea86d | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | h | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#ifndef MUONBYTESTREAMCNVTEST_MUONRDOTOMUONDIGIT_H
#define MUONBYTESTREAMCNVTEST_MUONRDOTOMUONDIGIT_H
#include "GaudiKernel/ToolHandle.h"
#include "AthenaBaseComps/AthAlgorithm.h"
class IMuonDigitizationTool;
class MuonRdoToMuonDigit : public AthAlgorithm {
public:
MuonRdoToMuonDigit(const std::string& name, ISvcLocator* pSvcLocator);
~MuonRdoToMuonDigit();
StatusCode initialize();
StatusCode execute();
StatusCode finalize();
private:
ToolHandle<IMuonDigitizationTool> m_digTool;
};
#endif
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
5beb47d9607f60a40ee6533b9d77aabcb30be7d9 | f8925857535c223bdff7e087767a51f1f9f16657 | /Assignment 3/Assignment 3/StringSplitter.h | 65c6aa71adb281f91eaae6baf8abde114a9b958d | [
"MIT"
] | permissive | justin-harper/cs122 | 388c6ac4162b2bf503d1ca68d3c0ca29f0d7fb48 | 83949bc097cf052ffe6b8bd82002377af4d9cede | refs/heads/master | 2021-01-13T05:00:02.683181 | 2017-02-07T04:21:38 | 2017-02-07T04:21:38 | 81,165,793 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,320 | h | /*
Assignment: 3
Description: Paycheck Calculator
Author: Justin Harper
WSU ID: 10696738 Completion Time: 8hrs
In completing this program, I received help from the following people:
myself
version 1.0 I am happy with this version!
*/
#ifndef STRINGSPLITTER_H
#define STRINGSPLITTER_H
#include <string>
#include <vector>
using namespace std;
class StringSplitter
{
public:
//Breaks apart the supplied text based on the given delimiter
static vector<string> split(string text, string delimiter)
{
//vectors are dynamically expanding arrays
vector<string> pieces;
//find the first delimiter
int location = text.find(delimiter);
//we are starting at the beginning of our string
int start = 0;
//go until we have no more delimiters
while(location != string::npos)
{
//add the current piece to our list of pieces
string piece = text.substr(start, location - start);
pieces.push_back(piece);
//update our index markers for the next round
start = location + 1;
location = text.find(delimiter, start);
}
//at the end of our loop, we're going to have one trailing piece to take care of.
//handle that now.
string piece = text.substr(start, location - start);
pieces.push_back(piece);
//now, return the completed vector
return pieces;
}
};
#endif | [
"justin.harper@outlook.com"
] | justin.harper@outlook.com |
3b57e499468d066328ed6bdee28d49e6f46a233f | 47a0a6676349129af4873dc1951531bd76b28228 | /base/memory/read_only_shared_memory_region.cc | 8c0d27609c3fe60031329c32ad77fdf6d48af3f8 | [
"BSD-3-Clause"
] | permissive | Kaleb8812/chromium | f61c4a42e211ba4df707a45388a62e70dcae9cd7 | 4c098731f333f0d38b403af55133182d626be182 | refs/heads/master | 2022-12-23T01:13:33.470865 | 2018-04-06T11:44:50 | 2018-04-06T11:44:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,847 | cc | // Copyright 2018 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 "base/memory/read_only_shared_memory_region.h"
#include <utility>
#include "base/memory/shared_memory.h"
#include "build/build_config.h"
namespace base {
// static
MappedReadOnlyRegion ReadOnlySharedMemoryRegion::Create(size_t size) {
subtle::PlatformSharedMemoryRegion handle =
subtle::PlatformSharedMemoryRegion::CreateWritable(size);
if (!handle.IsValid())
return {};
void* memory_ptr = nullptr;
size_t mapped_size = 0;
if (!handle.MapAt(0, handle.GetSize(), &memory_ptr, &mapped_size))
return {};
WritableSharedMemoryMapping mapping(memory_ptr, mapped_size,
handle.GetGUID());
#if defined(OS_MACOSX) && !defined(OS_IOS)
handle.ConvertToReadOnly(memory_ptr);
#else
handle.ConvertToReadOnly();
#endif // defined(OS_MACOSX) && !defined(OS_IOS)
ReadOnlySharedMemoryRegion region(std::move(handle));
if (!region.IsValid())
return {};
return {std::move(region), std::move(mapping)};
}
// static
ReadOnlySharedMemoryRegion ReadOnlySharedMemoryRegion::Deserialize(
subtle::PlatformSharedMemoryRegion handle) {
return ReadOnlySharedMemoryRegion(std::move(handle));
}
// static
subtle::PlatformSharedMemoryRegion
ReadOnlySharedMemoryRegion::TakeHandleForSerialization(
ReadOnlySharedMemoryRegion region) {
return std::move(region.handle_);
}
ReadOnlySharedMemoryRegion::ReadOnlySharedMemoryRegion() = default;
ReadOnlySharedMemoryRegion::ReadOnlySharedMemoryRegion(
ReadOnlySharedMemoryRegion&& region) = default;
ReadOnlySharedMemoryRegion& ReadOnlySharedMemoryRegion::operator=(
ReadOnlySharedMemoryRegion&& region) = default;
ReadOnlySharedMemoryRegion::~ReadOnlySharedMemoryRegion() = default;
ReadOnlySharedMemoryRegion ReadOnlySharedMemoryRegion::Duplicate() {
return ReadOnlySharedMemoryRegion(handle_.Duplicate());
}
ReadOnlySharedMemoryMapping ReadOnlySharedMemoryRegion::Map() {
return MapAt(0, handle_.GetSize());
}
ReadOnlySharedMemoryMapping ReadOnlySharedMemoryRegion::MapAt(off_t offset,
size_t size) {
if (!IsValid())
return {};
void* memory = nullptr;
size_t mapped_size = 0;
if (!handle_.MapAt(offset, size, &memory, &mapped_size))
return {};
return ReadOnlySharedMemoryMapping(memory, mapped_size, handle_.GetGUID());
}
bool ReadOnlySharedMemoryRegion::IsValid() const {
return handle_.IsValid();
}
ReadOnlySharedMemoryRegion::ReadOnlySharedMemoryRegion(
subtle::PlatformSharedMemoryRegion handle)
: handle_(std::move(handle)) {
CHECK_EQ(handle_.GetMode(),
subtle::PlatformSharedMemoryRegion::Mode::kReadOnly);
}
} // namespace base
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
a4bf03ea5d0791900184feebcd17092a5d9ed601 | 49fea82ce3cb1b9eef5de574c640333c28aba12d | /1091OOPIMW07/TS0703/main.cpp | 5953a5d608d962b33bf23d1f6d802cca213bc3e1 | [] | no_license | FelixH-XCIX/Object-Oriented-Programming | fb369f0dde1bad0516f004249466a78929ca8858 | 4df804521cedb7ea840eeeeedb169e988be8e4cc | refs/heads/main | 2023-02-07T11:31:27.030364 | 2021-01-02T16:13:21 | 2021-01-02T16:13:21 | 319,557,384 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,364 | cpp | //#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#define MAX 100
using namespace std;
int main()
{
int i, j, numbers[MAX];
string input;
while (getline(cin,input))
{
int size = input.length();
for (i = 0; i < size; i++)
{
numbers[i] = input[i] - '0';
}
for (i = 1; i <= 3; i++)
{
for (j = 0; j < size; j++)
{
switch (numbers[j])
{
case 0:
if (i == 1)
cout << (" _ ");
else if (i == 2)
cout << ("| |");
else if (i == 3)
cout << ("|_|");
break;
case 1:
if (i == 1)
cout << (" ");
else if (i == 2)
cout << (" |");
else if (i == 3)
cout << (" |");
break;
case 2:
if (i == 1)
cout << (" _ ");
else if (i == 2)
cout << (" _|");
else if (i == 3)
cout << ("|_ ");
break;
case 3:
if (i == 1)
cout << (" _ ");
else if (i == 2)
cout << (" _|");
else if (i == 3)
cout << (" _|");
break;
case 4:
if (i == 1)
cout << (" ");
else if (i == 2)
cout << ("|_|");
else if (i == 3)
cout << (" |");
break;
case 5:
if (i == 1)
cout << (" _ ");
else if (i == 2)
cout << ("|_ ");
else if (i == 3)
cout << (" _|");
break;
case 6:
if (i == 1)
cout << (" _ ");
else if (i == 2)
cout << ("|_ ");
else if (i == 3)
cout << ("|_|");
break;
case 7:
if (i == 1)
cout << (" _ ");
else if (i == 2)
cout << (" |");
else if (i == 3)
cout << (" |");
break;
case 8:
if (i == 1)
cout << (" _ ");
else if (i == 2)
cout << ("|_|");
else if (i == 3)
cout << ("|_|");
break;
case 9:
if (i == 1)
cout << (" _ ");
else if (i == 2)
cout << ("|_|");
else if (i == 3)
cout << (" _|");
break;
}
}
cout << endl;
}
}
return 0;
}
| [
"noreply@github.com"
] | FelixH-XCIX.noreply@github.com |
523a09011711fadf0454ecd2afb51ae72505c8b8 | 0f7f3bdd19f9c460bbf5f66ba79cb0c3cd80fa63 | /Results/Force0000005x52/main.cpp | d2f5b84d2b35ddf1638e2ff61caecdf9d2644cd5 | [] | no_license | shurikkuzmin/BinaryMicrochannel3D | 9c95d8c75cbbb3e83bc0dd81cec0385dbe199b7d | 152de567b25aa1b881dcb793db9fef57ec84392c | refs/heads/master | 2021-09-02T03:46:39.502135 | 2011-09-25T14:13:11 | 2011-09-25T14:13:11 | 115,768,117 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,934 | cpp | #include <mpi.h>
#include <iostream>
#include <math.h>
#include <fstream>
#include <string>
#include <sstream>
#include "mpi_singleton.h"
//Inclusion of lattice implementation
#include "lattice.hpp"
#include "solver.hpp"
#include "params_list.h"
#include "descriptor.h"
//Lattice Boltzmann initialization and parameters
const int NX=52;
const int NY=52;
const int NZ=1500;
const int NPOP=19;
const int NUM=NX*NY*NZ;
const int NUMTOTAL=NUM*NPOP;
const int NUMTIME=250001;
const int NUMOUTPUT=10000;
const int NUMSIGNAL=50;
//Binary-liquid initialization
const int width=10;
const int radius=6;
const double rhol=1.0;
const double rhog=1.0;
int main(int argc,char* argv[])
{
//Parallel Debugging
#ifdef DEBUG
int DebugWait=1;
while (DebugWait);
#endif /* DEBUG */
//Specify main communicator
MPISingleton mpi_singleton;
ParamsList params;
if (argc>1)
params.add("force_z",atof(argv[1])*0.000005);
else
params.add("force_z",0.00003);
std::cout<<params("force_z").value<double>()<<"\n";
//Specify parameters
params.add("omega",1.0);
params.add("aconst", 0.04);
params.add("kconst", 0.04);
params.add("gammaconst",1.0);
params.add("phase_gradient",0.0);
params.add("phase_wall",0.0);
params.add("rho_wall",0.5);
params.add("tau_phi",2.0);
params.add("tau_liq",2.5);
params.add("tau_gas",0.7);
params.add("force_x",0.0);
params.add("force_y",0.0);
//params.add("force_z",0.00003);
params.add("NX",NX);
params.add("NY",NY);
params.add("NZ",NZ);
Solver<Descriptor> solver(params);
//Solver initialization from the file
//solver.load_file("equili");
//Initialization
//Density and phase field initialization
double rho_temp;
double phase_temp;
double u_temp[3];
for (int counter=0; counter<NUM; counter++)
{
int iZ=counter/(NX*NY);
int iY=(counter%(NX*NY))/NX;
int iX=(counter%(NX*NY))%NX;
//Initialization of the part of the channel
//if ((iZ>=(NZ-1)/3)&&(iZ<=2*(NZ-1)/3)&&(iX*iX+iY*iY<=20*20))
if ((iZ>=(NZ-1)/3)&&(iZ<=2*(NZ-1)/3)&&(iX<=NX-width-1)&&(iY<=NY-width-1))
{
rho_temp=rhog;
phase_temp=-1.0;
u_temp[0]=0.0;
u_temp[1]=0.0;
u_temp[2]=0.0;
}
else
{
rho_temp=rhol;
phase_temp=1.0;
u_temp[0]=0.0;
u_temp[1]=0.0;
u_temp[2]=0.0;
}
// if ((iX==1)&&(iY!=NY-1))
// {
// rho_temp=rhog;
// phase_temp=-1.0;
// u_temp[0]=0.1;
// u_temp[1]=0.0;
// u_temp[2]=0.1;
// }
// if ((iY==1)&&(iX!=NX-1))
// {
// u_temp[0]=0.0;
// u_temp[1]=0.1;
// u_temp[2]=0.1;
// rho_temp=rhog;
// phase_temp=-1.0;
//
//
// }
solver.putDensity(iX,iY,iZ,iX,iY,iZ,rho_temp);
solver.putPhase(iX,iY,iZ,iX,iY,iZ,phase_temp);
solver.putVelocity(iX,iY,iZ,iX,iY,iZ,u_temp);
}
//Initialization of the populations
solver.init();
//Main iteration
for (int time_counter=0; time_counter<NUMTIME; time_counter++)
{
//Collision procedure with the reconstruction of the equilibrium populations
solver.collide_stream();
if (time_counter%NUMSIGNAL==0)
{
cout<<"Time is "<<time_counter<<"\n";
if (solver.checkNAN())
{
cout<<"Phase fields contain NaN values\n";
MPI_Abort(MPI_COMM_WORLD,-1);
}
}
//Output files
if (time_counter%NUMOUTPUT==0)
{
std::stringstream file_name;
std::stringstream time_string;
time_string<<time_counter;
file_name<<"phase"<<std::string(6-time_string.str().size(),'0')<<time_counter;
//solver.writeTextWholeVelocity(file_name.str());
solver.writeWholeDensityPhaseVelocity(file_name.str());
cout<<"Output is done on the step "<<time_counter<<"\n";
}
}
return 0;
}
| [
"shurik@alex-desktop.(none)"
] | shurik@alex-desktop.(none) |
1740096e05c7c09548ab31cc80c9d998b92cd5db | db1700bb59fa3f0e5f1e080c3ed69829850eea1f | /lab4/stackonarray.cpp | 02a68645160aa491c35e67cf880455fc7e539092 | [] | no_license | iperius93/209180 | 4d904f3699d06c2749966765f1a87f39a1de5080 | c87676bb8085d9724b5cea910ec090317d850728 | refs/heads/master | 2021-01-20T05:29:23.728190 | 2015-04-18T14:37:53 | 2015-04-18T14:37:53 | 31,706,670 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,108 | cpp |
/*
* stackonarray.cpp
*
* Created on: Mar 19, 2015
* Author: serek8
*/
#include "stackonarray.h"
StackOnArray::StackOnArray()
{
sizeOfTable =1;
index=0;
tableOfData = new int[1];
}
void StackOnArray::pushByOneAlloc(int arg)
{
if(index==0){
tableOfData[0] = arg;
++index; // teraz index = 1
return;
}
if(index==sizeOfTable)
{
int *tmpTableOfData = new int[index+1]; //index pokazuje zawsze na nastepny element ktory jest jeszcze pusty
for(int i =0 ; i<index; i++)
{
tmpTableOfData[i] = tableOfData[i];
}
delete[] tableOfData;
tableOfData = tmpTableOfData;
}
tableOfData[index] = arg;
sizeOfTable = ++index ;
//Po zakonczeniu tej funkcji index i sizeOfTable musza byc sobie rowne
}
void StackOnArray::pushByDoubleAlloc(int arg)
{
if(index==0){
tableOfData[0] = arg;
++index;
return;
}
if(sizeOfTable==index)
{
int *tmpTableOfData = new int[2*index];
sizeOfTable = 2*index;
for(int i =0 ; i<index; i++)
{
tmpTableOfData[i] = tableOfData[i];
}
delete[] tableOfData;
tableOfData = tmpTableOfData;
}
tableOfData[index++] = arg; // powiekszam index po przypisaniu nowej wartosci
}
int StackOnArray::pop()
{
return tableOfData[--index];
}
StackOnArray:: ~StackOnArray()
{
delete [] tableOfData;
}
int StackOnArray::returnIndex()
{
return index;
}
void StackOnArray::quicksort(int lewy, int prawy)
{
int v= this->tableOfData[(lewy+prawy)/2];
int i,j,x;
i=lewy;
j=prawy;
do
{
while(this->tableOfData[i]<v) i++;
while(this->tableOfData[j]>v) j--;
if(i<=j)
{
x=this->tableOfData[i];
this->tableOfData[i]=this->tableOfData[j];
this->tableOfData[j]=x;
i++;
j--;
}
}
while(i<=j);
if(j>lewy) this->quicksort(lewy, j);
if(i<prawy) this->quicksort(i, prawy);
}
void StackOnArray::wyswietl_stos()
{
for(int i=0;i<index;i++)
{
cout<<this->tableOfData[i]<<' ';
if(i%10 == 0 && i != 0) cout << endl;
}
}
| [
"rafal@Asus.(none)"
] | rafal@Asus.(none) |
97e41b3ed9bbfd98f709713fe94efb131bc54639 | 1be5334d362a3bb1fdf3ec4d87b316f65c866558 | /src/BLE_Connect_mac.cpp | 71ca3279c88e4059fb52c3c683cccd1f7dadf567 | [] | no_license | perrycharlton/BLE_CLIENT_MAC | 30ce76e7349f24dbacc54e5517a4f36f7f15b3d1 | e732bb892529e11e62fbbe25fc4adb2574304730 | refs/heads/master | 2020-12-02T18:46:43.985657 | 2019-12-31T12:39:31 | 2019-12-31T12:39:31 | 231,085,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,405 | cpp |
#include "BLEDevice.h"
#include <Arduino.h>
// The remote service we wish to connect to.
static BLEUUID serviceUUID("226c0000-6476-4566-7562-66734470666d");
// The characteristic of the remote service we are interested in.
static BLEUUID charUUID("226caa55-6476-4566-7562-66734470666d");
// static BLEAddress MJAddress("58:2d:34:32:2c:c7");
// static BLEAddress MJAddress("58:2d:34:32:33:6e");
// static BLEAddress MJAddress;
static const int addressSize = 5;
char const* address[addressSize] = { "58:2d:34:32:33:6e", "58:2d:34:32:2c:c7",
"58:2d:34:32:3c:f3", "58:2d:34:32:3c:f3", "58:2d:34:32:2e:d4"};
int i = 0;
char const* addrs;
// static boolean doConnect = false;
static boolean connected = false;
static BLERemoteService* pRemoteService;
static BLERemoteCharacteristic* pMyRemoteCharacteristic;
// static boolean doScan = false;
// static BLERemoteCharacteristic* pRemoteCharacteristic;
// static BLEAdvertisedDevice* myDevice;
static BLEClient* pClient;
static void notifyCallback(
BLERemoteCharacteristic* pBLERemoteCharacteristic,
uint8_t* pData,
size_t length,
bool isNotify) {
// Serial.print("Notify callback for characteristic ");
// Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
// Serial.print(" of data length ");
// Serial.println(length);
// Serial.print("data: ");
// Serial.println((char*)pData);
Serial.printf("Connected to mac: %s\t Data: %s\n", addrs, pData);
// pMyRemoteCharacteristic->registerForNotify(NULL, false);
// delay(300);
// pClient->disconnect();
}
// class MyClientCallback : public BLEClientCallbacks {
// void onConnect(BLEClient* pclient) {
// }
// void onDisconnect(BLEClient* pclient) {
// connected = false;
// // delete pClient;
// // delete pclient;
// Serial.println("onDisconnect");
// }
// };
bool connectToServer(char const* Address) {
BLEAddress MJAddress(Address);
// pClient = BLEDevice::createClient();
// Serial.println("Forming a connection to ");
// Serial.printf("Is client connected %i\n", pClient->isConnected());
// pClient->setClientCallbacks(new MyClientCallback());
connected = pClient->connect(MJAddress);
if(!connected){
// delete pClient;
// delete myDevice;
return false;
}
// Serial.printf("Connected = %i - Connected to mac: %s\n", pClient->isConnected(), MJAddress.toString().c_str());
// Serial.println(pClient->isConnected());
// Get a reference to a specific remote service on the server
// Obtain a reference to the service we are after in the remote BLE server.
pRemoteService = pClient->getService(serviceUUID);
if (pRemoteService == nullptr) {
Serial.print("Failed to find our service UUID: ");
Serial.println(serviceUUID.toString().c_str());
pClient->disconnect();
}
// Serial.printf(" - Found our service - %s\n" , pRemoteService->toString().c_str());
// Get a reference to a specific remote characteristic owned by the service
pMyRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
if (pMyRemoteCharacteristic == nullptr) {
Serial.print("Failed to find our characteristic UUID: ");
Serial.println(charUUID.toString().c_str());
pClient->disconnect();
}
pMyRemoteCharacteristic->registerForNotify(notifyCallback, true);
// Retrieve the current value of the remote characteristic.
delay(200);
std::string myValue = pMyRemoteCharacteristic->readValue();
// Serial.printf("Thes ae the values returned: %f\n", pMyRemoteCharacteristic->readFloat());
// pMyRemoteCharacteristic->registerForNotify(notifyCallback, false);
// Serial.printf("The notifcations value: %s\n\n", myValue.c_str());
connected = true;
return true;
}
void setup() {
Serial.begin(115200);
Serial.println("Starting Arduino BLE Client application...");
BLEDevice::init("");
// Create the client
pClient = BLEDevice::createClient();
}
// This is the Arduino main loop function.
void loop() {
// Serial.printf("Connection: %d\n", pClient->isConnected());
// pClient->isConnected();
if (!pClient->isConnected() ){
delay(1000);
Serial.println("Reconnecting");
addrs = address[i];
connectToServer(address[i]);
i < (addressSize-1)?i++:i=0;
Serial.printf("Reconnecting no = %i. Mac = %s\n", i, address[i]);
}
delay(1000);
} // End of loop | [
"perry@perrycharlton.com"
] | perry@perrycharlton.com |
018fa554ea0524382e817ff809fd467be1679454 | 939315e591a462843ea48a1690d76d6bcc95ea72 | /src/fine_grained_rw_bst.h | 46817adb375f070671cdeed95964c6e821bb7e2a | [] | no_license | VasuAgrawal/418FinalProject | f0014a3509407946c212780a8a57365e1691f127 | 99673dd1dfdc9410c8d5b7d4ac9c049f6724f2cb | refs/heads/master | 2021-01-19T22:21:01.273355 | 2017-05-13T02:22:20 | 2017-05-13T02:22:20 | 88,797,639 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 692 | h | #ifndef FINE_GRAINED_RW_BST_H_
#define FINE_GRAINED_RW_BST_H_
#include "bst.h"
#include <memory>
#include "utils.h"
class BST : public BinarySearchTree {
public:
bool insert(int x);
bool remove(int x);
bool contains(int x);
BST();
~BST();
BST(const BST&) = delete;
BST& operator=(const BST&) = delete;
private:
struct Node {
pthread_rwlock_t rwlock;
int value;
std::unique_ptr<Node> left;
std::unique_ptr<Node> right;
Node(int value);
};
// Dummy node to serve as the root. This should help eliminate special
// cases in a bunch of places.
//Node root;
std::unique_ptr<Node> root;
};
#endif
| [
"vasu_agrawal@yahoo.com"
] | vasu_agrawal@yahoo.com |
9fb38c2550c943739f31f58fd5da74a0dea8ee07 | d988f3302c7c4f49583fec21c07658ddb09b81e0 | /src/Cpl/Itc/ServiceMessage.h | f99607b5691113b98db0d4d4374daec3f693d186 | [] | no_license | johnttaylor/colony.apps | 2b10141d8cb30067a5e387e6c53af9955549b17b | 839f3d62b660111ab122a96f550c8ae9de63faa0 | refs/heads/develop | 2023-05-10T17:24:58.286447 | 2021-12-05T20:54:43 | 2021-12-05T20:54:43 | 41,272,799 | 0 | 0 | null | 2021-12-05T20:54:45 | 2015-08-24T00:10:30 | C | UTF-8 | C++ | false | false | 1,637 | h | #ifndef Cpl_Itc_ServiceMessage_h_
#define Cpl_Itc_ServiceMessage_h_
/*-----------------------------------------------------------------------------
* This file is part of the Colony.Core Project. The Colony.Core Project is an
* open source project with a BSD type of licensing agreement. See the license
* agreement (license.txt) in the top/ directory or on the Internet at
* http://integerfox.com/colony.core/license.txt
*
* Copyright (c) 2014-2020 John T. Taylor
*
* Redistributions of the source code must retain the above copyright notice.
*----------------------------------------------------------------------------*/
/** @file */
#include "Cpl/Itc/Message.h"
#include "Cpl/Itc/ReturnHandler.h"
///
namespace Cpl {
///
namespace Itc {
/** This class represents a defined message, which is posted to a mailbox-server
as a request. It includes members which enable the client to be notified when
the server thread has completed the request.
*/
class ServiceMessage : public Message
{
private:
/** References the handler which is invoked by the server thread when
it returns ownership of the message to the client.
*/
ReturnHandler& m_rh;
public:
/// Constructor
ServiceMessage( ReturnHandler& rh ) noexcept;
/** This operation is invoked by the server when it has completed the
operation implemented as a part of this message. Use of this operation
relinquishes the ownership of the message from the server (which invokes
the operation) to the client.
*/
void returnToSender() noexcept;
};
}; // end namespaces
};
#endif // end header latch
| [
"john.t.taylor@gmail.com"
] | john.t.taylor@gmail.com |
70d39bc8388a2e6fd5be569514b07f748b59f080 | 961dd3e240d615415f2a2fb0108aa23959475755 | /Blinker/examples/Blinker_ESPTOUCH/ESPTOUCH_MQTT/ESPTOUCH_MQTT.ino | 1f74eff8f4c37ba895e5145ac4f008938620edb7 | [
"MIT"
] | permissive | ilkerya/ArduinoLibraries | d2a2d8d7b88f3563d1b326369f6a3e4169c46fde | e7338a82d7aa987dff0a0fdb9ac0cea547104fe4 | refs/heads/master | 2020-04-08T16:23:20.419305 | 2018-11-28T14:37:11 | 2018-11-28T14:37:11 | 159,516,277 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,724 | ino | /* *****************************************************************
*
* Download latest Blinker library here:
* https://github.com/blinker-iot/blinker-library/archive/master.zip
*
*
* Blinker is a platform with iOS and Android apps to
* control embedded hardware like Arduino, Raspberrt Pi.
* You can easily build graphic interfaces for all your
* projects by simply dragging and dropping widgets.
*
* Docs: https://doc.blinker.app/
* https://github.com/blinker-iot/blinker-doc/wiki
*
* *****************************************************************
*
* Blinker 库下载地址:
* https://github.com/blinker-iot/blinker-library/archive/master.zip
*
* Blinker 是一个运行在 IOS 和 Android 上用于控制嵌入式硬件的应用程序。
* 你可以通过拖放控制组件,轻松地为你的项目建立图形化控制界面。
*
* 文档: https://doc.blinker.app/
* https://github.com/blinker-iot/blinker-doc/wiki
*
* *****************************************************************/
#define BLINKER_PRINT Serial
#define BLINKER_MQTT
#define BLINKER_ESP_SMARTCONFIG
#include <Blinker.h>
char auth[] = "Your MQTT Secret Key";
void setup()
{
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
Blinker.begin(auth);
}
void loop()
{
Blinker.run();
if (Blinker.available()) {
BLINKER_LOG2("Blinker.readString(): ", Blinker.readString());
uint32_t BlinkerTime = millis();
Blinker.beginFormat();
Blinker.vibrate();
Blinker.print("millis", BlinkerTime);
Blinker.endFormat();
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
} | [
"ilkerya@gmail.com"
] | ilkerya@gmail.com |
406582ce5925b9c2bf071800c7a0b268f44f9f55 | 887f3a72757ff8f691c1481618944b727d4d9ff5 | /third_party/gecko_1.9.1/win32/gecko_sdk/include/nsIHttpHeaderVisitor.h | 4a3acc9703e1efee2e966dfd9c990662ea71f821 | [] | no_license | zied-ellouze/gears | 329f754f7f9e9baa3afbbd652e7893a82b5013d1 | d3da1ed772ed5ae9b82f46f9ecafeb67070d6899 | refs/heads/master | 2020-04-05T08:27:05.806590 | 2015-09-03T13:07:39 | 2015-09-03T13:07:39 | 41,813,794 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,238 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/netwerk/protocol/http/public/nsIHttpHeaderVisitor.idl
*/
#ifndef __gen_nsIHttpHeaderVisitor_h__
#define __gen_nsIHttpHeaderVisitor_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIHttpHeaderVisitor */
#define NS_IHTTPHEADERVISITOR_IID_STR "0cf40717-d7c1-4a94-8c1e-d6c9734101bb"
#define NS_IHTTPHEADERVISITOR_IID \
{0x0cf40717, 0xd7c1, 0x4a94, \
{ 0x8c, 0x1e, 0xd6, 0xc9, 0x73, 0x41, 0x01, 0xbb }}
/**
* Implement this interface to visit http headers.
*
* @status FROZEN
*/
class NS_NO_VTABLE NS_SCRIPTABLE nsIHttpHeaderVisitor : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IHTTPHEADERVISITOR_IID)
/**
* Called by the nsIHttpChannel implementation when visiting request and
* response headers.
*
* @param aHeader
* the header being visited.
* @param aValue
* the header value (possibly a comma delimited list).
*
* @throw any exception to terminate enumeration
*/
/* void visitHeader (in ACString aHeader, in ACString aValue); */
NS_SCRIPTABLE NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIHttpHeaderVisitor, NS_IHTTPHEADERVISITOR_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIHTTPHEADERVISITOR \
NS_SCRIPTABLE NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIHTTPHEADERVISITOR(_to) \
NS_SCRIPTABLE NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue) { return _to VisitHeader(aHeader, aValue); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIHTTPHEADERVISITOR(_to) \
NS_SCRIPTABLE NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->VisitHeader(aHeader, aValue); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsHttpHeaderVisitor : public nsIHttpHeaderVisitor
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIHTTPHEADERVISITOR
nsHttpHeaderVisitor();
private:
~nsHttpHeaderVisitor();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsHttpHeaderVisitor, nsIHttpHeaderVisitor)
nsHttpHeaderVisitor::nsHttpHeaderVisitor()
{
/* member initializers and constructor code */
}
nsHttpHeaderVisitor::~nsHttpHeaderVisitor()
{
/* destructor code */
}
/* void visitHeader (in ACString aHeader, in ACString aValue); */
NS_IMETHODIMP nsHttpHeaderVisitor::VisitHeader(const nsACString & aHeader, const nsACString & aValue)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIHttpHeaderVisitor_h__ */
| [
"gears.daemon@fe895e04-df30-0410-9975-d76d301b4276"
] | gears.daemon@fe895e04-df30-0410-9975-d76d301b4276 |
6030686aff6853b93d476ac2cfbfc848293353f1 | 13d96ca0d2d2dcb4434e2c676b12866d402685ae | /polymorphism/Shapes/main.cpp | e031015c4ed8a00291ec70b99ca7241e79b2f126 | [] | no_license | merilinpisina/fmi-oop-2019-2020 | e7fb4576ce45ab387a721692c7d53c782500c22d | ba3af46b7759b44b9cbd3a1cfb60facefad784b7 | refs/heads/master | 2021-07-11T19:04:40.191672 | 2021-03-26T08:18:08 | 2021-03-26T08:18:08 | 241,052,236 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,529 | cpp | #include <fstream>
#include <iostream>
#include "FigureContainer.h"
void createVectorFromFile(FigureContainer& vec) {
std::ifstream ifs("Input.txt");
if (!ifs.is_open())
return;
while (!ifs.eof()) { //last reading will return nullptr...ok
Figure* curFig = Figure::createFigure(ifs);
if (curFig != nullptr && ifs) {
vec.push_back(curFig);
vec.back()->readFromFile(ifs);
}
}
ifs.close(); // not needed
}
void solveAtIndex(const FigureContainer& vec){
int index;
std::cout << "you are searching for Figure at index = ";
std::cin >> index;
int searched = 0;
for (size_t i = 0; i < vec.getSize(); i++){
size_t j = 0;
while (vec.getAt(i)->getFigureAt(j) != NULL) {
searched++;
if (searched - 1 == index) {
vec.getAt(i)->getFigureAt(j)->print();
return;
}
j++;
}
std::cout << '\n';
}
std::cout << "none";
}
void solveIsThere(const FigureContainer& vec){
double x, y;
std::cout << "enter coordinates for point A\n";
std::cin >> x >> y;
std::cout << "the following figures contain the point A ("
<< x << " ," << y << ")\n";
bool seen = false;
for (size_t i = 0; i < vec.getSize(); i++){
if (vec.getAt(i)->isInside(x, y)) {
seen = true;
std::cout << '\n';
}
}
if (!seen)
std::cout << "none\n";
}
int main() {
FigureContainer vec;
createVectorFromFile(vec);
std::cout << "all figures : \n";
for (size_t i = 0; i < vec.getSize(); i++)
vec.getAt(i)->print();
solveIsThere(vec);
solveAtIndex(vec);
return 0;
}
| [
"merilinpisina@gmail.com"
] | merilinpisina@gmail.com |
9198b56631737c3fd4a4d16e88178a847dd81d4a | 801d0701d19b392a4ff7c268d470959815462398 | /include/hl2sdk-css/game/client/c_baseplayer.h | 0e03b988805be78e74106ae3850370100e8a19d7 | [] | no_license | rdbo/CS-Source-Base | c6e21cc46bca5fb57f3e7f9ee44c3522fd072885 | 4605df4b11a2c779d56d16dd7e817536cdc541f7 | refs/heads/main | 2023-03-03T13:19:04.657557 | 2021-02-06T13:46:53 | 2021-02-06T13:46:53 | 335,521,112 | 6 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 21,246 | h | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Client-side CBasePlayer.
//
// - Manages the player's flashlight effect.
//
//=============================================================================//
#ifndef C_BASEPLAYER_H
#define C_BASEPLAYER_H
#ifdef _WIN32
#pragma once
#endif
#include "c_playerlocaldata.h"
#include "c_basecombatcharacter.h"
#include "playerstate.h"
#include "usercmd.h"
#include "shareddefs.h"
#include "timedevent.h"
#include "smartptr.h"
#include "fx_water.h"
#include "hintsystem.h"
#include "soundemittersystem/isoundemittersystembase.h"
#include "c_env_fog_controller.h"
class C_BaseCombatWeapon;
class C_BaseViewModel;
class C_FuncLadder;
class CFlashlightEffect;
extern int g_nKillCamMode;
extern int g_nKillCamTarget1;
extern int g_nKillCamTarget2;
class C_CommandContext
{
public:
bool needsprocessing;
CUserCmd cmd;
int command_number;
};
class C_PredictionError
{
public:
float time;
Vector error;
};
#define CHASE_CAM_DISTANCE 96.0f
#define WALL_OFFSET 6.0f
bool IsInFreezeCam( void );
//-----------------------------------------------------------------------------
// Purpose: Base Player class
//-----------------------------------------------------------------------------
class C_BasePlayer : public C_BaseCombatCharacter
{
public:
DECLARE_CLASS( C_BasePlayer, C_BaseCombatCharacter );
DECLARE_CLIENTCLASS();
DECLARE_PREDICTABLE();
DECLARE_INTERPOLATION();
C_BasePlayer();
virtual ~C_BasePlayer();
virtual void Spawn( void );
virtual void SharedSpawn(); // Shared between client and server.
// IClientEntity overrides.
virtual void OnPreDataChanged( DataUpdateType_t updateType );
virtual void OnDataChanged( DataUpdateType_t updateType );
virtual void PreDataUpdate( DataUpdateType_t updateType );
virtual void PostDataUpdate( DataUpdateType_t updateType );
virtual void ReceiveMessage( int classID, bf_read &msg );
virtual void OnRestore();
virtual void AddEntity( void );
virtual void MakeTracer( const Vector &vecTracerSrc, const trace_t &tr, int iTracerType );
virtual void GetToolRecordingState( KeyValues *msg );
void SetAnimationExtension( const char *pExtension );
C_BaseViewModel *GetViewModel( int viewmodelindex = 0 );
C_BaseCombatWeapon *GetActiveWeapon( void ) const;
const char *GetTracerType( void );
// View model prediction setup
virtual void CalcView( Vector &eyeOrigin, QAngle &eyeAngles, float &zNear, float &zFar, float &fov );
virtual void CalcViewModelView( const Vector& eyeOrigin, const QAngle& eyeAngles);
// Handle view smoothing when going up stairs
void SmoothViewOnStairs( Vector& eyeOrigin );
virtual float CalcRoll (const QAngle& angles, const Vector& velocity, float rollangle, float rollspeed);
void CalcViewRoll( QAngle& eyeAngles );
void CreateWaterEffects( void );
virtual void SetPlayerUnderwater( bool state );
void UpdateUnderwaterState( void );
bool IsPlayerUnderwater( void ) { return m_bPlayerUnderwater; }
virtual Vector Weapon_ShootPosition();
virtual void Weapon_DropPrimary( void ) {}
virtual Vector GetAutoaimVector( float flScale );
void SetSuitUpdate(const char *name, int fgroup, int iNoRepeat);
// Input handling
virtual bool CreateMove( float flInputSampleTime, CUserCmd *pCmd );
virtual void AvoidPhysicsProps( CUserCmd *pCmd );
virtual void PlayerUse( void );
CBaseEntity *FindUseEntity( void );
virtual bool IsUseableEntity( CBaseEntity *pEntity, unsigned int requiredCaps );
// Data handlers
virtual bool IsPlayer( void ) const { return true; }
virtual int GetHealth() const { return m_iHealth; }
int GetBonusProgress() const { return m_iBonusProgress; }
int GetBonusChallenge() const { return m_iBonusChallenge; }
// observer mode
virtual int GetObserverMode() const;
virtual CBaseEntity *GetObserverTarget() const;
void SetObserverTarget( EHANDLE hObserverTarget );
bool AudioStateIsUnderwater( Vector vecMainViewOrigin );
bool IsObserver() const;
bool IsHLTV() const;
void ResetObserverMode();
bool IsBot( void ) const { return false; }
// Eye position..
virtual Vector EyePosition();
virtual const QAngle &EyeAngles(); // Direction of eyes
void EyePositionAndVectors( Vector *pPosition, Vector *pForward, Vector *pRight, Vector *pUp );
virtual const QAngle &LocalEyeAngles(); // Direction of eyes
// This can be overridden to return something other than m_pRagdoll if the mod uses separate
// entities for ragdolls.
virtual IRagdoll* GetRepresentativeRagdoll() const;
// override the initial bone position for ragdolls
virtual void GetRagdollInitBoneArrays( matrix3x4_t *pDeltaBones0, matrix3x4_t *pDeltaBones1, matrix3x4_t *pCurrentBones, float boneDt );
// Returns eye vectors
void EyeVectors( Vector *pForward, Vector *pRight = NULL, Vector *pUp = NULL );
void CacheVehicleView( void ); // Calculate and cache the position of the player in the vehicle
bool IsSuitEquipped( void ) { return m_Local.m_bWearingSuit; };
// Team handlers
virtual void TeamChange( int iNewTeam );
// Flashlight
void Flashlight( void );
void UpdateFlashlight( void );
// Weapon selection code
virtual bool IsAllowedToSwitchWeapons( void ) { return !IsObserver(); }
virtual C_BaseCombatWeapon *GetActiveWeaponForSelection( void );
// Returns the view model if this is the local player. If you're in third person or
// this is a remote player, it returns the active weapon
// (and its appropriate left/right weapon if this is TF2).
virtual C_BaseAnimating* GetRenderedWeaponModel();
virtual bool IsOverridingViewmodel( void ) { return false; };
virtual int DrawOverriddenViewmodel( C_BaseViewModel *pViewmodel, int flags ) { return 0; };
virtual float GetDefaultAnimSpeed( void ) { return 1.0; }
void SetMaxSpeed( float flMaxSpeed ) { m_flMaxspeed = flMaxSpeed; }
float MaxSpeed() const { return m_flMaxspeed; }
// Should this object cast shadows?
virtual ShadowType_t ShadowCastType() { return SHADOWS_NONE; }
virtual bool ShouldReceiveProjectedTextures( int flags )
{
return false;
}
bool IsLocalPlayer( void ) const;
// Global/static methods
virtual void ThirdPersonSwitch( bool bThirdperson );
static bool ShouldDrawLocalPlayer();
static C_BasePlayer *GetLocalPlayer( void );
int GetUserID( void );
virtual bool CanSetSoundMixer( void );
// Called by the view model if its rendering is being overridden.
virtual bool ViewModel_IsTransparent( void );
#if !defined( NO_ENTITY_PREDICTION )
void AddToPlayerSimulationList( C_BaseEntity *other );
void SimulatePlayerSimulatedEntities( void );
void RemoveFromPlayerSimulationList( C_BaseEntity *ent );
void ClearPlayerSimulationList( void );
#endif
virtual void PhysicsSimulate( void );
virtual unsigned int PhysicsSolidMaskForEntity( void ) const { return MASK_PLAYERSOLID; }
// Prediction stuff
virtual bool ShouldPredict( void );
virtual void PreThink( void );
virtual void PostThink( void );
virtual void ItemPreFrame( void );
virtual void ItemPostFrame( void );
virtual void AbortReload( void );
virtual void SelectLastItem(void);
virtual void Weapon_SetLast( C_BaseCombatWeapon *pWeapon );
virtual bool Weapon_ShouldSetLast( C_BaseCombatWeapon *pOldWeapon, C_BaseCombatWeapon *pNewWeapon ) { return true; }
virtual bool Weapon_ShouldSelectItem( C_BaseCombatWeapon *pWeapon );
virtual bool Weapon_Switch( C_BaseCombatWeapon *pWeapon, int viewmodelindex = 0 ); // Switch to given weapon if has ammo (false if failed)
virtual C_BaseCombatWeapon *GetLastWeapon( void ) { return m_hLastWeapon.Get(); }
void ResetAutoaim( void );
virtual void SelectItem( const char *pstr, int iSubType = 0 );
virtual void UpdateClientData( void );
virtual float GetFOV( void );
int GetDefaultFOV( void ) const;
virtual bool IsZoomed( void ) { return false; }
bool SetFOV( CBaseEntity *pRequester, int FOV, float zoomRate, int iZoomStart = 0 );
void ClearZoomOwner( void );
float GetFOVDistanceAdjustFactor();
virtual void ViewPunch( const QAngle &angleOffset );
void ViewPunchReset( float tolerance = 0 );
void UpdateButtonState( int nUserCmdButtonMask );
int GetImpulse( void ) const;
virtual void Simulate();
virtual bool ShouldInterpolate();
virtual bool ShouldDraw();
virtual int DrawModel( int flags );
// Called when not in tactical mode. Allows view to be overriden for things like driving a tank.
virtual void OverrideView( CViewSetup *pSetup );
// returns the player name
const char * GetPlayerName();
virtual const Vector GetPlayerMins( void ) const; // uses local player
virtual const Vector GetPlayerMaxs( void ) const; // uses local player
// Is the player dead?
bool IsPlayerDead();
bool IsPoisoned( void ) { return m_Local.m_bPoisoned; }
C_BaseEntity *GetUseEntity();
// Vehicles...
IClientVehicle *GetVehicle();
bool IsInAVehicle() const { return ( NULL != m_hVehicle.Get() ) ? true : false; }
virtual void SetVehicleRole( int nRole );
void LeaveVehicle( void );
bool UsingStandardWeaponsInVehicle( void );
virtual void SetAnimation( PLAYER_ANIM playerAnim );
float GetTimeBase( void ) const;
float GetFinalPredictedTime() const;
bool IsInVGuiInputMode() const;
bool IsInViewModelVGuiInputMode() const;
C_CommandContext *GetCommandContext();
// Get the command number associated with the current usercmd we're running (if in predicted code).
int CurrentCommandNumber() const;
const CUserCmd *GetCurrentUserCommand() const;
const QAngle& GetPunchAngle();
void SetPunchAngle( const QAngle &angle );
float GetWaterJumpTime() const;
void SetWaterJumpTime( float flWaterJumpTime );
float GetSwimSoundTime( void ) const;
void SetSwimSoundTime( float flSwimSoundTime );
float GetDeathTime( void ) { return m_flDeathTime; }
void SetPreviouslyPredictedOrigin( const Vector &vecAbsOrigin );
const Vector &GetPreviouslyPredictedOrigin() const;
// CS wants to allow small FOVs for zoomed-in AWPs.
virtual float GetMinFOV() const;
virtual void DoMuzzleFlash();
virtual void PlayPlayerJingle();
virtual void UpdateStepSound( surfacedata_t *psurface, const Vector &vecOrigin, const Vector &vecVelocity );
virtual void PlayStepSound( Vector &vecOrigin, surfacedata_t *psurface, float fvol, bool force );
virtual surfacedata_t * GetFootstepSurface( const Vector &origin, const char *surfaceName );
virtual void GetStepSoundVelocities( float *velwalk, float *velrun );
virtual void SetStepSoundTime( stepsoundtimes_t iStepSoundTime, bool bWalking );
// Called by prediction when it detects a prediction correction.
// vDelta is the line from where the client had predicted the player to at the usercmd in question,
// to where the server says the client should be at said usercmd.
void NotePredictionError( const Vector &vDelta );
// Called by the renderer to apply the prediction error smoothing.
void GetPredictionErrorSmoothingVector( Vector &vOffset );
virtual void ExitLadder() {}
surfacedata_t *GetLadderSurface( const Vector &origin );
surfacedata_t *GetSurfaceData( void ) { return m_pSurfaceData; }
void SetLadderNormal( Vector vecLadderNormal ) { m_vecLadderNormal = vecLadderNormal; }
// Hints
virtual CHintSystem *Hints( void ) { return NULL; }
bool ShouldShowHints( void ) { return Hints() ? Hints()->ShouldShowHints() : false; }
bool HintMessage( int hint, bool bForce = false, bool bOnlyIfClear = false ) { return Hints() ? Hints()->HintMessage( hint, bForce, bOnlyIfClear ) : false; }
void HintMessage( const char *pMessage ) { if (Hints()) Hints()->HintMessage( pMessage ); }
virtual IMaterial *GetHeadLabelMaterial( void );
// Fog
fogparams_t *GetFogParams( void ) { return &m_CurrentFog; }
void FogControllerChanged( bool bSnap );
void UpdateFogController( void );
void UpdateFogBlend( void );
void IncrementEFNoInterpParity();
int GetEFNoInterpParity() const;
float GetFOVTime( void ){ return m_flFOVTime; }
virtual void OnAchievementAchieved( int iAchievement ) {}
protected:
fogparams_t m_CurrentFog;
EHANDLE m_hOldFogController;
public:
int m_StuckLast;
// Data for only the local player
CNetworkVarEmbedded( CPlayerLocalData, m_Local );
// Data common to all other players, too
CPlayerState pl;
// Player FOV values
int m_iFOV; // field of view
int m_iFOVStart; // starting value of the FOV changing over time (client only)
float m_flFOVTime; // starting time of the FOV zoom
int m_iDefaultFOV; // default FOV if no other zooms are occurring
EHANDLE m_hZoomOwner; // This is a pointer to the entity currently controlling the player's zoom
// Only this entity can change the zoom state once it has ownership
// For weapon prediction
bool m_fOnTarget; //Is the crosshair on a target?
char m_szAnimExtension[32];
int m_afButtonLast;
int m_afButtonPressed;
int m_afButtonReleased;
int m_nButtons;
CUserCmd *m_pCurrentCommand;
// Movement constraints
EHANDLE m_hConstraintEntity;
Vector m_vecConstraintCenter;
float m_flConstraintRadius;
float m_flConstraintWidth;
float m_flConstraintSpeedFactor;
protected:
void CalcPlayerView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov );
void CalcVehicleView(IClientVehicle *pVehicle, Vector& eyeOrigin, QAngle& eyeAngles,
float& zNear, float& zFar, float& fov );
virtual void CalcObserverView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov );
virtual Vector GetChaseCamViewOffset( CBaseEntity *target );
void CalcChaseCamView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov );
void CalcInEyeCamView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov );
virtual void CalcDeathCamView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov );
void CalcRoamingView(Vector& eyeOrigin, QAngle& eyeAngles, float& fov);
virtual void CalcFreezeCamView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov );
// Check to see if we're in vgui input mode...
void DetermineVguiInputMode( CUserCmd *pCmd );
// Used by prediction, sets the view angles for the player
virtual void SetLocalViewAngles( const QAngle &viewAngles );
virtual void SetViewAngles( const QAngle& ang );
// used by client side player footsteps
surfacedata_t* GetGroundSurface();
protected:
// Did we just enter a vehicle this frame?
bool JustEnteredVehicle();
// DATA
int m_iObserverMode; // if in spectator mode != 0
EHANDLE m_hObserverTarget; // current observer target
float m_flObserverChaseDistance; // last distance to observer traget
Vector m_vecFreezeFrameStart;
float m_flFreezeFrameStartTime; // Time at which we entered freeze frame observer mode
float m_flFreezeFrameDistance;
bool m_bWasFreezeFraming;
float m_flDeathTime; // last time player died
float m_flStepSoundTime;
private:
// Make sure no one calls this...
C_BasePlayer& operator=( const C_BasePlayer& src );
C_BasePlayer( const C_BasePlayer & ); // not defined, not accessible
// Vehicle stuff.
EHANDLE m_hVehicle;
EHANDLE m_hOldVehicle;
EHANDLE m_hUseEntity;
float m_flMaxspeed;
int m_iBonusProgress;
int m_iBonusChallenge;
CInterpolatedVar< Vector > m_iv_vecViewOffset;
// Not replicated
Vector m_vecWaterJumpVel;
float m_flWaterJumpTime; // used to be called teleport_time
int m_nImpulse;
float m_flSwimSoundTime;
Vector m_vecLadderNormal;
QAngle m_vecOldViewAngles;
bool m_bWasFrozen;
int m_flPhysics;
int m_nTickBase;
int m_nFinalPredictedTick;
EHANDLE m_pCurrentVguiScreen;
// Player flashlight dynamic light pointers
CFlashlightEffect *m_pFlashlight;
typedef CHandle<C_BaseCombatWeapon> CBaseCombatWeaponHandle;
CNetworkVar( CBaseCombatWeaponHandle, m_hLastWeapon );
#if !defined( NO_ENTITY_PREDICTION )
CUtlVector< CHandle< C_BaseEntity > > m_SimulatedByThisPlayer;
#endif
// players own view models, left & right hand
CHandle< C_BaseViewModel > m_hViewModel[ MAX_VIEWMODELS ];
float m_flOldPlayerZ;
float m_flOldPlayerViewOffsetZ;
Vector m_vecVehicleViewOrigin; // Used to store the calculated view of the player while riding in a vehicle
QAngle m_vecVehicleViewAngles; // Vehicle angles
float m_flVehicleViewFOV;
int m_nVehicleViewSavedFrame; // Used to mark which frame was the last one the view was calculated for
// For UI purposes...
int m_iOldAmmo[ MAX_AMMO_TYPES ];
C_CommandContext m_CommandContext;
// For underwater effects
float m_flWaterSurfaceZ;
bool m_bResampleWaterSurface;
TimedEvent m_tWaterParticleTimer;
CSmartPtr<WaterDebrisEffect> m_pWaterEmitter;
bool m_bPlayerUnderwater;
friend class CPrediction;
// HACK FOR TF2 Prediction
friend class CTFGameMovementRecon;
friend class CGameMovement;
friend class CTFGameMovement;
friend class CHL1GameMovement;
friend class CCSGameMovement;
friend class CHL2GameMovement;
friend class CDODGameMovement;
friend class CPortalGameMovement;
// Accessors for gamemovement
float GetStepSize( void ) const { return m_Local.m_flStepSize; }
float m_flNextAvoidanceTime;
float m_flAvoidanceRight;
float m_flAvoidanceForward;
float m_flAvoidanceDotForward;
float m_flAvoidanceDotRight;
protected:
virtual bool IsDucked( void ) const { return m_Local.m_bDucked; }
virtual bool IsDucking( void ) const { return m_Local.m_bDucking; }
virtual float GetFallVelocity( void ) { return m_Local.m_flFallVelocity; }
void ForceSetupBonesAtTimeFakeInterpolation( matrix3x4_t *pBonesOut, float curtimeOffset );
float m_flLaggedMovementValue;
// These are used to smooth out prediction corrections. They're most useful when colliding with
// vphysics objects. The server will be sending constant prediction corrections, and these can help
// the errors not be so jerky.
Vector m_vecPredictionError;
float m_flPredictionErrorTime;
Vector m_vecPreviouslyPredictedOrigin; // Used to determine if non-gamemovement game code has teleported, or tweaked the player's origin
char m_szLastPlaceName[MAX_PLACE_NAME_LENGTH]; // received from the server
// Texture names and surface data, used by CGameMovement
int m_surfaceProps;
surfacedata_t* m_pSurfaceData;
float m_surfaceFriction;
char m_chTextureType;
bool m_bSentFreezeFrame;
float m_flFreezeZOffset;
byte m_ubEFNoInterpParity;
byte m_ubOldEFNoInterpParity;
private:
struct StepSoundCache_t
{
StepSoundCache_t() : m_usSoundNameIndex( 0 ) {}
CSoundParameters m_SoundParameters;
unsigned short m_usSoundNameIndex;
};
// One for left and one for right side of step
StepSoundCache_t m_StepSoundCache[ 2 ];
public:
const char *GetLastKnownPlaceName( void ) const { return m_szLastPlaceName; } // return the last nav place name the player occupied
float GetLaggedMovementValue( void ){ return m_flLaggedMovementValue; }
bool ShouldGoSouth( Vector vNPCForward, Vector vNPCRight ); //Such a bad name.
void SetOldPlayerZ( float flOld ) { m_flOldPlayerZ = flOld; }
};
EXTERN_RECV_TABLE(DT_BasePlayer);
//-----------------------------------------------------------------------------
// Inline methods
//-----------------------------------------------------------------------------
inline C_BasePlayer *ToBasePlayer( C_BaseEntity *pEntity )
{
if ( !pEntity || !pEntity->IsPlayer() )
return NULL;
#if _DEBUG
Assert( dynamic_cast<C_BasePlayer *>( pEntity ) != NULL );
#endif
return static_cast<C_BasePlayer *>( pEntity );
}
inline C_BaseEntity *C_BasePlayer::GetUseEntity()
{
return m_hUseEntity;
}
inline IClientVehicle *C_BasePlayer::GetVehicle()
{
C_BaseEntity *pVehicleEnt = m_hVehicle.Get();
return pVehicleEnt ? pVehicleEnt->GetClientVehicle() : NULL;
}
inline bool C_BasePlayer::IsObserver() const
{
return (GetObserverMode() != OBS_MODE_NONE);
}
inline int C_BasePlayer::GetImpulse( void ) const
{
return m_nImpulse;
}
inline C_CommandContext* C_BasePlayer::GetCommandContext()
{
return &m_CommandContext;
}
inline int CBasePlayer::CurrentCommandNumber() const
{
Assert( m_pCurrentCommand );
return m_pCurrentCommand->command_number;
}
inline const CUserCmd *CBasePlayer::GetCurrentUserCommand() const
{
Assert( m_pCurrentCommand );
return m_pCurrentCommand;
}
#endif // C_BASEPLAYER_H
| [
"rdbodev@gmail.com"
] | rdbodev@gmail.com |
de86afaeacd89c61157f3ba79837b0b30a3d2d6f | 88ae8695987ada722184307301e221e1ba3cc2fa | /components/security_interstitials/core/https_only_mode_metrics.h | 50efe38ed5554839101f8444a10227ff7e4ade8d | [
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 7,404 | h | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SECURITY_INTERSTITIALS_CORE_HTTPS_ONLY_MODE_METRICS_H_
#define COMPONENTS_SECURITY_INTERSTITIALS_CORE_HTTPS_ONLY_MODE_METRICS_H_
#include <cstddef>
#include "base/time/time.h"
namespace security_interstitials::https_only_mode {
// The main histogram that records events about HTTPS-First Mode and HTTPS
// Upgrades.
extern const char kEventHistogram[];
// Same as kEventHistogram, but only recorded if the event happened on a
// navigation where HFM was enabled due to the site engagement heuristic.
extern const char kEventHistogramWithEngagementHeuristic[];
extern const char kNavigationRequestSecurityLevelHistogram[];
// Histogram that records enabled/disabled states for sites. If HFM gets enabled
// or disabled due to Site Engagement on a site, records an entry.
extern const char kSiteEngagementHeuristicStateHistogram[];
// Histogram that records the current number of host that have HFM enabled due
// to the site engagement heuristic. Includes hosts that have HTTP allowed.
extern const char kSiteEngagementHeuristicHostCountHistogram[];
// Histogram that records the accumulated number of host that have HFM enabled
// at some point due to the site engagement heuristic. Includes hosts that have
// HTTP allowed.
extern const char kSiteEngagementHeuristicAccumulatedHostCountHistogram[];
// Histogram that records the duration a host has HFM enabled due to the site
// engagement heuristic. Only recorded for hosts removed from the HFM list.
// Recorded at the time of navigation when HFM upgrades trigger.
extern const char kSiteEngagementHeuristicEnforcementDurationHistogram[];
// Recorded by HTTPS-First Mode and HTTPS-Upgrade logic when a navigation is
// upgraded, or is eligible to be upgraded but wasn't.
//
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class Event {
// Navigation was upgraded from HTTP to HTTPS at some point (either the
// initial request or after a redirect).
kUpgradeAttempted = 0,
// Navigation succeeded after being upgraded to HTTPS.
kUpgradeSucceeded = 1,
// Navigation failed after being upgraded to HTTPS.
kUpgradeFailed = 2,
// kUpgradeCertError, kUpgradeNetError, kUpgradeTimedOut, and
// kUpgradeRedirectLoop are subsets of kUpgradeFailed. kUpgradeFailed should
// also be recorded whenever these events are recorded.
// Navigation failed due to a cert error.
kUpgradeCertError = 3,
// Navigation failed due to a net error.
kUpgradeNetError = 4,
// Navigation failed due to timing out.
kUpgradeTimedOut = 5,
// A prerendered HTTP navigation was cancelled.
kPrerenderCancelled = 6,
// An upgrade would have been attempted but wasn't because neither HTTPS-First
// Mode nor HTTPS Upgrading were enabled.
kUpgradeNotAttempted = 7,
// Upgrade failed due to encountering a redirect loop and failing early.
kUpgradeRedirectLoop = 8,
kMaxValue = kUpgradeRedirectLoop,
};
// Recorded by HTTPS-Upgrade logic when each step in a navigation request is
// observed, recording information about the protocol used. For a request with
// two redirects, this will be recorded three times (once for each redirect,
// then for the final URL).
//
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused. Values may be added to offer greater
// specificity in the future. Keep in sync with NavigationRequestSecurityLevel
// in enums.xml.
enum class NavigationRequestSecurityLevel {
// Request was ignored because not all prerequisites were met.
kUnknown = 0,
// Request was for a secure (HTTPS) resource.
kSecure = 1,
// Request was for an insecure (HTTP) resource.
kInsecure = 2,
// Request was for an insecure (HTTP) resource, but was internally redirected
// due to HSTS.
kHstsUpgraded = 3,
// Request was for localhost, and thus no network
// due to HSTS.
kLocalhost = 4,
// Request was for an insecure (HTTP) resource, but was internally redirected
// by the HTTPS-First Mode/HTTP Upgrading logic.
kUpgraded = 5,
// Request was for a URL with a scheme other than HTTP or HTTPS.
kOtherScheme = 6,
// Request was explicitly allowlisted by content or enterprise settings
// (NOT by clicking through the HFM interstitial / an upgrade failing).
kAllowlisted = 7,
// Request was insecure (HTTP), but was to a hostname that isn't globally
// unique (e.g. a bare RFC1918 IP address, single-label or .local hostname).
// This bucket is recorded IN ADDITION to kInsecure/kAllowlisted.
kNonUniqueHostname = 8,
// Request was insecure (HTTP), but was to a URL that was fully typed (as
// opposed to autocompleted) that included an explicit http scheme.
kExplicitHttpScheme = 9,
kMaxValue = kExplicitHttpScheme,
};
// Recorded by the Site Engagement Heuristic logic, recording whether HFM should
// be enabled on a site due to its HTTP and HTTPS site engagement scores. Only
// recorded if the enabled/disabled state changes.
//
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused. Values may be added to offer greater
// specificity in the future. Keep in sync with SiteEngagementHeuristicState
// in enums.xml.
enum class SiteEngagementHeuristicState {
// HFM was not enabled and is now enabled on this site because its HTTPS score
// is high and HTTP score is low.
kEnabled = 0,
// HFM was enabled and is now disabled on this site because its HTTPS score is
// low or HTTP score is high.
kDisabled = 1,
kMaxValue = kDisabled,
};
// Stores the parameters to decide whether to show an interstitial for the
// current site.
struct HttpInterstitialState {
// Whether HTTPS-First Mode is enabled using the global UI toggle.
bool enabled_by_pref = false;
// Whether HTTPS-First Mode is enabled for the current site due to the
// site engagement heuristic.
bool enabled_by_engagement_heuristic = false;
// Whether HTTPS-First Mode is enabled because the user is in the Advanced
// Protection program.
bool enabled_by_advanced_protection = false;
};
// Helper to record an HTTPS-First Mode navigation event.
void RecordHttpsFirstModeNavigation(
Event event,
const HttpInterstitialState& interstitial_state);
// Helper to record a navigation request security level.
void RecordNavigationRequestSecurityLevel(NavigationRequestSecurityLevel level);
// Helper to record Site Engagement Heuristic enabled state.
void RecordSiteEngagementHeuristicState(SiteEngagementHeuristicState state);
// Helper to record metrics about the number of hosts affected by the Site
// Engagement Heuristic.
// `current_count` is the number of hosts that currently have HFM enabled.
// `accumulated_count` is the number of accumulated hosts that had HFM enabled
// at some point.
void RecordSiteEngagementHeuristicCurrentHostCounts(size_t current_count,
size_t accumulated_count);
void RecordSiteEngagementHeuristicEnforcementDuration(
base::TimeDelta enforcement_duration);
} // namespace security_interstitials::https_only_mode
#endif // COMPONENTS_SECURITY_INTERSTITIALS_CORE_HTTPS_ONLY_MODE_METRICS_H_
| [
"jengelh@inai.de"
] | jengelh@inai.de |
4c892992495110e209dab6f1875dd8caffacf817 | 920c4ef30727f0c51b5c9f00bdd9b923b541853e | /Code_Cpp/cppserver备份资料/code/library/source/operators/include/cookie/cookie.h | 2e32f7948bf9266e4aeb65dd898f7801db5f0c66 | [] | no_license | fishney/TDServer | 10e50cd156b9109816ddebde241614a28546842a | 19305fc7bf649a9add86146bd1bfd253efa6e9cb | refs/heads/master | 2023-03-16T22:24:45.802339 | 2017-10-19T07:02:56 | 2017-10-19T07:02:56 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 596 | h | /*----------------- cookie.h
*
* Copyright (C): 2011 Mokylin·Mokyqi
* Author : 赵文源
* Version : V1.0
* Date : 2012/6/27 19:32:53
*--------------------------------------------------------------
*
*------------------------------------------------------------*/
#pragma once
#include "basic/stringFunctions.h"
#include "encrypt/include/encrypts.h"
/*************************************************************/
namespace cookie
{
//--- 初始化
bool init (uint32 _timeout,pc_str _key);
//--- 登录验证
bool login_verify(url_parser&_param,std::string&_uname);
};
| [
"haibo tang"
] | haibo tang |
8df331dce45e7438630fdc1b125b0af0f608adf7 | 1edf35c781432e70c9083f306c08d7a55bdf5297 | /CIT125_Ch.13_Fig_13-13/CIT125_Ch.13_Fig_13-13.cpp | 1e6accaf88daf50bfe0814ce3ade026c9040eb94 | [] | no_license | LuigiRobles/CIT125_Ch.13_Fig_13-13 | eea0aa31d4e2f5c0e49e7248c558f003cf4d218e | dfa244e9c077e097e734e18eaeba53ee3cfc701f | refs/heads/master | 2022-11-30T15:38:07.593246 | 2020-08-02T22:55:49 | 2020-08-02T22:55:49 | 284,556,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,678 | cpp | // CIT125 Intro To C++ Luigi Robles
// 08-01-2020 Summer Term
// Ch.13 pg.475 Fig.13-13 Zip Code Program
// Checks whether a ZIP code contains valid number of characters
// and whether each character is a number
#include <iostream>
#include <string>
using namespace std;
//function prototype
char verifyNumeric(string zip);
int main()
{
//declare and initialize variables
string zipCode = "";
char isAllNumbers = ' ';
cout << "Five-character ZIP code (-1 to end): ";
cin >> zipCode; //input for ZIP code
while (zipCode != "-1")
{
if (zipCode.length() == 5) //checking ZIP code for 5 characters
{
cout << "-->Correct number of characters";
isAllNumbers = verifyNumeric(zipCode);
if (isAllNumbers == 'Y')
cout << endl << "-->All numbers";
else
cout << endl << "-->Not all numbers";
//end if
}
else
cout << "-->Incorrect number of characters"; //False path for anything below 5 characters
//end if
cout << endl << endl;
cout << "Five-characters ZIP code (-1 to end): ";
cin >> zipCode; //continue with loop if -1 is not entered
} //end while
return 0;
} //end of main function
//******Function Definitions*****
char verifyNumeric(string zip)
{
//determine whether each character is a number
string currentChar = "";
int sub = 0; //character subscript
char isANumber = 'Y'; //assume all numbers
while (sub < 5 && isANumber == 'Y')
{
currentChar = zip.substr(sub, 1);
if (currentChar >= "0" && currentChar <= "9")
//character is numeric, so check next character
sub += 1;
else
//character is not a number
isANumber = 'N';
//end if
} //end while
return isANumber;
} //end of verifyNumeric function | [
"Luigi.robles0846@my.riohondo.edu"
] | Luigi.robles0846@my.riohondo.edu |
c69c2043865e13927ba8892068074461863cdc79 | 0e4d04d7fbedcd245d084d7296ca1b06d06de89e | /project/CardFour.h | 23e0a30f33c825482f7b8f968690f625f977e2be | [] | no_license | mennatallah-nawar/Snakes-and-ladders-game | fe314477c9953cb81abbb5530330be84f325bc06 | 8386b6e0c4564052b11eb0f4ffe1d7cc11cd4362 | refs/heads/master | 2023-05-15T18:23:15.584650 | 2021-06-13T23:02:06 | 2021-06-13T23:02:06 | 376,606,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | h | #pragma once
#include "Card.h"
class CardFour :public Card
{
Cell* pCell;
public:
CardFour(const CellPosition& pos); // A Constructor takes card position
virtual void Apply(Grid* pGrid, Player* pPlayer); // Applies the effect of CardOne on the passed Player
// by decrementing the player's wallet by the walletAmount data member
//virtual bool Validate();
virtual void CopyCard(Grid* pGrid);
virtual void CutCard(Grid* pGrid);
virtual void PasteCard(Grid* pGrid);
void Save(ofstream& OutFile, TYPE CARD);
void Read(ifstream& Infile);
~CardFour();
};
| [
"55787939+mennatallah-nawar@users.noreply.github.com"
] | 55787939+mennatallah-nawar@users.noreply.github.com |
4a0c6a3732cf0316f43b1a0b09332273bb89b381 | b9a83ad74c8864660cb2c13fd712f709f522848d | /include/Old_Junk/Matrix.h | 7461a817631510106338f29fde360efa06e339ec | [] | no_license | 95ellismle/Spin_Accumulation | 3e50c6522c7da9a445575aca2e43e6cbf384aaf1 | 4e259c694a515fa105d794703d7335682e9d17d5 | refs/heads/master | 2021-01-20T13:11:58.527151 | 2017-08-30T14:06:29 | 2017-08-30T14:06:29 | 101,739,809 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,148 | h | #ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include "correctors.h"
////////////////////////////////////////////////// SYSTEM SETUP PARAMETERS /////////////////////////////////////////////////////////////////////////
// Parameters affecting accuracy and the dimensions of the system // //
extern const double dx; // The space step (m) //
extern const double dt; // The time step (s) //
extern const double T; // The total time (s) //
extern const double L; // The total length (m) //
extern const double F1_Boundaries[2]; // Position of the first ferromagnetic layer //
extern const double F2_Boundaries[2]; // Position of the first ferromagnetic layer //
// //
// Material Properties. First in the array is the Magnet, the Second is in a non-magnet. //
//
extern const double DL; //
extern const double j_e; //
extern const double beta[2]; // The charge current polarisation //
extern const double beta_prime[2]; // The spin current polarisation //
extern const double lambda_sf[2]; // The spin flip length //
extern const double lambda_J[2]; // A damping coefficient (spin accumulation precession around Magnetisation) //
extern const double lambda_phi[2]; // Another damping coefficient (a dephasing lengthscale) //
extern const double D[2]; // Diffusivity 1st item is for the magnet and 2nd is for the non-magnet //
extern const double minf_magnitude; // The magnitude of the equilibrium spin accumlation vector //
// //
// The magnetisations of the layers //
// //
extern const double M1[3]; // F1 Magnetisation, this code will only work with an x and y magnetisation //
extern const double M2[3]; // F2 Magnetisation, this code will only work with an x and y magnetisation //
// //
// The Number of Time Steps to Save //
// //
extern unsigned int Saves; // F1 Magnetisation, this code will only work with an x and y magnetisation //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The lengths of the data storage containers and the number of iterations.
extern const unsigned int x_coords_len;
extern const unsigned int Iterations;
// The Positions of the Magnetic Layers in the Storage Containers.
extern const unsigned int F1_Boundaries_Indices[2];
extern const unsigned int F2_Boundaries_Indices[2];
// Constants to use later
extern const double fact1;
extern const double fact2;
extern const double fact3[2];
// Vectors
extern double Byy;
extern double Bzz;
extern double B1yz;
extern double B2yz;
extern std::vector<double> vec_beta;
extern std::vector<double> diff_beta;
extern std::vector<double> Sx;
extern std::vector<double> v;
extern std::vector<double> S2x;
extern std::vector<double> Cy;
extern std::vector<double> Cz;
extern std::vector<unsigned int> steps_to_save;
// Data Storage Containers
//
// The Save Vectors Save the number of time steps requested evenly spaced.
extern std::vector < std::vector < double > > Save_Ux;
extern std::vector < std::vector < double > > Save_Uy;
extern std::vector < std::vector < double > > Save_Uz;
//
// These Vectors are used in the calculations
extern std::vector<double> Uz;
extern std::vector<double> Uz_half;
extern std::vector<double> Uy;
extern std::vector<double> Uy_half;
extern std::vector<double> Ux;
// The A Matrix
extern std::vector<double> A;
// A function to recreate the A Matrix
void A_Refresher(std::vector<double> a, std::vector<double> b, std::vector<double> c, std::vector<double> L)
{
for (unsigned int i=3; i<(x_coords_len-1)*3;i+=3)
{
unsigned int x = (int) i/3;
A[i] = -a[x];
A[i+1] = 1+(2*b[x])+L[x];
A[i+2] = -c[x]+L[x];
}
A[0] = 0;
A[1] = 1;
A[2] = 0;
A[3*x_coords_len-1] = 0;
A[3*x_coords_len-2] = 1;
A[3*x_coords_len-3] = 0;
}
// A function to solve the Matrix equation
std::vector<double> Solver(std::vector<double> & input_array, int xyz)
{
std::vector <double> tmp_array (input_array);
if (xyz == 0)
{
for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + Z_NM_corrector(i);
}
for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + Z1_corrector(i);
}
for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + Z_NM_corrector(i);
}
for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + Z2_corrector(i);
}
for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++)
{
tmp_array[i] = tmp_array[i] + Z_NM_corrector(i);
}
}
else if (xyz == 1)
{
for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + Z_NM_corrector(i);
}
for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + Z1_half_corrector(i);
}
for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + Z_NM_corrector(i);
}
for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + Z2_half_corrector(i);
}
for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++)
{
tmp_array[i] = tmp_array[i] + Z_NM_corrector(i);
}
}
else if (xyz == 2)
{
for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + Y_NM_corrector(i);
}
for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + Y1_corrector(i);
}
for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + Y_NM_corrector(i);
}
for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + Y2_corrector(i);
}
for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++)
{
tmp_array[i] = tmp_array[i] + Y_NM_corrector(i);
}
}
else if (xyz == 3)
{
for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + Y_NM_corrector(i);
}
for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + Y1_half_corrector(i);
}
for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + Y_NM_corrector(i);
}
for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + Y2_half_corrector(i);
}
for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++)
{
tmp_array[i] = tmp_array[i] + Y_NM_corrector(i);
}
}
else if (xyz == 4)
{
for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + X_NM_corrector(i);
}
for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + X1_corrector(i);
}
for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + X_NM_corrector(i);
}
for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + X2_corrector(i);
}
for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++)
{
tmp_array[i] = tmp_array[i] + X_NM_corrector(i);
}
}
else if (xyz == 5)
{
for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + X_NM_corrector(i);
}
for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + X1_half_corrector(i);
}
for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++)
{
tmp_array[i] = tmp_array[i] + X_NM_corrector(i);
}
for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++)
{
tmp_array[i] = tmp_array[i] + X2_half_corrector(i);
}
for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++)
{
tmp_array[i] = tmp_array[i] + X_NM_corrector(i);
}
}
int counter = 1;
for(unsigned int i=3; i<3*(x_coords_len-1);i+=3)
{
double mul = A[i]/A[i-2];
double new_value = (double) tmp_array[counter] - tmp_array[counter-1]*mul;
tmp_array[counter] = new_value;
A[i+1] = A[i+1] - A[i-1]*mul;
A[i] = A[i] - A[i-2]*mul;
counter++;
}
counter = x_coords_len-1;
for(int i=3*(x_coords_len-1); i>3; i-=3)
{
double mul = A[i-1]/A[i+1];
double new_value = (double) tmp_array[counter-1] - tmp_array[counter]*mul;
tmp_array[counter-1] = new_value;
A[i-1] = A[i-1] - A[i+1]*mul;
counter--;
}
for(unsigned int i=1; i<x_coords_len-1; i++)
{
double new_value = (double) tmp_array[i]/A[3*i+1];
tmp_array[i] = new_value;
}
//Neumann (floating) boundary conditions
tmp_array[0] = tmp_array[1] - (tmp_array[2]-tmp_array[1])/2.718;
tmp_array[x_coords_len-1] = tmp_array[x_coords_len-2]-(tmp_array[x_coords_len-3]-tmp_array[x_coords_len-2])/2.718;
return tmp_array;
}
#endif
| [
"95ellismle@gmail.com"
] | 95ellismle@gmail.com |
75327733cd670cec55bafd616332a7285b667b78 | 9aca1f5d7bc86908a1d3e4b3795264bfe9df5a9d | /interval_map.cpp | 618104f85ecce94e60ca746aad603afd051da399 | [] | no_license | conin/Version | 26c1e7003b8ed0fe7c2cced218832667b2f0a500 | 5ba0bf1aacf6ee96edad85e47cdf5ac617f76e15 | refs/heads/master | 2021-01-01T04:18:33.176738 | 2017-10-22T17:39:35 | 2017-10-22T17:39:35 | 58,603,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,488 | cpp | #include <assert.h>
#include <map>
#include <limits>
#include<iostream>
template<class K, class V>
class interval_map
{
friend void IntervalMapTest();
private:
std::map<K,V> m_map;
public:
interval_map( V const& val)
{
m_map.insert(m_map.begin(),std::make_pair(std::numeric_limits<K>::lowest(),val));
}
void assign(K const& keyBegin, K const& keyEnd, V const& val)
{
// INSERT YOUR SOLUTION HERE
int size = (int)(keyEnd - keyBegin);//It defines (key,val)pairs have to be inserted/updated
if (size <= 0)
{
//do nothing
}
else
{
typename std::map<K, V>::iterator it = m_map.begin();//iterator to parse map
bool found = false; //if value is found then set this to true
while (it != m_map.end())
{
if (it->second == val)
{
//remove this and insert from beginning.
//We cannot override key values(const)
m_map.erase(it);
found = true;
break;
}
it++;
}
if (found)
{
K key = keyBegin; //start key value since we can't update const variable
while (size > 0)
{
//insert new (key,value) pair
m_map[key] = val;
key++;
size--;
}
}
}
}
V const& operator[]( K const& key ) const
{
return ( --m_map.upper_bound(key) )->second;
}
};
void IntervalMapTest()
{
}
int main()
{
IntervalMapTest();
interval_map<float, double> m_interval(5.3242);
m_interval.assign(95.0f, 195.0f, 5.3242);
} | [
"noreply@github.com"
] | conin.noreply@github.com |
5a5870d5bb0790aad3211bc30014287392e1f14f | 97876f53d0f943095aad81ff1861daf98e2bd46c | /practice/AOJ/ALDS1/ALDS1_5_D.cc | b29758295cc413c81cf87b84cd81d85897e11a56 | [] | no_license | aita/cpp-junks | 7f7c4dad596605f25a83ee36e1898a8c839ad237 | 2a3efe9b63d7dcb926aa4f51a09417c2d031f42b | refs/heads/main | 2023-03-09T03:33:18.901666 | 2021-02-21T05:50:00 | 2021-02-21T05:50:00 | 328,188,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,163 | cc | #include <vector>
#include <iostream>
using namespace std;
using long64 = long long int;
using int_vec = vector<long64>;
long64 inversion = 0;
void merge(int_vec& v, int_vec& left, int_vec& right) {
auto it = v.begin();
auto l = left.begin();
auto r = right.begin();
auto n = left.size();
while (l != left.end() && r != right.end()) {
if (*l <= *r) {
*it++ = *l++;
--n;
} else {
*it++ = *r++;
inversion += n;
}
}
if (l != left.end()) {
copy(l, left.end(), it);
} else {
copy(r, right.end(), it);
}
return;
}
void merge_sort(int_vec& v) {
if (v.size() < 2) {
return;
}
auto mid = v.begin() + distance(v.begin(), v.end()) / 2;
auto left = int_vec(v.begin(), mid);
auto right = int_vec(mid, v.end());
merge_sort(left);
merge_sort(right);
merge(v, left, right);
return;
}
int main() {
int n;
cin >> n;
int_vec v;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
v.push_back(x);
}
merge_sort(v);
cout << inversion << endl;
return 0;
} | [
"792803+aita@users.noreply.github.com"
] | 792803+aita@users.noreply.github.com |
77969f4c70ca56aa199d5957ab3d793bdabf46fc | a1cc22bafb4429b53898962b1131333420eddf05 | /cmdstan/stan/lib/stan_math/test/unit/math/rev/meta/VectorBuilderHelper_test.cpp | ac845bbfe35ce5555226d59d779a212b8c5f71f3 | [
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"Apache-2.0",
"BSD-3-Clause",
"GPL-3.0-only"
] | permissive | metrumresearchgroup/Torsten | d9510b00242b9f77cdc989657a4956b3018a5f3a | 0168482d400e4b819acadbc28cc817dd1a037c1b | refs/heads/master | 2023-09-01T17:44:46.020886 | 2022-05-18T22:46:35 | 2022-05-18T22:46:35 | 124,574,336 | 50 | 18 | BSD-3-Clause | 2023-09-09T06:32:36 | 2018-03-09T17:48:27 | C++ | UTF-8 | C++ | false | false | 3,134 | cpp | #include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <gtest/gtest.h>
#include <vector>
TEST(MetaTraitsRevScal, VectorBuilderHelper_false_true) {
using stan::VectorBuilderHelper;
using stan::math::size;
using stan::math::var;
var a_var(1);
VectorBuilderHelper<double, false, true> dvv1(size(a_var));
EXPECT_THROW(dvv1[0], std::logic_error);
EXPECT_THROW(dvv1.data(), std::logic_error);
}
TEST(MetaTraitsRevArr, VectorBuilderHelper_false_true) {
using stan::VectorBuilderHelper;
using stan::math::size;
using stan::math::var;
using std::vector;
std::vector<var> a_std_vector(3);
VectorBuilderHelper<double, false, true> dvv2(size(a_std_vector));
EXPECT_THROW(dvv2[0], std::logic_error);
EXPECT_THROW(dvv2.data(), std::logic_error);
}
TEST(MetaTraitsRevArr, VectorBuilderHelper_true_true) {
using stan::VectorBuilderHelper;
using stan::math::size;
using stan::math::var;
using std::vector;
var a_var(1);
std::vector<var> a_std_vector(3);
VectorBuilderHelper<double, true, true> dvv1(size(a_var));
dvv1[0] = 0.0;
EXPECT_FLOAT_EQ(0.0, dvv1[0]);
std::vector<double> data1;
EXPECT_NO_THROW(data1 = dvv1.data());
EXPECT_EQ(size(a_var), data1.size());
VectorBuilderHelper<double, true, true> dvv2(size(a_std_vector));
dvv2[0] = 0.0;
dvv2[1] = 1.0;
dvv2[2] = 2.0;
EXPECT_FLOAT_EQ(0.0, dvv2[0]);
EXPECT_FLOAT_EQ(1.0, dvv2[1]);
EXPECT_FLOAT_EQ(2.0, dvv2[2]);
std::vector<double> data2;
EXPECT_NO_THROW(data2 = dvv2.data());
EXPECT_EQ(size(a_std_vector), data2.size());
}
TEST(MetaTraitsRevMat, VectorBuilderHelper_false_true) {
using Eigen::Dynamic;
using Eigen::Matrix;
using stan::VectorBuilderHelper;
using stan::math::size;
using stan::math::var;
Matrix<var, Dynamic, 1> a_vector(4);
Matrix<var, 1, Dynamic> a_row_vector(5);
VectorBuilderHelper<double, false, true> dvv3(size(a_vector));
EXPECT_THROW(dvv3[0], std::logic_error);
EXPECT_THROW(dvv3.data(), std::logic_error);
VectorBuilderHelper<double, false, true> dvv4(size(a_row_vector));
EXPECT_THROW(dvv4[0], std::logic_error);
EXPECT_THROW(dvv3.data(), std::logic_error);
}
TEST(MetaTraitsRevMat, VectorBuilderHelper_true_true) {
using Eigen::Dynamic;
using Eigen::Matrix;
using stan::VectorBuilderHelper;
using stan::math::size;
using stan::math::var;
Matrix<var, Dynamic, 1> a_vector(4);
Matrix<var, 1, Dynamic> a_row_vector(5);
VectorBuilderHelper<double, true, true> dvv3(size(a_vector));
dvv3[0] = 0.0;
dvv3[1] = 1.0;
dvv3[2] = 2.0;
EXPECT_FLOAT_EQ(0.0, dvv3[0]);
EXPECT_FLOAT_EQ(1.0, dvv3[1]);
EXPECT_FLOAT_EQ(2.0, dvv3[2]);
std::vector<double> data3;
EXPECT_NO_THROW(data3 = dvv3.data());
EXPECT_EQ(size(a_vector), data3.size());
VectorBuilderHelper<double, true, true> dvv4(size(a_row_vector));
dvv4[0] = 0.0;
dvv4[1] = 1.0;
dvv4[2] = 2.0;
EXPECT_FLOAT_EQ(0.0, dvv4[0]);
EXPECT_FLOAT_EQ(1.0, dvv4[1]);
EXPECT_FLOAT_EQ(2.0, dvv4[2]);
std::vector<double> data4;
EXPECT_NO_THROW(data4 = dvv4.data());
EXPECT_EQ(size(a_row_vector), data4.size());
}
| [
"yzhang@c-path.org"
] | yzhang@c-path.org |
1bdb1c450e69ee01ca9d19295b1a1deb7d8973a4 | 5c6a0e9ae96f04b0f269d24bfc838d075b1190d1 | /TouchDemo/object/buttons/mechButtons/SwitchButtonHandler.h | a2a2691e35665ba70fc5d204f6cd3ae8b5523662 | [] | no_license | EvdochukArtem/TouchDemo | 192cc0aae85c82a12930811e03bfe89564faba27 | 5f5fa616cf7b2b994d2e878d580c1eae14113cca | refs/heads/master | 2021-05-21T06:41:02.271198 | 2021-03-31T12:58:47 | 2021-03-31T12:58:47 | 252,588,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | h | #pragma once
#include "SwitchButton.h"
class CSwitchButtonHandler
{
public:
CSwitchButtonHandler() {};
~CSwitchButtonHandler() {};
static void CALLBACK OnSwitchButtonPress(MOUSE_EVNT bEvent, CSwitchButton* btn);
}; | [
"evdochukartem@gmail.com"
] | evdochukartem@gmail.com |
30cd76f92ec36bd75dd9255b6e3e0e45dad7d6b7 | 524dd1a8e629da15699a0b80a2d700579f141713 | /20-Constructer_Overloading.cpp | 98bc59bb6b64a86fe5104c51d5f5543aa5fb386a | [] | no_license | Shakti-chaudhary/Cpp-Learn-Code-with-harry- | 9dc1766c699f196b655516684b7e1f12324a8f61 | 03d2e3144e72268862f10132807a8114441ad109 | refs/heads/master | 2023-06-03T09:43:22.628283 | 2021-06-29T04:16:51 | 2021-06-29T04:16:51 | 375,919,058 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 629 | cpp | #include <iostream>
using namespace std;
class complex
{
int a;
int b;
public:
void printdata() { cout << "The no is : " << a << " and +i : " << b << endl; }
complex(); /* ***************** Constructer Overloading ********************** */
complex(int x);
complex(int x, int y);
};
complex::complex(){
int a=0;
int b=0;
}
complex::complex(int x){a=x;b=0;} /* Constructer with default Arguments */
complex::complex(int x,int y){a=x;b=y;}
int main()
{
complex A;
complex B(5);
complex C(13, 32);
A.printdata();
B.printdata();
C.printdata();
return 0;
} | [
"shaktichaudhary4321@gmail.com"
] | shaktichaudhary4321@gmail.com |
d0af6888d29b2e61e16cc19a51e7585b39ea1648 | c03b1c7da6b5b44681fda3bc3d06dc194eff0fdd | /example/Classes/HelloWorldScene.cpp | bab99ebfb1e5d603d886b0ad88a27191ac1609c3 | [
"MIT"
] | permissive | adjust/cocos2dx_sdk | 190b57a04ed46459ca9bac4e2ebcbb5f17656faf | 8189ea0515fb33c40eef5f69cf9147f726605d1c | refs/heads/master | 2023-08-01T00:13:58.449498 | 2022-10-20T10:46:49 | 2022-10-20T10:46:49 | 37,716,849 | 11 | 12 | MIT | 2022-10-20T10:46:51 | 2015-06-19T10:48:57 | C++ | UTF-8 | C++ | false | false | 8,274 | cpp | #include <platform/CCApplication.h>
#include "HelloWorldScene.h"
#include "AppDelegate.h"
#include "Adjust/Adjust2dx.h"
#include "Adjust/AdjustEvent2dx.h"
USING_NS_CC;
Scene *HelloWorld::createScene() {
return HelloWorld::create();
}
// on "init" you need to initialize your instance
bool HelloWorld::init() {
//////////////////////////////
// 1. super init first
if (!Scene::init()) {
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
// Create a Label to identify the sample
auto label = Label::create();
label->setString("Adjust Cocos2dx Examples app");
label->setSystemFontSize(19);
label->setTextColor(Color4B::BLUE);
// position the label on the center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height));
// add the label as a child to this layer
this->addChild(label, 1);
/////////////////////////////
// 3. add main menu
auto mainmenu = Menu::create();
int index = 2;
int offset = 35;
int divide = 20;
// Track Event
auto position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Track Event", position,
CC_CALLBACK_1(HelloWorld::onTrackEvent, this));
// Track Revenue Event
position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Track Revenue Event", position,
CC_CALLBACK_1(HelloWorld::onTrackRevenueEvent, this));
// Track Callback Event
position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Track Callback Event", position,
CC_CALLBACK_1(HelloWorld::onTrackCallbackEvent, this));
// Track Partner Event
position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Track Partner Event", position,
CC_CALLBACK_1(HelloWorld::onTrackPartnerEvent, this));
// Enable offline mode
position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Enable Offline Mode", position,
CC_CALLBACK_1(HelloWorld::onEnableOfflineMode, this));
// Disable offline mode
position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Disable Offline Mode", position,
CC_CALLBACK_1(HelloWorld::onDisableOfflineMode, this));
// Enable SDK
position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Enable SDK", position, CC_CALLBACK_1(HelloWorld::onEnableSdk, this));
// Disable SDK
position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Disable SDK", position, CC_CALLBACK_1(HelloWorld::onDisableSdk, this));
// is Sdk Enabled
position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Is SDK Enabled?", position,
CC_CALLBACK_1(HelloWorld::onIsSdkEnabled, this));
// Send Push Token
position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Send Push Token", position,
CC_CALLBACK_1(HelloWorld::onSendPushToken, this));
// Get IDs
position =
Vec2(origin.x + visibleSize.width / 2,
origin.y + visibleSize.height - label->getContentSize().height
+ offset
- divide * (++index));
makeButton(mainmenu, "Get IDs", position, CC_CALLBACK_1(HelloWorld::onGetIds, this));
// Add main menu to screen
mainmenu->setPosition(Vec2::ZERO);
this->addChild(mainmenu, 1);
return true;
}
void HelloWorld::makeButton(Menu *menu, std::string title, Vec2 position,
const ccMenuCallback &callback) {
auto itemlabel = Label::create();
itemlabel->setString(title);
itemlabel->setSystemFontSize(15);
auto menuItem = MenuItemLabel::create(itemlabel);
menuItem->setCallback(callback);
menuItem->setPosition(position);
menu->addChild(menuItem, 2);
}
void HelloWorld::onTrackEvent(cocos2d::Ref *pSender) {
auto adjustEvent = AdjustEvent2dx("g3mfiw");
Adjust2dx::trackEvent(adjustEvent);
}
void HelloWorld::onTrackRevenueEvent(cocos2d::Ref *pSender) {
auto adjustEvent = AdjustEvent2dx("a4fd35");
adjustEvent.setRevenue(10.0, "USD");
adjustEvent.setTransactionId("DUMMY_TRANSACTION_ID");
Adjust2dx::trackEvent(adjustEvent);
}
void HelloWorld::onTrackCallbackEvent(cocos2d::Ref *pSender) {
auto adjustEvent = AdjustEvent2dx("34vgg9");
adjustEvent.addCallbackParameter("DUMMY_KEY_1", "DUMMY_VALUE_1");
adjustEvent.addCallbackParameter("DUMMY_KEY_2", "DUMMY_VALUE_2");
Adjust2dx::trackEvent(adjustEvent);
}
void HelloWorld::onTrackPartnerEvent(cocos2d::Ref *pSender) {
auto adjustEvent = AdjustEvent2dx("w788qs");
adjustEvent.addPartnerParameter("DUMMY_KEY_1", "DUMMY_VALUE_1");
adjustEvent.addPartnerParameter("DUMMY_KEY_2", "DUMMY_VALUE_2");
Adjust2dx::trackEvent(adjustEvent);
}
void HelloWorld::onEnableOfflineMode(cocos2d::Ref *pSender) {
Adjust2dx::setOfflineMode(true);
}
void HelloWorld::onDisableOfflineMode(cocos2d::Ref *pSender) {
Adjust2dx::setOfflineMode(false);
}
void HelloWorld::onEnableSdk(cocos2d::Ref *pSender) {
Adjust2dx::setEnabled(true);
}
void HelloWorld::onDisableSdk(cocos2d::Ref *pSender) {
Adjust2dx::setEnabled(false);
}
void HelloWorld::onIsSdkEnabled(cocos2d::Ref *pSender) {
if (Adjust2dx::isEnabled()) {
CCLOG(">>> SDK is enabled");
} else {
CCLOG(">>> SDK is disabled");
}
}
void HelloWorld::onSendPushToken(cocos2d::Ref *pSender) {
Adjust2dx::setDeviceToken("bunny_foo_foo");
}
void HelloWorld::onGetIds(cocos2d::Ref *pSender) {
CCLOG(">>> Adid = %s", Adjust2dx::getAdid().c_str());
Adjust2dx::getGoogleAdId([](std::string adId) {
CCLOG(">>> Google Ad Id = %s", adId.c_str());
});
CCLOG(">>> Amazon Ad Id = %s", Adjust2dx::getAmazonAdId().c_str());
CCLOG(">>> Get IDFA = %s", Adjust2dx::getIdfa().c_str());
auto attribution = Adjust2dx::getAttribution();
CCLOG(">>> Attribution:");
CCLOG("Tracker token = %s", attribution.getTrackerToken().c_str());
CCLOG("Tracker name = %s", attribution.getTrackerName().c_str());
CCLOG("Network = %s", attribution.getNetwork().c_str());
CCLOG("Campaign = %s", attribution.getCampaign().c_str());
CCLOG("Adgroup = %s", attribution.getAdgroup().c_str());
CCLOG("Creative = %s", attribution.getCreative().c_str());
CCLOG("Click label = %s", attribution.getClickLabel().c_str());
CCLOG("Adid = %s", attribution.getAdid().c_str());
}
| [
"ugi@adjust.com"
] | ugi@adjust.com |
eb7b65657cf2c71cfca6d79f1a7ac8fb7ab332e9 | 8adec48dfaee1cdfd6c7f4d2fb3038aa1c17bda6 | /WProf/src/chrome/browser/protector/protector_service.cc | aa16f7f9329aa4111b249638fab579629f07932e | [
"BSD-3-Clause"
] | permissive | kusoof/wprof | ef507cfa92b3fd0f664d0eefef7fc7d6cd69481e | 8511e9d4339d3d6fad5e14ad7fff73dfbd96beb8 | refs/heads/master | 2021-01-11T00:52:51.152225 | 2016-12-10T23:51:14 | 2016-12-10T23:51:14 | 70,486,057 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,657 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/protector/protector_service.h"
#include "base/logging.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/protector/composite_settings_change.h"
#include "chrome/browser/protector/keys.h"
#include "chrome/browser/protector/protected_prefs_watcher.h"
#include "chrome/browser/protector/protector_utils.h"
#include "chrome/browser/protector/settings_change_global_error.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/notification_source.h"
#include "net/base/registry_controlled_domain.h"
namespace protector {
namespace {
// Returns true if changes with URLs |url1| and |url2| can be merged.
bool CanMerge(const GURL& url1, const GURL& url2) {
VLOG(1) << "Checking if can merge " << url1.spec() << " with " << url2.spec();
// All Google URLs are considered the same one.
if (google_util::IsGoogleHostname(url1.host(),
google_util::DISALLOW_SUBDOMAIN)) {
return google_util::IsGoogleHostname(url2.host(),
google_util::DISALLOW_SUBDOMAIN);
}
// Otherwise URLs must have the same domain.
return net::RegistryControlledDomainService::SameDomainOrHost(url1, url2);
}
} // namespace
ProtectorService::ProtectorService(Profile* profile)
: profile_(profile),
has_active_change_(false) {
// Start observing pref changes.
prefs_watcher_.reset(new ProtectedPrefsWatcher(profile));
}
ProtectorService::~ProtectorService() {
DCHECK(!IsShowingChange()); // Should have been dismissed by Shutdown.
}
void ProtectorService::ShowChange(BaseSettingChange* change) {
DCHECK(change);
// Change instance will either be owned by |this| or deleted after this call.
scoped_ptr<BaseSettingChange> change_ptr(change);
DVLOG(1) << "Init change";
if (!protector::IsEnabled()) {
change_ptr->InitWhenDisabled(profile_);
return;
} else if (!change_ptr->Init(profile_)) {
LOG(WARNING) << "Error while initializing, dismissing change";
return;
}
Item* item_to_merge_with = FindItemToMergeWith(change_ptr.get());
if (item_to_merge_with) {
// CompositeSettingsChange takes ownership of merged changes.
BaseSettingChange* existing_change = item_to_merge_with->change.release();
CompositeSettingsChange* merged_change =
existing_change->MergeWith(change_ptr.release());
item_to_merge_with->change.reset(merged_change);
item_to_merge_with->was_merged = true;
if (item_to_merge_with->error->GetBubbleView())
item_to_merge_with->show_when_merged = true;
// Remove old GlobalError instance. Later in OnRemovedFromProfile() a new
// GlobalError instance will be created for the composite change.
item_to_merge_with->error->RemoveFromProfile();
} else if (change->IsUserVisible()) {
Item new_item;
SettingsChangeGlobalError* error =
new SettingsChangeGlobalError(change_ptr.get(), this);
new_item.error.reset(error);
new_item.change.reset(change_ptr.release());
items_.push_back(new_item);
// Do not show the bubble immediately if another one is active.
error->AddToProfile(profile_, !has_active_change_);
has_active_change_ = true;
} else {
VLOG(1) << "Not showing a change because it's not user-visible.";
}
}
bool ProtectorService::IsShowingChange() const {
return !items_.empty();
}
void ProtectorService::ApplyChange(BaseSettingChange* change,
Browser* browser) {
change->Apply(browser);
DismissChange(change);
}
void ProtectorService::DiscardChange(BaseSettingChange* change,
Browser* browser) {
change->Discard(browser);
DismissChange(change);
}
void ProtectorService::DismissChange(BaseSettingChange* change) {
Items::iterator item = std::find_if(items_.begin(), items_.end(),
MatchItemByChange(change));
DCHECK(item != items_.end());
item->error->RemoveFromProfile();
}
void ProtectorService::OpenTab(const GURL& url, Browser* browser) {
DCHECK(browser);
chrome::ShowSingletonTab(browser, url);
}
ProtectedPrefsWatcher* ProtectorService::GetPrefsWatcher() {
return prefs_watcher_.get();
}
void ProtectorService::StopWatchingPrefsForTesting() {
prefs_watcher_.reset();
}
ProtectorService::Item* ProtectorService::FindItemToMergeWith(
const BaseSettingChange* change) {
if (!change->CanBeMerged())
return NULL;
GURL url = change->GetNewSettingURL();
for (Items::iterator item = items_.begin(); item != items_.end(); item++) {
if (item->change->CanBeMerged() &&
CanMerge(url, item->change->GetNewSettingURL()))
return &*item;
}
return NULL;
}
void ProtectorService::Shutdown() {
while (IsShowingChange())
items_[0].error->RemoveFromProfile();
}
void ProtectorService::OnApplyChange(SettingsChangeGlobalError* error,
Browser* browser) {
DVLOG(1) << "Apply change";
error->change()->Apply(browser);
has_active_change_ = false;
}
void ProtectorService::OnDiscardChange(SettingsChangeGlobalError* error,
Browser* browser) {
DVLOG(1) << "Discard change";
error->change()->Discard(browser);
has_active_change_ = false;
}
void ProtectorService::OnDecisionTimeout(SettingsChangeGlobalError* error) {
DVLOG(1) << "Timeout";
error->change()->Timeout();
}
void ProtectorService::OnRemovedFromProfile(SettingsChangeGlobalError* error) {
Items::iterator item = std::find_if(items_.begin(), items_.end(),
MatchItemByError(error));
DCHECK(item != items_.end());
if (item->was_merged) {
bool show_new_error = !has_active_change_ || item->show_when_merged;
item->was_merged = false;
item->show_when_merged = false;
// Item was merged with another change instance and error has been removed,
// create a new one for the composite change.
item->error.reset(new SettingsChangeGlobalError(item->change.get(), this));
item->error->AddToProfile(profile_, show_new_error);
has_active_change_ = true;
return;
}
items_.erase(item);
// If no other change is shown and there are changes that haven't been shown
// yet, show the first one.
if (!has_active_change_) {
for (item = items_.begin(); item != items_.end(); ++item) {
if (!item->error->HasShownBubbleView()) {
item->error->ShowBubble();
has_active_change_ = true;
return;
}
}
}
}
BaseSettingChange* ProtectorService::GetLastChange() {
return items_.empty() ? NULL : items_.back().change.get();
}
ProtectorService::Item::Item()
: was_merged(false),
show_when_merged(false) {
}
ProtectorService::Item::~Item() {
}
ProtectorService::MatchItemByChange::MatchItemByChange(
const BaseSettingChange* other) : other_(other) {
}
bool ProtectorService::MatchItemByChange::operator()(
const ProtectorService::Item& item) {
return item.change->Contains(other_);
}
ProtectorService::MatchItemByError::MatchItemByError(
const SettingsChangeGlobalError* other) : other_(other) {
}
bool ProtectorService::MatchItemByError::operator()(
const ProtectorService::Item& item) {
return other_ == item.error.get();
}
} // namespace protector
| [
"kusoof@kookaburra.(none)"
] | kusoof@kookaburra.(none) |
1055e773373fb34198642a8095e6aa6b01e60eac | fed36be2b78410eb5191417b61ba8142d5576ac2 | /mixtureModelCPU/readData.cpp | 244cef4ca5e3f1577ca8469a35558361588d32f0 | [] | no_license | cyberaide/biostatistics | 68bd25a1edaf458b9795f4059c93f7fa56018f11 | 86b8dd1a469b222eee09a13bbdc3de4a5f795633 | refs/heads/master | 2016-09-15T22:13:40.528403 | 2013-02-08T11:27:25 | 2013-02-08T11:27:25 | 4,278,883 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,571 | cpp | /*
* readData.cpp
*
* Created on: Nov 4, 2008
* Author: Doug Roberts
* Modified by: Andrew Pangborn
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
extern "C"
float* readData(char* f, int* ndims, int* nevents);
float* readBIN(char* f, int* ndims, int* nevents);
float* readCSV(char* f, int* ndims, int* nevents);
float* readData(char* f, int* ndims, int* nevents) {
int length = strlen(f);
printf("File Extension: %s\n",f+length-3);
if(strcmp(f+length-3,"bin") == 0) {
return readBIN(f,ndims,nevents);
} else {
return readCSV(f,ndims,nevents);
}
}
float* readBIN(char* f, int* ndims, int* nevents) {
FILE* fin = fopen(f,"rb");
fread(nevents,4,1,fin);
fread(ndims,4,1,fin);
printf("Number of elements removed for memory alignment: %d\n",*nevents % (16 * 2));
*nevents -= *nevents % (16 * 2) ; // 2 gpus
int num_elements = (*ndims)*(*nevents);
printf("Number of rows: %d\n",*nevents);
printf("Number of cols: %d\n",*ndims);
float* data = (float*) malloc(sizeof(float)*num_elements);
fread(data,sizeof(float),num_elements,fin);
fclose(fin);
return data;
}
float* readCSV(char* f, int* ndims, int* nevents) {
string line1;
ifstream file(f);
vector<string> lines;
int num_dims = 0;
char* temp;
float* data;
if (file.is_open()) {
while(!file.eof()) {
getline(file, line1);
if (!line1.empty()) {
lines.push_back(line1);
}
}
file.close();
}
else {
cout << "Unable to read the file " << f << endl;
return NULL;
}
if(lines.size() > 0) {
line1 = lines[0];
string line2 (line1.begin(), line1.end());
temp = strtok((char*)line1.c_str(), ",");
while(temp != NULL) {
num_dims++;
temp = strtok(NULL, ",");
}
lines.erase(lines.begin()); // Remove first line, assumed to be header
int num_events = (int)lines.size();
//int pad_size = 64 - (num_events % 64);
//if(pad_size == 64) pad_size = 0;
//pad_size = 0;
//printf("Number of events in input file: %d\n",num_events);
//printf("Number of padding events added for alignment: %d\n",pad_size);
printf("Number of events removed to ensure memory alignment %d\n",num_events % (16 * 2));
num_events -= num_events % (16 * 2);
// Allocate space for all the FCS data
data = (float*)malloc(sizeof(float) * num_dims * (num_events));
if(!data){
printf("Cannot allocate enough memory for FCS data.\n");
return NULL;
}
for (int i = 0; i < num_events; i++) {
temp = strtok((char*)lines[i].c_str(), ",");
for (int j = 0; j < num_dims; j++) {
if(temp == NULL) {
free(data);
return NULL;
}
data[i * num_dims + j] = atof(temp);
temp = strtok(NULL, ",");
}
}
//for(int i = num_events; i < num_events+pad_size; i++) {
// for(int j = 0; j < num_dims; j++) {
// data[i * num_dims + j] = 0.0f;
// }
//}
//num_events += pad_size;
*ndims = num_dims;
*nevents = num_events;
return data;
} else {
return NULL;
}
}
| [
"apangborn@6884be23-2c2a-0410-b59a-f50d4d03ee1a"
] | apangborn@6884be23-2c2a-0410-b59a-f50d4d03ee1a |
ad79e11b5f0cc9ad7258b4deacf8e4eeb1b610c4 | f0a26ec6b779e86a62deaf3f405b7a83868bc743 | /Engine/Source/Editor/GraphEditor/Private/KismetNodes/SGraphNodeK2Base.cpp | 589afd53c93423f2d237060fb92b99ea6c6078d6 | [] | no_license | Tigrouzen/UnrealEngine-4 | 0f15a56176439aef787b29d7c80e13bfe5c89237 | f81fe535e53ac69602bb62c5857bcdd6e9a245ed | refs/heads/master | 2021-01-15T13:29:57.883294 | 2014-03-20T15:12:46 | 2014-03-20T15:12:46 | 18,375,899 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,675 | cpp | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#include "GraphEditorCommon.h"
#include "SGraphNodeK2Base.h"
#include "Editor/UnrealEd/Public/Kismet2/KismetDebugUtilities.h"
#include "Editor/UnrealEd/Public/Kismet2/BlueprintEditorUtils.h"
#include "KismetNodeInfoContext.h"
#include "IDocumentation.h"
#define LOCTEXT_NAMESPACE "SGraphNodeK2Base"
//////////////////////////////////////////////////////////////////////////
// SGraphNodeK2Base
const FLinearColor SGraphNodeK2Base::BreakpointHitColor(0.7f, 0.0f, 0.0f);
const FLinearColor SGraphNodeK2Base::LatentBubbleColor(1.f, 0.5f, 0.25f);
const FLinearColor SGraphNodeK2Base::TimelineBubbleColor(0.7f, 0.5f, 0.5f);
const FLinearColor SGraphNodeK2Base::PinnedWatchColor(0.7f, 0.5f, 0.5f);
void SGraphNodeK2Base::UpdateStandardNode()
{
SGraphNode::UpdateGraphNode();
// clear the default tooltip, to make room for our custom "complex" tooltip
SetToolTip(NULL);
}
void SGraphNodeK2Base::UpdateCompactNode()
{
InputPins.Empty();
OutputPins.Empty();
// error handling set-up
TSharedPtr<SWidget> ErrorText = SetupErrorReporting();
// Reset variables that are going to be exposed, in case we are refreshing an already setup node.
RightNodeBox.Reset();
LeftNodeBox.Reset();
TSharedPtr< SToolTip > NodeToolTip = SNew( SToolTip );
if ( !GraphNode->GetTooltip().IsEmpty() )
{
NodeToolTip = IDocumentation::Get()->CreateToolTip( TAttribute< FText >( this, &SGraphNode::GetNodeTooltip ), NULL, GraphNode->GetDocumentationLink(), GraphNode->GetDocumentationExcerptName() );
}
//
// ______________________
// | (>) L | | R (>) |
// | (>) E | | I (>) |
// | (>) F | + | G (>) |
// | (>) T | | H (>) |
// | | | T (>) |
// |_______|______|_______|
//
this->ContentScale.Bind( this, &SGraphNode::GetContentScale );
this->ChildSlot
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SVerticalBox)
+SVerticalBox::Slot()
.AutoHeight()
.Padding( FMargin(5.0f, 1.0f) )
[
ErrorText->AsShared()
]
+SVerticalBox::Slot()
[
// NODE CONTENT AREA
SNew(SOverlay)
.ToolTip( NodeToolTip.ToSharedRef() )
+SOverlay::Slot()
[
SNew(SImage)
.Image( FEditorStyle::GetBrush("Graph.CompactNode.Body") )
]
+SOverlay::Slot()
.HAlign(HAlign_Center)
// Pad out so that the node circles do not
// overlap the background text.
.Padding( FMargin(23,0) )
[
// MIDDLE
SNew(STextBlock)
.TextStyle( FEditorStyle::Get(), "Graph.CompactNode.Title" )
.Text( this, &SGraphNodeK2Base::GetNodeCompactTitle )
]
+SOverlay::Slot()
.Padding( FMargin(0,3) )
[
SNew(SHorizontalBox)
+SHorizontalBox::Slot()
.Padding( FMargin(0,0,5,0) )
.HAlign(HAlign_Left)
.VAlign(VAlign_Center)
.FillWidth(1.0f)
[
// LEFT
SAssignNew(LeftNodeBox, SVerticalBox)
]
+SHorizontalBox::Slot()
.AutoWidth()
.Padding( FMargin(5,0,0,0) )
.HAlign(HAlign_Right)
.VAlign(VAlign_Center)
[
// RIGHT
SAssignNew(RightNodeBox, SVerticalBox)
]
]
]
];
CreatePinWidgets();
// Hide pin labels
for (int32 PinIndex=0; PinIndex < this->InputPins.Num(); ++PinIndex)
{
InputPins[PinIndex]->SetShowLabel(false);
}
for (int32 PinIndex = 0; PinIndex < this->OutputPins.Num(); ++PinIndex)
{
OutputPins[PinIndex]->SetShowLabel(false);
}
}
TSharedPtr<SToolTip> SGraphNodeK2Base::GetComplexTooltip()
{
TSharedPtr<SToolTip> NodeToolTip;
TSharedRef<SToolTip> DefaultToolTip = IDocumentation::Get()->CreateToolTip(TAttribute<FText>(this, &SGraphNode::GetNodeTooltip), NULL, GraphNode->GetDocumentationLink(), GraphNode->GetDocumentationExcerptName());
struct LocalUtils
{
static EVisibility IsToolTipVisible(TSharedRef<SGraphNodeK2Base> const NodeWidget)
{
return NodeWidget->GetNodeTooltip().IsEmpty() ? EVisibility::Collapsed : EVisibility::Visible;
}
static EVisibility IsToolTipHeadingVisible(TSharedRef<SGraphNodeK2Base> const NodeWidget)
{
return NodeWidget->GetToolTipHeading().IsEmpty() ? EVisibility::Collapsed : EVisibility::Visible;
}
static bool IsInteractive()
{
const FModifierKeysState ModifierKeys = FSlateApplication::Get().GetModifierKeys();
return ( ModifierKeys.IsAltDown() && ModifierKeys.IsControlDown() );
}
};
TSharedRef<SGraphNodeK2Base> ThisRef = SharedThis(this);
SAssignNew(NodeToolTip, SToolTip)
.Visibility_Static(&LocalUtils::IsToolTipVisible, ThisRef)
.IsInteractive_Static(&LocalUtils::IsInteractive)
[
SNew(SVerticalBox)
// heading container
+SVerticalBox::Slot()
[
SNew(SVerticalBox)
.Visibility_Static(&LocalUtils::IsToolTipHeadingVisible, ThisRef)
+SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Font(FEditorStyle::GetFontStyle(TEXT("Kismet.Tooltip.SubtextFont")))
.ColorAndOpacity(FSlateColor::UseSubduedForeground())
.Text(this, &SGraphNodeK2Base::GetToolTipHeading)
]
+SVerticalBox::Slot()
.AutoHeight()
.Padding(0.f, 2.f, 0.f, 5.f)
[
SNew(SBorder)
// use the border's padding to actually create the horizontal line
.Padding(1.f)
.BorderImage(FEditorStyle::GetBrush(TEXT("Menu.Separator")))
]
]
// tooltip body
+SVerticalBox::Slot()
.AutoHeight()
[
DefaultToolTip->GetContent()
]
];
return NodeToolTip;
}
FText SGraphNodeK2Base::GetToolTipHeading() const
{
if (UK2Node const* K2Node = CastChecked<UK2Node>(GraphNode))
{
return K2Node->GetToolTipHeading();
}
return FText::GetEmpty();
}
/**
* Update this GraphNode to match the data that it is observing
*/
void SGraphNodeK2Base::UpdateGraphNode()
{
UK2Node* K2Node = CastChecked<UK2Node>(GraphNode);
const bool bCompactMode = K2Node->ShouldDrawCompact();
if (bCompactMode)
{
UpdateCompactNode();
}
else
{
UpdateStandardNode();
}
}
bool SGraphNodeK2Base::RequiresSecondPassLayout() const
{
UK2Node* K2Node = CastChecked<UK2Node>(GraphNode);
const bool bBeadMode = K2Node->ShouldDrawAsBead();
return bBeadMode;
}
FString SGraphNodeK2Base::GetNodeCompactTitle() const
{
UK2Node* K2Node = CastChecked<UK2Node>(GraphNode);
return K2Node->GetCompactNodeTitle();
}
/** Populate the brushes array with any overlay brushes to render */
void SGraphNodeK2Base::GetOverlayBrushes(bool bSelected, const FVector2D WidgetSize, TArray<FOverlayBrushInfo>& Brushes) const
{
UBlueprint* OwnerBlueprint = FBlueprintEditorUtils::FindBlueprintForNodeChecked(GraphNode);
// Search for an enabled or disabled breakpoint on this node
UBreakpoint* Breakpoint = FKismetDebugUtilities::FindBreakpointForNode(OwnerBlueprint, GraphNode);
if (Breakpoint != NULL)
{
FOverlayBrushInfo BreakpointOverlayInfo;
if (Breakpoint->GetLocation()->IsA<UK2Node_Composite>()
|| Breakpoint->GetLocation()->IsA<UK2Node_MacroInstance>())
{
if (Breakpoint->IsEnabledByUser())
{
BreakpointOverlayInfo.Brush = FEditorStyle::GetBrush(FKismetDebugUtilities::IsBreakpointValid(Breakpoint) ? TEXT("Kismet.DebuggerOverlay.Breakpoint.EnabledAndValidCollapsed") : TEXT("Kismet.DebuggerOverlay.Breakpoint.EnabledAndInvalidCollapsed"));
}
else
{
BreakpointOverlayInfo.Brush = FEditorStyle::GetBrush(TEXT("Kismet.DebuggerOverlay.Breakpoint.DisabledCollapsed"));
}
}
else
{
if (Breakpoint->IsEnabledByUser())
{
BreakpointOverlayInfo.Brush = FEditorStyle::GetBrush(FKismetDebugUtilities::IsBreakpointValid(Breakpoint) ? TEXT("Kismet.DebuggerOverlay.Breakpoint.EnabledAndValid") : TEXT("Kismet.DebuggerOverlay.Breakpoint.EnabledAndInvalid"));
}
else
{
BreakpointOverlayInfo.Brush = FEditorStyle::GetBrush(TEXT("Kismet.DebuggerOverlay.Breakpoint.Disabled"));
}
}
if(BreakpointOverlayInfo.Brush != NULL)
{
BreakpointOverlayInfo.OverlayOffset -= BreakpointOverlayInfo.Brush->ImageSize/2.f;
}
Brushes.Add(BreakpointOverlayInfo);
}
// Is this the current instruction?
if (FKismetDebugUtilities::GetCurrentInstruction() == GraphNode)
{
FOverlayBrushInfo IPOverlayInfo;
// Pick icon depending on whether we are on a hit breakpoint
const bool bIsOnHitBreakpoint = FKismetDebugUtilities::GetMostRecentBreakpointHit() == GraphNode;
IPOverlayInfo.Brush = FEditorStyle::GetBrush( bIsOnHitBreakpoint ? TEXT("Kismet.DebuggerOverlay.InstructionPointerBreakpoint") : TEXT("Kismet.DebuggerOverlay.InstructionPointer") );
if (IPOverlayInfo.Brush != NULL)
{
float Overlap = 10.f;
IPOverlayInfo.OverlayOffset.X = (WidgetSize.X/2.f) - (IPOverlayInfo.Brush->ImageSize.X/2.f);
IPOverlayInfo.OverlayOffset.Y = (Overlap - IPOverlayInfo.Brush->ImageSize.Y);
}
IPOverlayInfo.AnimationEnvelope = FVector2D(0.f, 10.f);
Brushes.Add(IPOverlayInfo);
}
// @todo remove if Timeline nodes are rendered in their own slate widget
if (const UK2Node_Timeline* Timeline = Cast<const UK2Node_Timeline>(GraphNode))
{
float Offset = 0.0f;
if (Timeline && Timeline->bAutoPlay)
{
FOverlayBrushInfo IPOverlayInfo;
IPOverlayInfo.Brush = FEditorStyle::GetBrush( TEXT("Graph.Node.Autoplay") );
if (IPOverlayInfo.Brush != NULL)
{
const float Padding = 2.5f;
IPOverlayInfo.OverlayOffset.X = WidgetSize.X - IPOverlayInfo.Brush->ImageSize.X - Padding;
IPOverlayInfo.OverlayOffset.Y = Padding;
}
Brushes.Add(IPOverlayInfo);
Offset = IPOverlayInfo.Brush->ImageSize.X;
}
if (Timeline && Timeline->bLoop)
{
FOverlayBrushInfo IPOverlayInfo;
IPOverlayInfo.Brush = FEditorStyle::GetBrush( TEXT("Graph.Node.Loop") );
if (IPOverlayInfo.Brush != NULL)
{
const float Padding = 2.5f;
IPOverlayInfo.OverlayOffset.X = WidgetSize.X - IPOverlayInfo.Brush->ImageSize.X - Padding - Offset;
IPOverlayInfo.OverlayOffset.Y = Padding;
}
Brushes.Add(IPOverlayInfo);
}
}
// Display an icon depending on the type of node and it's settings
if (const UK2Node* K2Node = Cast<const UK2Node>(GraphNode))
{
FName ClientIcon = K2Node->GetCornerIcon();
if ( ClientIcon != NAME_None )
{
FOverlayBrushInfo IPOverlayInfo;
IPOverlayInfo.Brush = FEditorStyle::GetBrush( ClientIcon );
if (IPOverlayInfo.Brush != NULL)
{
IPOverlayInfo.OverlayOffset.X = (WidgetSize.X - (IPOverlayInfo.Brush->ImageSize.X/2.f))-3.f;
IPOverlayInfo.OverlayOffset.Y = (IPOverlayInfo.Brush->ImageSize.Y/-2.f)+2.f;
}
Brushes.Add(IPOverlayInfo);
}
}
}
void SGraphNodeK2Base::GetNodeInfoPopups(FNodeInfoContext* Context, TArray<FGraphInformationPopupInfo>& Popups) const
{
FKismetNodeInfoContext* K2Context = (FKismetNodeInfoContext*)Context;
// Display any pending latent actions
if (UObject* ActiveObject = K2Context->ActiveObjectBeingDebugged)
{
TArray<FKismetNodeInfoContext::FObjectUUIDPair>* Pairs = K2Context->NodesWithActiveLatentActions.Find(GraphNode);
if (Pairs != NULL)
{
for (int32 Index = 0; Index < Pairs->Num(); ++Index)
{
FKismetNodeInfoContext::FObjectUUIDPair Action = (*Pairs)[Index];
if (Action.Object == ActiveObject)
{
if (UWorld* World = GEngine->GetWorldFromContextObject(Action.Object))
{
FLatentActionManager& LatentActionManager = World->GetLatentActionManager();
const FString LatentDesc = LatentActionManager.GetDescription(Action.Object, Action.UUID);
const FString& ActorLabel = Action.GetDisplayName();
new (Popups) FGraphInformationPopupInfo(NULL, LatentBubbleColor, LatentDesc);
}
}
}
}
// Display pinned watches
if (K2Context->WatchedNodeSet.Contains(GraphNode))
{
UBlueprint* Blueprint = K2Context->SourceBlueprint;
const UEdGraphSchema* Schema = GraphNode->GetSchema();
FString PinnedWatchText;
int32 ValidWatchCount = 0;
for (int32 PinIndex = 0; PinIndex < GraphNode->Pins.Num(); ++PinIndex)
{
UEdGraphPin* WatchPin = GraphNode->Pins[PinIndex];
if (K2Context->WatchedPinSet.Contains(WatchPin))
{
if (ValidWatchCount > 0)
{
PinnedWatchText += TEXT("\n");
}
FString PinName = UEdGraphSchema_K2::TypeToString(WatchPin->PinType);
PinName += TEXT(" ");
PinName += Schema->GetPinDisplayName(WatchPin);
FString WatchText;
const FKismetDebugUtilities::EWatchTextResult WatchStatus = FKismetDebugUtilities::GetWatchText(/*inout*/ WatchText, Blueprint, ActiveObject, WatchPin);
switch (WatchStatus)
{
case FKismetDebugUtilities::EWTR_Valid:
PinnedWatchText += FString::Printf(*LOCTEXT("WatchingAndValid", "Watching %s\n\t%s").ToString(), *PinName, *WatchText);//@TODO: Print out object being debugged name?
break;
case FKismetDebugUtilities::EWTR_NotInScope:
PinnedWatchText += FString::Printf(*LOCTEXT("WatchingWhenNotInScope", "Watching %s\n\t(not in scope)").ToString(), *PinName);
break;
case FKismetDebugUtilities::EWTR_NoProperty:
PinnedWatchText += FString::Printf(*LOCTEXT("WatchingUnknownProperty", "Watching %s\n\t(no debug data)").ToString(), *PinName);
break;
default:
case FKismetDebugUtilities::EWTR_NoDebugObject:
PinnedWatchText += FString::Printf(*LOCTEXT("WatchingNoDebugObject", "Watching %s").ToString(), *PinName);
break;
}
ValidWatchCount++;
}
}
if (ValidWatchCount)
{
new (Popups) FGraphInformationPopupInfo(NULL, PinnedWatchColor, PinnedWatchText);
}
}
}
}
const FSlateBrush* SGraphNodeK2Base::GetShadowBrush(bool bSelected) const
{
const UK2Node* K2Node = CastChecked<UK2Node>(GraphNode);
const bool bCompactMode = K2Node->ShouldDrawCompact();
if (bSelected && bCompactMode)
{
return FEditorStyle::GetBrush( "Graph.CompactNode.ShadowSelected" );
}
else
{
return SGraphNode::GetShadowBrush(bSelected);
}
}
void SGraphNodeK2Base::PerformSecondPassLayout(const TMap< UObject*, TSharedRef<SNode> >& NodeToWidgetLookup) const
{
TSet<UEdGraphNode*> PrevNodes;
TSet<UEdGraphNode*> NextNodes;
// Gather predecessor/successor nodes
for (int32 PinIndex = 0; PinIndex < GraphNode->Pins.Num(); ++PinIndex)
{
UEdGraphPin* Pin = GraphNode->Pins[PinIndex];
if (Pin->LinkedTo.Num() > 0)
{
if (Pin->Direction == EGPD_Input)
{
for (int32 LinkIndex = 0; LinkIndex < Pin->LinkedTo.Num(); ++LinkIndex)
{
PrevNodes.Add(Pin->LinkedTo[LinkIndex]->GetOwningNode());
}
}
if (Pin->Direction == EGPD_Output)
{
for (int32 LinkIndex = 0; LinkIndex < Pin->LinkedTo.Num(); ++LinkIndex)
{
NextNodes.Add(Pin->LinkedTo[LinkIndex]->GetOwningNode());
}
}
}
}
// Place this node smack between them
const float Height = 0.0f;
PositionThisNodeBetweenOtherNodes(NodeToWidgetLookup, PrevNodes, NextNodes, Height);
}
#undef LOCTEXT_NAMESPACE
| [
"michaellam430@gmail.com"
] | michaellam430@gmail.com |
7e39bd2f099b1e8e160a6fe4e8435ffdd7a155f6 | 6e27c245fe0b0f2f7d6c9293b3cf182f9b0fe19c | /khf0.cpp | db002227f46349b505be4611638234bef6788749 | [] | no_license | csaba215/dekla-homework | 868999a4a6f1120992b149fc4ae797146d3dc4b0 | e1b600dba021d8ddaae91ecfdef27fdedc390962 | refs/heads/master | 2023-06-06T19:54:06.659223 | 2021-06-30T17:39:12 | 2021-06-30T17:39:12 | 381,783,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,943 | cpp | #include "cekla.h"// így szabályos C++ program is
int pow2(const int A, const int N, const int P) {
if (N > 0)
return pow2(A, N-1, P*A);
else
return P;
}
const list reverse2(const list L, const list L0) {
if (L == nil) return L0;
return reverse2(tl(L), cons(hd(L), L0));
}
const list felbont2(const int szam,const int szamrendszer,const list lista){
if(szam == 0)
return lista;
int darab = szam%szamrendszer;
const list l = cons(darab,lista);
return felbont2((szam-darab)/szamrendszer,szamrendszer,l);
}
int pow(const int A, const int N){
return pow2(A, N, 1);
}
const list reverse(const list L) {
return reverse2(L,nil);
}
const list felbont(const int szam,const int szamrendszer){
return felbont2(szam,szamrendszer,nil);
}
int vissza2(const list L,const int A, const int sum,const int n){
if(L == nil)
return sum;
return vissza2(tl(L),A,sum+hd(L)*pow(A,n),n+1);
}
int vissza(const list L,const int A){
return vissza2(L,A,0,0);
}
const list bont(const list l1,const list l2,const int n){
if(l1 == nil)
return l2;
if(n%2==0)
return bont(tl(l1),cons(hd(l1),l2),n+1);
return bont(tl(l1),l2,n+1);
}
const list osszefuz(const list paratlan_forditva,const list paros){
if(paratlan_forditva == nil)
return paros;
return osszefuz(tl(paratlan_forditva),cons(hd(paratlan_forditva),paros));
}
int atrendezett(const int S, const int A) {
const list lista = felbont(S,A);
const list paros_forditva = bont(lista,nil,1);
const list paratlan_forditva = bont(lista,nil,0);
const list paros = reverse(paros_forditva);
const list atrendezett = reverse(osszefuz(paratlan_forditva,paros));
return vissza(atrendezett,A);
}
int main() {// szabályos függvénydeklaráció
writeln(atrendezett(123, 10));
writeln(atrendezett(101, 10));
writeln(atrendezett(5, 2));
writeln(atrendezett(1023, 10));
writeln(atrendezett(11, 3));
writeln(atrendezett(162738495, 10));
writeln(atrendezett(15263748, 10));
}
| [
"csaba215@gmail.com"
] | csaba215@gmail.com |
36dab40cc09adcd59be7a6774546c545d1cf5094 | dd1dda0434b7a487854eddf89914f74d15324a10 | /DX11Tutorial-GlassAndIce/modelclass.cpp | ec60d2618c5cd37d077d692c8c70a7de82c44cec | [] | no_license | KsGin-Fork/DX11Tutorial | 02e8014d4bd84f559a5584cf98b4642e2743ee93 | 66bd8d13a161b909702f9ad753f15a5107400cbb | refs/heads/master | 2020-03-21T06:57:46.154782 | 2018-04-27T15:06:47 | 2018-04-27T15:06:47 | 138,252,211 | 0 | 1 | null | 2018-06-22T03:52:36 | 2018-06-22T03:52:36 | null | UTF-8 | C++ | false | false | 7,128 | cpp | ////////////////////////////////////////////////////////////////////////////////
// Filename: modelclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "modelclass.h"
ModelClass::ModelClass()
{
m_vertexBuffer = 0;
m_indexBuffer = 0;
m_Texture = 0;
m_model = 0;
m_NormalTexture = 0;
}
ModelClass::ModelClass(const ModelClass& other)
{
}
ModelClass::~ModelClass()
{
}
bool ModelClass::Initialize(ID3D11Device* device, char* textureFilename, char* modelFilename , char* normalFilename)
{
bool result;
// Load in the model data,
result = LoadModel(modelFilename);
if(!result)
{
return false;
}
// Initialize the vertex and index buffers.
result = InitializeBuffers(device);
if(!result)
{
return false;
}
// Load the texture for this model.
result = LoadTexture(device, textureFilename);
if(!result)
{
return false;
}
if (normalFilename) {
result = LoadNormalTexture(device, normalFilename);
if(!result)
{
return false;
}
}
return true;
}
ID3D11ShaderResourceView* ModelClass::GetNormalTexture() {
return m_NormalTexture->GetTexture();
}
bool ModelClass::LoadNormalTexture(ID3D11Device* device, char* filename) {
bool result;
// Create the texture object.
m_NormalTexture = new TextureClass;
if(!m_NormalTexture)
{
return false;
}
// Initialize the texture object.
result = m_NormalTexture->Initialize(device, filename);
if(!result)
{
return false;
}
return true;
}
void ModelClass::ReleaseNormalTexture() {
if (m_NormalTexture) {
m_NormalTexture->Shutdown();
delete m_NormalTexture;
m_NormalTexture = 0;
}
}
void ModelClass::Shutdown()
{
// Release the model texture.
ReleaseTexture();
// Shutdown the vertex and index buffers.
ShutdownBuffers();
// Release the model data.
ReleaseModel();
return;
}
void ModelClass::Render(ID3D11DeviceContext* deviceContext)
{
// Put the vertex and index buffers on the graphics pipeline to prepare them for drawing.
RenderBuffers(deviceContext);
return;
}
int ModelClass::GetIndexCount()
{
return m_indexCount;
}
ID3D11ShaderResourceView* ModelClass::GetTexture()
{
return m_Texture->GetTexture();
}
bool ModelClass::InitializeBuffers(ID3D11Device* device)
{
VertexType* vertices;
unsigned long* indices;
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;
int i;
// Create the vertex array.
vertices = new VertexType[m_vertexCount];
if(!vertices)
{
return false;
}
// Create the index array.
indices = new unsigned long[m_indexCount];
if(!indices)
{
return false;
}
// Load the vertex array and index array with data.
for(i=0; i<m_vertexCount; i++)
{
vertices[i].position = DirectX::XMFLOAT3(m_model[i].x, m_model[i].y, m_model[i].z);
vertices[i].texture = DirectX::XMFLOAT2(m_model[i].tu, m_model[i].tv);
vertices[i].normal = DirectX::XMFLOAT3(m_model[i].nx, m_model[i].ny, m_model[i].nz);
indices[i] = i;
}
// Set up the description of the static vertex buffer.
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the vertex data.
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// Now create the vertex buffer.
result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer);
if(FAILED(result))
{
return false;
}
// Set up the description of the static index buffer.
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * m_indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the index data.
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// Create the index buffer.
result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer);
if(FAILED(result))
{
return false;
}
// Release the arrays now that the vertex and index buffers have been created and loaded.
delete [] vertices;
vertices = 0;
delete [] indices;
indices = 0;
return true;
}
void ModelClass::ShutdownBuffers()
{
// Release the index buffer.
if(m_indexBuffer)
{
m_indexBuffer->Release();
m_indexBuffer = 0;
}
// Release the vertex buffer.
if(m_vertexBuffer)
{
m_vertexBuffer->Release();
m_vertexBuffer = 0;
}
return;
}
void ModelClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
unsigned int stride;
unsigned int offset;
// Set vertex buffer stride and offset.
stride = sizeof(VertexType);
offset = 0;
// Set the vertex buffer to active in the input assembler so it can be rendered.
deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
// Set the index buffer to active in the input assembler so it can be rendered.
deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
// Set the type of primitive that should be rendered from this vertex buffer, in this case triangles.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
return;
}
bool ModelClass::LoadTexture(ID3D11Device* device, CHAR* filename)
{
bool result;
// Create the texture object.
m_Texture = new TextureClass;
if(!m_Texture)
{
return false;
}
// Initialize the texture object.
result = m_Texture->Initialize(device, filename);
if(!result)
{
return false;
}
return true;
}
void ModelClass::ReleaseTexture()
{
// Release the texture object.
if(m_Texture)
{
m_Texture->Shutdown();
delete m_Texture;
m_Texture = 0;
}
return;
}
bool ModelClass::LoadModel(char* filename)
{
ifstream fin;
char input;
int i;
// Open the model file. If it could not open the file then exit.
fin.open(filename);
if(fin.fail())
{
return false;
}
// Read up to the value of vertex count.
fin.get(input);
while(input != ':')
{
fin.get(input);
}
// Read in the vertex count.
fin >> m_vertexCount;
// Set the number of indices to be the same as the vertex count.
m_indexCount = m_vertexCount;
// Create the model using the vertex count that was read in.
m_model = new ModelType[m_vertexCount];
if(!m_model)
{
return false;
}
// Read up to the beginning of the data.
fin.get(input);
while(input != ':')
{
fin.get(input);
}
fin.get(input);
fin.get(input);
// Read in the vertex data.
for(i=0; i<m_vertexCount; i++)
{
fin >> m_model[i].x >> m_model[i].y >> m_model[i].z;
fin >> m_model[i].tu >> m_model[i].tv;
fin >> m_model[i].nx >> m_model[i].ny >> m_model[i].nz;
}
// Close the model file.
fin.close();
return true;
}
void ModelClass::ReleaseModel()
{
if(m_model)
{
delete [] m_model;
m_model = 0;
}
return;
} | [
"imqqyangfan@gmail.com"
] | imqqyangfan@gmail.com |
2d9fbe9e00327093325992303c09dea4b6b38279 | 1b8e1ddcb86f0a5cd018bc6b3400c8c6fb1c1984 | /server/server/activity/.svn/text-base/EntityActivityComponent.h.svn-base | 2a478d33d3168192f761c587c50e1a285db4d5df | [] | no_license | yzfrs/ddianle_d1 | 5e9a3ab0ad646ca707368850c01f8117a09f5bfd | abffb574419cc2a8a361702e012cdd14f1102a6d | refs/heads/master | 2021-01-01T03:32:51.973703 | 2016-05-12T09:27:00 | 2016-05-12T09:27:00 | 58,615,329 | 0 | 2 | null | null | null | null | GB18030 | C++ | false | false | 16,447 | #ifndef __ENTITYACTIVITYCOMPONENT_H__
#define __ENTITYACTIVITYCOMPONENT_H__
// 累计在线时长奖励的数据库只存储最新的数据,不会删除或者清零。
// 数据是否有效只在DB存储出来后做由程序做处理。
#include <list>
#include "../logic/RoleComponentImpl.h"
#include "../logic/EntityComponent.h"
#include "ActivityDataStruct.h"
#define INVITATION_DB_QUERY_MIN_INTERVAL 5
using namespace std;
class CEntityNetComponent;
class CEntityTimerComponent;
class CEntityAttributeComponent;
class CEntityItemComponent;
class CEntityMailComponent;
class CEntityFriendComponent;
class CEntityChatComponent;
class CCummulativeRechareActivityInfo;
class CCummulativeSpendActivityInfo;
class CExchangeItemActivityInfo;
class CShowInTimeOnlineActivity;
class CPlainTextActivityInfo;
class CGiftCodeActivityInfo;
class COnlineRewardActivity;
class CumulativeSpendGotMedalActivityData;
class BuyItemGotMedalActivityData;
class CEntityCoupleComponent;
class CProprietaryActivityInfo;
class CEntityQuestComponent;
class CEntityVIPComponent;
class CEntityQuestNewComponent;
class CEntityMedalComponent;
class CEntityDanceGroupComponent;
class CEntityActivityComponent : public CEntityComponent, public CommonSubscriber
{
public:
CEntityActivityComponent();
~CEntityActivityComponent();
public:
virtual void OnEvent(CComponentEvent& refEvent);
virtual void Start();
virtual void OnLogin();
virtual void OnLogout();
virtual void OnUpdate(const unsigned long &nTimeElapsed);
virtual void SerializeComponent(CParamPool &IOBuff);
virtual const char* SerializeName(){
return "Activity";
};
virtual bool CreateFromDB(ROLEINFO_DB* pRoleInfoDB);
virtual bool PacketToDB(ROLEINFO_DB *pRoleInforDB) const;
virtual bool PacketToCache( ROLEINFO_DB* pRoleInforDB ) const;
virtual void SendExtraStaticData(){};
virtual void PacketBuff(std::list<BuffData>& listBuff);
virtual void OnNotify(IParam ¶m);
void RegComponentNetMsgMap();
void SendAllActivitiesInfo();
public:
void OnOnlineRewardActivityStart();
void OnOnlineRewardActivityEnd();
void OnCumulativeRechargeActivityStart();
void OnCumulativeRechargeActivityEnd();
void UpdateOnlineRewardInfoToClient();
void OnPlayerRecharge(int nCharge);
void LogMeetAction(int nAction, unsigned int nCoupleRoleID = 0, int nAmuseID = 0);
void OnTestActivity(int nPara1, int nPara2, int nPara3);
bool IsSharedToSocial(EUISocialShare ui);
void SetSharedToSocial(EUISocialShare ui, bool b, bool bToDB = true);
time_t GetFirstSharedTime(EUISocialShare ui);
bool CanGetPhotoShareVIPReward() const {
return m_bNotGetPhotoShareVIPReward;
}
void SetNotGetPhotoShareVIPReward(bool bNoGetVIPReward) {
m_bNotGetPhotoShareVIPReward = bNoGetVIPReward;
}
void OnActivityChange(unsigned char nActivityID, bool bOpen);
EUISocialShare GetEUISocialShareByActivityID(EActivity eActivity);
EActivity GetActivityIDByEUISocialShare(EUISocialShare eUI);
void AddCumulativeSpendBill(int nValue);
void AddCumulativeSpendBindBill(int nValue);
private:
void _OnGetAllActivitiesInfo(GameMsg_Base & msg, CSlotPeer &slotPeer);
void GetCDKeyInfo(GameMsg_Base & msg, CSlotPeer &slotPeer);
void GetBindActivationInfo(GameMsg_Base & msg, CSlotPeer &slotPeer);
// 获取在线奖励
void _OnGetOnlineReward(GameMsg_Base & msg, CSlotPeer &slotPeer);
//获取礼品
void _OnGetGift(GameMsg_Base & msg, CSlotPeer &slotPeer);
//累计充值
void _OnGetCumulativeRechargeReward(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnExchangeItem(GameMsg_Base & msg, CSlotPeer &slotPeer);
//累计消费
void OnGetCumulativeSpendReward(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _LoadCumulativeSpendInfo();
void _LoadCumulativeSpendInfoForMedal();
int GetCumulativeSpendValue(int nCurrencyType);
int GetCumulativeSpendValueForMedal(int nCurType);
// 累计消费获取勋章
void OnGetCumulativeSpendGotMedalReward(GameMsg_Base &msg, CSlotPeer &slotPeer);
void LoadCumulativeSpendGotMedalReward();
bool CanGetCumulativeSpendGotMedalRewards(unsigned char nIndex);
//IOS尊享版奖励领取操作
void _OnGetProprietaryReward(GameMsg_Base & msg, CSlotPeer &slotPeer);
//活动扩展数据
void _OnGetExtraActivityInfo(GameMsg_Base & msg, CSlotPeer &slotPeer);
//圣诞免费礼物
void _SaveXmasFreeRewardInfo(unsigned int nLastGetRewardTime);
void _LoadXmasFreeRewardInfo();
void _SendXmasFreeRewardActivityInfo();
void _OnGetXmasActivityInfo(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnGetXmasFreeReward(GameMsg_Base & msg, CSlotPeer &slotPeer);
//许愿活动
void _LoadFestivalWishInfo();
void _SaveFestivalWishInfo();
void _SendFestivalWishActivityInfo();
void _OnGetFestivalWishActivityInfo(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnRoleFestivalWish(GameMsg_Base & msg, CSlotPeer &slotPeer);
//祝福活动
void _SaveBlessInfo(CFestivalBlessInfoDB *pBlessEntryDB);
void _SaveRoleBlessActivityInfo(unsigned int nGetRewardTime);
void _LoadRoleBlessActivityInfo();
void _OnGetFestivalBlessActivityInfo(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _BlessFriend(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _BlessFriend_G(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _GetFestivalBlessReward(GameMsg_Base & msg, CSlotPeer &slotPeer);
bool _ReachCumulativeRechargeRequire(int nCurRechargeNum, int nLevel);
bool _ReachCumulativeSpendRequire(int nCurRechargeNum, int nLevel);
void _LoadCumulativeRechargeInfo();
//拼图活动
void _LoadRolePuzzleDB();
void _UpdateRolePuzzleDB(int nOriTime, const CRolePuzzleActivityInfo & rPuzzleInfo);
void _InitRolePuzzleInfo(const std::list<CRolePuzzleActivityDB> &rlistPuzzle);
void _InitRolePuzzleInfo(CRoleAllPuzzleDB *pPuzzleDB);
void _OnFillPuzzle(GameMsg_Base & msg, CSlotPeer &slotPeer);
void SyncPuzzleData();
//玩家招募活动
void _SetInvitationActivity(CInvitationActivityInfo& activity);
void _OnGetInvitationInviterInfo(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnBindInvitationCode(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnGetInviterCumulativeReward(GameMsg_Base & msg, CSlotPeer &slotPeer);
// 新手七天乐活动
void _SetFresherActivity(CFresherActivityInfo &activity);
void _OnGetFresherReward(GameMsg_Base & msg, CSlotPeer &slotPeer);
bool _HasReceivedAllFresherReward();
bool HaveGetFresherReward(int nDay);
bool ReissueVipReward(std::list<CReward> & viprewardlist);
//商城社交分享
void _SetMallShareActivity(CMallShareActivityData& activity);
// 数据库加载邀请人数和已经获得的奖励信息
void _OnDBCheckInvitationCode(QueryBase& rQuery);
void _OnDBGetInvitationInfo(QueryBase& rQuery);
// 邂逅活动
void _OnMeetMatch(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnMeetCancelMatch(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnMeetLeaveScene(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnMeetCameraEvent(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnMeetEnd(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnMeetEnterAmuseScene(GameMsg_Base & msg, CSlotPeer &slotPeer);
//普通社交分享功能
void _OnSocialShare(GameMsg_Base & msg, CSlotPeer &slotPeer);
//社交分享活动
void _OnActivitySocialShare(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnRequestVipExtraReward(GameMsg_Base &msg, CSlotPeer &slotPeer);
void SendAllShareActivitiesCanFirst();
void SendCanSocialShareFirst(EUISocialShare ui, bool bCanShare);
void SyncGiftData();
// 光效石兑换
void ExchangeEffectStone();
//数据库加载礼品
void _OnLoadGift(QueryBase & rQuery);
void _OnLoadCumulativeRechargeInfo(QueryBase & rQuery);
void _OnLoadCumulativeSpendInfo(QueryBase & rQuery);
void _OnLoadCumulativeSpendInfoForMedal(QueryBase& rQuery);
void _OnDBLoadXmasFreeRewardInfo(QueryBase & rQuery);
void _OnDBLoadRoleBlessActivityInfo(QueryBase & rQuery);
void _OnDBLoadRoleFestivalWishActivityInfo(QueryBase & rQuery);
void _OnDBLoadRolePuzzleActivityInfo(QueryBase & rQuery);
void OnQueryCumulativeSpendGotMedalReward(QueryBase &rQuery);
void OnQueryBuyItemGotMedalRewardedInfo(QueryBase &rQuery);
void _SendPlayerMsg(GameMsg_Base *pMsg);
void _SetNextKeepOnlineReward(int nIndex, CKeepOnlineReward & onlineInfo, bool bCanReset = true);
void _ResetKeepOnlineRewardInfo();
void _UpdateOnlineRewardInfoDB();
void _HandleOnlineInfo(CKeepOnlineReward & onlineRewardInfo, unsigned int nNow);
void _OnOnlineRewardActivityReset();
void _SetCumulativeRechargeActivity(CCummulativeRechareActivityInfo & activity);
void _SetCumulativeSpendActivity(CCummulativeSpendActivityInfo & activity);
bool _HasReceivedCumulativeReward(int nLevel);
bool _HasReceivedCumulativeSpendReward(int nLevel);
bool IsSpendRewardEmpty();
void SetCumulativeSpendGotMedalActivity(CumulativeSpendGotMedalActivityData &rActivity);
bool HasReceivedCumulativeSpendGotMedalReward(int nIndex);
void OnRequestBuyItemGotMedalReward(GameMsg_Base &msg, CSlotPeer &slotPeer);
void SetBuyItemGotMedalActivity(BuyItemGotMedalActivityData &rActivity) const;
bool HasReceivedBuyItemGotMedalReward(unsigned char nIndex) const;
bool CanGetBuyItemGotMedalRewards(unsigned char nIndex) const;
void GetBuyItemGotMedalRewardedInfo(unsigned char nIndex, bool *rReceived, unsigned short *rCurrentCount) const;
void LoadBuyItemGotMedalRewardedInfo();
void UpdateBuyItemGotMedalInfo(unsigned int nItemType, unsigned short nItemCount);
void _SetExchangeItemActivity(CExchangeItemActivityInfo & activity);
bool _ReachExchangeItemRequire(int nLevel);
void _SetInTimeOnlineActivity(CShowInTimeOnlineActivity & activity);
void _SetPlainTextActivity(CPlainTextActivityInfo & activity);
void _SetGiftCodeActivity(CGiftCodeActivityInfo & activity);
void _SetOnlineRewardActivity(COnlineRewardActivity & activit);
bool _OnlineRewardActivityActivated();
void _SendPlayerReward(int nIndex);
void _SetMallSocialShareActivity(CMallSocialShareActivityData &activity);
void _SetPhotoSocialShareActivity(CPhotoSocialShareActivityData &activity);
void _SetProprietaryAcitivty(CProprietaryActivityInfo& activity);
// 获取长效累冲信息
void OnGetLongactingCumulativeRechargeInfo(GameMsg_Base & msg, CSlotPeer &slotPeer);
// 领取长效累冲奖励
void OnGetLongactingCumulativeReward(GameMsg_Base & msg, CSlotPeer &slotPeer);
// 获取长效累冲广播
void OnGetLongactingCumulativeBoardCast(GameMsg_Base & msg, CSlotPeer &slotPeer);
void _OnGetLongactingCumulativeBoardCast(GameMsg_Base & msg, CSlotPeer &slotPeer);
public://...........舞团红包................
// 获取红包列表
void OnGetRedEnvelopeList(GameMsg_Base &msg, CSlotPeer &slotPeer);
void _OnGetRedEnvelopeList(GameMsg_Base &msg, CSlotPeer &slotPeer);
// 获取红包详细信息
void OnGetRedEnvelopeDetails(GameMsg_Base &msg, CSlotPeer &slotPeer);
void _OnGetRedEnvelopeDetails(GameMsg_Base &msg, CSlotPeer &slotPeer);
// 新红包广播
void OnNewRedEnvelopeNotice(GameMsg_Base &msg, CSlotPeer &slotPeer);
// 设置匿名
void OnSetAnonymity(GameMsg_Base &msg, CSlotPeer &slotPeer);
// 开红包
void OnOpenRedEnvelope(GameMsg_Base &msg, CSlotPeer &slotPeer);
void _OnOpenRedEnvelope(GameMsg_Base &msg, CSlotPeer &slotPeer);
//
void OnGetCanOpenRedEnvelopeCount(GameMsg_Base &msg, CSlotPeer &slotPeer);
void _OnGetCanOpenRedEnvelopeCount(GameMsg_Base &msg, CSlotPeer &slotPeer);
public:
// 更新奖励序列
void UpdateLongactingRechargeRewardIndex(unsigned int nRewardIndex);
private:
CEntityNetComponent * m_pRoleNet;
CEntityTimerComponent * m_pRoleTimer;
CEntityAttributeComponent * m_pRoleAttr;
CEntityItemComponent * m_pRoleItem;
CEntityMailComponent * m_pRoleMail;
CEntityFriendComponent * m_pRoleFriend;
CEntityChatComponent * m_pRoleChat;
CEntityCoupleComponent * m_pRoleCouple;
CEntityQuestComponent * m_pRoleFresherQuest;
CEntityVIPComponent * m_pRoleVip;
CEntityQuestNewComponent * m_pRoleQuest;
CEntityMedalComponent * m_pRoleMedal;
CEntityDanceGroupComponent * m_pRoleDanceGroup;
private:
int m_nLastStop;
unsigned long m_nTimeElapsed;
unsigned long m_nUpdateDBTimeElapse;
std::map< int, GiftDB > m_GiftMap; //当前玩家的礼品列表
// 累计充值
int m_nCumulativeRechargeNum; //累积充值,表示当前开启的累计充值活动的数值
bool m_bLoadCumulativeRechargeDB;//是否已经加载了玩家累计充值的数据
std::vector<int> m_vecCumulativeRewards;
// 累计消费
std::vector<unsigned int> m_CumulativeSpendReward;
unsigned int m_nCumulativeBill;
unsigned int m_nCumulativeBindBill;
bool m_bLoadCumulativeSpendSuc;
/// <summary>
/// 记录勋章累计消费活动的值
/// <summary
unsigned int m_nCumulativeBillForMedal;
unsigned int m_nCumulativeBindBillForMedal;
std::vector<unsigned int> m_CumulativeSpendRewardForMedal;
std::vector<bool> m_vectCumulativeSpendGotMedalReward;
// 购买物品获取勋章
BuyItemGotMedalRewardedInfoMap m_mapBuyItemGotMedalRewardedInfo;
// 圣诞节免费领取
CRoleXmasFreeRewardInfo m_roleXmasFreeRewardInfo;
// 许愿活动
CRoleFestivalWishActivityInfo m_roleFestivalWishActivityInfo;
// 祝福活动
CRoleBlessActivityInfo m_roleBlessActivityInfo;
// 拼图活动
bool m_bCheckPuzzleOpen;
std::map<int, CRolePuzzleActivityInfo> m_rolePuzzleActivityInfo;
// 新玩家招募活动
unsigned int m_nInvitationBindCount;
CRoleInvitationRewardDBMap m_InvitationRewards;
unsigned int m_nInvitationQueryTime;
// 新手七天乐活动
std::set<int> m_FresherRewardDays;
int m_nFresherDay;
int m_nCurrentFresherDay; //最后领取奖励的day
bool m_bProprietaryReward; //是否已经领取过尊享版的奖励
// 社交分享
std::map<EUISocialShare, time_t> m_mapSocialShareRecord;
std::map<EActivity, EUISocialShare> m_mapSocialShareActivity2UI; //社交分享的活动id与界面id的对应关系
bool m_bNotGetPhotoShareVIPReward; // 拍照分享没有获得VIP奖励
// 在线奖励
CKeepOnlineReward m_keepOnlineRewardInfo;
// 长效累冲活动
unsigned int m_nLongactingCumulativeRechargeIndex; //奖励序列
// 光效石兑换活动
bool m_bHaveExchangeItem;
std::list<CItem> m_listExchangeItem;
};
typedef CRoleComponentImpl<CEntityActivityComponent, CGetRoleProcessorObj, CGetRoleProcessorObj> CRoleActivity;
#endif
| [
"root@localhost.localdomain"
] | root@localhost.localdomain | |
dd3aec142915f1a66b4c79be0d2df1eff48fcbc9 | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/third_party/blink/renderer/bindings/modules/v8/v8_webgl_shader_precision_format.h | 4236e9987855a97e4005eafff22afffcbdab703f | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,017 | h | // 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.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/interface.h.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_WEBGL_SHADER_PRECISION_FORMAT_H_
#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_WEBGL_SHADER_PRECISION_FORMAT_H_
#include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h"
#include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
MODULES_EXPORT extern const WrapperTypeInfo v8_webgl_shader_precision_format_wrapper_type_info;
class V8WebGLShaderPrecisionFormat {
STATIC_ONLY(V8WebGLShaderPrecisionFormat);
public:
MODULES_EXPORT static bool HasInstance(v8::Local<v8::Value>, v8::Isolate*);
static v8::Local<v8::Object> FindInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*);
MODULES_EXPORT static v8::Local<v8::FunctionTemplate> DomTemplate(v8::Isolate*, const DOMWrapperWorld&);
static WebGLShaderPrecisionFormat* ToImpl(v8::Local<v8::Object> object) {
return ToScriptWrappable(object)->ToImpl<WebGLShaderPrecisionFormat>();
}
MODULES_EXPORT static WebGLShaderPrecisionFormat* ToImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>);
MODULES_EXPORT static constexpr const WrapperTypeInfo* GetWrapperTypeInfo() {
return &v8_webgl_shader_precision_format_wrapper_type_info;
}
static constexpr int kInternalFieldCount = kV8DefaultWrapperInternalFieldCount;
// Callback functions
MODULES_EXPORT static void RangeMinAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&);
MODULES_EXPORT static void RangeMaxAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&);
MODULES_EXPORT static void PrecisionAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&);
static void InstallRuntimeEnabledFeaturesOnTemplate(
v8::Isolate*,
const DOMWrapperWorld&,
v8::Local<v8::FunctionTemplate> interface_template);
};
template <>
struct V8TypeOf<WebGLShaderPrecisionFormat> {
typedef V8WebGLShaderPrecisionFormat Type;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_WEBGL_SHADER_PRECISION_FORMAT_H_
| [
"xueqi@zjmedia.net"
] | xueqi@zjmedia.net |
b81d40829bfb0323fc11f8b54d86e03521be63f4 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /teambition-aliyun/src/model/GetProjectTaskInfoResult.cc | 34a468e28411b106654de0b897449462c2b22e00 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 4,114 | cc | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/teambition-aliyun/model/GetProjectTaskInfoResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Teambition_aliyun;
using namespace AlibabaCloud::Teambition_aliyun::Model;
GetProjectTaskInfoResult::GetProjectTaskInfoResult() :
ServiceResult()
{}
GetProjectTaskInfoResult::GetProjectTaskInfoResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
GetProjectTaskInfoResult::~GetProjectTaskInfoResult()
{}
void GetProjectTaskInfoResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto objectNode = value["Object"];
if(!objectNode["TasklistId"].isNull())
object_.tasklistId = objectNode["TasklistId"].asString();
if(!objectNode["TaskflowstatusId"].isNull())
object_.taskflowstatusId = objectNode["TaskflowstatusId"].asString();
if(!objectNode["TaskType"].isNull())
object_.taskType = objectNode["TaskType"].asString();
if(!objectNode["IsDeleted"].isNull())
object_.isDeleted = objectNode["IsDeleted"].asString() == "true";
if(!objectNode["CreatorId"].isNull())
object_.creatorId = objectNode["CreatorId"].asString();
if(!objectNode["IsTopInProject"].isNull())
object_.isTopInProject = objectNode["IsTopInProject"].asString() == "true";
if(!objectNode["ExecutorId"].isNull())
object_.executorId = objectNode["ExecutorId"].asString();
if(!objectNode["StoryPoint"].isNull())
object_.storyPoint = objectNode["StoryPoint"].asString();
if(!objectNode["Created"].isNull())
object_.created = objectNode["Created"].asString();
if(!objectNode["OrganizationId"].isNull())
object_.organizationId = objectNode["OrganizationId"].asString();
if(!objectNode["IsDone"].isNull())
object_.isDone = objectNode["IsDone"].asString() == "true";
if(!objectNode["Id"].isNull())
object_.id = objectNode["Id"].asString();
if(!objectNode["Updated"].isNull())
object_.updated = objectNode["Updated"].asString();
if(!objectNode["SprintId"].isNull())
object_.sprintId = objectNode["SprintId"].asString();
if(!objectNode["ProjectId"].isNull())
object_.projectId = objectNode["ProjectId"].asString();
if(!objectNode["Content"].isNull())
object_.content = objectNode["Content"].asString();
if(!objectNode["Note"].isNull())
object_.note = objectNode["Note"].asString();
if(!objectNode["DueDate"].isNull())
object_.dueDate = objectNode["DueDate"].asString();
if(!objectNode["StartDate"].isNull())
object_.startDate = objectNode["StartDate"].asString();
if(!objectNode["Visible"].isNull())
object_.visible = objectNode["Visible"].asString();
if(!objectNode["Priority"].isNull())
object_.priority = objectNode["Priority"].asString();
auto allInvolveMembers = objectNode["InvolveMembers"]["InvolveMember"];
for (auto value : allInvolveMembers)
object_.involveMembers.push_back(value.asString());
if(!value["Successful"].isNull())
successful_ = value["Successful"].asString() == "true";
if(!value["ErrorCode"].isNull())
errorCode_ = value["ErrorCode"].asString();
if(!value["ErrorMsg"].isNull())
errorMsg_ = value["ErrorMsg"].asString();
}
std::string GetProjectTaskInfoResult::getErrorMsg()const
{
return errorMsg_;
}
GetProjectTaskInfoResult::Object GetProjectTaskInfoResult::getObject()const
{
return object_;
}
std::string GetProjectTaskInfoResult::getErrorCode()const
{
return errorCode_;
}
bool GetProjectTaskInfoResult::getSuccessful()const
{
return successful_;
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
cb84acc9090f131e319281811b8001b4d31ae013 | 1cb1b83de025d1ad1e756e0b8028d5164965925d | /ABC/A-MaximizeTheFormula.cpp | 27c995902dc1244e73e7de7e26dff11245ea1256 | [] | no_license | FukeKazki/CompetitionProgramming | 7c39aceec00a9ce393a7054a921b4f08a35aba0e | 4fff369180b35d230f19d8935344468a7da4bff4 | refs/heads/master | 2022-10-09T15:34:02.391840 | 2022-10-02T07:52:44 | 2022-10-02T07:52:44 | 181,264,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | #include <iostream>
using namespace std;
int main() {
int A, B, C;
cin >> A >> B >> C;
if(A < B) swap(A, B);
if(B < C) swap(B, C);
if(A < B) swap(A, B);
cout << A*10+B+C << endl;
return 0;
} | [
"kazkichi0906@gmail.com"
] | kazkichi0906@gmail.com |
06c1bf6098a778d66f61705d2a0bd8d1b494c724 | c2f3f4eb99725ac6398e73eef47d8a289ee54de0 | /Lesson14-LCD Touch Screen/Lessons/Example08-ShowBMP/ShowBMP/ShowBMP.ino | c71c6b4089bfcc327a93493c2728171c01dfee23 | [] | no_license | keywish/keywish-tft-lcd-touch-kit | c1e207b99053e483e77ce38164b8966081bc1208 | 158f17ce5d482ed54fec52f1c3dc615b46cb3d44 | refs/heads/master | 2021-09-03T03:54:31.531591 | 2018-01-05T09:23:36 | 2018-01-05T09:23:36 | 115,197,279 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,484 | ino | /***********************************************************************
* When using the BREAKOUT BOARD only, use these 8 data lines to the LCD:
* For the Arduino Uno, Duemilanove, Diecimila, etc.:
* D0 connects to digital pin 8 (Notice these are
* D1 connects to digital pin 9 NOT in order!)
* D2 connects to digital pin 2
* D3 connects to digital pin 3
* D4 connects to digital pin 4
* D5 connects to digital pin 5
* D6 connects to digital pin 6
* D7 connects to digital pin 7
* For the Arduino Mega, use digital pins 22 through 29
* (on the 2-row header at the end of the board).
***********************************************************************/
// IMPORTANT: Adafruit_TFTLCD LIBRARY MUST BE SPECIFICALLY
// CONFIGURED FOR EITHER THE TFT SHIELD OR THE BREAKOUT BOARD.
// SEE RELEVANT COMMENTS IN Adafruit_TFTLCD.h FOR SETUP.
//Technical support:goodtft@163.com
#include "Adafruit_GFX.h" // Hardware-specific library
#include "MCUFRIEND_kbv.h"
#include <SD.h>
#include <SPI.h>
// wiring with UNO or Mega2560:
//--------------POWER Pins--------------------------------
// 5V connects to DC 5V
// GND connects to Ground
// 3V3 do not need to connect(NC)
//--------------LCD Display Pins--------------------------
// LCD_RD connects to Analog pin A0
// LCD_WR connects to Analog pin A1
// LCD_RS connects to Analog pin A2
// LCD_CS connects to Analog pin A3
// LCD_RST connects to Analog pin A4
// LCD_D0 connects to digital pin 8
// LCD_D1 connects to digital pin 9
// LCD_D2 connects to digital pin 2
// LCD_D3 connects to digital pin 3
// LCD_D4 connects to digital pin 4
// LCD_D5 connects to digital pin 5
// LCD_D6 connects to digital pin 6
// LCD_D7 connects to digital pin 7
//--------------SD-card fuction Pins ----------------------
//This Connection Only for UNO, Do not support Mega2560
//because they use different Hardware-SPI Pins
//SD_SS connects to digital pin 10
//SD_DI connects to digital pin 11
//SD_DO connects to digital pin 12
//SD_SCK connects to digital pin 13
#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0
#define PIN_SD_CS 10 // Adafruit SD shields and modules: pin 10
#define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin
// When using the BREAKOUT BOARD only, use these 8 data lines to the LCD:
// For the Arduino Uno, Duemilanove, Diecimila, etc.:
// D0 connects to digital pin 8 (Notice these are
// D1 connects to digital pin 9 NOT in order!)
// D2 connects to digital pin 2
// D3 connects to digital pin 3
// D4 connects to digital pin 4
// D5 connects to digital pin 5
// D6 connects to digital pin 6
// D7 connects to digital pin 7
// For the Arduino Mega, use digital pins 22 through 29
// (on the 2-row header at the end of the board).
// Assign human-readable names to some common 16-bit color values:
#define BLACK 0x0000
#define BLUE 0x001F
#define RED 0xF800
#define GREEN 0x07E0
#define CYAN 0x07FF
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define WHITE 0xFFFF
//Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
MCUFRIEND_kbv tft;
#define MAX_BMP 10 // bmp file num
#define FILENAME_LEN 20 // max file name length
const int __Gnbmp_height = 320; // bmp hight
const int __Gnbmp_width = 240; // bmp width
unsigned char __Gnbmp_image_offset = 0; // offset
int __Gnfile_num = 4; // num of file
char __Gsbmp_files[4][FILENAME_LEN] = // add file name here
{
"flower.bmp",
"tiger.bmp",
"tree.bmp",
"RedRose.bmp",
};
File bmpFile;
/*********************************************/
// This procedure reads a bitmap and draws it to the screen
// its sped up by reading many pixels worth of data at a time
// instead of just one pixel at a time. increading the buffer takes
// more RAM but makes the drawing a little faster. 20 pixels' worth
// is probably a good place
#define BUFFPIXEL 60 // must be a divisor of 240
#define BUFFPIXEL_X3 180 // BUFFPIXELx3
void bmpdraw(File f, int x, int y)
{
bmpFile.seek(__Gnbmp_image_offset);
uint32_t time = millis();
uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer
for (int i=0; i< __Gnbmp_height; i++) {
for(int j=0; j<(240/BUFFPIXEL); j++) {
bmpFile.read(sdbuffer, BUFFPIXEL_X3);
uint8_t buffidx = 0;
int offset_x = j*BUFFPIXEL;
unsigned int __color[BUFFPIXEL];
for(int k=0; k<BUFFPIXEL; k++) {
__color[k] = sdbuffer[buffidx+2]>>3; // read
__color[k] = __color[k]<<6 | (sdbuffer[buffidx+1]>>2); // green
__color[k] = __color[k]<<5 | (sdbuffer[buffidx+0]>>3); // blue
buffidx += 3;
}
for (int m = 0; m < BUFFPIXEL; m ++) {
tft.drawPixel(m+offset_x, i,__color[m]);
}
}
}
Serial.print(millis() - time, DEC);
Serial.println(" ms");
}
boolean bmpReadHeader(File f)
{
// read header
uint32_t tmp;
uint8_t bmpDepth;
if (read16(f) != 0x4D42) {
// magic bytes missing
return false;
}
// read file size
tmp = read32(f);
Serial.print("size 0x");
Serial.println(tmp, HEX);
// read and ignore creator bytes
read32(f);
__Gnbmp_image_offset = read32(f);
Serial.print("offset ");
Serial.println(__Gnbmp_image_offset, DEC);
// read DIB header
tmp = read32(f);
Serial.print("header size ");
Serial.println(tmp, DEC);
int bmp_width = read32(f);
int bmp_height = read32(f);
if(bmp_width != __Gnbmp_width || bmp_height != __Gnbmp_height) { // if image is not 320x240, return false
return false;
}
if (read16(f) != 1)
return false;
bmpDepth = read16(f);
Serial.print("bitdepth ");
Serial.println(bmpDepth, DEC);
if (read32(f) != 0) {
// compression not supported!
return false;
}
Serial.print("compression ");
Serial.println(tmp, DEC);
return true;
}
/*********************************************/
// These read data from the SD card file and convert them to big endian
// (the data is stored in little endian format!)
// LITTLE ENDIAN!
uint16_t read16(File f)
{
uint16_t d;
uint8_t b;
b = f.read();
d = f.read();
d <<= 8;
d |= b;
return d;
}
// LITTLE ENDIAN!
uint32_t read32(File f)
{
uint32_t d;
uint16_t b;
b = read16(f);
d = read16(f);
d <<= 16;
d |= b;
return d;
}
void setup(void) {
Serial.begin(9600);
Serial.println(F("TFT LCD test"));
#ifdef USE_ADAFRUIT_SHIELD_PINOUT
Serial.println(F("Using Adafruit 2.4\" TFT Arduino Shield Pinout"));
#else
Serial.println(F("Using Adafruit 2.4\" TFT Breakout Board Pinout"));
#endif
Serial.print("TFT size is "); Serial.print(tft.width()); Serial.print("x"); Serial.println(tft.height());
tft.reset();
uint16_t identifier = tft.readID();
if(identifier==0x0101)
identifier=0x9341;
if(identifier == 0x9325) {
Serial.println(F("Found ILI9325 LCD driver"));
} else if(identifier == 0x4535) {
Serial.println(F("Found LGDP4535 LCD driver"));
}else if(identifier == 0x9328) {
Serial.println(F("Found ILI9328 LCD driver"));
} else if(identifier == 0x7575) {
Serial.println(F("Found HX8347G LCD driver"));
} else if(identifier == 0x9341) {
Serial.println(F("Found ILI9341 LCD driver"));
} else if(identifier == 0x8357) {
Serial.println(F("Found HX8357D LCD driver"));
} else {
Serial.print(F("Unknown LCD driver chip: "));
Serial.println(identifier, HEX);
Serial.println(F("If using the Adafruit 2.4\" TFT Arduino shield, the line:"));
Serial.println(F(" #define USE_ADAFRUIT_SHIELD_PINOUT"));
Serial.println(F("should appear in the library header (Adafruit_TFT.h)."));
Serial.println(F("If using the breakout board, it should NOT be #defined!"));
Serial.println(F("Also if using the breakout, double-check that all wiring"));
Serial.println(F("matches the tutorial."));
return;
}
tft.begin(identifier);
tft.fillScreen(BLUE);
//Init SD_Card
pinMode(10, OUTPUT);
if (!SD.begin(10)) {
Serial.println("initialization failed!");
tft.setCursor(0, 0);
tft.setTextColor(WHITE);
tft.setTextSize(1);
tft.println("SD Card Init fail.");
}else
Serial.println("initialization done.");
}
void loop(void) {
for(unsigned char i=0; i<__Gnfile_num; i++) {
bmpFile = SD.open(__Gsbmp_files[i]);
if (! bmpFile) {
Serial.println("didnt find image");
tft.setTextColor(WHITE); tft.setTextSize(1);
tft.println("didnt find BMPimage");
while (1);
}
if(! bmpReadHeader(bmpFile)) {
Serial.println("bad bmp");
tft.setTextColor(WHITE); tft.setTextSize(1);
tft.println("bad bmp");
return;
}
bmpdraw(bmpFile, 0, 0);
bmpFile.close();
delay(1000);
delay(1000);
}
}
| [
"baron@keywish-robot.com"
] | baron@keywish-robot.com |
62e76a6831c97c2982a15bd515998fd4b5313933 | 68ca8045e4c4b90a2560444fd964335f5bd2c4fc | /Source/Uprising/Public/Weapon/RangedWeapon.h | 693a80e4829ccb29a7e105238fd43ace48881c0e | [
"BSD-3-Clause"
] | permissive | jwoo1601/Unknown-Planet-Zeropist | 959fbf81e9e639c893fe1877d8e7a5d6ffe176a1 | 745ed270c9450c81d90a833c22c7845c6536173f | refs/heads/master | 2020-12-27T10:02:23.353950 | 2020-02-03T01:52:48 | 2020-02-03T01:52:48 | 237,861,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | h | // Copyright 2017 Ground Breaking Games. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Components/ArrowComponent.h"
#include "Components/SphereComponent.h"
#include "Weapon/Weapon.h"
#include "RangedWeapon.generated.h"
/**
*
*/
UCLASS(abstract, BlueprintType, Blueprintable)
class CLIENT_API ARangedWeapon : public AWeapon
{
GENERATED_BODY()
public:
ARangedWeapon(FObjectInitializer const& ObjectInitializer);
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent &e) override;
virtual void PreSave(const class ITargetPlatform* TargetPlatform) override;
#endif
private:
UPROPERTY(EditAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
FVector MuzzleOffset;
#if WITH_EDITORONLY_DATA
UPROPERTY(EditAnywhere, meta = (AllowPrivateAccess = "true"))
USphereComponent *MuzzleOffsetEd;
UPROPERTY(VisibleAnywhere, meta = (AllowPrivateAccess = "true"))
UArrowComponent *LaunchDirectionEd;
#endif
protected:
virtual TSubclassOf<class UAttackType> GetBaseAttackTypeClass_Implementation() const override;
public:
FORCEINLINE FVector GetMuzzleOffset() const { return MuzzleOffset; }
};
| [
"jkim504@myseneca.ca"
] | jkim504@myseneca.ca |
4d817a33c943b96839af4329d731b84164bda5e9 | 7c9e037f9d3b8ba210c6b7b35432b9b88c0a0664 | /4th sem programs/DAA/num_den.cpp | dee78b96d61172a544002ecd0bf92c4205d6be9e | [] | no_license | msatul1305/2nd-year-study-materials-computerScience | 876e3b2cf616953715cf92201a0098a3d67e8781 | 6eec20de52eaba720c596a9a9e9f96e9ff164ed9 | refs/heads/master | 2021-04-29T14:50:24.549898 | 2019-10-21T19:07:56 | 2019-10-21T19:07:56 | 121,784,242 | 1 | 8 | null | 2019-10-21T19:07:57 | 2018-02-16T18:15:00 | C++ | UTF-8 | C++ | false | false | 673 | cpp | #include<iostream>
using namespace std;
int fact(int *a,int d)
{
int j=0;
for(int i=1;i<=d;i++)
{
if(d%i==0)
{
a[j]=i;
j++;
}
}
cout<<"factors of "<<d<<": ";
for(int i=0;i<j;i++)
cout<<a[i]<<" ";
cout<<"\n";
return j;
}
main()
{
int a[100],b[100],n,d,sum=0,k=0;
cout<<"enter the numerator and denominator:";
cin>>n>>d;
int l=fact(a,d);
int bitmsk=1<<l;
for(int i=1;i<bitmsk;i++)
{
for(int j=0;j<l;j++)
{
if(i&(1<<j))
{
b[k]=a[j];
sum+=a[j];
k++;
}
}
if(sum==n)
{
for(int x=0;x<k;x++)
cout<<b[x]<<" ";
cout<<"\n";
}
sum=0;k=0;
}
//cout<<"\n";
}
| [
"noreply@github.com"
] | msatul1305.noreply@github.com |
550fc13e2058cd58b015a86e30ff4a2d91bbfea8 | 1269dc9b0f101302fa50416d6e4bcf287c2b58cb | /Leetcode(209-1239)/1046_last_stone_weight1.cpp | b798fa997b8f9325815654b6b9bd47e848e75c58 | [] | no_license | rishabkr/Competitive-Programming | 22cb75d972f1a56d855a24eb9513b073aee143b8 | cc2c146b228e24b3eefd3ab9b70706e2f4ba3eae | refs/heads/main | 2023-02-07T23:54:13.346228 | 2020-12-28T07:36:06 | 2020-12-28T07:36:06 | 324,932,430 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 787 | cpp | class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int>pq;
for(int stone : stones)
{
pq.push(stone);
}
while(pq.size()>1)
{
int stone1=pq.top();pq.pop();
int stone2=pq.top();pq.pop();
if(stone1==stone2)
{
continue;
}
else
{
if(stone1 > stone2)
{
pq.push(stone1-stone2);
}
else
{
pq.push(stone2-stone1);
}
}
}
return (pq.size() == 1)?pq.top():0;
}
}; | [
"noreply@github.com"
] | rishabkr.noreply@github.com |
ae7cc803b76d681fb667f3915bb13ce082a9e673 | fd4103e6f5116c776249b00171d8639313f05bc1 | /Src/Assembler/AssemView.h | a9fd065f01c7ab7e42b9ea69f15f069161b3e83c | [] | no_license | Wanghuaichen/TransCAD | 481f3b4e54cc066dde8679617a5b32ac2041911b | 35ca89af456065925984492eb23a0543e3125bb8 | refs/heads/master | 2020-03-25T03:54:51.488397 | 2018-06-25T17:38:39 | 2018-06-25T17:38:39 | 143,367,529 | 2 | 1 | null | 2018-08-03T02:30:03 | 2018-08-03T02:30:03 | null | UHC | C++ | false | false | 4,132 | h | // AssemView.h : iAssemView 클래스의 인터페이스
#pragma once
#include "AssemMacro.h"
#include ".\CHoopsView.h"
#include ".\AssemApplyConstraintDialog.h"
enum AssemModelHandedness
{
AssemHandednessSetLeft,
AssemHandednessSetRight,
AssemHandednessSetNone,
AssemHandednessNotSet
};
enum AssemModelView
{
AssemPartView,
AssemMeshView
};
class AssemHView;
class AssemDocument;
class PmeAssembly;
class AssemApplyConstraintDialog;
class ASSEM_API AssemView
: public CHoopsView
{
protected: // serialization에서만 만들어집니다.
AssemView();
DECLARE_DYNCREATE(AssemView)
// 특성
public:
AssemDocument* GetDocument() const;
AssemHView * GetHView() const;
void SetCoordinateSystemHandedness(HandednessMode rightOrLeft, bool emitMessage = true);
void SetWindowColor(COLORREF newTopColor, COLORREF newBottomColor, bool emitMessage = true);
void SetPolygonHandedness(AssemModelHandedness newHandedness);
void SetMarkupColor(COLORREF newColor, bool emitMessage = true);
void SetShadowColor(COLORREF newColor);
// 작업
private:
void ZoomCamera(double factor);
void SetInitialCameraPosition(double distance = 1000.0);
AssemModelView m_currentView;
HC_KEY m_selected_key;
BOOL OnGeomHandle;
public:
virtual void SetOperator(HBaseOperator * pNewOperator);
virtual HBaseOperator * GetOperator(void);
void FitWorld(void);
HC_KEY Selected_key() const { return m_selected_key; }
void SelectComponent(HC_KEY hKey);
void SetGeomHandleStatus(BOOL val) { OnGeomHandle = val; }
// 재정의
public:
// virtual void OnDraw(CDC* pDC); // 이 뷰를 그리기 위해 재정의되었습니다.
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
// 구현
public:
virtual ~AssemView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// 메시지 맵 함수를 생성했습니다.
protected:
DECLARE_MESSAGE_MAP()
public:
virtual void OnInitialUpdate();
protected:
virtual void OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView);
public:
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnViewPan();
afx_msg void OnUpdateViewPan(CCmdUI *pCmdUI);
afx_msg void OnViewOrbit();
afx_msg void OnUpdateViewOrbit(CCmdUI *pCmdUI);
afx_msg void OnViewZoomIn();
afx_msg void OnViewZoomOut();
afx_msg void OnViewZoomToWindow();
afx_msg void OnUpdateViewZoomToWindow(CCmdUI *pCmdUI);
afx_msg void OnViewFront();
afx_msg void OnViewBack();
afx_msg void OnViewLeft();
afx_msg void OnViewRight();
afx_msg void OnViewTop();
afx_msg void OnViewBottom();
afx_msg void OnViewWireframe();
afx_msg void OnUpdateViewWireframe(CCmdUI *pCmdUI);
afx_msg void OnViewFlatShading();
afx_msg void OnUpdateViewFlatShading(CCmdUI *pCmdUI);
afx_msg void OnViewGouroudShadihg();
afx_msg void OnUpdateViewGouroudShadihg(CCmdUI *pCmdUI);
afx_msg void OnViewPhongShading();
afx_msg void OnUpdateViewPhongShading(CCmdUI *pCmdUI);
afx_msg void OnViewHiddenLine();
afx_msg void OnUpdateViewHiddenLine(CCmdUI *pCmdUI);
afx_msg void OnViewActiveSketchViewpoint();
afx_msg void OnViewDefaultViewpoint();
afx_msg void OnViewZoomAll();
afx_msg void OnUpdateMeshGeneration(CCmdUI *pCmdUI);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
//afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
// Added by YK
protected:
AssemApplyConstraintDialog * m_pDialog;
public:
void CreateConstraintDialog( PmeStdAssemblyConstraintType type );
void DestroyActiveDialog( void );
afx_msg void OnApplyCoaxial();
afx_msg void OnApplyIncidence();
afx_msg void OnAppyParallel();
afx_msg void OnApplyPerpendicular();
afx_msg void OnApplyDistance();
afx_msg void OnApplyAngle();
};
#ifndef _DEBUG // AssemView.cpp의 디버그 버전
inline AssemDocument* AssemView::GetDocument() const
{ return reinterpret_cast<AssemDocument*>(m_pDocument); }
#endif
| [
"kyk5415@gmail.com"
] | kyk5415@gmail.com |
a41c7441ce384d9cf940d130dcef460ac7f18ba0 | 05fcca80c3fa1f4d78bf8f4aed7e8100cacb15a0 | /Young Tableau/young.cpp | c0aa885ab66bce509f7a4cc00b2a0bd757f1d2d1 | [] | no_license | diogommartins/Young-Tableau | 46be239e22f6b0deff70d12f6834d3174dc5c959 | 6ee2d65e2014792815752636c43f0c281f13b862 | refs/heads/master | 2016-09-06T07:37:30.364190 | 2015-06-15T04:59:49 | 2015-06-15T04:59:49 | 35,956,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,153 | cpp | //
// young.cpp
// Young Tableau
//
// Created by Diogo Martins on 5/20/15.
// Copyright (c) 2015 Diogo Martins. All rights reserved.
//
#include "young.h"
#define INFINITO INT_MAX
/**
1. O construtor cria um quadro vazio. Para tal, aloca espaço
para a matriz de inteiros Y, m × n e inicializa os valores com
a constante simbólica INT_MAX para representar ∞.
*/
young::young(int linhas, int colunas){
m = linhas;
n = colunas;
Y = new int*[m];
for (int i=0; i<m; i++)
Y[i] = new int[n];
for (int i=0; i<m; i++)
for(int j=0; j<n; j++)
Y[i][j] = INFINITO;
}
/**
2. O destrutor libera a memória alocada para a matriz Y .
*/
young::~young(){
delete Y;
}
/**
3. Função bool vazio() retorna true se o quadro está vazio e false,
caso contrário.
*/
bool young::vazio(){
for (int i=0; i<=m; i++)
for(int j=0; i<=n; i++)
if (Y[i][j] != INFINITO)
return false; // Se achou pelo menos uma posição preenchida
return true; // Não achou nenhuma posição preenchida
}
/**
4. Função bool cheio() retorna true se o quadro está cheio e false, caso contrário.
*/
bool young::cheio(){
for (int i=0; i<=m; i++)
for(int j=0; j<=n; j++)
if (Y[i][j] == INFINITO)
return false; // Se achou pelo menos uma posição vazia
return true; // Não achou nenhuma posição vazia
}
bool tem_esquerda(int &coluna)
{
return (coluna - 1 >= 0);
}
bool tem_topo(int &linha)
{
return (linha - 1 >= 0);
}
void young::youngify(int i, int j){
if (tem_topo(i) && (Y[i-1][j] > Y[i][j]))
{
int atual = Y[i][j];
Y[i][j] = Y[i-1][j];
Y[i-1][j] = atual;
youngify(i-1, j);
}
if(tem_esquerda(j) && (Y[i][j-1] > Y[i][j]))
{
int atual = Y[i][j];
Y[i][j] = Y[i][j-1];
Y[i][j-1] = atual;
youngify(i, j-1);
}
}
void troca(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void youngfy_remove(int **Y, int i, int j, int &m, int &n)
{
int menor_i = i;
int menor_j = j;
if (i+1 <= m && (Y[i][j] > Y[i+1][j]))
{
menor_i = i+1;
menor_j = j;
}
if (j+1 <= n && (Y[menor_i][menor_j] > Y[i][j+1]))
{
menor_i = i;
menor_j = j+1;
}
if ((menor_i != i) || (menor_j != j))
{
troca(Y[i][j], Y[menor_i][menor_j]);
youngfy_remove(Y, menor_i, menor_j, m, n);
}
}
/**
5. Função bool remove(int & elem) para extrair o menor elemento do quadro. Uma vez que o menor elemento está sempre na posição Y [1, 1] (no caso da linguagem C, Y [0, 0] ) a função pode retornar o elemento armazenado em Y [1, 1] e fazer Y [1, 1] = ∞ para indicar que o elemento não existe mais. Entretanto, tal fato pode deixar o quadro inconsistente. Isso acontece quando Y [1, 1] = ∞ e o quadro não está vazio.
*/
bool young::remove(int &elem){
if (!vazio()){
elem = Y[0][0];
Y[0][0] = INFINITO;
youngfy_remove(Y, 0, 0, m, n);
return true;
}
return false;
}
/**
6. Função bool insere(int valor), para inserir um elemento no quadro. Se o quadro não estiver cheio, então Y [m, n] = ∞ (no caso da linguagem C, Y [m − 1, n − 1] ) e é possível colocar o novo elemento nesta posição. Entretanto, o quadro pode ficar inconsistente. Pode-se resolver este problema recursivamente retraindo o elemento novo e trocando-o com o elemento da esquerda ou do topo até conseguir um quadro de Young. A função retorna true se o elemento foi inserido com sucesso e false, caso contrário.
*/
bool young::insere(int valor){
if (!cheio()){
Y[m-1][n-1] = valor;
youngify(m-1, n-1);
return true;
}
return false;
}
string human_representation(int &valor){
if (valor != INFINITO)
return to_string(valor);
return "∞";
}
void young::imprime(){
for (int i=0; i<m; i++){
for(int j=0; j<n; j++)
cout << human_representation(Y[i][j]) << "\t";
cout << "\n";
}
cout << "\n";
} | [
"diogo.martins@unirio.br"
] | diogo.martins@unirio.br |
53dea4ae952976b59350d802059074f05e3db401 | ed3b7df04010a4256ffff4b77c9887ecd78eb3e0 | /PacmanGameInstance.cpp | 795e8999dfe5c66667d341d4f2b93f558e3b7fd0 | [] | no_license | Xperience8/Pacman | fffd9b7eaaa56e1273c9c90f8da8d4a0b9b5bcb5 | bfa09f8fced1cf2cd42a0cbeb813240b6a59187c | refs/heads/master | 2021-05-04T10:45:26.188715 | 2016-09-05T15:59:50 | 2016-09-05T15:59:50 | 53,679,603 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 354 | cpp | // Copyright 2015 Patrick Jurasek. All Rights Reserved.
#include "Pacman.h"
#include "PacmanGameInstance.h"
#include "NavigationSystem/PacmanNavigationSystem.h"
void UPacmanGameInstance::Init()
{
NavigationSystem = NewObject<UPacmanNavigationSystem>(UPacmanNavigationSystem::StaticClass());
GNavigationSystem = NavigationSystem;
Super::Init();
}
| [
"jurasek.patrik@hotmail.com"
] | jurasek.patrik@hotmail.com |
126f05a106dae8ebeae774c1d94c83d862ffc7f3 | e8578293355f46775bc45bac5f605e1a1c04228a | /packages/pigeon/platform_tests/test_plugin/windows/test_plugin.cpp | ea71a076344e70482a6789f11ab480440c43bef4 | [
"BSD-3-Clause"
] | permissive | flutter/packages | 894505f1c52551034bbdf91a6d112188acdd35a0 | cd94db1f084adf0fe5665441eb8ad0dfc39a5893 | refs/heads/main | 2023-09-01T11:28:38.827379 | 2023-08-31T21:03:20 | 2023-08-31T21:03:20 | 99,045,602 | 3,581 | 2,225 | BSD-3-Clause | 2023-09-14T20:34:44 | 2017-08-01T21:43:32 | Dart | UTF-8 | C++ | false | false | 18,241 | cpp | // Copyright 2013 The Flutter 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 "test_plugin.h"
// This must be included before many other Windows headers.
#include <flutter/plugin_registrar_windows.h>
#include <windows.h>
#include <memory>
#include <optional>
#include <string>
#include "pigeon/core_tests.gen.h"
namespace test_plugin {
using core_tests_pigeontest::AllClassesWrapper;
using core_tests_pigeontest::AllNullableTypes;
using core_tests_pigeontest::AllTypes;
using core_tests_pigeontest::AnEnum;
using core_tests_pigeontest::ErrorOr;
using core_tests_pigeontest::FlutterError;
using core_tests_pigeontest::FlutterIntegrationCoreApi;
using core_tests_pigeontest::HostIntegrationCoreApi;
using flutter::EncodableList;
using flutter::EncodableMap;
using flutter::EncodableValue;
// static
void TestPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarWindows* registrar) {
auto plugin = std::make_unique<TestPlugin>(registrar->messenger());
HostIntegrationCoreApi::SetUp(registrar->messenger(), plugin.get());
registrar->AddPlugin(std::move(plugin));
}
TestPlugin::TestPlugin(flutter::BinaryMessenger* binary_messenger)
: flutter_api_(
std::make_unique<FlutterIntegrationCoreApi>(binary_messenger)) {}
TestPlugin::~TestPlugin() {}
std::optional<FlutterError> TestPlugin::Noop() { return std::nullopt; }
ErrorOr<AllTypes> TestPlugin::EchoAllTypes(const AllTypes& everything) {
return everything;
}
ErrorOr<std::optional<AllNullableTypes>> TestPlugin::EchoAllNullableTypes(
const AllNullableTypes* everything) {
if (!everything) {
return std::nullopt;
}
return *everything;
}
ErrorOr<std::optional<flutter::EncodableValue>> TestPlugin::ThrowError() {
return FlutterError("An error");
}
std::optional<FlutterError> TestPlugin::ThrowErrorFromVoid() {
return FlutterError("An error");
}
ErrorOr<std::optional<flutter::EncodableValue>>
TestPlugin::ThrowFlutterError() {
return FlutterError("code", "message", EncodableValue("details"));
}
ErrorOr<int64_t> TestPlugin::EchoInt(int64_t an_int) { return an_int; }
ErrorOr<double> TestPlugin::EchoDouble(double a_double) { return a_double; }
ErrorOr<bool> TestPlugin::EchoBool(bool a_bool) { return a_bool; }
ErrorOr<std::string> TestPlugin::EchoString(const std::string& a_string) {
return a_string;
}
ErrorOr<std::vector<uint8_t>> TestPlugin::EchoUint8List(
const std::vector<uint8_t>& a_uint8_list) {
return a_uint8_list;
}
ErrorOr<EncodableValue> TestPlugin::EchoObject(
const EncodableValue& an_object) {
return an_object;
}
ErrorOr<EncodableList> TestPlugin::EchoList(const EncodableList& a_list) {
return a_list;
}
ErrorOr<EncodableMap> TestPlugin::EchoMap(const EncodableMap& a_map) {
return a_map;
}
ErrorOr<AllClassesWrapper> TestPlugin::EchoClassWrapper(
const AllClassesWrapper& wrapper) {
return wrapper;
}
ErrorOr<AnEnum> TestPlugin::EchoEnum(const AnEnum& an_enum) { return an_enum; }
ErrorOr<std::optional<std::string>> TestPlugin::ExtractNestedNullableString(
const AllClassesWrapper& wrapper) {
const std::string* inner_string =
wrapper.all_nullable_types().a_nullable_string();
return inner_string ? std::optional<std::string>(*inner_string)
: std::nullopt;
}
ErrorOr<AllClassesWrapper> TestPlugin::CreateNestedNullableString(
const std::string* nullable_string) {
AllNullableTypes inner_object;
// The string pointer can't be passed through directly since the setter for
// a string takes a std::string_view rather than std::string so the pointer
// types don't match.
if (nullable_string) {
inner_object.set_a_nullable_string(*nullable_string);
} else {
inner_object.set_a_nullable_string(nullptr);
}
AllClassesWrapper wrapper(inner_object);
return wrapper;
}
ErrorOr<AllNullableTypes> TestPlugin::SendMultipleNullableTypes(
const bool* a_nullable_bool, const int64_t* a_nullable_int,
const std::string* a_nullable_string) {
AllNullableTypes someTypes;
someTypes.set_a_nullable_bool(a_nullable_bool);
someTypes.set_a_nullable_int(a_nullable_int);
// The string pointer can't be passed through directly since the setter for
// a string takes a std::string_view rather than std::string so the pointer
// types don't match.
if (a_nullable_string) {
someTypes.set_a_nullable_string(*a_nullable_string);
} else {
someTypes.set_a_nullable_string(nullptr);
}
return someTypes;
};
ErrorOr<std::optional<int64_t>> TestPlugin::EchoNullableInt(
const int64_t* a_nullable_int) {
if (!a_nullable_int) {
return std::nullopt;
}
return *a_nullable_int;
};
ErrorOr<std::optional<double>> TestPlugin::EchoNullableDouble(
const double* a_nullable_double) {
if (!a_nullable_double) {
return std::nullopt;
}
return *a_nullable_double;
};
ErrorOr<std::optional<bool>> TestPlugin::EchoNullableBool(
const bool* a_nullable_bool) {
if (!a_nullable_bool) {
return std::nullopt;
}
return *a_nullable_bool;
};
ErrorOr<std::optional<std::string>> TestPlugin::EchoNullableString(
const std::string* a_nullable_string) {
if (!a_nullable_string) {
return std::nullopt;
}
return *a_nullable_string;
};
ErrorOr<std::optional<std::vector<uint8_t>>> TestPlugin::EchoNullableUint8List(
const std::vector<uint8_t>* a_nullable_uint8_list) {
if (!a_nullable_uint8_list) {
return std::nullopt;
}
return *a_nullable_uint8_list;
};
ErrorOr<std::optional<EncodableValue>> TestPlugin::EchoNullableObject(
const EncodableValue* a_nullable_object) {
if (!a_nullable_object) {
return std::nullopt;
}
return *a_nullable_object;
};
ErrorOr<std::optional<EncodableList>> TestPlugin::EchoNullableList(
const EncodableList* a_nullable_list) {
if (!a_nullable_list) {
return std::nullopt;
}
return *a_nullable_list;
};
ErrorOr<std::optional<EncodableMap>> TestPlugin::EchoNullableMap(
const EncodableMap* a_nullable_map) {
if (!a_nullable_map) {
return std::nullopt;
}
return *a_nullable_map;
};
ErrorOr<std::optional<AnEnum>> TestPlugin::EchoNullableEnum(
const AnEnum* an_enum) {
if (!an_enum) {
return std::nullopt;
}
return *an_enum;
}
void TestPlugin::NoopAsync(
std::function<void(std::optional<FlutterError> reply)> result) {
result(std::nullopt);
}
void TestPlugin::ThrowAsyncError(
std::function<void(ErrorOr<std::optional<EncodableValue>> reply)> result) {
result(FlutterError("code", "message", EncodableValue("details")));
}
void TestPlugin::ThrowAsyncErrorFromVoid(
std::function<void(std::optional<FlutterError> reply)> result) {
result(FlutterError("code", "message", EncodableValue("details")));
}
void TestPlugin::ThrowAsyncFlutterError(
std::function<void(ErrorOr<std::optional<EncodableValue>> reply)> result) {
result(FlutterError("code", "message", EncodableValue("details")));
}
void TestPlugin::EchoAsyncAllTypes(
const AllTypes& everything,
std::function<void(ErrorOr<AllTypes> reply)> result) {
result(everything);
}
void TestPlugin::EchoAsyncInt(
int64_t an_int, std::function<void(ErrorOr<int64_t> reply)> result) {
result(an_int);
}
void TestPlugin::EchoAsyncDouble(
double a_double, std::function<void(ErrorOr<double> reply)> result) {
result(a_double);
}
void TestPlugin::EchoAsyncBool(
bool a_bool, std::function<void(ErrorOr<bool> reply)> result) {
result(a_bool);
}
void TestPlugin::EchoAsyncString(
const std::string& a_string,
std::function<void(ErrorOr<std::string> reply)> result) {
result(a_string);
}
void TestPlugin::EchoAsyncUint8List(
const std::vector<uint8_t>& a_uint8_list,
std::function<void(ErrorOr<std::vector<uint8_t>> reply)> result) {
result(a_uint8_list);
}
void TestPlugin::EchoAsyncObject(
const EncodableValue& an_object,
std::function<void(ErrorOr<EncodableValue> reply)> result) {
result(an_object);
}
void TestPlugin::EchoAsyncList(
const EncodableList& a_list,
std::function<void(ErrorOr<EncodableList> reply)> result) {
result(a_list);
}
void TestPlugin::EchoAsyncMap(
const EncodableMap& a_map,
std::function<void(ErrorOr<EncodableMap> reply)> result) {
result(a_map);
}
void TestPlugin::EchoAsyncEnum(
const AnEnum& an_enum, std::function<void(ErrorOr<AnEnum> reply)> result) {
result(an_enum);
}
void TestPlugin::EchoAsyncNullableAllNullableTypes(
const AllNullableTypes* everything,
std::function<void(ErrorOr<std::optional<AllNullableTypes>> reply)>
result) {
result(everything ? std::optional<AllNullableTypes>(*everything)
: std::nullopt);
}
void TestPlugin::EchoAsyncNullableInt(
const int64_t* an_int,
std::function<void(ErrorOr<std::optional<int64_t>> reply)> result) {
result(an_int ? std::optional<int64_t>(*an_int) : std::nullopt);
}
void TestPlugin::EchoAsyncNullableDouble(
const double* a_double,
std::function<void(ErrorOr<std::optional<double>> reply)> result) {
result(a_double ? std::optional<double>(*a_double) : std::nullopt);
}
void TestPlugin::EchoAsyncNullableBool(
const bool* a_bool,
std::function<void(ErrorOr<std::optional<bool>> reply)> result) {
result(a_bool ? std::optional<bool>(*a_bool) : std::nullopt);
}
void TestPlugin::EchoAsyncNullableString(
const std::string* a_string,
std::function<void(ErrorOr<std::optional<std::string>> reply)> result) {
result(a_string ? std::optional<std::string>(*a_string) : std::nullopt);
}
void TestPlugin::EchoAsyncNullableUint8List(
const std::vector<uint8_t>* a_uint8_list,
std::function<void(ErrorOr<std::optional<std::vector<uint8_t>>> reply)>
result) {
result(a_uint8_list ? std::optional<std::vector<uint8_t>>(*a_uint8_list)
: std::nullopt);
}
void TestPlugin::EchoAsyncNullableObject(
const EncodableValue* an_object,
std::function<void(ErrorOr<std::optional<EncodableValue>> reply)> result) {
result(an_object ? std::optional<EncodableValue>(*an_object) : std::nullopt);
}
void TestPlugin::EchoAsyncNullableList(
const EncodableList* a_list,
std::function<void(ErrorOr<std::optional<EncodableList>> reply)> result) {
result(a_list ? std::optional<EncodableList>(*a_list) : std::nullopt);
}
void TestPlugin::EchoAsyncNullableMap(
const EncodableMap* a_map,
std::function<void(ErrorOr<std::optional<EncodableMap>> reply)> result) {
result(a_map ? std::optional<EncodableMap>(*a_map) : std::nullopt);
}
void TestPlugin::EchoAsyncNullableEnum(
const AnEnum* an_enum,
std::function<void(ErrorOr<std::optional<AnEnum>> reply)> result) {
result(an_enum ? std::optional<AnEnum>(*an_enum) : std::nullopt);
}
void TestPlugin::CallFlutterNoop(
std::function<void(std::optional<FlutterError> reply)> result) {
flutter_api_->Noop([result]() { result(std::nullopt); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterThrowError(
std::function<void(ErrorOr<std::optional<flutter::EncodableValue>> reply)>
result) {
flutter_api_->ThrowError(
[result](const std::optional<flutter::EncodableValue>& echo) {
result(echo);
},
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterThrowErrorFromVoid(
std::function<void(std::optional<FlutterError> reply)> result) {
flutter_api_->ThrowErrorFromVoid(
[result]() { result(std::nullopt); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoAllTypes(
const AllTypes& everything,
std::function<void(ErrorOr<AllTypes> reply)> result) {
flutter_api_->EchoAllTypes(
everything, [result](const AllTypes& echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoAllNullableTypes(
const AllNullableTypes* everything,
std::function<void(ErrorOr<std::optional<AllNullableTypes>> reply)>
result) {
flutter_api_->EchoAllNullableTypes(
everything,
[result](const AllNullableTypes* echo) {
result(echo ? std::optional<AllNullableTypes>(*echo) : std::nullopt);
},
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterSendMultipleNullableTypes(
const bool* a_nullable_bool, const int64_t* a_nullable_int,
const std::string* a_nullable_string,
std::function<void(ErrorOr<AllNullableTypes> reply)> result) {
flutter_api_->SendMultipleNullableTypes(
a_nullable_bool, a_nullable_int, a_nullable_string,
[result](const AllNullableTypes& echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoBool(
bool a_bool, std::function<void(ErrorOr<bool> reply)> result) {
flutter_api_->EchoBool(
a_bool, [result](bool echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoInt(
int64_t an_int, std::function<void(ErrorOr<int64_t> reply)> result) {
flutter_api_->EchoInt(
an_int, [result](int64_t echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoDouble(
double a_double, std::function<void(ErrorOr<double> reply)> result) {
flutter_api_->EchoDouble(
a_double, [result](double echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoString(
const std::string& a_string,
std::function<void(ErrorOr<std::string> reply)> result) {
flutter_api_->EchoString(
a_string, [result](const std::string& echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoUint8List(
const std::vector<uint8_t>& a_list,
std::function<void(ErrorOr<std::vector<uint8_t>> reply)> result) {
flutter_api_->EchoUint8List(
a_list, [result](const std::vector<uint8_t>& echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoList(
const EncodableList& a_list,
std::function<void(ErrorOr<EncodableList> reply)> result) {
flutter_api_->EchoList(
a_list, [result](const EncodableList& echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoMap(
const EncodableMap& a_map,
std::function<void(ErrorOr<EncodableMap> reply)> result) {
flutter_api_->EchoMap(
a_map, [result](const EncodableMap& echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoEnum(
const AnEnum& an_enum, std::function<void(ErrorOr<AnEnum> reply)> result) {
flutter_api_->EchoEnum(
an_enum, [result](const AnEnum& echo) { result(echo); },
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoNullableBool(
const bool* a_bool,
std::function<void(ErrorOr<std::optional<bool>> reply)> result) {
flutter_api_->EchoNullableBool(
a_bool,
[result](const bool* echo) {
result(echo ? std::optional<bool>(*echo) : std::nullopt);
},
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoNullableInt(
const int64_t* an_int,
std::function<void(ErrorOr<std::optional<int64_t>> reply)> result) {
flutter_api_->EchoNullableInt(
an_int,
[result](const int64_t* echo) {
result(echo ? std::optional<int64_t>(*echo) : std::nullopt);
},
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoNullableDouble(
const double* a_double,
std::function<void(ErrorOr<std::optional<double>> reply)> result) {
flutter_api_->EchoNullableDouble(
a_double,
[result](const double* echo) {
result(echo ? std::optional<double>(*echo) : std::nullopt);
},
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoNullableString(
const std::string* a_string,
std::function<void(ErrorOr<std::optional<std::string>> reply)> result) {
flutter_api_->EchoNullableString(
a_string,
[result](const std::string* echo) {
result(echo ? std::optional<std::string>(*echo) : std::nullopt);
},
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoNullableUint8List(
const std::vector<uint8_t>* a_list,
std::function<void(ErrorOr<std::optional<std::vector<uint8_t>>> reply)>
result) {
flutter_api_->EchoNullableUint8List(
a_list,
[result](const std::vector<uint8_t>* echo) {
result(echo ? std::optional<std::vector<uint8_t>>(*echo)
: std::nullopt);
},
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoNullableList(
const EncodableList* a_list,
std::function<void(ErrorOr<std::optional<EncodableList>> reply)> result) {
flutter_api_->EchoNullableList(
a_list,
[result](const EncodableList* echo) {
result(echo ? std::optional<EncodableList>(*echo) : std::nullopt);
},
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoNullableMap(
const EncodableMap* a_map,
std::function<void(ErrorOr<std::optional<EncodableMap>> reply)> result) {
flutter_api_->EchoNullableMap(
a_map,
[result](const EncodableMap* echo) {
result(echo ? std::optional<EncodableMap>(*echo) : std::nullopt);
},
[result](const FlutterError& error) { result(error); });
}
void TestPlugin::CallFlutterEchoNullableEnum(
const AnEnum* an_enum,
std::function<void(ErrorOr<std::optional<AnEnum>> reply)> result) {
flutter_api_->EchoNullableEnum(
an_enum,
[result](const AnEnum* echo) {
result(echo ? std::optional<AnEnum>(*echo) : std::nullopt);
},
[result](const FlutterError& error) { result(error); });
}
} // namespace test_plugin
| [
"noreply@github.com"
] | flutter.noreply@github.com |
3bfb432a52e3e206b9366d9aaeea0a05162bd888 | 4e57cfc1809d50e979a6e46302065b4a99a26747 | /RenderEngine/FPCExtension.h | 11e170152bbc036eeb846e2368234f65554b40db | [] | no_license | GScience-Studio/MagicCube | ca2966d63d203d62df00ba40ff3e7c147758a98f | 9d51f8f87bcc461fa2a57ea5ac4606347d48711f | refs/heads/master | 2020-09-24T00:23:30.611638 | 2017-04-19T09:58:16 | 2017-04-19T09:58:16 | 67,795,557 | 9 | 4 | null | null | null | null | GB18030 | C++ | false | false | 234 | h | #pragma once
#include "ExtensionManager.h"
#include "FPCManager.h"
#include "Application.h"
//第一人称控制器扩展
class fpc_extension :public extension
{
public:
fpc_extension() :extension(std::string("FPCExtension")) {}
}; | [
"GM2000@outlook.com"
] | GM2000@outlook.com |
092d696783ca260cfb912c92194e6a56bbbf32c2 | b3814242f60ebb4393e4a105b91ac464078c88a7 | /shared/packets/ClientPacketWrapper.hpp | 3e3c0b018c2825f371c776a7875e8bf110e7b406 | [] | no_license | Techno-coder/SpaceShift | f858402c60637bfa68ff700c29557620cfee0966 | ed3a6a041d9d7ea2078242e38998f4f299e59040 | refs/heads/master | 2021-03-27T13:59:35.785446 | 2017-09-27T06:56:57 | 2017-09-27T06:56:57 | 103,614,271 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 464 | hpp | #pragma once
#include "PacketWrapper.hpp"
class ClientPacketWrapper : public PacketWrapper {
public:
enum class Type : sf::Uint16 {
DISCONNECT = 0,
AUTHENTICATION_REQUEST = 1,
CHECK_ALIVE_RESPONSE = 2,
QUICK_JOIN_REQUEST = 3,
MOVE_REQUEST = 5
} type = Type::DISCONNECT;
private:
sf::Uint16 getType() const override {
return static_cast<sf::Uint16>(type);
}
void setType(sf::Uint16 newType) override {
type = static_cast<Type>(newType);
}
}; | [
"zhiyuanqi@hotmail.co.nz"
] | zhiyuanqi@hotmail.co.nz |
05df86d3d1041bb549f6e6cb27c4fc07f24327b4 | e9f3369247da3435cd63f2d67aa95c890912255c | /problem399.cpp | 444faf9c2f9463834e309df423265a82a1680eec | [] | no_license | panthitesh6410/problem-solving-C- | 27b31a141669b91eb36709f0126be05f241dfb13 | 24b72fc795b7b5a44e22e5f6ca9faad462a097fb | refs/heads/master | 2021-11-15T21:52:33.523503 | 2021-10-17T16:20:58 | 2021-10-17T16:20:58 | 248,523,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | cpp | // Codechef March Cook-Off 2021 Div-3 Problem
#include<climits>
#include<iostream>
using namespace std;
bool has_odd_factors(unsigned long long int num){
unsigned long long int count = 0;
for(unsigned long long int i=1;i<=num/2;i++){
if(num%i == 0)
count++;
}
if(count % 2 != 0)
return true;
return false;
}
int main(){
int t;
cin>>t;
while(t--){
int guess;
// unsigned long long int num = 1;
for(unsigned long long int i=1;i<LLONG_MAX;i++){
if(has_odd_factors(i)){
cout<<i;
cin>>guess;
if(guess == 1)
continue;
}
}
}
return 0;
} | [
"panthitesh6410@gmail.com"
] | panthitesh6410@gmail.com |
285f48689df4cf2ae19bc3ad9a252b7a44db517d | 8b3e6319a91aaea381ff6dac26ddbe6018b75dd2 | /src/consensus/tx_verify.h | 7292fc30dd62e2214659fb9f628b3fd0f44c972d | [
"MIT"
] | permissive | JihanSilbert/Titan | 9ddd7d57a6fa59501ac748c853ef5ff3a12ba51e | 4dfd180ca8518c3ba7160c6cf113eb4e1237c42d | refs/heads/master | 2020-08-15T16:07:37.998031 | 2019-10-19T10:45:49 | 2019-10-19T10:45:49 | 215,368,860 | 0 | 0 | MIT | 2019-10-15T18:27:27 | 2019-10-15T18:27:27 | null | UTF-8 | C++ | false | false | 3,900 | h | // Copyright (c) 2017-2019 The Bitcoin Core developers
// Copyright (c) 2017 The Raven Core developers
// Copyright (c) 2018 The Rito Core developers
// Copyright (c) 2019 The Titancoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef TTN_CONSENSUS_TX_VERIFY_H
#define TTN_CONSENSUS_TX_VERIFY_H
#include "amount.h"
#include <stdint.h>
#include <vector>
#include <string>
class CBlockIndex;
class CCoinsViewCache;
class CTransaction;
class CValidationState;
class CAssetsCache;
class CTxOut;
class uint256;
/** Transaction validation functions */
/** Context-independent validity checks */
bool CheckTransaction(const CTransaction& tx, CValidationState& state, CAssetsCache* assetCache = nullptr, bool fCheckDuplicateInputs=true, bool fMemPoolCheck=false, bool fCheckAssetDuplicate = true, bool fForceDuplicateCheck = true);
namespace Consensus {
/**
* Check whether all inputs of this transaction are valid (no double spends and amounts)
* This does not modify the UTXO set. This does not check scripts and sigs.
* @param[out] txfee Set to the transaction fee if successful.
* Preconditions: tx.IsCoinBase() is false.
*/
bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee);
/** TTN START */
bool CheckTxAssets(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, std::vector<std::pair<std::string, uint256> >& vPairReissueAssets, const bool fRunningUnitTests = false, CAssetsCache* assetsCache=nullptr);
/** TTN END */
} // namespace Consensus
/** Auxiliary functions for transaction validation (ideally should not be exposed) */
/**
* Count ECDSA signature operations the old-fashioned (pre-0.6) way
* @return number of sigops this transaction's outputs will produce when spent
* @see CTransaction::FetchInputs
*/
unsigned int GetLegacySigOpCount(const CTransaction& tx);
/**
* Count ECDSA signature operations in pay-to-script-hash inputs.
*
* @param[in] mapInputs Map of previous transactions that have outputs we're spending
* @return maximum number of sigops required to validate this transaction's inputs
* @see CTransaction::FetchInputs
*/
unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
/**
* Compute total signature operation cost of a transaction.
* @param[in] tx Transaction for which we are computing the cost
* @param[in] inputs Map of previous transactions that have outputs we're spending
* @param[out] flags Script verification flags
* @return Total signature operation cost of tx
*/
int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags);
/**
* Check if transaction is final and can be included in a block with the
* specified height and time. Consensus critical.
*/
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
/**
* Calculates the block height and previous block's median time past at
* which the transaction will be considered final in the context of BIP 68.
* Also removes from the vector of input heights any entries which did not
* correspond to sequence locked inputs as they do not affect the calculation.
*/
std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block);
bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair);
/**
* Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
* Consensus critical. Takes as input a list of heights at which tx's inputs (in order) confirmed.
*/
bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block);
#endif // TTN_CONSENSUS_TX_VERIFY_H
| [
"info@jccoin.co"
] | info@jccoin.co |
2a089951cc662db9871094177018cda9a2997f2e | 0fb13dbb9903873f2a6b9833a6a1fac3e8d23909 | /AlphaCipher/Exceptions.h | 5764570070a97a317b793c58d1c9bba2d74f9f7d | [] | no_license | Kirusel/4laba-timp | fe8e93366b2024607d36b6d39cbd4bfdcd47617a | c2adc3f57f5d6d1a027cbf2f98e046878a4ceb5f | refs/heads/master | 2023-05-14T21:27:54.746485 | 2021-06-01T11:03:46 | 2021-06-01T11:03:46 | 372,798,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,367 | h | /**
* @class MyExceptions
* @author Kirill Koltunov 20PT1
* @date 06/01/21
* @file Exceptions.h
* @brief Header file for MyExpections
*/
#pragma once
#include <stdexcept>
#include <string>
#include <iostream>
using namespace std;
/// @brief Класс для обработки ошибок
class MyExceptions : public invalid_argument
{
private:
int num; ///< атрибут, хранящий код ошибки
string correction; ///< атрибут, хранящий информацию об исправлении ошибки
public:
/// @brief Запрещающий конструктор
MyExceptions() = delete;
/** @brief Конструктор с параметрами
* @param num - целочисленное число, хранящее информацию о коде ошибки
* @param error - строка, хранящая описание ошибки.
* @param correction - строка, хранящая информацию об исправлении ошибки
*/
MyExceptions (const string & error, const int &num, const string &fix);
/// @brief Предназначен для вывода информации об исправлении ошибки
void fix ();
/// @brief Предназначен для вывода кода ошибки
void code ();
}; | [
"kirill_koltunov@mail.ru"
] | kirill_koltunov@mail.ru |
2538a3a9b373b02173300a8cfb1b88e1081ffbb9 | 9b920b5572dd7196de8adea6ed9b4e3859bd90d7 | /code/Classes/Bullet.cpp | e2acc6951ce4f16dea4d2f3b88be395454eeb48e | [] | no_license | SYSUcarey/Survivor_Island | 712ac4d2758d383d20013dffe60834e06e43d50a | be062a0d445165b3341f2b5f2de4420258ecf7fc | refs/heads/master | 2020-03-24T14:11:02.152507 | 2018-07-29T13:04:35 | 2018-07-29T13:04:35 | 142,761,481 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 5,994 | cpp | #include"Bullet.h"
#include"GlobalVar.h"
USING_NS_CC;
bulletFactory* bulletFactory::bulletfactory = NULL;
bulletFactory::bulletFactory() {
initSpriteFrame();
}
bulletFactory* bulletFactory::getInstance() {
if (bulletfactory == NULL) {
bulletfactory = new bulletFactory();
}
return bulletfactory;
}
// 产生子弹,进入Vector中,返回子弹Sprite*
Sprite* bulletFactory::createBullet(int type, bool isPlayer1) {
// 根据不同类型的子弹,创建到场景子弹队列中,同时剩余弹药数要减一
// 如果子弹不足,返回NULL
if (isPlayer1 && bulletNumForPlayer1[type] <= 0) return NULL;
if (!isPlayer1 && bulletNumForPlayer2[type] <= 0) return NULL;
// 判断是否执行完射击动作(除了UZI都不能连发)
bool isShotDone = (isPlayer1) ? GlobalVar::getInstance()->player1_isShotDone : GlobalVar::getInstance()->player2_isShotDone;
if (type != 1 && !isShotDone) return NULL;
std::string pic = "bullet" + Value(type+1).asString() + ".png";
Sprite* b = Sprite::create(pic.c_str());
setScale_and_setRotation(b, type, isPlayer1);
if (isPlayer1) {
bulletForPlayer1[type].pushBack(b);
bulletNumForPlayer1[type]--;
}
else {
bulletForPlayer2[type].pushBack(b);
bulletNumForPlayer2[type]--;
}
return b;
}
//移除子弹
void bulletFactory::removeBullet(Sprite* sp, int type, bool isPlayer1) {
/*
Animation* anim = Animation::createWithSpriteFrames(monsterDead, 0.2);
Animate* ani = Animate::create(anim);
Sequence* seq = Sequence::create(ani, CallFunc::create(CC_CALLBACK_0(Sprite::removeFromParent, sp)), NULL);
sp->runAction(seq);
monster.eraseObject(sp);
*/
if (isPlayer1) {
bulletForPlayer1[type].eraseObject(sp);
}
else {
bulletForPlayer2[type].eraseObject(sp);
}
sp->removeFromParent();
}
void bulletFactory::moveMonster(Vec2 playerPos, float time) {
/*
for (auto i : monster) {
Vec2 Pos = i->getPosition();
Vec2 dir = playerPos - Pos;
dir.normalize();
i->runAction(MoveBy::create(time, dir * 30));
}
*/
}
//判断碰撞
Sprite* bulletFactory::collider(Rect rect) {
/*
for (auto i : monster) {
if (rect.containsPoint(i->getPosition())) {
return i;
}
}
return NULL;
*/
return NULL;
}
void bulletFactory::initSpriteFrame() {
/*
auto texture = Director::getInstance()->getTextureCache()->addImage("Monster.png");
monsterDead.reserve(4);
for (int i = 0; i < 4; i++) {
auto frame = SpriteFrame::createWithTexture(texture, CC_RECT_PIXELS_TO_POINTS(Rect(258 - 48 * i, 0, 42, 42)));
monsterDead.pushBack(frame);
}
*/
//auto bullet1_texture = Director::getInstance()->getTextureCache()->addImage("bullet1");
}
// 获得现有子弹数量
int bulletFactory::getBulletNum(int type, bool isPlayer1)
{
if (isPlayer1) return bulletNumForPlayer1[type];
return bulletNumForPlayer2[type];
}
// 获得场景中子弹的队列
Vector<Sprite*> bulletFactory::getBulletNumInScene(int type, bool isPlayer1)
{
if (isPlayer1) return bulletForPlayer1[type];
return bulletForPlayer2[type];
}
// 根据子弹类型、玩家朝向调节子弹大小和方向和锚点(激光枪)
void bulletFactory::setScale_and_setRotation(Sprite* b, int type, bool isPlayer1)
{
// 获得玩家的朝向toward
std::string toward = (isPlayer1) ? GlobalVar::getInstance()->player1_toward : GlobalVar::getInstance()->player2_toward;
//根据type调整精灵大小,根据toward设置锚点
switch (type)
{
case 0 :
b->setScale(0.5);
break;
case 1 :
b->setScaleY(0.5);
break;
case 2 :
b->setScale(0.5);
break;
case 3 :
b->setScale(0.2);
break;
case 4 :
b->setScaleY(1.5);
break;
case 5 :
b->setScaleY(0.5);
b->ignoreAnchorPointForPosition(false);
b->setAnchorPoint(ccp(1, 0));
break;
default:
break;
}
//根据朝向toward设置子弹旋转
float angle;
for (int i = 0; i < 8; i++) {
if (toward == GlobalVar::getInstance()->Direction[i]) {
angle = i * 45;
break;
}
}
b->setRotation(angle);
}
// 子弹发射之后的轨迹运行
void bulletFactory::moveBullet(Sprite * b, int type, bool isPlayer1) {
// 获得玩家朝向
std::string toward = (isPlayer1) ? GlobalVar::getInstance()->player1_toward : GlobalVar::getInstance()->player2_toward;
Vec2 nextNearPos = Vec2(0, 0);
Vec2 nextFarPos = Vec2(0, 0);
if (toward == GlobalVar::getInstance()->Direction[0]) {
nextNearPos = Vec2(-300, 0);
nextFarPos = Vec2(-500,0);
}
else if (toward == GlobalVar::getInstance()->Direction[1]) {
nextNearPos = Vec2(-200, 200);
nextFarPos = Vec2(-350, 350);
}
else if (toward == GlobalVar::getInstance()->Direction[2]) {
nextNearPos = Vec2(0, 300);
nextFarPos = Vec2(0, 500);
}
else if (toward == GlobalVar::getInstance()->Direction[3]) {
nextNearPos = Vec2(200, 200);
nextFarPos = Vec2(350, 350);
}
else if (toward == GlobalVar::getInstance()->Direction[4]) {
nextNearPos = Vec2(300, 0);
nextFarPos = Vec2(500, 0);
}
else if (toward == GlobalVar::getInstance()->Direction[5]) {
nextNearPos = Vec2(200, -200);
nextFarPos = Vec2(350, -350);
}
else if (toward == GlobalVar::getInstance()->Direction[6]) {
nextNearPos = Vec2(0, -300);
nextFarPos = Vec2(0, -500);
}
else if (toward == GlobalVar::getInstance()->Direction[7]) {
nextNearPos = Vec2(-200, -200);
nextFarPos = Vec2(-350, -350);
}
auto MoveToNear = MoveBy::create(0.5f, nextNearPos);
auto MoveToFar = MoveBy::create(0.5f, nextFarPos);
auto disapper = CallFunc::create([&, b, type, isPlayer1]() {
removeBullet(b, type, isPlayer1);
});
auto sequence1 = Sequence::create(MoveToNear, disapper, NULL);
auto sequence2 = Sequence::create(MoveToFar, disapper, NULL);
switch (type)
{
case 0:
case 1:
case 2:
b->runAction(sequence1);
break;
case 3:
case 4:
case 5:
b->runAction(sequence2);
default:
break;
}
}
void bulletFactory::clear() {
bulletForPlayer1->clear();
bulletForPlayer2->clear();
// 玩家现在拥有的弹药数目
for (int i = 0; i < 6; i++) {
bulletNumForPlayer1[i] = 9999;
bulletNumForPlayer2[i] = 9999;
}
}
| [
"944131226@qq.com"
] | 944131226@qq.com |
0a505a8e0020e100e1a0d83f1d5470ebe0dfaf00 | 4ab592fb354f75b42181d5375d485031960aaa7d | /DES_GOBSTG/DES_GOBSTG/Class/Player.cpp | 2a59e185a0d1e2d558f110407142b35f07c87400 | [] | no_license | CBE7F1F65/cca610e2e115c51cef211fafb0f66662 | 806ced886ed61762220b43300cb993ead00949dc | b3cdff63d689e2b1748e9cd93cedd7e8389a7057 | refs/heads/master | 2020-12-24T14:55:56.999923 | 2010-07-23T04:24:59 | 2010-07-23T04:24:59 | 32,192,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,505 | cpp | #include "../header/Player.h"
#include "../header/Process.h"
#include "../header/BGLayer.h"
#include "../header/SE.h"
#include "../header/PlayerBullet.h"
#include "../header/Item.h"
#include "../header/Enemy.h"
#include "../header/Bullet.h"
#include "../header/Chat.h"
#include "../header/BossInfo.h"
#include "../header/EffectIDDefine.h"
#include "../header/SpriteItemManager.h"
#include "../header/FrontDisplayName.h"
#include "../header/FrontDisplay.h"
#include "../header/EventZone.h"
#include "../header/BResource.h"
#include "../header/Scripter.h"
#include "../header/GameInput.h"
#include "../header/GameAI.h"
#define _GAMERANK_MIN 8
#define _GAMERANK_MAX 22
#define _GAMERANK_ADDINTERVAL 9000
#define _GAMERANK_STAGEOVERADD -8
#define _PL_SHOOTCHARGEINFI_1 8
#define _PL_SHOOTCHARGEINFI_2 47
#define _PL_SHOOTCHARGEINFI_3 63
#define _PL_SHOOTCHARGEINFI_4 127
#define _PLAYER_DEFAULETCARDLEVEL_(X) (X?9:8)
#define _PLAYER_DEFAULETBOSSLEVEL_(X) (X?9:8)
#define _CARDLEVEL_ADDINTERVAL 3600
#define _BOSSLEVEL_ADDINTERVAL 3600
#define _CARDLEVEL_MAX 16
#define _BOSSLEVEL_MAX 16
#define _PLAYER_LIFECOSTMAX 2880
#define _PLAYER_COMBOHITMAX 999
#define _PLAYER_SHOOTPUSHOVER 9
#define _PLAYER_SHOOTNOTPUSHOVER 9
#define _PL_SPELLBONUS_BOSS_1 100000
#define _PL_SPELLBONUS_BOSS_2 300000
#define _PL_SPELLBONUS_BOSS_3 500000
Player Player::p[M_PL_MATCHMAXPLAYER];
float Player::lostStack = 0;
bool Player::able = false;
BYTE Player::rank = _GAMERANK_MIN;
int Player::lilycount = 0;
DWORD Player::alltime = 0;
BYTE Player::raisespellstopplayerindex = 0;
BYTE Player::round = 0;
#define _PL_MERGETOPOS_X_(X) (M_GAMESQUARE_CENTER_X_(X))
#define _PL_MERGETOPOS_Y (M_GAMESQUARE_BOTTOM - 64)
#define _PL_SHOOTINGCHARGE_1 0x01
#define _PL_SHOOTINGCHARGE_2 0x02
#define _PL_SHOOTINGCHARGE_3 0x04
#define _PL_SHOOTINGCHARGE_4 0x08
#define _PL_CHARGEZONE_R_2 188.0f
#define _PL_CHARGEZONE_R_3 252.0f
#define _PL_CHARGEZONE_R_4 444.5f
#define _PL_CHARGEZONE_MAXTIME_2 49
#define _PL_CHARGEZONE_MAXTIME_3 65
#define _PL_CHARGEZONE_MAXTIME_4 129
Player::Player()
{
effGraze.exist = false;
effChange.exist = false;
effInfi.exist = false;
effCollapse.exist = false;
effMerge.exist = false;
effBorder.exist = false;
effBorderOn.exist = false;
effBorderOff.exist = false;
sprite = NULL;
spdrain = NULL;
nowID = 0;
ID_sub_1 = 0;
ID_sub_2 = 0;
}
Player::~Player()
{
SpriteItemManager::FreeSprite(&sprite);
SpriteItemManager::FreeSprite(&spdrain);
}
void Player::ClearSet(BYTE _round)
{
x = PL_MERGEPOS_X_(playerindex);
y = PL_MERGEPOS_Y;
round = _round;
for(int i=0;i<PL_SAVELASTMAX;i++)
{
lastx[i] = x;
lasty[i] = y;
lastmx[i] = x;
lastmy[i] = y;
}
timer = 0;
angle = 0;
flag = PLAYER_MERGE;
bSlow = false;
bCharge = false;
bDrain = false;
bInfi = true;
hscale = 1.0f;
vscale = 1.0f;
alpha = 0xff;
diffuse = 0xffffff;
mergetimer = 0;
shottimer = 0;
collapsetimer = 0;
shoottimer = 0;
draintimer = 0;
chargetimer = 0;
slowtimer = 0;
fasttimer = 0;
playerchangetimer = 0;
costlifetimer = 0;
shootchargetimer = 0;
shootingchargeflag = 0;
nowshootingcharge = 0;
fExPoint = 0;
nGhostPoint = 0;
nBulletPoint = 0;
nSpellPoint = 0;
nLifeCost = 0;
fCharge = 0;
if (_round == 0)
{
fChargeMax = PLAYER_CHARGEONE;
winflag = 0;
}
cardlevel = _PLAYER_DEFAULETCARDLEVEL_(_round);
bosslevel = _PLAYER_DEFAULETBOSSLEVEL_(_round);
nowcardlevel = cardlevel;
nowbosslevel = bosslevel;
infitimer = 0;
rechargedelaytimer = 0;
infireasonflag = 0;
shootpushtimer = 0;
shootnotpushtimer = 0;
spellstoptimer = 0;
speedfactor = 1.0f;
// add
// initlife = PLAYER_DEFAULTINITLIFE;
exist = true;
nComboHit = 0;
nComboHitOri = 0;
nComboGage = 0;
nBounceAngle = 0;
drainx = x;
drainy = y;
drainheadangle = 0;
draintimer = 0;
drainhscale = 1;
drainvscale = 0;
draincopyspriteangle = 0;
if (effGraze.exist)
{
effGraze.Stop(true);
effGraze.MoveTo(x, y, 0, true);
}
if (effChange.exist)
{
effChange.Stop(true);
effChange.MoveTo(x, y, 0, true);
}
if (effInfi.exist)
{
effInfi.Stop(true);
effInfi.MoveTo(x, y, 0, true);
}
if (effCollapse.exist)
{
effCollapse.Stop(true);
effCollapse.MoveTo(x, y, 0, true);
}
if (effMerge.exist)
{
effMerge.Stop(true);
effMerge.MoveTo(x, y, 0, true);
}
if (effBorder.exist)
{
effBorder.Stop(true);
effBorder.MoveTo(x, y, 0, true);
}
if (effBorderOn.exist)
{
effBorderOn.Stop(true);
effBorderOn.MoveTo(x, y, 0, true);
}
if (effBorderOff.exist)
{
effBorderOff.Stop(true);
effBorderOff.MoveTo(x, y, 0, true);
}
changePlayerID(nowID, true);
setShootingCharge(0);
esChange.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERCHANGE, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y, 0, 3.0f);
esChange.colorSet(0x7fffffff, BLEND_ALPHAADD);
esChange.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0);
esShot.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERSHOT, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y, 0, 1.2f);
esShot.colorSet(0xccff0000);
esShot.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0);
esPoint.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERPOINT, SpriteItemManager::GetIndexByName(SI_PLAYER_POINT), x, y);
esPoint.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0);
esCollapse.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERCOLLAPSE, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y);
esCollapse.actionSet(0, 0, 160);
esCollapse.colorSet(0x80ffffff);
}
void Player::ClearRound(BYTE round/* =0 */)
{
raisespellstopplayerindex = 0xff;
if (round)
{
rank += _GAMERANK_STAGEOVERADD;
if (rank < _GAMERANK_MIN)
{
rank = _GAMERANK_MIN;
}
AddLilyCount(-1000);
for (int i=0; i<M_PL_MATCHMAXPLAYER; i++)
{
p[i].valueSet(i, round);
}
}
else
{
rank = _GAMERANK_MIN;
lilycount = 0;
alltime = 0;
}
}
//add
void Player::valueSet(BYTE _playerindex, BYTE round)
{
playerindex = _playerindex;
nowID = ID;
ClearSet(round);
initFrameIndex();
UpdatePlayerData();
SetDrainSpriteInfo(x, y);
nLife = initlife;
if (round == 0)
{
lostStack = 0;
}
setFrame(PLAYER_FRAME_STAND);
effGraze.valueSet(EFF_PL_GRAZE, playerindex, *this);
effGraze.Stop();
effChange.valueSet(EFF_PL_CHANGE, playerindex, *this);
effChange.Stop();
effInfi.valueSet(EFF_PL_INFI, playerindex, *this);
effInfi.Stop();
effCollapse.valueSet(EFF_PL_COLLAPSE, playerindex, *this);
effCollapse.Stop();
effMerge.valueSet(EFF_PL_MERGE, playerindex, *this);
effMerge.Stop();
effBorder.valueSet(EFF_PL_BORDER, playerindex, *this);
effBorder.Stop();
effBorderOn.valueSet(EFF_PL_BORDERON, playerindex, *this);
effBorderOn.Stop();
effBorderOff.valueSet(EFF_PL_BORDEROFF, playerindex, *this);
effBorderOff.Stop();
SetAble(true);
}
bool Player::Action()
{
alltime++;
AddLostStack();
for (int i=0; i<M_PL_MATCHMAXPLAYER; i++)
{
if (gametime % _CARDLEVEL_ADDINTERVAL == 0)
{
p[i].AddCardBossLevel(1, 0);
}
if (gametime % _BOSSLEVEL_ADDINTERVAL == 0)
{
p[i].AddCardBossLevel(0, 1);
}
DWORD stopflag = Process::mp.GetStopFlag();
bool binstop = FRAME_STOPFLAGCHECK_PLAYERINDEX_(stopflag, i, FRAME_STOPFLAG_PLAYER);
bool binspellstop = FRAME_STOPFLAGCHECK_PLAYERINDEX_(stopflag, i, FRAME_STOPFLAG_PLAYERSPELL);
GameInput::gameinput[i].updateActiveInput(binspellstop);
if (p[i].exist)
{
if (!binstop && !binspellstop)
{
p[i].action();
}
else if (binspellstop)
{
p[i].actionInSpellStop();
}
else
{
p[i].actionInStop();
}
if (!p[i].exist)
{
return false;
}
}
}
if (gametime % _GAMERANK_ADDINTERVAL == 0)
{
rank++;
if (rank > _GAMERANK_MAX)
{
rank = _GAMERANK_MAX;
}
}
AddLilyCount(0, true);
return true;
}
void Player::action()
{
float nowspeed = 0;
timer++;
alpha = 0xff;
if(timer == 1)
flag |= PLAYER_MERGE;
//savelast
if(lastmx[0] != x || lastmy[0] != y)
{
for(int i=PL_SAVELASTMAX-1;i>0;i--)
{
lastmx[i] = lastmx[i-1];
lastmy[i] = lastmy[i-1];
}
lastmx[0] = x;
lastmy[0] = y;
}
for(int i=PL_SAVELASTMAX-1;i>0;i--)
{
lastx[i] = lastx[i-1];
lasty[i] = lasty[i-1];
}
lastx[0] = x;
lasty[0] = y;
//AI
// GameAI::ai[playerindex].UpdateBasicInfo(x, y, speed, slowspeed, BResource::bres.playerdata[nowID].collision_r);
GameAI::ai[playerindex].SetMove();
//
if(flag & PLAYER_MERGE)
{
if(Merge())
{
flag &= ~PLAYER_MERGE;
}
}
if(flag & PLAYER_SHOT)
{
if(Shot())
{
flag &= ~PLAYER_SHOT;
}
}
if (flag & PLAYER_COSTLIFE)
{
if (CostLife())
{
flag &= ~PLAYER_COSTLIFE;
}
}
if(flag & PLAYER_COLLAPSE)
{
if(Collapse())
{
flag &= ~PLAYER_COLLAPSE;
return;
}
}
if(flag & PLAYER_SLOWCHANGE)
{
if(SlowChange())
{
flag &= ~PLAYER_SLOWCHANGE;
}
}
if(flag & PLAYER_FASTCHANGE)
{
if(FastChange())
{
flag &= ~PLAYER_FASTCHANGE;
}
}
if(flag & PLAYER_PLAYERCHANGE)
{
if(PlayerChange())
{
flag &= ~PLAYER_PLAYERCHANGE;
}
}
if(flag & PLAYER_SHOOT)
{
if(Shoot())
{
flag &= ~PLAYER_SHOOT;
}
}
if(flag & PLAYER_BOMB)
{
if(Bomb())
{
flag &= ~PLAYER_BOMB;
}
}
if(flag & PLAYER_DRAIN)
{
if(Drain())
{
flag &= ~PLAYER_DRAIN;
}
}
if (flag & PLAYER_CHARGE)
{
if (Charge())
{
flag &= ~PLAYER_CHARGE;
}
}
if(flag & PLAYER_GRAZE)
{
if(Graze())
{
flag &= ~PLAYER_GRAZE;
}
}
nLifeCost++;
if (nLifeCost > _PLAYER_LIFECOSTMAX)
{
nLifeCost = _PLAYER_LIFECOSTMAX;
}
if (rechargedelaytimer)
{
rechargedelaytimer--;
}
if (shootchargetimer)
{
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOOTCHARGEONE, playerindex);
PlayerBullet::BuildShoot(playerindex, nowID, shootchargetimer, true);
shootchargetimer--;
}
if (infitimer > 0)
{
infitimer--;
bInfi = true;
}
else if (infitimer == PLAYER_INFIMAX)
{
bInfi = true;
}
else
{
bInfi = false;
}
if (nComboGage)
{
nComboGage--;
if (nComboGage == PLAYER_COMBORESET)
{
AddComboHit(-1, true);
}
else if (!nComboGage)
{
AddSpellPoint(-1);
}
}
for (list<EventZone>::iterator it=EventZone::ezone[playerindex].begin(); it!=EventZone::ezone[playerindex].end(); it++)
{
if (it->timer < 0)
{
continue;
}
if ((it->type) & EVENTZONE_TYPEMASK_PLAYER)
{
if (it->isInRect(x, y, r))
{
if (it->type & EVENTZONE_TYPE_PLAYERDAMAGE)
{
DoShot();
}
if (it->type & EVENTZONE_TYPE_PLAYEREVENT)
{
}
if (it->type & EVENTZONE_TYPE_PLAYERSPEED)
{
speedfactor = it->power;
}
}
}
}
//input
if(!(flag & PLAYER_SHOT || flag & PLAYER_COLLAPSE))
{
if (GameInput::GetKey(playerindex, KSI_SLOW))
{
bSlow = true;
flag &= ~PLAYER_FASTCHANGE;
if (GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_DOWN))
{
if (!(flag & PLAYER_SLOWCHANGE))
{
slowtimer = 0;
flag |= PLAYER_SLOWCHANGE;
}
}
}
else
{
bSlow = false;
flag &= ~PLAYER_SLOWCHANGE;
if (GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_UP))
{
if (!(flag & PLAYER_FASTCHANGE))
{
fasttimer = 0;
flag |= PLAYER_FASTCHANGE;
}
}
}
if(bSlow)
{
nowspeed = slowspeed;
}
else
{
nowspeed = speed;
}
nowspeed *= speedfactor;
if(GameInput::GetKey(playerindex, KSI_FIRE))
{
if (!Chat::chatitem.IsChatting())
{
flag |= PLAYER_SHOOT;
}
shootnotpushtimer = 0;
}
else
{
if (shootnotpushtimer < 0xff)
{
shootnotpushtimer++;
}
}
if (shootpushtimer < _PLAYER_SHOOTPUSHOVER)
{
if (GameInput::GetKey(playerindex, KSI_FIRE))
{
shootpushtimer++;
}
else
{
shootpushtimer = 0;
}
}
else
{
if (!GameInput::GetKey(playerindex, KSI_FIRE))
{
bCharge = false;
flag &= ~PLAYER_CHARGE;
shootpushtimer = 0;
}
else
{
if (!rechargedelaytimer)
{
flag &= ~PLAYER_SHOOT;
bCharge = true;
if (shootpushtimer >= _PLAYER_SHOOTPUSHOVER && !(flag & PLAYER_CHARGE))
{
chargetimer = 0;
flag |= PLAYER_CHARGE;
shootpushtimer = 0xff;
}
}
}
}
if (GameInput::GetKey(playerindex, KSI_DRAIN))
{
bDrain = true;
if (GameInput::GetKey(playerindex, KSI_DRAIN, DIKEY_DOWN))
{
if (!(flag & PLAYER_DRAIN))
{
draintimer = 0;
SetDrainSpriteInfo(x, y, 0, 0);
}
}
flag |= PLAYER_DRAIN;
}
else
{
bDrain = false;
flag &= ~PLAYER_DRAIN;
}
if((GameInput::GetKey(playerindex, KSI_UP) ^ GameInput::GetKey(playerindex, KSI_DOWN)) &&
GameInput::GetKey(playerindex, KSI_LEFT) ^ GameInput::GetKey(playerindex, KSI_RIGHT))
nowspeed *= M_SQUARE_2;
if(GameInput::GetKey(playerindex, KSI_UP))
y -= nowspeed;
if(GameInput::GetKey(playerindex, KSI_DOWN))
y += nowspeed;
if(GameInput::GetKey(playerindex, KSI_LEFT))
{
updateFrame(PLAYER_FRAME_LEFTPRE);
x -= nowspeed;
}
if(GameInput::GetKey(playerindex, KSI_RIGHT))
{
if (!GameInput::GetKey(playerindex, KSI_LEFT))
{
updateFrame(PLAYER_FRAME_RIGHTPRE);
}
else
{
updateFrame(PLAYER_FRAME_STAND);
}
x += nowspeed;
}
if (!GameInput::GetKey(playerindex, KSI_LEFT) && !GameInput::GetKey(playerindex, KSI_RIGHT))
{
updateFrame(PLAYER_FRAME_STAND);
}
}
if(GameInput::GetKey(playerindex, KSI_QUICK) && !(flag & PLAYER_MERGE))
{
callBomb();
}
if (!(flag & PLAYER_MERGE) || mergetimer >= 32)
{
if(x > PL_MOVABLE_RIGHT_(playerindex))
x = PL_MOVABLE_RIGHT_(playerindex);
else if(x < PL_MOVABLE_LEFT_(playerindex))
x = PL_MOVABLE_LEFT_(playerindex);
if(y > PL_MOVABLE_BOTTOM)
y = PL_MOVABLE_BOTTOM;
else if(y < PL_MOVABLE_TOP)
y = PL_MOVABLE_TOP;
}
//AI
GameAI::ai[playerindex].UpdateBasicInfo(x, y, speed*speedfactor, slowspeed*speedfactor, r, BResource::bres.playerdata[nowID].aidraintime);
float aiaimx = _PL_MERGETOPOS_X_(playerindex);
float aiaimy = _PL_MERGETOPOS_Y;
bool tobelow = false;
if (PlayerBullet::activelocked[playerindex] != PBLOCK_LOST)
{
aiaimx = Enemy::en[playerindex][PlayerBullet::activelocked[playerindex]].x;
aiaimy = Enemy::en[playerindex][PlayerBullet::activelocked[playerindex]].y + 120;
tobelow = true;
}
else if (PlayerBullet::locked[playerindex] != PBLOCK_LOST)
{
aiaimx = Enemy::en[playerindex][PlayerBullet::locked[playerindex]].x;
aiaimy = Enemy::en[playerindex][PlayerBullet::locked[playerindex]].y;
}
GameAI::ai[playerindex].SetAim(aiaimx, aiaimy, tobelow);
//
//
speedfactor = 1.0f;
if (bInfi && timer % 8 < 4)
{
diffuse = 0xff99ff;
}
else
diffuse = 0xffffff;
esChange.action();
esShot.action();
esPoint.action();
effGraze.MoveTo(x, y);
effGraze.action();
effCollapse.action();
effBorderOn.action();
effBorderOff.action();
if(!(flag & PLAYER_GRAZE))
effGraze.Stop();
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
if (pg[i].exist)
{
pg[i].action();
}
}
}
void Player::actionInSpellStop()
{
spellstoptimer++;
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERINSPELLSTOP, playerindex);
}
void Player::actionInStop()
{
// Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERINSTOP, playerindex);
}
bool Player::Merge()
{
mergetimer++;
if(mergetimer == 1)
{
SetInfi(PLAYERINFI_MERGE, 60);
if(GameInput::GetKey(playerindex, KSI_SLOW))
{
flag |= PLAYER_SLOWCHANGE;
slowtimer = 0;
flag &= ~PLAYER_FASTCHANGE;
}
else
{
flag |= PLAYER_FASTCHANGE;
fasttimer = 0;
flag &= ~PLAYER_SLOWCHANGE;
}
}
else if (mergetimer <= 24)
{
float interval = mergetimer / 24.0f;
x = INTER(PL_MERGEPOS_X_(playerindex), _PL_MERGETOPOS_X_(playerindex), interval);
y = INTER(PL_MERGEPOS_Y, _PL_MERGETOPOS_Y, interval);
flag &= ~PLAYER_SHOOT;
alpha = INTER(0, 0xff, interval);
}
else if(mergetimer < 60)
{
alpha = 0xff;
}
else if(mergetimer == 60)
{
mergetimer = 0;
return true;
}
return false;
}
bool Player::Shot()
{
shottimer++;
// TODO:
if(bInfi)
{
shottimer = 0;
return true;
}
if(shottimer == 1)
{
// Item::undrainAll();
SE::push(SE_PLAYER_SHOT, x);
}
else if(shottimer == shotdelay)
{
shottimer = 0;
flag |= PLAYER_COSTLIFE;
return true;
}
esShot.hscale = (shotdelay - shottimer) * 4.0f / shotdelay;
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOT, playerindex);
return false;
}
bool Player::CostLife()
{
costlifetimer++;
if (costlifetimer == 1)
{
AddLilyCount(-1500);
if (nLife == 1)
{
nLife = 0;
flag |= PLAYER_COLLAPSE;
costlifetimer = 0;
return true;
}
int nLifeCostNum = nLifeCost / 720 + 2;
if (nLife > nLifeCostNum+1)
{
nLife -= nLifeCostNum;
}
else
{
FrontDisplay::fdisp.gameinfodisplay.lastlifecountdown[playerindex] = FDISP_COUNTDOWNTIME;
SE::push(SE_PLAYER_ALERT, x);
nLife = 1;
}
nLifeCost -= 1440;
if (nLifeCost < 0)
{
nLifeCost = 0;
}
SetInfi(PLAYERINFI_COSTLIFE, 120);
if (nLife == 1)
{
AddCharge(0, PLAYER_CHARGEMAX);
}
else
{
AddCharge(0, 130-nLife * 10);
}
nBounceAngle = randt();
}
else if (costlifetimer == 50)
{
EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, playerindex, x, y, 10, 0, 0, 10, EVENTZONE_EVENT_NULL, 15.6);
}
else if (costlifetimer == 60)
{
costlifetimer = 0;
return true;
}
else
{
GameInput::SetKey(playerindex, KSI_UP, false);
GameInput::SetKey(playerindex, KSI_DOWN, false);
GameInput::SetKey(playerindex, KSI_LEFT, false);
GameInput::SetKey(playerindex, KSI_RIGHT, false);
// GameInput::SetKey(playerindex, KSI_FIRE, false);
GameInput::SetKey(playerindex, KSI_QUICK, false);
GameInput::SetKey(playerindex, KSI_SLOW, false);
GameInput::SetKey(playerindex, KSI_DRAIN, false);
x += cost(nBounceAngle) * ((60-costlifetimer) / 20.0f);
y += sint(nBounceAngle) * ((60-costlifetimer) / 20.0f);
}
return false;
}
bool Player::Collapse()
{
collapsetimer++;
if(collapsetimer == 1)
{
for (int i=0; i<M_PL_MATCHMAXPLAYER; i++)
{
EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, i, p[i].x, p[i].y, 64, EVENTZONE_OVERZONE, 0, 1000, EVENTZONE_EVENT_NULL, 16);
p[i].SetInfi(PLAYERINFI_COLLAPSE, 64);
}
esCollapse.x = x;
esCollapse.y = y;
SE::push(SE_PLAYER_DEAD, x);
effCollapse.MoveTo(x, y , 0, true);
effCollapse.Fire();
p[1-playerindex].winflag |= 1<<round;
}
else if(collapsetimer == 64)
{
x = PL_MERGEPOS_X_(playerindex);
y = PL_MERGEPOS_Y;
for(int i=0;i<PL_SAVELASTMAX;i++)
{
lastx[i] = x;
lasty[i] = y;
lastmx[i] = x;
lastmy[i] = y;
}
timer = 0;
collapsetimer = 0;
vscale = 1.0f;
flag |= PLAYER_MERGE;
AddCharge(0, 130);
// SetInfi(PLAYERINFI_COLLAPSE);
exist = false;
if(GameInput::GetKey(playerindex, KSI_SLOW))
{
flag |= PLAYER_SLOWCHANGE;
slowtimer = 0;
flag &= ~PLAYER_FASTCHANGE;
}
else
{
flag |= PLAYER_FASTCHANGE;
fasttimer = 0;
flag &= ~PLAYER_SLOWCHANGE;
}
effCollapse.Stop();
return true;
}
esCollapse.hscale = collapsetimer / 1.5f;
esCollapse.alpha = (BYTE)((WORD)(0xff * collapsetimer) / 0x3f);
esCollapse.colorSet(0xff0000);
alpha = (0xff - collapsetimer * 4);
vscale = (float)(collapsetimer)/40.0f + 1.0f;
return false;
}
bool Player::Shoot()
{
if(Chat::chatitem.IsChatting())
{
shoottimer = 0;
return true;
}
if (!(flag & PLAYER_SHOT) && !(flag & PLAYER_COSTLIFE))
{
PlayerBullet::BuildShoot(playerindex, nowID, shoottimer);
}
shoottimer++;
//
if(shootnotpushtimer > _PLAYER_SHOOTNOTPUSHOVER)
{
shoottimer = 0;
return true;
}
return false;
}
bool Player::Drain()
{
draintimer++;
bDrain = true;
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERDRAIN, playerindex);
return false;
}
bool Player::Bomb()
{
BYTE ncharge;
BYTE nchargemax;
GetNCharge(&ncharge, &nchargemax);
if (nchargemax > 1)
{
BYTE nChargeLevel = shootCharge(nchargemax, true);
if (nChargeLevel == nchargemax)
{
AddCharge(-PLAYER_CHARGEMAX, -PLAYER_CHARGEMAX);
}
else
{
AddCharge((nChargeLevel-nchargemax)*PLAYER_CHARGEONE, (nChargeLevel-nchargemax)*PLAYER_CHARGEONE);
}
}
return true;
}
bool Player::SlowChange()
{
if(GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_DOWN))
slowtimer = 0;
bSlow = true;
slowtimer++;
if(slowtimer == 1)
{
ResetPlayerGhost();
SE::push(SE_PLAYER_SLOWON, x);
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
pg[i].timer = 0;
}
}
else if(slowtimer == 16)
{
esPoint.colorSet(0xffffffff);
slowtimer = 0;
return true;
}
esPoint.actionSet(0, 0, (24 - slowtimer) * 25);
esPoint.colorSet(((slowtimer*16)<<24)+0xffffff);
return false;
}
bool Player::FastChange()
{
if(GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_UP))
fasttimer = 0;
bSlow = false;
fasttimer++;
if(fasttimer == 1)
{
ResetPlayerGhost();
SE::push(SE_PLAYER_SLOWOFF, x);
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
pg[i].timer = 0;
}
}
else if(fasttimer == 16)
{
esPoint.colorSet(0x00ffffff);
fasttimer = 0;
return true;
}
esPoint.colorSet(((0xff-fasttimer*16)<<24)+0xffffff);
return false;
}
bool Player::Charge()
{
chargetimer++;
if (chargetimer == 1)
{
SE::push(SE_PLAYER_CHARGEON, x);
}
BYTE nChargeLevel = AddCharge(chargespeed);
if (!GameInput::GetKey(playerindex, KSI_FIRE))
{
shootCharge(nChargeLevel);
chargetimer = 0;
fCharge = 0;
if (nChargeLevel > 0)
{
rechargedelaytimer = rechargedelay;
}
return true;
}
bCharge = true;
return false;
}
bool Player::PlayerChange()
{
if(GameInput::GetKey(playerindex, KSI_DRAIN, DIKEY_DOWN))
playerchangetimer = 0;
playerchangetimer++;
if(playerchangetimer == 1)
{
}
else if(playerchangetimer == 16)
{
playerchangetimer = 0;
return true;
}
esChange.colorSet(0x3030ff | (((16-playerchangetimer) * 16)<<16));
return false;
}
void Player::changePlayerID(WORD toID, bool moveghost/* =false */)
{
nowID = toID;
ResetPlayerGhost(moveghost);
UpdatePlayerData();
}
bool Player::Graze()
{
effGraze.Fire();
SE::push(SE_PLAYER_GRAZE, x);
return true;
}
void Player::DoEnemyCollapse(float x, float y, BYTE type)
{
float addcharge = nComboHitOri / 128.0f + 1.0f;
if (addcharge > 2.0f)
{
addcharge = 2.0f;
}
AddComboHit(1, true);
AddCharge(0, addcharge);
enemyData * edata = &(BResource::bres.enemydata[type]);
AddExPoint(edata->expoint, x, y);
int addghostpoint;
if (edata->ghostpoint < 0)
{
addghostpoint = nComboHitOri + 3;
if (addghostpoint > 28)
{
addghostpoint = 28;
}
}
else
{
addghostpoint = edata->ghostpoint;
}
AddGhostPoint(addghostpoint, x, y);
int addbulletpoint;
float _x = x + randtf(-4.0f, 4.0f);
float _y = y + randtf(-4.0f, 4.0f);
if (edata->bulletpoint < 0)
{
addbulletpoint = nComboHitOri * 3 + 27;
if (addbulletpoint > 60)
{
addbulletpoint = 60;
}
}
else
{
addbulletpoint = edata->bulletpoint;
}
AddBulletPoint(addbulletpoint, _x, _y);
int addspellpoint;
if (edata->spellpoint == -1)
{
if (nComboHitOri == 1)
{
addspellpoint = 20;
}
else
{
addspellpoint = nComboHitOri * 30 - 20;
if (addspellpoint > 3000)
{
addspellpoint = 3000;
}
}
}
else if (edata->spellpoint == -2)
{
if (nComboHitOri == 1)
{
addspellpoint = 2000;
}
else
{
addspellpoint = (nComboHitOri + 4) * 200;
if (addspellpoint > 11000)
{
addspellpoint = 11000;
}
}
}
else
{
addspellpoint = edata->spellpoint;
}
AddSpellPoint(addspellpoint);
}
void Player::DoGraze(float x, float y)
{
if(!(flag & (PLAYER_MERGE | PLAYER_SHOT | PLAYER_COLLAPSE)))
{
flag |= PLAYER_GRAZE;
}
}
void Player::DoPlayerBulletHit(int hitonfactor)
{
if (hitonfactor < 0)
{
AddComboHit(-1, true);
}
}
void Player::DoSendBullet(float x, float y, int sendbonus)
{
for (int i=0; i<sendbonus; i++)
{
AddComboHit(1, false);
AddGhostPoint(2, x, y);
AddBulletPoint(3, x, y);
int addspellpoint = nComboHitOri * 9;
if (addspellpoint > 1000)
{
addspellpoint = 1000;
}
AddSpellPoint(addspellpoint);
}
}
void Player::DoShot()
{
if (!bInfi && !(flag & (PLAYER_SHOT | PLAYER_COLLAPSE)))
{
flag |= PLAYER_SHOT;
AddComboHit(-1, true);
AddSpellPoint(-1);
}
}
void Player::DoItemGet(WORD itemtype, float _x, float _y)
{
switch (itemtype)
{
case ITEM_GAUGE:
AddCharge(0, PLAYER_CHARGEMAX);
break;
case ITEM_BULLET:
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDITEMBULLET, playerindex);
// Item::SendBullet(1-playerindex, _x, _y, EFFSPSET_SYSTEM_SENDITEMBULLET);
break;
case ITEM_EX:
AddBulletPoint(1, _x, _y);
AddExPoint(100, _x, _y);
break;
case ITEM_POINT:
AddSpellPoint(70000+rank*7000);
break;
}
}
void Player::GetNCharge(BYTE * ncharge, BYTE * nchargemax)
{
if (ncharge)
{
*ncharge = (BYTE)(fCharge/PLAYER_CHARGEONE);
}
if (nchargemax)
{
*nchargemax = (BYTE)(fChargeMax/PLAYER_CHARGEONE);
}
}
void Player::GetSpellClassAndLevel(BYTE * spellclass, BYTE * spelllevel, int _shootingchargeflag)
{
BYTE usingshootingchargeflag = shootingchargeflag;
if (_shootingchargeflag > 0)
{
usingshootingchargeflag = _shootingchargeflag;
}
if (spellclass)
{
if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_4)
{
if ((usingshootingchargeflag & _PL_SHOOTINGCHARGE_3) || (usingshootingchargeflag & _PL_SHOOTINGCHARGE_2))
{
*spellclass = 4;
}
else
{
*spellclass = 3;
}
}
else if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_3)
{
*spellclass = 2;
}
else if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_2)
{
*spellclass = 1;
}
else
{
*spellclass = 0;
}
}
if (spelllevel)
{
if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_4)
{
*spelllevel = nowbosslevel;
}
else if(usingshootingchargeflag)
{
*spelllevel = nowcardlevel;
}
else
{
*spelllevel = 0;
}
}
}
void Player::ResetPlayerGhost(bool move /* = false */)
{
int tid = nowID;
tid *= PLAYERGHOSTMAX * 2;
if (bSlow)
{
tid += PLAYERGHOSTMAX;
}
for (int i=0; i<PLAYERGHOSTMAX; i++)
{
pg[i].valueSet(playerindex, tid+i, move);
}
}
void Player::Render()
{
if (spdrain && bDrain)
{
SpriteItemManager::RenderSpriteEx(spdrain, drainx, drainy, ARC(drainheadangle), drainhscale, drainvscale);
if (draincopyspriteangle)
{
SpriteItemManager::RenderSpriteEx(spdrain, drainx, drainy, ARC(drainheadangle+draincopyspriteangle), drainhscale, drainvscale);
}
}
if (sprite)
{
sprite->SetColor(alpha<<24|diffuse);
SpriteItemManager::RenderSpriteEx(sprite, x, y, 0, hscale, vscale);
}
}
void Player::RenderEffect()
{
effGraze.Render();
for(int i=0;i<PLAYERGHOSTMAX;i++)
{
if (pg[i].exist)
{
pg[i].Render();
}
}
if(flag & PLAYER_PLAYERCHANGE)
{
esChange.Render();
}
if(flag & PLAYER_SHOT)
esShot.Render();
effBorderOff.Render();
if(bSlow || flag & PLAYER_FASTCHANGE)
{
esPoint.Render();
esPoint.headangle = -esPoint.headangle;
esPoint.Render();
esPoint.headangle = -esPoint.headangle;
}
if(flag & PLAYER_COLLAPSE)
esCollapse.Render();
effCollapse.Render();
}
void Player::callCollapse()
{
if (flag & PLAYER_COLLAPSE)
{
return;
}
flag |= PLAYER_COLLAPSE;
collapsetimer = 0;
}
bool Player::callBomb()
{
if (Chat::chatitem.IsChatting() || (flag & PLAYER_COLLAPSE))
{
return false;
}
return Bomb();
}
void Player::callSlowFastChange(bool toslow)
{
if (toslow)
{
GameInput::SetKey(playerindex, KSI_SLOW);
}
else
{
GameInput::SetKey(playerindex, KSI_SLOW, false);
}
}
void Player::callPlayerChange()
{
flag |= PLAYER_PLAYERCHANGE;
playerchangetimer = 0;
}
void Player::setShootingCharge(BYTE _shootingchargeflag)
{
if (!_shootingchargeflag)
{
shootingchargeflag = 0;
}
else
{
shootingchargeflag |= _shootingchargeflag;
if (shootingchargeflag & _PL_SHOOTINGCHARGE_1)
{
shootchargetimer = BResource::bres.playerdata[nowID].shootchargetime;
}
if (_shootingchargeflag & ~_PL_SHOOTINGCHARGE_1)
{
nowshootingcharge = _shootingchargeflag;
if (_shootingchargeflag & _PL_SHOOTINGCHARGE_4)
{
nowbosslevel = bosslevel;
}
else
{
nowcardlevel = cardlevel;
}
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOOTCHARGE, playerindex);
}
}
}
BYTE Player::shootCharge(BYTE nChargeLevel, bool nodelete)
{
if (flag & PLAYER_COLLAPSE)
{
return 0;
}
if (!nChargeLevel)
{
return 0;
}
if (nChargeLevel > 3 && nChargeLevel < 7 && Enemy::bossindex[1-playerindex] != 0xff)
{
if (nChargeLevel == 4)
{
return shootCharge(3, nodelete);
}
else if (nChargeLevel == 6)
{
return shootCharge(7, nodelete);
}
return 0;
}
setShootingCharge(0);
int chargezonemaxtime=1;
float chargezoner=0;
switch (nChargeLevel)
{
case 1:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_1);
setShootingCharge(_PL_SHOOTINGCHARGE_1);
// AddCardBossLevel(1, 0);
break;
case 2:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_2);
if (!nodelete)
{
setShootingCharge(_PL_SHOOTINGCHARGE_1);
}
setShootingCharge(_PL_SHOOTINGCHARGE_2);
AddCardBossLevel(1, 0);
chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_2;
chargezoner = _PL_CHARGEZONE_R_2;
break;
case 3:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_3);
if (!nodelete)
{
setShootingCharge(_PL_SHOOTINGCHARGE_1);
}
setShootingCharge(_PL_SHOOTINGCHARGE_3);
AddCardBossLevel(1, 0);
chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_3;
chargezoner = _PL_CHARGEZONE_R_3;
break;
case 4:
SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_4);
if (!nodelete)
{
setShootingCharge(_PL_SHOOTINGCHARGE_1);
}
setShootingCharge(_PL_SHOOTINGCHARGE_4);
AddCardBossLevel(0, 1);
chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_4;
chargezoner = _PL_CHARGEZONE_R_4;
break;
case 5:
setShootingCharge(_PL_SHOOTINGCHARGE_4);
AddCardBossLevel(0, 1);
break;
case 6:
setShootingCharge(_PL_SHOOTINGCHARGE_3);
setShootingCharge(_PL_SHOOTINGCHARGE_4);
AddCardBossLevel(1, 1);
break;
case 7:
setShootingCharge(_PL_SHOOTINGCHARGE_3);
AddCardBossLevel(1, 0);
break;
}
if (nChargeLevel > 1)
{
raisespellstopplayerindex = playerindex;
spellstoptimer = 0;
Process::mp.SetStop(FRAME_STOPFLAG_SPELLSET|FRAME_STOPFLAG_PLAYERINDEX_0|FRAME_STOPFLAG_PLAYERINDEX_1, PL_SHOOTINGCHARGE_STOPTIME);
if (chargezoner)
{
EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, playerindex, x, y, chargezonemaxtime, 0, 0, 10, EVENTZONE_EVENT_NULL, chargezoner/chargezonemaxtime, -2, SpriteItemManager::GetIndexByName(SI_PLAYER_CHARGEZONE), 400);
}
if (nChargeLevel < 5)
{
AddCharge(-PLAYER_CHARGEONE*(nChargeLevel-1), -PLAYER_CHARGEONE*(nChargeLevel-1));
}
AddLilyCount(-500);
FrontDisplay::fdisp.OnShootCharge(playerindex, nowshootingcharge);
}
return nChargeLevel;
}
void Player::SendEx(BYTE playerindex, float x, float y)
{
int _esindex = EffectSp::Build(EFFSPSET_SYSTEM_SENDEXATTACK, playerindex, EffectSp::senditemexsiid, x, y);
if (_esindex >= 0)
{
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDEX, playerindex);
SE::push(SE_BULLET_SENDEX, x);
}
}
void Player::AddExPoint(float expoint, float x, float y)
{
fExPoint += expoint;
float fexsend = fExSendParaB + fExSendParaA * rank;
if (fexsend < fExSendMax)
{
fexsend = fExSendMax;
}
if (fExPoint >= fexsend)
{
AddExPoint(-fexsend, x, y);
SendEx(1-playerindex, x, y);
}
}
void Player::AddGhostPoint(int ghostpoint, float x, float y)
{
nGhostPoint += ghostpoint;
if (nGhostPoint >= 60-rank*1.5f)
{
if (nBulletPoint >= 10)
{
AddGhostPoint(-(60-rank*2), x, y);
AddBulletPoint(-10, x, y);
Enemy::SendGhost(1-playerindex, x, y, EFFSPSET_SYSTEM_SENDGHOST);
}
}
}
void Player::AddBulletPoint(int bulletpoint, float x, float y)
{
nBulletPoint += bulletpoint * 4 / 3;
if (nBulletPoint >= 120-rank*4)
{
AddBulletPoint(-(120-rank*4), x, y);
BYTE setID = EFFSPSET_SYSTEM_SENDBLUEBULLET;
if (randt(0, 2) == 0)
{
setID = EFFSPSET_SYSTEM_SENDREDBULLET;
}
Bullet::SendBullet(1-playerindex, x, y, setID);
}
}
void Player::AddSpellPoint(int spellpoint)
{
if (spellpoint < 0)
{
nSpellPoint = 0;
return;
}
spellpoint = spellpoint * rank / 10 + spellpoint;
int spellpointone = spellpoint % 10;
if (spellpointone)
{
spellpoint += 10-spellpointone;
}
if (nSpellPoint < _PL_SPELLBONUS_BOSS_1 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_1 ||
nSpellPoint < _PL_SPELLBONUS_BOSS_2 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_2)
{
shootCharge(5);
}
else if (nSpellPoint < _PL_SPELLBONUS_BOSS_3 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_3)
{
shootCharge(6);
}
nSpellPoint += spellpoint;
if (nSpellPoint > PLAYER_NSPELLPOINTMAX)
{
nSpellPoint = PLAYER_NSPELLPOINTMAX;
}
}
void Player::AddComboHit(int combo, bool ori)
{
if (combo < 0)
{
nComboHit = 0;
nComboHitOri = 0;
return;
}
nComboHit += combo;
if (nComboHit > PLAYER_NCOMBOHITMAX)
{
nComboHit = PLAYER_NCOMBOHITMAX;
}
if (ori)
{
nComboHitOri += combo;
if (nComboHitOri > PLAYER_NCOMBOHITMAX)
{
nComboHitOri = PLAYER_NCOMBOHITMAX;
}
}
if (nComboGage < 74)
{
nComboGage += 30;
if (nComboGage < 74)
{
nComboGage = 74;
}
}
else if (nComboGage < 94)
{
nComboGage += 5;
}
else
{
nComboGage += 2;
}
if (nComboGage > PLAYER_COMBOGAGEMAX)
{
nComboGage = PLAYER_COMBOGAGEMAX;
}
}
BYTE Player::AddCharge(float addcharge, float addchargemax)
{
BYTE ncharge;
BYTE nchargemax;
GetNCharge(&ncharge, &nchargemax);
float addchargemaxval = addchargemax;
if (addchargemax > 0)
{
addchargemaxval = addchargemax * BResource::bres.playerdata[nowID].addchargerate;
}
fChargeMax += addchargemaxval;
if (fChargeMax > PLAYER_CHARGEMAX)
{
fChargeMax = PLAYER_CHARGEMAX;
}
if (fChargeMax < 0)
{
fChargeMax = 0;
}
fCharge += addcharge;
if (fCharge > fChargeMax)
{
fCharge = fChargeMax;
}
if (fCharge < 0)
{
fCharge = 0;
}
BYTE nchargenow;
BYTE nchargemaxnow;
GetNCharge(&nchargenow, &nchargemaxnow);
if (nchargenow > ncharge)
{
SE::push(SE_PLAYER_CHARGEUP);
}
if (nchargemaxnow > nchargemax)
{
FrontDisplay::fdisp.gameinfodisplay.gaugefilledcountdown[playerindex] = FDISP_COUNTDOWNTIME;
}
return nchargenow;
}
void Player::AddLilyCount(int addval, bool bytime/* =false */)
{
if (bytime)
{
if (gametime < 5400)
{
AddLilyCount(gametime/1800+3);
}
else
{
AddLilyCount(7);
}
}
lilycount += addval;
if (lilycount > 10000)
{
Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDLILY, rank);
AddLilyCount(-10000);
}
else if (lilycount < 0)
{
lilycount = 0;
}
}
void Player::AddCardBossLevel(int cardleveladd, int bossleveladd)
{
cardlevel += cardleveladd;
bosslevel += bossleveladd;
if (cardlevel > _CARDLEVEL_MAX)
{
cardlevel = _CARDLEVEL_MAX;
}
if (bosslevel > _BOSSLEVEL_MAX)
{
bosslevel = _BOSSLEVEL_MAX;
}
}
| [
"CBE7F1F65@4a173d03-4959-223b-e14c-e2eaa5fc8a8b"
] | CBE7F1F65@4a173d03-4959-223b-e14c-e2eaa5fc8a8b |
3745f8e268d8371423614905e3e3b0b3cce30b84 | 05b3c7d89a652eda02c76c86795496019bf49a4d | /Source/Section47/Map/S47TriggerDoor.cpp | 23750e7bd3561a92a35cdb3657e2fd6453d62044 | [] | no_license | pasqueta/Section47 | 38ba462884d269bb4a852f63df2ec838a99dfa30 | 97cdb13908a34931b3f6d0f41da014465f67ecd7 | refs/heads/master | 2020-11-28T08:19:59.740638 | 2019-07-23T15:50:18 | 2019-07-23T15:50:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,284 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "S47TriggerDoor.h"
#include "Components/BoxComponent.h"
#include "S47Character.h"
#include "S47Types.h"
#include "S47Room.h"
#include "S47RoomLevel.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Enemy/S47Enemy.h"
AS47TriggerDoor::AS47TriggerDoor()
{
BoxComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxComponent"));
if (RootComponent != nullptr)
{
BoxComponent->SetupAttachment(RootComponent);
}
}
void AS47TriggerDoor::BeginPlay()
{
Super::BeginPlay();
if (nullptr != BoxComponent)
{
BoxComponent->OnComponentBeginOverlap.AddUniqueDynamic(this, &AS47TriggerDoor::OnTriggerEnter);
BoxComponent->OnComponentEndOverlap.AddUniqueDynamic(this, &AS47TriggerDoor::OnTriggerExit);
}
}
void AS47TriggerDoor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (!isOpen && !locked && CharacterList.Num() > 0)
{
OnOpenDoor();
isOpen = true;
}
else if (isOpen && (locked || CharacterList.Num() <= 0))
{
OnCloseDoor();
isOpen = false;
}
}
void AS47TriggerDoor::SetRoomsAlwaysVisible(bool _visible)
{
if (nullptr != m_pRoomA && nullptr != m_pRoomA->GetLevelScript())
{
m_pRoomA->GetLevelScript()->AlwaysVisible = _visible;
}
if (nullptr != m_pRoomB && nullptr != m_pRoomB->GetLevelScript())
{
m_pRoomB->GetLevelScript()->AlwaysVisible = _visible;
}
}
void AS47TriggerDoor::OnTriggerEnter(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult)
{
AS47Character* OtherCharacter = Cast<AS47Character>(OtherActor);
UCapsuleComponent* OtherCapsule = Cast<UCapsuleComponent>(OtherComp);
if (OtherCharacter != nullptr && OtherCapsule != nullptr && OtherCapsule == OtherCharacter->GetCapsuleComponent() && !CharacterList.Contains(OtherCharacter))
{
CharacterList.Add(OtherCharacter);
AS47Enemy* OtherCharacter = Cast<AS47Enemy>(OtherActor);
if (OtherCharacter != nullptr && OtherCharacter->GetCharacterMovement()->CanEverCrouch())
{
OtherCharacter->nbDoorEnter++;
OtherCharacter->CrouchBP();
}
//GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Green, *FString::Printf(TEXT("[%s] Character Enter %s"), GET_NETMODE_TEXT(), *GetNameSafe(OtherCharacter)));
}
}
void AS47TriggerDoor::OnTriggerExit(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
AS47Character* OtherCharacter = Cast<AS47Character>(OtherActor);
UCapsuleComponent* OtherCapsule = Cast<UCapsuleComponent>(OtherComp);
if (OtherCharacter != nullptr && OtherCapsule != nullptr && OtherCapsule == OtherCharacter->GetCapsuleComponent() && CharacterList.Contains(OtherCharacter))
{
CharacterList.Remove(OtherCharacter);
AS47Enemy* OtherCharacter = Cast<AS47Enemy>(OtherActor);
if (OtherCharacter != nullptr && OtherCharacter->GetCharacterMovement()->CanEverCrouch())
{
OtherCharacter->nbDoorEnter--;
if (OtherCharacter->nbDoorEnter <= 0)
{
OtherCharacter->UnCrouchBP();
}
}
//GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Orange, *FString::Printf(TEXT("[%s] Character Exit %s"), GET_NETMODE_TEXT(), *GetNameSafe(OtherCharacter)));
}
}
| [
"vince.col.colin@gmail.com"
] | vince.col.colin@gmail.com |
882edd9353385949fd53187f189035ed6805f8d0 | d2bd315e9f5ad3c4bf5894c1bfe3c8357042ad7f | /비전프로그래밍/14주차/CV_20193148_14_1.cpp | a7bc7d2894c50d8ce7f94264d9af3ae0e156a152 | [] | no_license | bluebluerabbit/School_3.1 | 6007939717aa67ad58eadff88cf9532dc6867cb8 | a36f9b6d21eff95a226f58344c11884e3863ca23 | refs/heads/main | 2023-08-04T05:16:30.811280 | 2021-09-23T06:37:58 | 2021-09-23T06:37:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,275 | cpp | #include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void read_trainData(string fn, Mat& trainingData, Mat& lables) {
FileStorage fs(fn, FileStorage::READ);
CV_Assert(fs.isOpened());
fs["TrainingData"] >> trainingData;
fs["classes"] >> lables;
fs.release();
trainingData.convertTo(trainingData, CV_32FC1);
}
Ptr<ml::SVM> SVM_create(int type, int max_iter, double epsilon) {
Ptr<ml::SVM> svm = ml::SVM::create();
svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::LINEAR);
svm->setGamma(1);
svm->setC(1);
TermCriteria criteria(type, max_iter, epsilon);
svm->setTermCriteria(criteria);
return svm;
}
int classify_plates(Ptr<ml::SVM> svm, vector<Mat> candi_img) {
for (int i = 0; i < (int)candi_img.size(); i++) {
Mat onerow = candi_img[i].reshape(1, 1);
onerow.convertTo(onerow, CV_32F);
Mat results;
svm->predict(onerow, results);
if (results.at<float>(0) == 1)
return i;
}
return -1;
}
Mat preprocessing(Mat image) {
Mat gray, th_img, morph;
Mat kernel(5, 15, CV_8UC1, Scalar(1));
cvtColor(image, gray, COLOR_BGR2GRAY);
blur(gray, gray, Size(5, 5));
Sobel(gray, gray, CV_8U, 1, 0, 3);
threshold(gray, th_img, 120, 255, THRESH_BINARY);
morphologyEx(th_img, morph, MORPH_CLOSE, kernel);
return morph;
}
bool vertify_plate(RotatedRect mr) {
float size = mr.size.area();
float aspect = (float)mr.size.height / mr.size.width;
if (aspect < 1) aspect = 1 / aspect;
bool ch1 = size > 2000 && size < 30000;
bool ch2 = aspect > 1.3 && aspect < 6.4;
return ch1 && ch2;
}
void find_candidates(Mat img, vector<RotatedRect>& candidates) {
vector< vector< Point> > contours;
findContours(img.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for (int i = 0; i < (int)contours.size(); i++) {
RotatedRect rot_rect = minAreaRect(contours[i]);
if (vertify_plate(rot_rect)) {
candidates.push_back(rot_rect);
}
}
}
void draw_rotatedRect(Mat& img, RotatedRect mr, Scalar color, int thickness = 2) {
Point2f pts[4];
mr.points(pts);
for (int i = 0; i < 4; ++i) {
line(img, pts[i], pts[(i + 1) % 4], color, thickness);
}
}
void refine_candidate(Mat image, RotatedRect& candi) {
Mat fill(image.size() + Size(2, 2), CV_8UC1, Scalar(0));
Scalar dif1(25, 25, 25), dif2(25, 25, 25);
int flags = 4 + 0xff00;
flags += FLOODFILL_FIXED_RANGE + FLOODFILL_MASK_ONLY;
vector<Point2f> rand_pt(15);
randn(rand_pt, 0, 7);
Rect img_rect(Point(0, 0), image.size());
for (int i = 0; i < rand_pt.size(); i++) {
Point2f seed = candi.center + rand_pt[i];
if (img_rect.contains(seed)) {
Rect a = Rect();
floodFill(image, fill, seed, Scalar(), &a, dif1, dif2, flags);
}
}
vector<Point> fill_pts;
for (int i = 0; i < fill.rows; i++) {
for (int j = 0; j < fill.cols; j++) {
if (fill.at<uchar>(i, j) == 255)
fill_pts.push_back(Point(j, i));
}
}
candi = minAreaRect(fill_pts);
}
void rotate_plate(Mat image, Mat& corp_img, RotatedRect candi) {
float aspect = (float)candi.size.width / candi.size.height;
float angle = candi.angle;
if (aspect < 1) {
swap(candi.size.width, candi.size.height);
angle += 90;
}
Mat rotmat = getRotationMatrix2D(candi.center, angle, 1);
warpAffine(image, corp_img, rotmat, image.size(), INTER_CUBIC);
getRectSubPix(corp_img, candi.size, candi.center, corp_img);
}
vector<Mat> make_candidates(Mat image, vector<RotatedRect>& candidates) {
vector<Mat> candidates_img;
for (int i = 0; i < (int)candidates.size();) {
refine_candidate(image, candidates[i]);
if (vertify_plate(candidates[i])) {
Mat corp_img;
rotate_plate(image, corp_img, candidates[i]);
cvtColor(corp_img, corp_img, COLOR_BGR2GRAY);
resize(corp_img, corp_img, Size(144, 28), 0, 0, INTER_CUBIC);
candidates_img.push_back(corp_img);
i++;
}
else {
candidates.erase(candidates.begin() + i);
}
}
return candidates_img;
}
int main() {
Mat trainingData, labels;
read_trainData("SVMDATA.xml", trainingData, labels);
Ptr<ml::SVM> svm = SVM_create(TermCriteria::MAX_ITER, 1000, 0);
svm->train(trainingData, ml::ROW_SAMPLE, labels); // 학습수행
//Ptr<ml::SVM> svm = ml::StatModel::load<ml::SVM>("../SVMtrain.xml");
int car_no;
cout << "차량 영상 번호 (0-20) : ";
cin >> car_no;
string fn = format("image/test_car/%02d.jpg", car_no);
Mat image = imread(fn, 1);
CV_Assert(image.data);
Mat morph = preprocessing(image);
vector<RotatedRect> candidates;
find_candidates(morph, candidates);
vector<Mat> candidate_img = make_candidates(image, candidates);
int plate_no = classify_plates(svm, candidate_img);
if (plate_no >= 0)
draw_rotatedRect(image, candidates[plate_no], Scalar(0, 255, 0), 2);
imshow("번호판영상", candidate_img[plate_no]);
imshow("image", image);
waitKey();
return 0;
} | [
"jinjoo021@naver.com"
] | jinjoo021@naver.com |
24141b14318920d7d7574e5adc57d49dc773caf7 | e7af25e1e1f1bc5e222ac3487869023cc06f2986 | /inference/inference/examples/AudioToWords.h | 38d028dc1faa625baee2644b7c294e27312920ee | [
"BSD-3-Clause"
] | permissive | samin9796/wav2letter | 688d92297eccb6b1cd37b0a950018c73bc62c3bf | 6fdb54bbc37938c1663d9d263a3d33a5cc3168d9 | refs/heads/master | 2022-09-12T00:13:20.135436 | 2020-06-03T02:20:51 | 2020-06-03T02:22:20 | 269,457,835 | 1 | 0 | NOASSERTION | 2020-06-04T20:23:26 | 2020-06-04T20:23:26 | null | UTF-8 | C++ | false | false | 1,542 | h | /**
* Copyright (c) Facebook, Inc. and its affiliates.
* 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.
*/
#pragma once
#include <istream>
#include <memory>
#include <ostream>
#include <string>
#include "inference/decoder/Decoder.h"
#include "inference/module/nn/nn.h"
namespace w2l {
namespace streaming {
// @inputAudioStream is a 16KHz wav file.
void audioStreamToWordsStream(
std::istream& inputAudioStream,
std::ostream& outputWordsStream,
std::shared_ptr<streaming::Sequential> dnnModule,
std::shared_ptr<const DecoderFactory> decoderFactory,
const DecoderOptions& decoderOptions,
int nTokens);
// @inputFileName is a 16KHz wav file.
// @errorStream file errors are written to errorStream.
void audioFileToWordsFile(
const std::string& inputFileName,
const std::string& outputFileName,
std::shared_ptr<streaming::Sequential> dnnModule,
std::shared_ptr<const DecoderFactory> decoderFactory,
const DecoderOptions& decoderOptions,
int nTokens,
std::ostream& errorStream);
// @inputFileName is a 16KHz wav file.
// Errors are throws as exceptions.
void audioFileToWordsFile(
const std::string& inputFileName,
const std::string& outputFileName,
std::shared_ptr<streaming::Sequential> dnnModule,
std::shared_ptr<const DecoderFactory> decoderFactory,
const DecoderOptions& decoderOptions,
int nTokens);
} // namespace streaming
} // namespace w2l
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
b215f78f414fba84a03b2d58c81ebaee0ac79a7e | 0f23651b08fd5a8ce21b9e78e39e61618996073b | /lib/CodeGen/MachineOutliner.cpp | b52d3ebfeff41d56f9a645a3ea801c472dac57e0 | [
"NCSA"
] | permissive | arcosuc3m/clang-contracts | 3983773f15872514f7b6ae72d7fea232864d7e3d | 99446829e2cd96116e4dce9496f88cc7df1dbe80 | refs/heads/master | 2021-07-04T03:24:03.156444 | 2018-12-12T11:41:18 | 2018-12-12T12:56:08 | 118,155,058 | 31 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 49,248 | cpp | //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Replaces repeated sequences of instructions with function calls.
///
/// This works by placing every instruction from every basic block in a
/// suffix tree, and repeatedly querying that tree for repeated sequences of
/// instructions. If a sequence of instructions appears often, then it ought
/// to be beneficial to pull out into a function.
///
/// The MachineOutliner communicates with a given target using hooks defined in
/// TargetInstrInfo.h. The target supplies the outliner with information on how
/// a specific sequence of instructions should be outlined. This information
/// is used to deduce the number of instructions necessary to
///
/// * Create an outlined function
/// * Call that outlined function
///
/// Targets must implement
/// * getOutliningCandidateInfo
/// * insertOutlinerEpilogue
/// * insertOutlinedCall
/// * insertOutlinerPrologue
/// * isFunctionSafeToOutlineFrom
///
/// in order to make use of the MachineOutliner.
///
/// This was originally presented at the 2016 LLVM Developers' Meeting in the
/// talk "Reducing Code Size Using Outlining". For a high-level overview of
/// how this pass works, the talk is available on YouTube at
///
/// https://www.youtube.com/watch?v=yorld-WSOeU
///
/// The slides for the talk are available at
///
/// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
///
/// The talk provides an overview of how the outliner finds candidates and
/// ultimately outlines them. It describes how the main data structure for this
/// pass, the suffix tree, is queried and purged for candidates. It also gives
/// a simplified suffix tree construction algorithm for suffix trees based off
/// of the algorithm actually used here, Ukkonen's algorithm.
///
/// For the original RFC for this pass, please see
///
/// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
///
/// For more information on the suffix tree data structure, please see
/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
///
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/Twine.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include <functional>
#include <map>
#include <sstream>
#include <tuple>
#include <vector>
#define DEBUG_TYPE "machine-outliner"
using namespace llvm;
using namespace ore;
STATISTIC(NumOutlined, "Number of candidates outlined");
STATISTIC(FunctionsCreated, "Number of functions created");
namespace {
/// \brief An individual sequence of instructions to be replaced with a call to
/// an outlined function.
struct Candidate {
/// Set to false if the candidate overlapped with another candidate.
bool InCandidateList = true;
/// The start index of this \p Candidate.
unsigned StartIdx;
/// The number of instructions in this \p Candidate.
unsigned Len;
/// The index of this \p Candidate's \p OutlinedFunction in the list of
/// \p OutlinedFunctions.
unsigned FunctionIdx;
/// Contains all target-specific information for this \p Candidate.
TargetInstrInfo::MachineOutlinerInfo MInfo;
/// \brief The number of instructions that would be saved by outlining every
/// candidate of this type.
///
/// This is a fixed value which is not updated during the candidate pruning
/// process. It is only used for deciding which candidate to keep if two
/// candidates overlap. The true benefit is stored in the OutlinedFunction
/// for some given candidate.
unsigned Benefit = 0;
Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx)
: StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {}
Candidate() {}
/// \brief Used to ensure that \p Candidates are outlined in an order that
/// preserves the start and end indices of other \p Candidates.
bool operator<(const Candidate &RHS) const { return StartIdx > RHS.StartIdx; }
};
/// \brief The information necessary to create an outlined function for some
/// class of candidate.
struct OutlinedFunction {
/// The actual outlined function created.
/// This is initialized after we go through and create the actual function.
MachineFunction *MF = nullptr;
/// A number assigned to this function which appears at the end of its name.
unsigned Name;
/// The number of candidates for this OutlinedFunction.
unsigned OccurrenceCount = 0;
/// \brief The sequence of integers corresponding to the instructions in this
/// function.
std::vector<unsigned> Sequence;
/// Contains all target-specific information for this \p OutlinedFunction.
TargetInstrInfo::MachineOutlinerInfo MInfo;
/// \brief Return the number of instructions it would take to outline this
/// function.
unsigned getOutliningCost() {
return (OccurrenceCount * MInfo.CallOverhead) + Sequence.size() +
MInfo.FrameOverhead;
}
/// \brief Return the number of instructions that would be saved by outlining
/// this function.
unsigned getBenefit() {
unsigned NotOutlinedCost = OccurrenceCount * Sequence.size();
unsigned OutlinedCost = getOutliningCost();
return (NotOutlinedCost < OutlinedCost) ? 0
: NotOutlinedCost - OutlinedCost;
}
OutlinedFunction(unsigned Name, unsigned OccurrenceCount,
const std::vector<unsigned> &Sequence,
TargetInstrInfo::MachineOutlinerInfo &MInfo)
: Name(Name), OccurrenceCount(OccurrenceCount), Sequence(Sequence),
MInfo(MInfo) {}
};
/// Represents an undefined index in the suffix tree.
const unsigned EmptyIdx = -1;
/// A node in a suffix tree which represents a substring or suffix.
///
/// Each node has either no children or at least two children, with the root
/// being a exception in the empty tree.
///
/// Children are represented as a map between unsigned integers and nodes. If
/// a node N has a child M on unsigned integer k, then the mapping represented
/// by N is a proper prefix of the mapping represented by M. Note that this,
/// although similar to a trie is somewhat different: each node stores a full
/// substring of the full mapping rather than a single character state.
///
/// Each internal node contains a pointer to the internal node representing
/// the same string, but with the first character chopped off. This is stored
/// in \p Link. Each leaf node stores the start index of its respective
/// suffix in \p SuffixIdx.
struct SuffixTreeNode {
/// The children of this node.
///
/// A child existing on an unsigned integer implies that from the mapping
/// represented by the current node, there is a way to reach another
/// mapping by tacking that character on the end of the current string.
DenseMap<unsigned, SuffixTreeNode *> Children;
/// A flag set to false if the node has been pruned from the tree.
bool IsInTree = true;
/// The start index of this node's substring in the main string.
unsigned StartIdx = EmptyIdx;
/// The end index of this node's substring in the main string.
///
/// Every leaf node must have its \p EndIdx incremented at the end of every
/// step in the construction algorithm. To avoid having to update O(N)
/// nodes individually at the end of every step, the end index is stored
/// as a pointer.
unsigned *EndIdx = nullptr;
/// For leaves, the start index of the suffix represented by this node.
///
/// For all other nodes, this is ignored.
unsigned SuffixIdx = EmptyIdx;
/// \brief For internal nodes, a pointer to the internal node representing
/// the same sequence with the first character chopped off.
///
/// This acts as a shortcut in Ukkonen's algorithm. One of the things that
/// Ukkonen's algorithm does to achieve linear-time construction is
/// keep track of which node the next insert should be at. This makes each
/// insert O(1), and there are a total of O(N) inserts. The suffix link
/// helps with inserting children of internal nodes.
///
/// Say we add a child to an internal node with associated mapping S. The
/// next insertion must be at the node representing S - its first character.
/// This is given by the way that we iteratively build the tree in Ukkonen's
/// algorithm. The main idea is to look at the suffixes of each prefix in the
/// string, starting with the longest suffix of the prefix, and ending with
/// the shortest. Therefore, if we keep pointers between such nodes, we can
/// move to the next insertion point in O(1) time. If we don't, then we'd
/// have to query from the root, which takes O(N) time. This would make the
/// construction algorithm O(N^2) rather than O(N).
SuffixTreeNode *Link = nullptr;
/// The parent of this node. Every node except for the root has a parent.
SuffixTreeNode *Parent = nullptr;
/// The number of times this node's string appears in the tree.
///
/// This is equal to the number of leaf children of the string. It represents
/// the number of suffixes that the node's string is a prefix of.
unsigned OccurrenceCount = 0;
/// The length of the string formed by concatenating the edge labels from the
/// root to this node.
unsigned ConcatLen = 0;
/// Returns true if this node is a leaf.
bool isLeaf() const { return SuffixIdx != EmptyIdx; }
/// Returns true if this node is the root of its owning \p SuffixTree.
bool isRoot() const { return StartIdx == EmptyIdx; }
/// Return the number of elements in the substring associated with this node.
size_t size() const {
// Is it the root? If so, it's the empty string so return 0.
if (isRoot())
return 0;
assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
// Size = the number of elements in the string.
// For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
return *EndIdx - StartIdx + 1;
}
SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link,
SuffixTreeNode *Parent)
: StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
SuffixTreeNode() {}
};
/// A data structure for fast substring queries.
///
/// Suffix trees represent the suffixes of their input strings in their leaves.
/// A suffix tree is a type of compressed trie structure where each node
/// represents an entire substring rather than a single character. Each leaf
/// of the tree is a suffix.
///
/// A suffix tree can be seen as a type of state machine where each state is a
/// substring of the full string. The tree is structured so that, for a string
/// of length N, there are exactly N leaves in the tree. This structure allows
/// us to quickly find repeated substrings of the input string.
///
/// In this implementation, a "string" is a vector of unsigned integers.
/// These integers may result from hashing some data type. A suffix tree can
/// contain 1 or many strings, which can then be queried as one large string.
///
/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
/// suffix tree construction. Ukkonen's algorithm is explained in more detail
/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
/// paper is available at
///
/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
class SuffixTree {
public:
/// Stores each leaf node in the tree.
///
/// This is used for finding outlining candidates.
std::vector<SuffixTreeNode *> LeafVector;
/// Each element is an integer representing an instruction in the module.
ArrayRef<unsigned> Str;
private:
/// Maintains each node in the tree.
SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
/// The root of the suffix tree.
///
/// The root represents the empty string. It is maintained by the
/// \p NodeAllocator like every other node in the tree.
SuffixTreeNode *Root = nullptr;
/// Maintains the end indices of the internal nodes in the tree.
///
/// Each internal node is guaranteed to never have its end index change
/// during the construction algorithm; however, leaves must be updated at
/// every step. Therefore, we need to store leaf end indices by reference
/// to avoid updating O(N) leaves at every step of construction. Thus,
/// every internal node must be allocated its own end index.
BumpPtrAllocator InternalEndIdxAllocator;
/// The end index of each leaf in the tree.
unsigned LeafEndIdx = -1;
/// \brief Helper struct which keeps track of the next insertion point in
/// Ukkonen's algorithm.
struct ActiveState {
/// The next node to insert at.
SuffixTreeNode *Node;
/// The index of the first character in the substring currently being added.
unsigned Idx = EmptyIdx;
/// The length of the substring we have to add at the current step.
unsigned Len = 0;
};
/// \brief The point the next insertion will take place at in the
/// construction algorithm.
ActiveState Active;
/// Allocate a leaf node and add it to the tree.
///
/// \param Parent The parent of this node.
/// \param StartIdx The start index of this node's associated string.
/// \param Edge The label on the edge leaving \p Parent to this node.
///
/// \returns A pointer to the allocated leaf node.
SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
unsigned Edge) {
assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
SuffixTreeNode *N = new (NodeAllocator.Allocate())
SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
Parent.Children[Edge] = N;
return N;
}
/// Allocate an internal node and add it to the tree.
///
/// \param Parent The parent of this node. Only null when allocating the root.
/// \param StartIdx The start index of this node's associated string.
/// \param EndIdx The end index of this node's associated string.
/// \param Edge The label on the edge leaving \p Parent to this node.
///
/// \returns A pointer to the allocated internal node.
SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
unsigned EndIdx, unsigned Edge) {
assert(StartIdx <= EndIdx && "String can't start after it ends!");
assert(!(!Parent && StartIdx != EmptyIdx) &&
"Non-root internal nodes must have parents!");
unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
SuffixTreeNode *N = new (NodeAllocator.Allocate())
SuffixTreeNode(StartIdx, E, Root, Parent);
if (Parent)
Parent->Children[Edge] = N;
return N;
}
/// \brief Set the suffix indices of the leaves to the start indices of their
/// respective suffixes. Also stores each leaf in \p LeafVector at its
/// respective suffix index.
///
/// \param[in] CurrNode The node currently being visited.
/// \param CurrIdx The current index of the string being visited.
void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) {
bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
// Store the length of the concatenation of all strings from the root to
// this node.
if (!CurrNode.isRoot()) {
if (CurrNode.ConcatLen == 0)
CurrNode.ConcatLen = CurrNode.size();
if (CurrNode.Parent)
CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
}
// Traverse the tree depth-first.
for (auto &ChildPair : CurrNode.Children) {
assert(ChildPair.second && "Node had a null child!");
setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
}
// Is this node a leaf?
if (IsLeaf) {
// If yes, give it a suffix index and bump its parent's occurrence count.
CurrNode.SuffixIdx = Str.size() - CurrIdx;
assert(CurrNode.Parent && "CurrNode had no parent!");
CurrNode.Parent->OccurrenceCount++;
// Store the leaf in the leaf vector for pruning later.
LeafVector[CurrNode.SuffixIdx] = &CurrNode;
}
}
/// \brief Construct the suffix tree for the prefix of the input ending at
/// \p EndIdx.
///
/// Used to construct the full suffix tree iteratively. At the end of each
/// step, the constructed suffix tree is either a valid suffix tree, or a
/// suffix tree with implicit suffixes. At the end of the final step, the
/// suffix tree is a valid tree.
///
/// \param EndIdx The end index of the current prefix in the main string.
/// \param SuffixesToAdd The number of suffixes that must be added
/// to complete the suffix tree at the current phase.
///
/// \returns The number of suffixes that have not been added at the end of
/// this step.
unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
SuffixTreeNode *NeedsLink = nullptr;
while (SuffixesToAdd > 0) {
// Are we waiting to add anything other than just the last character?
if (Active.Len == 0) {
// If not, then say the active index is the end index.
Active.Idx = EndIdx;
}
assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
// The first character in the current substring we're looking at.
unsigned FirstChar = Str[Active.Idx];
// Have we inserted anything starting with FirstChar at the current node?
if (Active.Node->Children.count(FirstChar) == 0) {
// If not, then we can just insert a leaf and move too the next step.
insertLeaf(*Active.Node, EndIdx, FirstChar);
// The active node is an internal node, and we visited it, so it must
// need a link if it doesn't have one.
if (NeedsLink) {
NeedsLink->Link = Active.Node;
NeedsLink = nullptr;
}
} else {
// There's a match with FirstChar, so look for the point in the tree to
// insert a new node.
SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
unsigned SubstringLen = NextNode->size();
// Is the current suffix we're trying to insert longer than the size of
// the child we want to move to?
if (Active.Len >= SubstringLen) {
// If yes, then consume the characters we've seen and move to the next
// node.
Active.Idx += SubstringLen;
Active.Len -= SubstringLen;
Active.Node = NextNode;
continue;
}
// Otherwise, the suffix we're trying to insert must be contained in the
// next node we want to move to.
unsigned LastChar = Str[EndIdx];
// Is the string we're trying to insert a substring of the next node?
if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
// If yes, then we're done for this step. Remember our insertion point
// and move to the next end index. At this point, we have an implicit
// suffix tree.
if (NeedsLink && !Active.Node->isRoot()) {
NeedsLink->Link = Active.Node;
NeedsLink = nullptr;
}
Active.Len++;
break;
}
// The string we're trying to insert isn't a substring of the next node,
// but matches up to a point. Split the node.
//
// For example, say we ended our search at a node n and we're trying to
// insert ABD. Then we'll create a new node s for AB, reduce n to just
// representing C, and insert a new leaf node l to represent d. This
// allows us to ensure that if n was a leaf, it remains a leaf.
//
// | ABC ---split---> | AB
// n s
// C / \ D
// n l
// The node s from the diagram
SuffixTreeNode *SplitNode =
insertInternalNode(Active.Node, NextNode->StartIdx,
NextNode->StartIdx + Active.Len - 1, FirstChar);
// Insert the new node representing the new substring into the tree as
// a child of the split node. This is the node l from the diagram.
insertLeaf(*SplitNode, EndIdx, LastChar);
// Make the old node a child of the split node and update its start
// index. This is the node n from the diagram.
NextNode->StartIdx += Active.Len;
NextNode->Parent = SplitNode;
SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
// SplitNode is an internal node, update the suffix link.
if (NeedsLink)
NeedsLink->Link = SplitNode;
NeedsLink = SplitNode;
}
// We've added something new to the tree, so there's one less suffix to
// add.
SuffixesToAdd--;
if (Active.Node->isRoot()) {
if (Active.Len > 0) {
Active.Len--;
Active.Idx = EndIdx - SuffixesToAdd + 1;
}
} else {
// Start the next phase at the next smallest suffix.
Active.Node = Active.Node->Link;
}
}
return SuffixesToAdd;
}
public:
/// Construct a suffix tree from a sequence of unsigned integers.
///
/// \param Str The string to construct the suffix tree for.
SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
Root->IsInTree = true;
Active.Node = Root;
LeafVector = std::vector<SuffixTreeNode *>(Str.size());
// Keep track of the number of suffixes we have to add of the current
// prefix.
unsigned SuffixesToAdd = 0;
Active.Node = Root;
// Construct the suffix tree iteratively on each prefix of the string.
// PfxEndIdx is the end index of the current prefix.
// End is one past the last element in the string.
for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
PfxEndIdx++) {
SuffixesToAdd++;
LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
}
// Set the suffix indices of each leaf.
assert(Root && "Root node can't be nullptr!");
setSuffixIndices(*Root, 0);
}
};
/// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings.
struct InstructionMapper {
/// \brief The next available integer to assign to a \p MachineInstr that
/// cannot be outlined.
///
/// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
unsigned IllegalInstrNumber = -3;
/// \brief The next available integer to assign to a \p MachineInstr that can
/// be outlined.
unsigned LegalInstrNumber = 0;
/// Correspondence from \p MachineInstrs to unsigned integers.
DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
InstructionIntegerMap;
/// Corresponcence from unsigned integers to \p MachineInstrs.
/// Inverse of \p InstructionIntegerMap.
DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
/// The vector of unsigned integers that the module is mapped to.
std::vector<unsigned> UnsignedVec;
/// \brief Stores the location of the instruction associated with the integer
/// at index i in \p UnsignedVec for each index i.
std::vector<MachineBasicBlock::iterator> InstrList;
/// \brief Maps \p *It to a legal integer.
///
/// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
/// \p IntegerInstructionMap, and \p LegalInstrNumber.
///
/// \returns The integer that \p *It was mapped to.
unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
// Get the integer for this instruction or give it the current
// LegalInstrNumber.
InstrList.push_back(It);
MachineInstr &MI = *It;
bool WasInserted;
DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
ResultIt;
std::tie(ResultIt, WasInserted) =
InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
unsigned MINumber = ResultIt->second;
// There was an insertion.
if (WasInserted) {
LegalInstrNumber++;
IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
}
UnsignedVec.push_back(MINumber);
// Make sure we don't overflow or use any integers reserved by the DenseMap.
if (LegalInstrNumber >= IllegalInstrNumber)
report_fatal_error("Instruction mapping overflow!");
assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
"Tried to assign DenseMap tombstone or empty key to instruction.");
assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
"Tried to assign DenseMap tombstone or empty key to instruction.");
return MINumber;
}
/// Maps \p *It to an illegal integer.
///
/// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
///
/// \returns The integer that \p *It was mapped to.
unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
unsigned MINumber = IllegalInstrNumber;
InstrList.push_back(It);
UnsignedVec.push_back(IllegalInstrNumber);
IllegalInstrNumber--;
assert(LegalInstrNumber < IllegalInstrNumber &&
"Instruction mapping overflow!");
assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
"IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
"IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
return MINumber;
}
/// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
/// and appends it to \p UnsignedVec and \p InstrList.
///
/// Two instructions are assigned the same integer if they are identical.
/// If an instruction is deemed unsafe to outline, then it will be assigned an
/// unique integer. The resulting mapping is placed into a suffix tree and
/// queried for candidates.
///
/// \param MBB The \p MachineBasicBlock to be translated into integers.
/// \param TRI \p TargetRegisterInfo for the module.
/// \param TII \p TargetInstrInfo for the module.
void convertToUnsignedVec(MachineBasicBlock &MBB,
const TargetRegisterInfo &TRI,
const TargetInstrInfo &TII) {
for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
It++) {
// Keep track of where this instruction is in the module.
switch (TII.getOutliningType(*It)) {
case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
mapToIllegalUnsigned(It);
break;
case TargetInstrInfo::MachineOutlinerInstrType::Legal:
mapToLegalUnsigned(It);
break;
case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
break;
}
}
// After we're done every insertion, uniquely terminate this part of the
// "string". This makes sure we won't match across basic block or function
// boundaries since the "end" is encoded uniquely and thus appears in no
// repeated substring.
InstrList.push_back(MBB.end());
UnsignedVec.push_back(IllegalInstrNumber);
IllegalInstrNumber--;
}
InstructionMapper() {
// Make sure that the implementation of DenseMapInfo<unsigned> hasn't
// changed.
assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
"DenseMapInfo<unsigned>'s empty key isn't -1!");
assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
"DenseMapInfo<unsigned>'s tombstone key isn't -2!");
}
};
/// \brief An interprocedural pass which finds repeated sequences of
/// instructions and replaces them with calls to functions.
///
/// Each instruction is mapped to an unsigned integer and placed in a string.
/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
/// is then repeatedly queried for repeated sequences of instructions. Each
/// non-overlapping repeated sequence is then placed in its own
/// \p MachineFunction and each instance is then replaced with a call to that
/// function.
struct MachineOutliner : public ModulePass {
static char ID;
StringRef getPassName() const override { return "Machine Outliner"; }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineModuleInfo>();
AU.addPreserved<MachineModuleInfo>();
AU.setPreservesAll();
ModulePass::getAnalysisUsage(AU);
}
MachineOutliner() : ModulePass(ID) {
initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
}
/// Find all repeated substrings that satisfy the outlining cost model.
///
/// If a substring appears at least twice, then it must be represented by
/// an internal node which appears in at least two suffixes. Each suffix is
/// represented by a leaf node. To do this, we visit each internal node in
/// the tree, using the leaf children of each internal node. If an internal
/// node represents a beneficial substring, then we use each of its leaf
/// children to find the locations of its substring.
///
/// \param ST A suffix tree to query.
/// \param TII TargetInstrInfo for the target.
/// \param Mapper Contains outlining mapping information.
/// \param[out] CandidateList Filled with candidates representing each
/// beneficial substring.
/// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
/// type of candidate.
///
/// \returns The length of the longest candidate found.
unsigned findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
InstructionMapper &Mapper,
std::vector<Candidate> &CandidateList,
std::vector<OutlinedFunction> &FunctionList);
/// \brief Replace the sequences of instructions represented by the
/// \p Candidates in \p CandidateList with calls to \p MachineFunctions
/// described in \p FunctionList.
///
/// \param M The module we are outlining from.
/// \param CandidateList A list of candidates to be outlined.
/// \param FunctionList A list of functions to be inserted into the module.
/// \param Mapper Contains the instruction mappings for the module.
bool outline(Module &M, const ArrayRef<Candidate> &CandidateList,
std::vector<OutlinedFunction> &FunctionList,
InstructionMapper &Mapper);
/// Creates a function for \p OF and inserts it into the module.
MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
InstructionMapper &Mapper);
/// Find potential outlining candidates and store them in \p CandidateList.
///
/// For each type of potential candidate, also build an \p OutlinedFunction
/// struct containing the information to build the function for that
/// candidate.
///
/// \param[out] CandidateList Filled with outlining candidates for the module.
/// \param[out] FunctionList Filled with functions corresponding to each type
/// of \p Candidate.
/// \param ST The suffix tree for the module.
/// \param TII TargetInstrInfo for the module.
///
/// \returns The length of the longest candidate found. 0 if there are none.
unsigned buildCandidateList(std::vector<Candidate> &CandidateList,
std::vector<OutlinedFunction> &FunctionList,
SuffixTree &ST, InstructionMapper &Mapper,
const TargetInstrInfo &TII);
/// \brief Remove any overlapping candidates that weren't handled by the
/// suffix tree's pruning method.
///
/// Pruning from the suffix tree doesn't necessarily remove all overlaps.
/// If a short candidate is chosen for outlining, then a longer candidate
/// which has that short candidate as a suffix is chosen, the tree's pruning
/// method will not find it. Thus, we need to prune before outlining as well.
///
/// \param[in,out] CandidateList A list of outlining candidates.
/// \param[in,out] FunctionList A list of functions to be outlined.
/// \param Mapper Contains instruction mapping info for outlining.
/// \param MaxCandidateLen The length of the longest candidate.
/// \param TII TargetInstrInfo for the module.
void pruneOverlaps(std::vector<Candidate> &CandidateList,
std::vector<OutlinedFunction> &FunctionList,
InstructionMapper &Mapper, unsigned MaxCandidateLen,
const TargetInstrInfo &TII);
/// Construct a suffix tree on the instructions in \p M and outline repeated
/// strings from that tree.
bool runOnModule(Module &M) override;
};
} // Anonymous namespace.
char MachineOutliner::ID = 0;
namespace llvm {
ModulePass *createMachineOutlinerPass() { return new MachineOutliner(); }
} // namespace llvm
INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
false)
unsigned
MachineOutliner::findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
InstructionMapper &Mapper,
std::vector<Candidate> &CandidateList,
std::vector<OutlinedFunction> &FunctionList) {
CandidateList.clear();
FunctionList.clear();
unsigned MaxLen = 0;
// FIXME: Visit internal nodes instead of leaves.
for (SuffixTreeNode *Leaf : ST.LeafVector) {
assert(Leaf && "Leaves in LeafVector cannot be null!");
if (!Leaf->IsInTree)
continue;
assert(Leaf->Parent && "All leaves must have parents!");
SuffixTreeNode &Parent = *(Leaf->Parent);
// If it doesn't appear enough, or we already outlined from it, skip it.
if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
continue;
// Figure out if this candidate is beneficial.
unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size();
// Too short to be beneficial; skip it.
// FIXME: This isn't necessarily true for, say, X86. If we factor in
// instruction lengths we need more information than this.
if (StringLen < 2)
continue;
// If this is a beneficial class of candidate, then every one is stored in
// this vector.
std::vector<Candidate> CandidatesForRepeatedSeq;
// Describes the start and end point of each candidate. This allows the
// target to infer some information about each occurrence of each repeated
// sequence.
// FIXME: CandidatesForRepeatedSeq and this should be combined.
std::vector<
std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
RepeatedSequenceLocs;
// Figure out the call overhead for each instance of the sequence.
for (auto &ChildPair : Parent.Children) {
SuffixTreeNode *M = ChildPair.second;
if (M && M->IsInTree && M->isLeaf()) {
// Each sequence is over [StartIt, EndIt].
MachineBasicBlock::iterator StartIt = Mapper.InstrList[M->SuffixIdx];
MachineBasicBlock::iterator EndIt =
Mapper.InstrList[M->SuffixIdx + StringLen - 1];
CandidatesForRepeatedSeq.emplace_back(M->SuffixIdx, StringLen,
FunctionList.size());
RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt));
// Never visit this leaf again.
M->IsInTree = false;
}
}
// We've found something we might want to outline.
// Create an OutlinedFunction to store it and check if it'd be beneficial
// to outline.
TargetInstrInfo::MachineOutlinerInfo MInfo =
TII.getOutlininingCandidateInfo(RepeatedSequenceLocs);
std::vector<unsigned> Seq;
for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
Seq.push_back(ST.Str[i]);
OutlinedFunction OF(FunctionList.size(), Parent.OccurrenceCount, Seq,
MInfo);
unsigned Benefit = OF.getBenefit();
// Is it better to outline this candidate than not?
if (Benefit < 1) {
// Outlining this candidate would take more instructions than not
// outlining.
// Emit a remark explaining why we didn't outline this candidate.
std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C =
RepeatedSequenceLocs[0];
MachineOptimizationRemarkEmitter MORE(
*(C.first->getParent()->getParent()), nullptr);
MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
C.first->getDebugLoc(),
C.first->getParent());
R << "Did not outline " << NV("Length", StringLen) << " instructions"
<< " from " << NV("NumOccurrences", RepeatedSequenceLocs.size())
<< " locations."
<< " Instructions from outlining all occurrences ("
<< NV("OutliningCost", OF.getOutliningCost()) << ")"
<< " >= Unoutlined instruction count ("
<< NV("NotOutliningCost", StringLen * OF.OccurrenceCount) << ")"
<< " (Also found at: ";
// Tell the user the other places the candidate was found.
for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) {
R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
RepeatedSequenceLocs[i].first->getDebugLoc());
if (i != e - 1)
R << ", ";
}
R << ")";
MORE.emit(R);
// Move to the next candidate.
continue;
}
if (StringLen > MaxLen)
MaxLen = StringLen;
// At this point, the candidate class is seen as beneficial. Set their
// benefit values and save them in the candidate list.
for (Candidate &C : CandidatesForRepeatedSeq) {
C.Benefit = Benefit;
C.MInfo = MInfo;
CandidateList.push_back(C);
}
FunctionList.push_back(OF);
// Move to the next function.
Parent.IsInTree = false;
}
return MaxLen;
}
void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList,
std::vector<OutlinedFunction> &FunctionList,
InstructionMapper &Mapper,
unsigned MaxCandidateLen,
const TargetInstrInfo &TII) {
// Return true if this candidate became unbeneficial for outlining in a
// previous step.
auto ShouldSkipCandidate = [&FunctionList](Candidate &C) {
// Check if the candidate was removed in a previous step.
if (!C.InCandidateList)
return true;
// Check if C's associated function is still beneficial after previous
// pruning steps.
OutlinedFunction &F = FunctionList[C.FunctionIdx];
if (F.OccurrenceCount < 2 || F.getBenefit() < 1) {
assert(F.OccurrenceCount > 0 &&
"Can't remove OutlinedFunction with no occurrences!");
F.OccurrenceCount--;
C.InCandidateList = false;
return true;
}
// C is in the list, and F is still beneficial.
return false;
};
// Remove C from the candidate space, and update its OutlinedFunction.
auto Prune = [&FunctionList](Candidate &C) {
// Get the OutlinedFunction associated with this Candidate.
OutlinedFunction &F = FunctionList[C.FunctionIdx];
// Update C's associated function's occurrence count.
assert(F.OccurrenceCount > 0 &&
"Can't remove OutlinedFunction with no occurrences!");
F.OccurrenceCount--;
// Remove C from the CandidateList.
C.InCandidateList = false;
DEBUG(dbgs() << "- Removed a Candidate \n";
dbgs() << "--- Num fns left for candidate: " << F.OccurrenceCount
<< "\n";
dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
<< "\n";);
};
// TODO: Experiment with interval trees or other interval-checking structures
// to lower the time complexity of this function.
// TODO: Can we do better than the simple greedy choice?
// Check for overlaps in the range.
// This is O(MaxCandidateLen * CandidateList.size()).
for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
It++) {
Candidate &C1 = *It;
// If C1 was already pruned, or its function is no longer beneficial for
// outlining, move to the next candidate.
if (ShouldSkipCandidate(C1))
continue;
// The minimum start index of any candidate that could overlap with this
// one.
unsigned FarthestPossibleIdx = 0;
// Either the index is 0, or it's at most MaxCandidateLen indices away.
if (C1.StartIdx > MaxCandidateLen)
FarthestPossibleIdx = C1.StartIdx - MaxCandidateLen;
// Compare against the candidates in the list that start at at most
// FarthestPossibleIdx indices away from C1. There are at most
// MaxCandidateLen of these.
for (auto Sit = It + 1; Sit != Et; Sit++) {
Candidate &C2 = *Sit;
// Is this candidate too far away to overlap?
if (C2.StartIdx < FarthestPossibleIdx)
break;
// If C2 was already pruned, or its function is no longer beneficial for
// outlining, move to the next candidate.
if (ShouldSkipCandidate(C2))
continue;
unsigned C2End = C2.StartIdx + C2.Len - 1;
// Do C1 and C2 overlap?
//
// Not overlapping:
// High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
//
// We sorted our candidate list so C2Start <= C1Start. We know that
// C2End > C2Start since each candidate has length >= 2. Therefore, all we
// have to check is C2End < C2Start to see if we overlap.
if (C2End < C1.StartIdx)
continue;
// C1 and C2 overlap.
// We need to choose the better of the two.
//
// Approximate this by picking the one which would have saved us the
// most instructions before any pruning.
if (C1.Benefit >= C2.Benefit) {
Prune(C2);
} else {
Prune(C1);
// C1 is out, so we don't have to compare it against anyone else.
break;
}
}
}
}
unsigned
MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList,
std::vector<OutlinedFunction> &FunctionList,
SuffixTree &ST, InstructionMapper &Mapper,
const TargetInstrInfo &TII) {
std::vector<unsigned> CandidateSequence; // Current outlining candidate.
unsigned MaxCandidateLen = 0; // Length of the longest candidate.
MaxCandidateLen =
findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
// Sort the candidates in decending order. This will simplify the outlining
// process when we have to remove the candidates from the mapping by
// allowing us to cut them out without keeping track of an offset.
std::stable_sort(CandidateList.begin(), CandidateList.end());
return MaxCandidateLen;
}
MachineFunction *
MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
InstructionMapper &Mapper) {
// Create the function name. This should be unique. For now, just hash the
// module name and include it in the function name plus the number of this
// function.
std::ostringstream NameStream;
NameStream << "OUTLINED_FUNCTION_" << OF.Name;
// Create the function using an IR-level function.
LLVMContext &C = M.getContext();
Function *F = dyn_cast<Function>(
M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
assert(F && "Function was null!");
// NOTE: If this is linkonceodr, then we can take advantage of linker deduping
// which gives us better results when we outline from linkonceodr functions.
F->setLinkage(GlobalValue::PrivateLinkage);
F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
IRBuilder<> Builder(EntryBB);
Builder.CreateRetVoid();
MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
const TargetSubtargetInfo &STI = MF.getSubtarget();
const TargetInstrInfo &TII = *STI.getInstrInfo();
// Insert the new function into the module.
MF.insert(MF.begin(), &MBB);
TII.insertOutlinerPrologue(MBB, MF, OF.MInfo);
// Copy over the instructions for the function using the integer mappings in
// its sequence.
for (unsigned Str : OF.Sequence) {
MachineInstr *NewMI =
MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
NewMI->dropMemRefs();
// Don't keep debug information for outlined instructions.
// FIXME: This means outlined functions are currently undebuggable.
NewMI->setDebugLoc(DebugLoc());
MBB.insert(MBB.end(), NewMI);
}
TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo);
return &MF;
}
bool MachineOutliner::outline(Module &M,
const ArrayRef<Candidate> &CandidateList,
std::vector<OutlinedFunction> &FunctionList,
InstructionMapper &Mapper) {
bool OutlinedSomething = false;
// Replace the candidates with calls to their respective outlined functions.
for (const Candidate &C : CandidateList) {
// Was the candidate removed during pruneOverlaps?
if (!C.InCandidateList)
continue;
// If not, then look at its OutlinedFunction.
OutlinedFunction &OF = FunctionList[C.FunctionIdx];
// Was its OutlinedFunction made unbeneficial during pruneOverlaps?
if (OF.OccurrenceCount < 2 || OF.getBenefit() < 1)
continue;
// If not, then outline it.
assert(C.StartIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
MachineBasicBlock *MBB = (*Mapper.InstrList[C.StartIdx]).getParent();
MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.StartIdx];
unsigned EndIdx = C.StartIdx + C.Len - 1;
assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
assert(EndIt != MBB->end() && "EndIt out of bounds!");
EndIt++; // Erase needs one past the end index.
// Does this candidate have a function yet?
if (!OF.MF) {
OF.MF = createOutlinedFunction(M, OF, Mapper);
FunctionsCreated++;
}
MachineFunction *MF = OF.MF;
const TargetSubtargetInfo &STI = MF->getSubtarget();
const TargetInstrInfo &TII = *STI.getInstrInfo();
// Insert a call to the new function and erase the old sequence.
TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo);
StartIt = Mapper.InstrList[C.StartIdx];
MBB->erase(StartIt, EndIt);
OutlinedSomething = true;
// Statistics.
NumOutlined++;
}
DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
return OutlinedSomething;
}
bool MachineOutliner::runOnModule(Module &M) {
// Is there anything in the module at all?
if (M.empty())
return false;
MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
const TargetSubtargetInfo &STI =
MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
const TargetRegisterInfo *TRI = STI.getRegisterInfo();
const TargetInstrInfo *TII = STI.getInstrInfo();
InstructionMapper Mapper;
// Build instruction mappings for each function in the module.
for (Function &F : M) {
MachineFunction &MF = MMI.getOrCreateMachineFunction(F);
// Is the function empty? Safe to outline from?
if (F.empty() || !TII->isFunctionSafeToOutlineFrom(MF))
continue;
// If it is, look at each MachineBasicBlock in the function.
for (MachineBasicBlock &MBB : MF) {
// Is there anything in MBB?
if (MBB.empty())
continue;
// If yes, map it.
Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
}
}
// Construct a suffix tree, use it to find candidates, and then outline them.
SuffixTree ST(Mapper.UnsignedVec);
std::vector<Candidate> CandidateList;
std::vector<OutlinedFunction> FunctionList;
// Find all of the outlining candidates.
unsigned MaxCandidateLen =
buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
// Remove candidates that overlap with other candidates.
pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII);
// Outline each of the candidates and return true if something was outlined.
return outline(M, CandidateList, FunctionList, Mapper);
}
| [
"courbet@91177308-0d34-0410-b5e6-96231b3b80d8"
] | courbet@91177308-0d34-0410-b5e6-96231b3b80d8 |
8ec1e634de9ae260111539f2229dfbbcebc4d92c | 4adc21ab6d15a336fe6d4ae9a2eb375573dc1885 | /CvGameCoreDLL_Expansion2/CvArmyAI.cpp | 88e1e7129005255a64aac314fbac54bf6f403cf1 | [] | no_license | Surfal/Community-Patch-DLL | ec9e3c99c7e276fc7d4cbc1506ff75acabe005fb | 6acdb55620175a0cca6197141a3ffaa22aab0203 | refs/heads/master | 2021-01-21T05:37:06.412814 | 2015-06-13T20:01:44 | 2015-06-13T20:01:44 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 19,447 | cpp | /* -------------------------------------------------------------------------------------------------------
© 1991-2012 Take-Two Interactive Software and its subsidiaries. Developed by Firaxis Games.
Sid Meier's Civilization V, Civ, Civilization, 2K Games, Firaxis Games, Take-Two Interactive Software
and their respective logos are all trademarks of Take-Two interactive Software, Inc.
All other marks and trademarks are the property of their respective owners.
All rights reserved.
------------------------------------------------------------------------------------------------------- */
#include "CvGameCoreDLLPCH.h"
#include "CvGlobals.h"
#include "CvPlayerAI.h"
#include "CvTeam.h"
#include "CvArmyAI.h"
#include "CvUnit.h"
#include "CvGameCoreUtils.h"
#include "CvMap.h"
#include "CvPlot.h"
#include "ICvDLLUserInterface.h"
#include "CvAStar.h"
#include "CvInfos.h"
#include "CvEnumSerialization.h"
#include "FStlContainerSerialization.h"
// include after all other headers
#include "LintFree.h"
// Public Functions...
/// Constructor
CvArmyAI::CvArmyAI()
{
Reset(0, NO_PLAYER, true);
}
/// Destructor
CvArmyAI::~CvArmyAI()
{
Uninit();
}
/// Initialize
void CvArmyAI::Init(int iID, PlayerTypes eOwner, int iOperationID)
{
//--------------------------------
// Init saved data
Reset(iID, eOwner, iOperationID);
}
/// Deallocate memory
void CvArmyAI::Uninit()
{
m_FormationEntries.clear();
}
/// Initializes data members that are serialize
void CvArmyAI::Reset(int iID, PlayerTypes eOwner, int iOperationID, bool /* bConstructorCall */)
{
//--------------------------------
// Uninit class
Uninit();
m_iID = iID;
m_eOwner = eOwner;
m_iOperationID = iOperationID;
m_iCurrentX = -1;
m_iCurrentY = -1;
m_iGoalX = -1;
m_iGoalY = -1;
m_eDomainType = DOMAIN_LAND;
m_iFormationIndex = NO_MUFORMATION;
m_eAIState = NO_ARMYAISTATE;
m_FormationEntries.clear();
}
/// Delete the army
void CvArmyAI::Kill()
{
CvAssert(GetOwner() != NO_PLAYER);
CvAssertMsg(GetID() != FFreeList::INVALID_INDEX, "GetID() is not expected to be equal with FFreeList::INVALID_INDEX");
int iUnitID;
iUnitID = GetFirstUnitID();
while(iUnitID != ARMY_NO_UNIT)
{
UnitHandle pThisUnit = GET_PLAYER(GetOwner()).getUnit(iUnitID);
if(pThisUnit)
{
pThisUnit->setArmyID(FFreeList::INVALID_INDEX);
}
iUnitID = GetNextUnitID();
}
m_FormationEntries.clear();
}
/// Read from binary data store
void CvArmyAI::read(FDataStream& kStream)
{
// Init saved data
Reset();
// Version number to maintain backwards compatibility
uint uiVersion;
kStream >> uiVersion;
MOD_SERIALIZE_INIT_READ(kStream);
kStream >> m_iID;
kStream >> m_eOwner;
kStream >> m_iCurrentX;
kStream >> m_iCurrentY;
kStream >> m_iGoalX;
kStream >> m_iGoalY;
kStream >> m_eDomainType;
kStream >> m_iFormationIndex;
kStream >> m_eAIState;
kStream >> m_iOperationID;
int iEntriesToRead;
kStream >> iEntriesToRead;
for(int iI = 0; iI < iEntriesToRead; iI++)
{
CvArmyFormationSlot slot;
kStream >> slot;
m_FormationEntries.push_back(slot);
}
}
/// Write to binary data store
void CvArmyAI::write(FDataStream& kStream) const
{
// Current version number
uint uiVersion = 1;
kStream << uiVersion;
MOD_SERIALIZE_INIT_WRITE(kStream);
kStream << m_iID;
kStream << m_eOwner;
kStream << m_iCurrentX;
kStream << m_iCurrentY;
kStream << m_iGoalX;
kStream << m_iGoalY;
kStream << m_eDomainType;
kStream << m_iFormationIndex;
kStream << m_eAIState;
kStream << m_iOperationID;
kStream << (int)m_FormationEntries.size();
for(uint ui = 0; ui < m_FormationEntries.size(); ui++)
{
kStream << m_FormationEntries[ui];
}
}
// ACCESSORS
/// Retrieve this army's ID
int CvArmyAI::GetID()
{
return m_iID;
}
/// Set this army's ID
void CvArmyAI::SetID(int iID)
{
m_iID = iID;
}
/// Retrieve this army's team
TeamTypes CvArmyAI::GetTeam() const
{
if(GetOwner() != NO_PLAYER)
{
return GET_PLAYER(GetOwner()).getTeam();
}
return NO_TEAM;
}
/// Retrieve current army state
ArmyAIState CvArmyAI::GetArmyAIState() const
{
return (ArmyAIState) m_eAIState;
}
/// Set current army state
void CvArmyAI::SetArmyAIState(ArmyAIState eNewArmyAIState)
{
m_eAIState = (int) eNewArmyAIState;
}
/// Find average speed of units in army
int CvArmyAI::GetMovementRate()
{
int iMovementAverage = 2; // A reasonable default
int iNumUnits = 0;
int iTotalMovementAllowance = 0;
UnitHandle pUnit;
pUnit = GetFirstUnit();
while(pUnit)
{
iNumUnits++;
iTotalMovementAllowance += pUnit->baseMoves();
pUnit = GetNextUnit();
}
if(iNumUnits > 0)
{
iMovementAverage = (iTotalMovementAllowance + (iNumUnits / 2)) / iNumUnits;
}
return iMovementAverage;
}
/// Get center of mass of units in army (account for world wrap!)
CvPlot* CvArmyAI::GetCenterOfMass(DomainTypes eDomainRequired)
{
CvPlot* pRtnValue = NULL;
int iTotalX = 0;
int iTotalY = 0;
int iNumUnits = 0;
UnitHandle pUnit;
int iReferenceUnitX = -1;
int iWorldWidth = GC.getMap().getGridWidth();
pUnit = GetFirstUnit();
if(pUnit)
{
iReferenceUnitX = pUnit->getX();
}
while(pUnit)
{
int iUnitX = pUnit->getX();
bool bWorldWrapAdjust = false;
int iDiff = iUnitX - iReferenceUnitX;
if(abs(iDiff) > (iWorldWidth / 2))
{
bWorldWrapAdjust = true;
}
if(bWorldWrapAdjust)
{
iTotalX += iUnitX + iWorldWidth;
}
else
{
iTotalX += iUnitX;
}
iTotalY += pUnit->getY();
iNumUnits++;
pUnit = GetNextUnit();
}
if(iNumUnits > 0)
{
int iAverageX = (iTotalX + (iNumUnits / 2)) / iNumUnits;
if(iAverageX >= iWorldWidth)
{
iAverageX = iAverageX - iWorldWidth;
}
int iAverageY = (iTotalY + (iNumUnits / 2)) / iNumUnits;
pRtnValue = GC.getMap().plot(iAverageX, iAverageY);
}
// Domain check
if (eDomainRequired != NO_DOMAIN && pRtnValue)
{
if (pRtnValue->isWater() && eDomainRequired == DOMAIN_LAND || !pRtnValue->isWater() && eDomainRequired == DOMAIN_SEA)
{
// Find an adjacent plot that works
for (int iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
CvPlot *pLoopPlot = plotDirection(pRtnValue->getX(), pRtnValue->getY(), ((DirectionTypes)iI));
if (pLoopPlot != NULL)
{
if (pLoopPlot->isWater() && eDomainRequired == DOMAIN_SEA || !pLoopPlot->isWater() && eDomainRequired == DOMAIN_LAND)
{
return pLoopPlot;
}
}
}
// Try two plots out if really having problems
for (int iDX = -2; iDX <= 2; iDX++)
{
for (int iDY = -2; iDY <= 2; iDY++)
{
CvPlot *pLoopPlot = plotXYWithRangeCheck(pRtnValue->getX(), pRtnValue->getY(), iDX, iDY, 2);
if (pLoopPlot)
{
if (plotDistance(pRtnValue->getX(), pRtnValue->getY(), pLoopPlot->getX(), pLoopPlot->getY()) == 2)
{
if (pLoopPlot->isWater() && eDomainRequired == DOMAIN_SEA || !pLoopPlot->isWater() && eDomainRequired == DOMAIN_LAND)
{
return pLoopPlot;
}
}
}
}
}
// Give up - just use location of first unit
pUnit = GetFirstUnit();
pRtnValue = pUnit->plot();
}
}
return pRtnValue;
}
/// Return distance from this plot of unit in army farthest away
int CvArmyAI::GetFurthestUnitDistance(CvPlot* pPlot)
{
int iLargestDistance = 0;
UnitHandle pUnit;
int iNewDistance;
pUnit = GetFirstUnit();
while(pUnit)
{
iNewDistance = plotDistance(pUnit->getX(), pUnit->getY(), pPlot->getX(), pPlot->getY());
if(iNewDistance > iLargestDistance)
{
iLargestDistance = iNewDistance;
}
pUnit = GetNextUnit();
}
return iLargestDistance;
}
// FORMATION ACCESSORS
/// Retrieve index of the formation used by this army
int CvArmyAI::GetFormationIndex() const
{
return m_iFormationIndex;
}
/// Set index of the formation used by this army
void CvArmyAI::SetFormationIndex(int iFormationIndex)
{
CvArmyFormationSlot slot;
if(m_iFormationIndex != iFormationIndex)
{
m_iFormationIndex = iFormationIndex;
CvMultiUnitFormationInfo* thisFormation = GC.getMultiUnitFormationInfo(m_iFormationIndex);
if(thisFormation)
{
int iNumSlots = thisFormation->getNumFormationSlotEntries();
// Build all the formation entries
m_FormationEntries.clear();
for(int iI = 0; iI < iNumSlots; iI++)
{
slot.SetUnitID(ARMY_NO_UNIT);
slot.SetTurnAtCheckpoint(ARMYSLOT_UNKNOWN_TURN_AT_CHECKPOINT);
m_FormationEntries.push_back(slot);
}
}
}
}
/// How many slots are there in this formation if filled
int CvArmyAI::GetNumFormationEntries() const
{
return m_FormationEntries.size();
}
/// How many slots do we currently have filled?
int CvArmyAI::GetNumSlotsFilled() const
{
int iRtnValue = 0;
for(unsigned int iI = 0; iI < m_FormationEntries.size(); iI++)
{
if(m_FormationEntries[iI].m_iUnitID != ARMY_NO_UNIT)
{
iRtnValue++;
}
}
return iRtnValue;
}
/// What turn will a unit arrive on target?
void CvArmyAI::SetEstimatedTurn(int iSlotID, int iTurns)
{
int iTurnAtCheckpoint;
if(iTurns == ARMYSLOT_NOT_INCLUDING_IN_OPERATION || iTurns == ARMYSLOT_UNKNOWN_TURN_AT_CHECKPOINT)
{
iTurnAtCheckpoint = iTurns;
}
else
{
iTurnAtCheckpoint = GC.getGame().getGameTurn() + iTurns;
}
m_FormationEntries[iSlotID].SetTurnAtCheckpoint(iTurnAtCheckpoint);
}
/// What turn will the army as a whole arrive on target?
int CvArmyAI::GetTurnAtNextCheckpoint() const
{
int iRtnValue = ARMYSLOT_NOT_INCLUDING_IN_OPERATION;
for(unsigned int iI = 0; iI < m_FormationEntries.size(); iI++)
{
if(m_FormationEntries[iI].m_iEstimatedTurnAtCheckpoint == ARMYSLOT_UNKNOWN_TURN_AT_CHECKPOINT)
{
return ARMYSLOT_UNKNOWN_TURN_AT_CHECKPOINT;
}
else if(m_FormationEntries[iI].m_iEstimatedTurnAtCheckpoint > iRtnValue)
{
iRtnValue = m_FormationEntries[iI].m_iEstimatedTurnAtCheckpoint;
}
}
return iRtnValue;
}
/// Recalculate when each unit will arrive on target
void CvArmyAI::UpdateCheckpointTurns()
{
for(unsigned int iI = 0; iI < m_FormationEntries.size(); iI++)
{
// No reestimate for units being built
if(m_FormationEntries[iI].GetUnitID() != ARMY_NO_UNIT)
{
CvUnit* pUnit = GET_PLAYER(m_eOwner).getUnit(m_FormationEntries[iI].GetUnitID());
CvPlot* pMusterPlot = GC.getMap().plot(GetX(), GetY());
if(pUnit && pMusterPlot)
{
int iTurnsToReachCheckpoint = TurnsToReachTarget(pUnit, pMusterPlot, true /*bReusePaths*/, true, true);
if(iTurnsToReachCheckpoint < MAX_INT)
{
SetEstimatedTurn(iI, iTurnsToReachCheckpoint);
}
}
}
}
}
/// How many units of this type are in army?
int CvArmyAI::GetUnitsOfType(MultiunitPositionTypes ePosition) const
{
int iRtnValue = 0;
for(unsigned int iI = 0; iI < m_FormationEntries.size(); iI++)
{
if(m_FormationEntries[iI].m_iUnitID != ARMY_NO_UNIT)
{
CvUnit* pUnit = GET_PLAYER(m_eOwner).getUnit(m_FormationEntries[iI].m_iUnitID);
if(pUnit->getMoves() > 0)
{
CvMultiUnitFormationInfo* thisFormation = GC.getMultiUnitFormationInfo(m_iFormationIndex);
if(thisFormation)
{
const CvFormationSlotEntry& thisSlotEntry = thisFormation->getFormationSlotEntry(iI);
if(thisSlotEntry.m_ePositionType == ePosition)
{
iRtnValue++;
}
}
}
}
}
return iRtnValue;
}
/// Can all units in this army move on ocean?
bool CvArmyAI::IsAllOceanGoing()
{
UnitHandle pUnit;
pUnit = GetFirstUnit();
while(pUnit)
{
if(pUnit->getDomainType() != DOMAIN_SEA && !pUnit->IsHasEmbarkAbility())
{
return false;
}
// If can move over ocean, not a coastal vessel
if(pUnit->isTerrainImpassable(TERRAIN_OCEAN))
{
return false;
}
pUnit = GetNextUnit();
}
return true;
}
// UNIT STRENGTH ACCESSORS
/// Total unit power
int CvArmyAI::GetTotalPower()
{
int iRtnValue = 0;
int iUnitID;
iUnitID = GetFirstUnitID();
while(iUnitID != ARMY_NO_UNIT)
{
UnitHandle pThisUnit = GET_PLAYER(GetOwner()).getUnit(iUnitID);
if(pThisUnit)
{
iRtnValue += pThisUnit->GetPower();
}
iUnitID = GetNextUnitID();
}
return iRtnValue;
}
// POSITION ACCESSORS
/// Army's current X position
int CvArmyAI::GetX() const
{
return m_iCurrentX;
}
/// Army's current Y position
int CvArmyAI::GetY() const
{
return m_iCurrentY;
}
/// Set current army X position
void CvArmyAI::SetX(int iX)
{
m_iCurrentX = iX;
}
/// Set current army Y position
void CvArmyAI::SetY(int iY)
{
m_iCurrentY = iY;
}
/// Set current army position, passing in X and Y
void CvArmyAI::SetXY(int iX, int iY)
{
m_iCurrentX = iX;
m_iCurrentY = iY;
}
/// Retrieve the army's current plot
CvPlot* CvArmyAI::Plot() const
{
return GC.getMap().plotCheckInvalid(m_iCurrentX, m_iCurrentY);
}
/// Retrieve the army's current area
int CvArmyAI::GetArea() const
{
// try to find what plot we are in
CvPlot* pPlot = GC.getMap().plotCheckInvalid(m_iCurrentX, m_iCurrentY);
if(pPlot != NULL)
{
return pPlot->getArea();
}
else
{
// since there is no plot return the invalid index
return FFreeList::INVALID_INDEX;
}
}
/// Land or sea army?
DomainTypes CvArmyAI::GetDomainType() const
{
return (DomainTypes) m_eDomainType;
}
/// Set whether a land or sea army
void CvArmyAI::SetDomainType(DomainTypes domainType)
{
m_eDomainType = domainType;
}
/// Everyone in the water now?
bool CvArmyAI::AreAllInWater()
{
UnitHandle pUnit;
pUnit = GetFirstUnit();
while(pUnit)
{
if(!pUnit->plot()->isWater())
{
return false;
}
pUnit = GetNextUnit();
}
return true;
}
// GOAL ACCESSORS
/// Retrieve target plot for army movement
CvPlot* CvArmyAI::GetGoalPlot() const
{
return GC.getMap().plotCheckInvalid(m_iGoalX, m_iGoalY);
}
/// Set target plot for army movement
void CvArmyAI::SetGoalPlot(CvPlot* pGoalPlot)
{
CvAssertMsg(pGoalPlot, "Setting army goal to a NULL plot - please show Ed and send save.");
if(pGoalPlot)
{
m_iGoalX = pGoalPlot->getX();
m_iGoalY = pGoalPlot->getY();
}
else
{
m_iGoalX = -1;
m_iGoalY = -1;
}
}
/// Retrieve target plot X coordinate
int CvArmyAI::GetGoalX() const
{
return m_iGoalX;
}
/// Retrieve target plot Y coordinate
int CvArmyAI::GetGoalY() const
{
return m_iGoalY;
}
/// Set target for army movement using X, Y coordinates
void CvArmyAI::SetGoalXY(int iX, int iY)
{
m_iGoalX = iX;
m_iGoalY = iY;
}
// UNIT HANDLING
/// Add a unit to our army (and we know which slot)
void CvArmyAI::AddUnit(int iUnitID, int iSlotNum)
{
CvAssertMsg(iUnitID != ARMY_NO_UNIT,"Expect unit to be non-NULL");
CvPlayer& thisPlayer = GET_PLAYER(m_eOwner);
UnitHandle pThisUnit = thisPlayer.getUnit(iUnitID);
// remove this unit from an army if it is already in one
thisPlayer.removeFromArmy(pThisUnit->getArmyID(), GetID());
m_FormationEntries[iSlotNum].SetUnitID(iUnitID);
pThisUnit->setArmyID(GetID());
// Finally, compute when we think this unit will arrive at the next checkpoint
CvPlot* pMusterPlot = GC.getMap().plot(GetX(), GetY());
if(pMusterPlot)
{
int iTurnsToReachCheckpoint = TurnsToReachTarget(pThisUnit, pMusterPlot, true /*bReusePaths*/, true, true);
if(iTurnsToReachCheckpoint < MAX_INT)
{
SetEstimatedTurn(iSlotNum, iTurnsToReachCheckpoint);
}
}
}
/// Remove a unit from the army
bool CvArmyAI::RemoveUnit(int iUnitToRemoveID)
{
bool bWasOneOrMoreRemoved = false;
CvArmyFormationSlot slot;
for(int iI = 0; iI < (int)m_FormationEntries.size(); iI++)
{
slot = m_FormationEntries[iI];
if(slot.GetUnitID() == iUnitToRemoveID)
{
UnitHandle pThisUnit = GET_PLAYER(GetOwner()).getUnit(iUnitToRemoveID);
if(pThisUnit)
{
// Clears unit's army ID and erase from formation entries
pThisUnit->setArmyID(FFreeList::INVALID_INDEX);
m_FormationEntries[iI].SetUnitID(ARMY_NO_UNIT);
bWasOneOrMoreRemoved = true;
// Tell the associate operation that a unit was lost
CvAIOperation* pThisOperation = GET_PLAYER(GetOwner()).getAIOperation(m_iOperationID);
if(pThisOperation)
{
pThisOperation->UnitWasRemoved(GetID(), iI);
}
}
}
}
return bWasOneOrMoreRemoved;
}
/// Is this part of an operation that allows units to be poached by tactical AI?
bool CvArmyAI::CanTacticalAIInterruptUnit(int /* iUnitId */) const
{
// If the operation is still assembling, by all means interrupt it
if(m_eAIState == ARMYAISTATE_WAITING_FOR_UNITS_TO_REINFORCE ||
m_eAIState == ARMYAISTATE_WAITING_FOR_UNITS_TO_CATCH_UP)
{
return true;
}
if(m_eOwner >=0 && m_eOwner < MAX_PLAYERS)
{
CvAIOperation* op = GET_PLAYER(m_eOwner).getAIOperation(m_iOperationID);
if(op)
{
return op->CanTacticalAIInterruptOperation();
}
}
return false;
}
/// Retrieve units from the army - first call (ARMY_NO_UNIT if none found)
int CvArmyAI::GetFirstUnitID()
{
m_CurUnitIter = m_FormationEntries.begin();
if(m_CurUnitIter == m_FormationEntries.end())
{
return ARMY_NO_UNIT;
}
else
{
// First entry could not be filled yet
while(m_CurUnitIter != m_FormationEntries.end())
{
if(m_CurUnitIter->GetUnitID() != ARMY_NO_UNIT)
{
return m_CurUnitIter->GetUnitID();
}
++m_CurUnitIter;
}
return ARMY_NO_UNIT;
}
}
/// Retrieve units from the army - subsequent call (ARMY_NO_UNIT if none found)
int CvArmyAI::GetNextUnitID()
{
if(m_CurUnitIter != m_FormationEntries.end())
{
++m_CurUnitIter;
while(m_CurUnitIter != m_FormationEntries.end())
{
if(m_CurUnitIter->GetUnitID() != ARMY_NO_UNIT)
{
return m_CurUnitIter->GetUnitID();
}
++m_CurUnitIter;
}
return ARMY_NO_UNIT;
}
return ARMY_NO_UNIT;
}
/// Retrieve units from the army - first call (UnitHandle version)
UnitHandle CvArmyAI::GetFirstUnit()
{
UnitHandle pRtnValue;
int iUnitID = GetFirstUnitID();
if(iUnitID != ARMY_NO_UNIT)
{
pRtnValue = UnitHandle(GET_PLAYER(m_eOwner).getUnit(iUnitID));
FAssertMsg(pRtnValue, "Bogus unit in army - tell Ed");
}
return pRtnValue;
}
/// Retrieve units from the army - subsequent call (UnitHandle version)
UnitHandle CvArmyAI::GetNextUnit()
{
UnitHandle pRtnValue;
int iUnitID = GetNextUnitID();
if(iUnitID != ARMY_NO_UNIT)
{
pRtnValue = UnitHandle(GET_PLAYER(m_eOwner).getUnit(iUnitID));
FAssertMsg(pRtnValue, "Bogus unit in army - tell Ed");
}
return pRtnValue;
}
/// Find first unit who is sitting in this domain
UnitHandle CvArmyAI::GetFirstUnitInDomain(DomainTypes eDomain)
{
UnitHandle pUnit, pCurrentUnit;
pCurrentUnit = GetFirstUnit();
while(pCurrentUnit)
{
if(pCurrentUnit->plot()->isWater() && eDomain == DOMAIN_SEA || !pCurrentUnit->plot()->isWater() && eDomain == DOMAIN_LAND)
{
return pCurrentUnit;
}
pCurrentUnit = GetNextUnit();
}
return pUnit;
}
// PER TURN PROCESSING
/// Process another turn for the army
void CvArmyAI::DoTurn()
{
// do something with the army
DoDelayedDeath();
}
/// Kill off the army if waiting to die (returns true if army was killed)
bool CvArmyAI::DoDelayedDeath()
{
if(GetNumSlotsFilled() == 0 && m_eAIState != ARMYAISTATE_WAITING_FOR_UNITS_TO_REINFORCE)
{
Kill();
return true;
}
return false;
}
FDataStream& operator<<(FDataStream& saveTo, const CvArmyAI& readFrom)
{
readFrom.write(saveTo);
return saveTo;
}
FDataStream& operator>>(FDataStream& loadFrom, CvArmyAI& writeTo)
{
writeTo.read(loadFrom);
return loadFrom;
}
FDataStream& operator<<(FDataStream& saveTo, const CvArmyFormationSlot& readFrom)
{
saveTo << readFrom.m_iUnitID;
saveTo << readFrom.m_iEstimatedTurnAtCheckpoint;
saveTo << readFrom.m_bStartedOnOperation;
return saveTo;
}
FDataStream& operator>>(FDataStream& loadFrom, CvArmyFormationSlot& writeTo)
{
loadFrom >> writeTo.m_iUnitID;
loadFrom >> writeTo.m_iEstimatedTurnAtCheckpoint;
loadFrom >> writeTo.m_bStartedOnOperation;
return loadFrom;
}
| [
"thewizardofwas@gmail.com"
] | thewizardofwas@gmail.com |
0ba508cdcde0de23809c24cf732bd04e2d3864d2 | 342b769878fef1b452487c022b067a40aea1f9fa | /src/undistortImage.cpp | c83da4a15b0eb492cf6ca99efd29157d9fd03792 | [] | no_license | yupengfei8421/SLAM | 1b2551beb4e474d95bf7f644b74e2fd691f4326d | 2f39badc9c3db095d3be7d7ce9ea93b53563a67f | refs/heads/main | 2023-03-31T10:48:55.703211 | 2021-04-05T02:42:14 | 2021-04-05T02:42:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,854 | cpp | #include <opencv2/opencv.hpp>
#include <string>
using namespace std;
string image_file = "../cmake-build-debug/distorted.png"; // 请确保路径正确
int main(int argc, char **argv)
{
// 本程序实现去畸变部分的代码。尽管我们可以调用OpenCV的去畸变,但自己实现一遍有助于理解。
// 畸变参数
double k1 = -0.28340811, k2 = 0.07395907, p1 = 0.00019359, p2 = 1.76187114e-05;
// 内参
double fx = 458.654, fy = 457.296, cx = 367.215, cy = 248.375;
cv::Mat image = cv::imread(image_file, 0); // 图像是灰度图,CV_8UC1
int rows = image.rows, cols = image.cols;
cv::Mat image_undistort = cv::Mat(rows, cols, CV_8UC1); // 去畸变以后的图
// 计算去畸变后图像的内容
for (int v = 0; v < rows; v++) {
for (int u = 0; u < cols; u++) {
// 按照公式,计算点(u,v)对应到畸变图像中的坐标(u_distorted, v_distorted)
double x = (u - cx) / fx, y = (v - cy) / fy;
double r = sqrt(x * x + y * y);
double x_distorted = x * (1 + k1 * r * r + k2 * r * r * r * r) + 2 * p1 * x * y + p2 * (r * r + 2 * x * x);
double y_distorted = y * (1 + k1 * r * r + k2 * r * r * r * r) + p1 * (r * r + 2 * y * y) + 2 * p2 * x * y;
double u_distorted = fx * x_distorted + cx;
double v_distorted = fy * y_distorted + cy;
// 赋值 (最近邻插值)
if (u_distorted >= 0 && v_distorted >= 0 && u_distorted < cols && v_distorted < rows) {
image_undistort.at<uchar>(v, u) = image.at<uchar>((int) v_distorted, (int) u_distorted);
} else {
image_undistort.at<uchar>(v, u) = 0;
}
}
}
// 画图去畸变后图像
cv::imshow("distorted", image);
cv::imshow("undistorted", image_undistort);
cv::waitKey();
cv::imwrite("../cmake-build-debug/undistorted.png", image_undistort);
return 0;
}
| [
"120153710@qq.com"
] | 120153710@qq.com |
478c12b07cb9d6d4c37e5f804168e9f976eba9fc | 9856ad398afbe61f021f46fe1573819ce51fb9dc | /gov2.cc | a711a14884b5390c0432acc9e1146e5603c08bba | [
"MIT"
] | permissive | vteromero/integer-compression-benchmarks | 2c62e278e54fa16eea5d9510ba348253411dacd8 | 03b5a113993b78503ce065e413d9f6a9ce6501da | refs/heads/master | 2022-05-24T07:05:01.205250 | 2022-03-18T11:44:27 | 2022-03-18T11:44:27 | 220,762,839 | 5 | 0 | MIT | 2022-03-18T10:50:32 | 2019-11-10T08:36:40 | C++ | UTF-8 | C++ | false | false | 10,829 | cc | // Copyright (c) 2019 Vicente Romero Calero. All rights reserved.
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include "common.h"
#include "benchmark/include/benchmark/benchmark.h"
#include "SIMDCompressionAndIntersection/include/binarypacking.h"
#include "SIMDCompressionAndIntersection/include/fastpfor.h"
#include "SIMDCompressionAndIntersection/include/variablebyte.h"
#include "SIMDCompressionAndIntersection/include/varintgb.h"
#include "VTEnc/vtenc.h"
class Gov2SortedDataSet : public benchmark::Fixture {
private:
std::ifstream _inFile;
char _buffer[4096];
size_t _bufferCount;
size_t _bufferOffset;
public:
void SetUp(const ::benchmark::State& state) {}
void TearDown(const ::benchmark::State& state) {}
void openFile() {
const std::string fileName = GlobalState::dataDirectory + std::string("/gov2.sorted");
_inFile.open(fileName, std::ios::in | std::ios::binary);
if (_inFile.fail()) {
throw std::logic_error("Failed to open '" + fileName + "'");
}
_bufferCount = 0;
_bufferOffset = 0;
}
void closeFile() {
_inFile.close();
}
void refreshBuffer() {
// Here, it is assumed that the file has a size multiple of 4, so there is no
// left bytes to copy over when refreshing the buffer.
_inFile.read(_buffer, sizeof(_buffer));
if (_inFile.eof()) {
throw "End of file";
}
_bufferCount = _inFile.gcount();
_bufferOffset = 0;
}
uint32_t readNextUint32() {
if ((_bufferCount - _bufferOffset) < 4) {
refreshBuffer();
}
uint32_t value;
std::memcpy(&value, &(_buffer[_bufferOffset]), sizeof(value));
_bufferOffset += 4;
return value;
}
bool loadNextSet(std::vector<uint32_t>& data) {
data.clear();
try {
uint32_t len = readNextUint32();
for (size_t i = 0; i < len; ++i) {
data.push_back(readNextUint32());
}
} catch (...) {
return false;
}
return true;
}
};
static void benchmarkGov2SortedDataSet(
Gov2SortedDataSet* obj,
benchmark::State& state,
void (*func)(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats
))
{
CompressionStats stats(state);
std::vector<uint32_t> data;
for (auto _ : state) {
state.PauseTiming();
stats.Reset();
obj->openFile();
state.ResumeTiming();
while (1) {
state.PauseTiming();
if (!obj->loadNextSet(data)) break;
state.ResumeTiming();
func(data, state, stats);
}
state.PauseTiming();
obj->closeFile();
state.ResumeTiming();
}
stats.SetFinalStats();
}
static void encodeWithCopy(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
state.PauseTiming();
std::vector<uint32_t> copyTo(data.size());
state.ResumeTiming();
std::copy(data.begin(), data.end(), copyTo.begin());
state.PauseTiming();
stats.UpdateInputLengthInBytes(data.size() * sizeof(uint32_t));
stats.UpdateEncodedLengthInBytes(data.size() * sizeof(uint32_t));
state.ResumeTiming();
}
static void encodeWithVTEnc(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
state.PauseTiming();
std::vector<uint8_t> encoded(vtenc_max_encoded_size32(data.size()));
vtenc *handler = vtenc_create();
assert(handler != NULL);
vtenc_config(handler, VTENC_CONFIG_ALLOW_REPEATED_VALUES, 0);
vtenc_config(handler, VTENC_CONFIG_SKIP_FULL_SUBTREES, 1);
vtenc_config(handler, VTENC_CONFIG_MIN_CLUSTER_LENGTH, static_cast<size_t>(state.range(0)));
state.ResumeTiming();
vtenc_encode32(handler, data.data(), data.size(), encoded.data(), encoded.size());
state.PauseTiming();
stats.UpdateInputLengthInBytes(data.size() * sizeof(uint32_t));
stats.UpdateEncodedLengthInBytes(vtenc_encoded_size(handler));
vtenc_destroy(handler);
state.ResumeTiming();
}
static void decodeWithVTEnc(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
state.PauseTiming();
std::vector<uint8_t> encoded(vtenc_max_encoded_size32(data.size()));
vtenc *handler = vtenc_create();
assert(handler != NULL);
vtenc_config(handler, VTENC_CONFIG_ALLOW_REPEATED_VALUES, 0);
vtenc_config(handler, VTENC_CONFIG_SKIP_FULL_SUBTREES, 1);
vtenc_config(handler, VTENC_CONFIG_MIN_CLUSTER_LENGTH, static_cast<size_t>(state.range(0)));
vtenc_encode32(handler, data.data(), data.size(), encoded.data(), encoded.size());
size_t encodedLength = vtenc_encoded_size(handler);
std::vector<uint32_t> decoded(data.size());
state.ResumeTiming();
vtenc_decode32(handler, encoded.data(), encodedLength, decoded.data(), decoded.size());
state.PauseTiming();
if (data != decoded) {
throw std::logic_error("equality check failed");
}
stats.UpdateInputLengthInBytes(data.size() * sizeof(uint32_t));
stats.UpdateEncodedLengthInBytes(encodedLength);
vtenc_destroy(handler);
state.ResumeTiming();
}
static void encodeWithSIMDCompressionCodec(
SIMDCompressionLib::IntegerCODEC& codec,
size_t blockSize,
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
state.PauseTiming();
SIMDCompressionUtil comp(codec, blockSize, data);
state.ResumeTiming();
comp.Encode();
state.PauseTiming();
stats.UpdateInputLengthInBytes(comp.InputLength() * sizeof(uint32_t));
stats.UpdateEncodedLengthInBytes(comp.EncodedLength() * sizeof(uint32_t));
state.ResumeTiming();
}
static void decodeWithSIMDCompressionCodec(
SIMDCompressionLib::IntegerCODEC& codec,
size_t blockSize,
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
state.PauseTiming();
SIMDCompressionUtil comp(codec, blockSize, data);
comp.Encode();
state.ResumeTiming();
comp.Decode();
state.PauseTiming();
comp.EqualityCheck();
stats.UpdateInputLengthInBytes(comp.InputLength() * sizeof(uint32_t));
stats.UpdateEncodedLengthInBytes(comp.EncodedLength() * sizeof(uint32_t));
state.ResumeTiming();
}
static void encodeWithDeltaVariableByte(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
SIMDCompressionLib::VByte<true> codec;
encodeWithSIMDCompressionCodec(codec, 1, data, state, stats);
}
static void decodeWithDeltaVariableByte(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
SIMDCompressionLib::VByte<true> codec;
decodeWithSIMDCompressionCodec(codec, 1, data, state, stats);
}
static void encodeWithDeltaVarIntGB(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
SIMDCompressionLib::VarIntGB<true> codec;
encodeWithSIMDCompressionCodec(codec, 1, data, state, stats);
}
static void decodeWithDeltaVarIntGB(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
SIMDCompressionLib::VarIntGB<true> codec;
decodeWithSIMDCompressionCodec(codec, 1, data, state, stats);
}
static void encodeWithDeltaBinaryPacking(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
SIMDCompressionLib::BinaryPacking<SIMDCompressionLib::BasicBlockPacker> codec;
encodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats);
}
static void decodeWithDeltaBinaryPacking(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
SIMDCompressionLib::BinaryPacking<SIMDCompressionLib::BasicBlockPacker> codec;
decodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats);
}
static void encodeWithDeltaFastPFor128(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
SIMDCompressionLib::FastPFor<4, true> codec;
encodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats);
}
static void decodeWithDeltaFastPFor128(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
SIMDCompressionLib::FastPFor<4, true> codec;
encodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats);
}
static void encodeWithDeltaFastPFor256(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
SIMDCompressionLib::FastPFor<8, true> codec;
encodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats);
}
static void decodeWithDeltaFastPFor256(
std::vector<uint32_t>& data,
benchmark::State& state,
CompressionStats& stats)
{
SIMDCompressionLib::FastPFor<8, true> codec;
encodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats);
}
BENCHMARK_F(Gov2SortedDataSet, Copy)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, encodeWithCopy);
}
BENCHMARK_DEFINE_F(Gov2SortedDataSet, VTEncEncode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, encodeWithVTEnc);
}
BENCHMARK_REGISTER_F(Gov2SortedDataSet, VTEncEncode)
->RangeMultiplier(2)->Range(1, 1<<8);
BENCHMARK_DEFINE_F(Gov2SortedDataSet, VTEncDecode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, decodeWithVTEnc);
}
BENCHMARK_REGISTER_F(Gov2SortedDataSet, VTEncDecode)
->RangeMultiplier(2)->Range(1, 1<<8);
BENCHMARK_F(Gov2SortedDataSet, DeltaVariableByteEncode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, encodeWithDeltaVariableByte);
}
BENCHMARK_F(Gov2SortedDataSet, DeltaVariableByteDecode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, decodeWithDeltaVariableByte);
}
BENCHMARK_F(Gov2SortedDataSet, DeltaVarIntGBEncode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, encodeWithDeltaVarIntGB);
}
BENCHMARK_F(Gov2SortedDataSet, DeltaVarIntGBDecode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, decodeWithDeltaVarIntGB);
}
BENCHMARK_F(Gov2SortedDataSet, DeltaBinaryPackingEncode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, encodeWithDeltaBinaryPacking);
}
BENCHMARK_F(Gov2SortedDataSet, DeltaBinaryPackingDecode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, decodeWithDeltaBinaryPacking);
}
BENCHMARK_F(Gov2SortedDataSet, DeltaFastPFor128Encode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, encodeWithDeltaFastPFor128);
}
BENCHMARK_F(Gov2SortedDataSet, DeltaFastPFor128Decode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, decodeWithDeltaFastPFor128);
}
BENCHMARK_F(Gov2SortedDataSet, DeltaFastPFor256Encode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, encodeWithDeltaFastPFor256);
}
BENCHMARK_F(Gov2SortedDataSet, DeltaFastPFor256Decode)(benchmark::State& state) {
benchmarkGov2SortedDataSet(this, state, decodeWithDeltaFastPFor256);
}
| [
"vteromero@gmail.com"
] | vteromero@gmail.com |
090f2a7d24edaa30bfdae194162cba83ed387385 | cc99f8aac33b56f040a7be3dbc4c90812df1d40d | /Directx9sdk/Samples/C++/DirectPlay/Maze/MazeConsoleClient/Main.cpp | c9d5c7c72cbb92c3a8eb8eb34e14e4d63ffee934 | [] | no_license | Kiddinglife/t3d | a71231f298646fc57b145783f0935914ae29fdf1 | bec8ed964588611ebf4d11bb4518a7ab92958a38 | refs/heads/main | 2023-03-02T06:07:18.513787 | 2021-02-14T10:12:16 | 2021-02-14T10:12:16 | 338,776,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,942 | cpp | //----------------------------------------------------------------------------
// File: main.cpp
//
// Desc: This is a DirectPlay 8 client/server sample. The client comes in two flavors.
// A console based version, and a D3D client. The D3D client can optionally
// be run as screen saver by simply copying mazeclient.exe to your
// \winnt\system32\ and renaming it to mazeclient.scr. This will make
// it a screen saver that will be detected by the display control panel.
//
// Copyright (c) 1999-2001 Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#define D3D_OVERLOADS
#include <windows.h>
#include <D3DX8.h>
#include <dplay8.h>
#include "DXUtil.h"
#include "SyncObjects.h"
#include "IMazeGraphics.h"
#include "DummyConnector.h"
#include "MazeApp.h"
#include "MazeServer.h"
#include "ConsoleGraphics.h"
#include "MazeApp.h"
CMazeApp g_MazeApp;
CConsoleGraphics g_ConsoleGraphics;
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
int __cdecl main( int argc, TCHAR* argv[] )
{
// Verify Unicode compatibility.
#ifdef UNICODE
{
if( GetVersion() & 0x80000000 ) // High bit enabled for Win95/98/Me
{
MessageBox( NULL, TEXT("You're attemping to run a Unicode application")
TEXT(" in a Windows 9x/Me environment.")
TEXT("\nPlease recompile this application in ANSI mode.")
TEXT("\n\nThe program will now exit."),
TEXT("Compatibility Error"), MB_OK | MB_ICONERROR );
return 0;
}
}
#endif //UNICODE
if( FAILED( g_MazeApp.Create( &g_ConsoleGraphics ) ) )
return 0;
return g_MazeApp.Run( 0 );
}
| [
"jake.zhang.work@gmail.com"
] | jake.zhang.work@gmail.com |
bc620a075208aa4d771d47fd11ccb973ebe8118c | b503a9cb9537047c618660684433935ffec54e0e | /Codeforces/1040D.cpp | 6b24fc69acd48ab6a530b9228f49d57475351230 | [] | no_license | mayank98/OnlinePractice | 0aa4499b769ebe4e0cb83ad7c9b4742e097af592 | dd169e03e0abe5c2b8d415a54b570dc1d0689e77 | refs/heads/master | 2021-01-21T14:28:11.264413 | 2018-10-17T08:01:42 | 2018-10-17T08:01:42 | 95,284,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,083 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define MOD 1000000007
int main()
{
ios_base::sync_with_stdio(false); cout.tie(0); cin.tie(0);
// memset(dp,-1,sizeof(dp));
// cout << fixed << setprecision(16);
ll n,k;
cin >> n >> k;
ll l=1,r=n,mid;
string response;
default_random_engine generator;
while(true)
{
if(r-l+1==4*k)
{
uniform_int_distribution <ll> distribution(l,r);
ll num=distribution(generator);
cout << num << " " << num << flush;
cin >> response;
if(response=="Yes")
return 0;
}
mid=(l+r)/2;
cout << max((ll)1,l-k) << " " << min(mid+k,n) << flush;
cin >> response;
if(response=="Yes")
{
l=max((ll)1,l-k);
r=min(mid+k,n);
if(l==r)
return 0;
}
else if(response=="No")
{
l=max((ll)1,mid-k);
r=min(r+k,n);
}
else
return 0;
}
} | [
"mayankgupta18198@gmail.com"
] | mayankgupta18198@gmail.com |
2169f06ebd5435ba02aab661bc5de2998ed9f931 | 8de2b74ec67494a917e25f7fd93ce707b2cebca9 | /Library/include/Disposition.h | 61bd7e46d16ddc539802d38586ee083f4d7747cf | [
"BSD-2-Clause"
] | permissive | dwhobrey/MindCausalModellingLibrary | fffa5db6420bc66446f8989e172997f2f641bc32 | 797d716e785d2dcd5c373ab385c20d3a74bbfcb0 | refs/heads/master | 2021-01-10T12:25:04.194940 | 2020-02-10T07:01:03 | 2020-02-10T07:01:03 | 49,404,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,093 | h | #pragma once
namespace Plato {
class ClassTypeInfo;
class Identifier;
class Container;
class Path;
class Bundle;
/// <summary>
/// Base class for modelling dispositions.
/// </summary>
/// <remarks>
/// <para>
/// Dispositions (DIDs) are modelled as classes that take dynamic bundles of inputs and outputs.
/// DIDs can be born or die, and can be superposed in regions.
/// </para>
/// <para>
/// Dispositions (DIDs) are modelled as classes that take dynamic bundles of inputs and outputs.
/// DIDs can be born or die, and can be superposed in regions.
/// </para>
/// <para>
/// Permitted operations: AddBundle, AddConnection, AddConverter, AddAlias, AddLink, AddLocation.
/// But not: AddFlow, AddRegion.
/// </para>
/// <para>
/// The container holds Bundles for the categories of inputs and outputs.
/// </para>
/// </remarks>
class Disposition : public Container {
#pragma region // Class variables.
public:
/// <summary>
/// Class type information.
/// </summary>
static const ClassTypeInfo* TypeInfo;
/// <summary>
/// Gets the class type info for the dynamic class instance type.
/// </summary>
virtual const ClassTypeInfo* GetClassTypeInfo() const { return TypeInfo; }
/// <summary>
/// The kinds of properties this container can hold.
/// </summary>
static const ClassTypeInfo::HashSet* PropertyTypes;
#pragma endregion
public:
/// <summary>
/// Indicates if this DID is superimposed in the region.
/// </summary>
bool IsSuperposed;
/// <summary>
/// Tells model that output doesn't vary if input remains same.
/// </summary>
bool IsInputSafe;
#pragma region // Constructors.
public:
/// <summary>
/// Create a new disposition.
/// </summary>
/// <param name="creator">The element that created this element.</param>
/// <param name="parent">The hierarchical parent of this element.</param>
/// <param name="elementName">The name of the element.</param>
/// <param name="scope">The scope of the element.</param>
Disposition(Container* creator = NULL, Container* parent = NULL,
Identifier& elementName = Identifier::Generate("Disposition"),
PropertyScopesEnum scope = PropertyScopes::Public);
/// <summary>
/// Deallocate object.
/// </summary>
virtual ~Disposition();
#pragma endregion
public:
/// <summary>
/// Called by the simulator to update DIDs state.
/// Equivalent to one epoch in simulated time.
/// </summary>
virtual void Update();
private:
friend class InitializerCatalogue;
/// <summary>
/// The class initializer.
/// </summary>
static void Initializer();
/// <summary>
/// The class finalizer.
/// </summary>
static void Finalizer();
};
}
| [
"dwhobrey@outlook.com"
] | dwhobrey@outlook.com |
1ee7173fb1dbf0a0beb1f4c35cbd25a639c5bf73 | 258eabbb32dea482e339d9486f09ac87a950f2dd | /ROV2021/Motor.cpp | 82ad1cf106ad3a45d4c3b8a7de5e5708a28d1564 | [] | no_license | AndrewGrishchenko/MATE2021 | fc938c236bc6b6f3d91b29efc5d8f4d44cade95d | 444c697e720b0054fe500e7a98e11cd2a209e4bf | refs/heads/main | 2023-04-18T18:50:52.484336 | 2021-05-08T02:25:53 | 2021-05-08T02:25:53 | 310,301,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 191 | cpp | #include "Motor.h"
bool Motor::get_inverse()
{
return m_is_inverse;
}
void Motor::set_inverse(bool inverse)
{
m_is_inverse = inverse;
}
int8_t Motor::get_power()
{
return m_power;
}
| [
"andrew26080537@gmail.com"
] | andrew26080537@gmail.com |
26ac65ac6359f8ae81b7c0efa9625f955223c911 | dddbd2d53246c1fbe956598a40530f502d2663e8 | /src/engine/Mesh.hpp | 6528341d351ef455096c7447c9d5e9ca3f73779a | [
"Apache-2.0"
] | permissive | planteater8/shadowfox-engine | 0f89c83802d2c9d2224a7d02615794ecc21ab369 | dee6791038613ccebc7113bc9d2939159174df1f | refs/heads/master | 2021-01-21T01:05:39.050520 | 2013-02-06T22:51:51 | 2013-02-06T22:51:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,388 | hpp | /******************************************************************************
*
* ShadowFox Engine Source
* Copyright (C) 2012-2013 by ShadowFox Studios
* Created: 2012-07-19 by Taylor Snead
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
#pragma once
#include "stdafx.hpp"
// External
// Internal
#include "Material.hpp"
#include "Vertex.hpp"
#include "Component.hpp"
namespace sfs
{
/** @addtogroup Engine
* @{
*/
/** @addtogroup Rendering
* @{
*/
/** The Mesh class that holds a 3D mesh and possibly an animated skeleton.
* @remarks
* This class controls a Mesh as defined by the 3d importing library.
* It handles holding a list of vertices, bones, faces, etc. It also
* holds a list of animations and things involving that. Keep in mind
* that this class isn't used directly for MeshRendering for Entities.
* The MeshRenderer class is used for that, and MeshRenderer has functions
* to manage changing the model and animset of the Mesh, and for attaching
* children mesh to it (possible, not sure yet)
* @todo
* Be sure this works fully in conjuction with the importers Mesh classes.
* Have this display as-is (ONLY for debug purposes; Later, require an Entity with MeshRenderer and SceneNode)
*/
class Mesh : public Component
{
friend class Renderer;
public:
Mesh();
~Mesh();
virtual void Init();
virtual void Update();
virtual void OnDestroy();
void SetInput(string path);
void SetTexture(string name);
vector<Vertex> vertices;
vector<uint32_t> indices;
Material material;
protected:
string file = "";
uint32_t vertexBuffer = 0;
uint32_t indexBuffer = 0;
uint32_t matrixId = 0;
bool castShadows = true;
bool receiveShadows = true;
bool initialized = false;
private:
};
/// @}
/// @}
}
| [
"taylorsnead@gmail.com"
] | taylorsnead@gmail.com |
4f9a5bcd04735c024c6a0c531be9d953a66d4ee5 | 9239ce416eb9dd4eb0a80fa1e7edc9cd4dcc8821 | /Graphics/Group.cpp | edfff75a2cad075694510fcac782abe56afd183a | [] | no_license | GKaszewski/Brick-Engine | c7b49ee171d432dff28439dcc0d885af71763201 | 4055c71cd06e54877a3755d680bc13fc567cd26d | refs/heads/master | 2022-06-13T14:28:38.119529 | 2021-08-14T14:11:25 | 2021-08-14T14:11:25 | 228,939,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | cpp | #include "Group.hpp"
Group::Group() : m_drawables{} {
}
void Group::draw(sf::RenderTarget& target, sf::RenderStates states) const {
for (const auto& drawable : m_drawables) {
target.draw(drawable, states);
}
}
const sf::Drawable& Group::operator[](std::size_t index) {
return m_drawables[index];
}
std::size_t Group::push_back(const sf::Drawable& drawable) {
m_drawables.push_back(drawable);
return m_drawables.size() - 1;
}
const sf::Drawable& Group::pop_back() {
const auto& drawable = m_drawables.back();
m_drawables.pop_back();
return drawable;
}
| [
"gabrielkaszewski@gmail.com"
] | gabrielkaszewski@gmail.com |
d42057cec2a4ceaba79e03d4a74626bcee4145e8 | e1bcc690199ce42049923747b55cd6d3bc061dcc | /kernel/include/memory/heap.hpp | 5e833f65b510bb5f9c05342c750713246474ba9a | [] | no_license | jasoncouture/CustomOS | 7cb9dbd311b676c63fa4b4378042b918ee34a816 | 77edd7702453ceabeaf6165db80609a2f3fab057 | refs/heads/main | 2023-04-02T12:52:33.015130 | 2021-03-28T04:39:30 | 2021-03-28T04:39:30 | 343,938,650 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 887 | hpp | #pragma once
#include <stddef.h>
#include <stdint.h>
#include <memory/pageallocator.hpp>
#include <memory/paging/virtualaddressmanager.hpp>
enum HeapSegmentFlag
{
IsFree = 0,
Valid = 1
};
struct HeapSegment {
size_t Length;
HeapSegment* Next;
HeapSegment* Previous;
uint8_t Flags;
void CombineWithNext();
void CombineWithPrevious();
bool GetFlag(HeapSegmentFlag flag);
void SetFlag(HeapSegmentFlag flag);
void SetFlag(HeapSegmentFlag flag, bool value);
void ClearFlag(HeapSegmentFlag flag);
HeapSegment* Split(size_t size);
void* Address();
}__attribute__((packed));
void* kmalloc(size_t size);
void* calloc(size_t count, size_t size);
void* malloc(size_t size);
void* realloc(void* pointer, size_t size);
void free(void* address);
void InitializeHeap(VirtualAddressManager *virtualAddressManager, PageAllocator *pageAllocator); | [
"jasonc@alertr.info"
] | jasonc@alertr.info |
59630de2cdcae909379ce75c388b80fda055942d | 32a6ac6cbec63296ba68838ad4699b995810c6cd | /compiled/cpp_stl_11/ts_packet_header.h | ec29bd3a886a275b0b37bd07a5bfbd385079e461 | [
"MIT"
] | permissive | smarek/ci_targets | a33696ddaa97daa77c0aecbdfb20c67546c729bc | c5edee7b0901fd8e7f75f85245ea4209b38e0cb3 | refs/heads/master | 2022-12-01T22:54:38.478115 | 2020-08-10T13:36:36 | 2020-08-19T07:12:14 | 286,483,420 | 0 | 0 | MIT | 2020-08-10T13:30:22 | 2020-08-10T13:30:21 | null | UTF-8 | C++ | false | false | 2,171 | h | #pragma once
// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
#include "kaitai/kaitaistruct.h"
#include <stdint.h>
#include <memory>
#if KAITAI_STRUCT_VERSION < 9000L
#error "Incompatible Kaitai Struct C++/STL API: version 0.9 or later is required"
#endif
/**
* describes the first 4 header bytes of a TS Packet header
*/
class ts_packet_header_t : public kaitai::kstruct {
public:
enum adaptation_field_control_enum_t {
ADAPTATION_FIELD_CONTROL_ENUM_RESERVED = 0,
ADAPTATION_FIELD_CONTROL_ENUM_PAYLOAD_ONLY = 1,
ADAPTATION_FIELD_CONTROL_ENUM_ADAPTATION_FIELD_ONLY = 2,
ADAPTATION_FIELD_CONTROL_ENUM_ADAPTATION_FIELD_AND_PAYLOAD = 3
};
ts_packet_header_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = nullptr, ts_packet_header_t* p__root = nullptr);
private:
void _read();
public:
~ts_packet_header_t();
void _clean_up();
private:
uint8_t m_sync_byte;
bool m_transport_error_indicator;
bool m_payload_unit_start_indicator;
bool m_transport_priority;
uint64_t m_pid;
uint64_t m_transport_scrambling_control;
adaptation_field_control_enum_t m_adaptation_field_control;
uint64_t m_continuity_counter;
std::string m_ts_packet_remain;
ts_packet_header_t* m__root;
kaitai::kstruct* m__parent;
public:
uint8_t sync_byte() const { return m_sync_byte; }
bool transport_error_indicator() const { return m_transport_error_indicator; }
bool payload_unit_start_indicator() const { return m_payload_unit_start_indicator; }
bool transport_priority() const { return m_transport_priority; }
uint64_t pid() const { return m_pid; }
uint64_t transport_scrambling_control() const { return m_transport_scrambling_control; }
adaptation_field_control_enum_t adaptation_field_control() const { return m_adaptation_field_control; }
uint64_t continuity_counter() const { return m_continuity_counter; }
std::string ts_packet_remain() const { return m_ts_packet_remain; }
ts_packet_header_t* _root() const { return m__root; }
kaitai::kstruct* _parent() const { return m__parent; }
};
| [
"kaitai-bot@kaitai.io"
] | kaitai-bot@kaitai.io |
04fdc302fca4e95894f708f9a89c247af15a47d4 | d53f888b7720dc6fcb31016ba151931afb42a925 | /shilibaohu_1.0/ESP8266.h | c194dc04304d6e9ca8402f60b49f92e041796966 | [] | no_license | 000562/- | 9e019f2578cfd52c6aaabaeb7b92b7716b6365ac | d648a3a896b3e177eda3532574768e24b5e041d7 | refs/heads/master | 2020-04-12T15:48:26.993375 | 2018-12-20T15:37:55 | 2018-12-20T15:37:55 | 162,593,055 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,347 | h | /**
@author Wu Pengfei<pengfei.wu@itead.cc>
* @par Copyright:
* Copyright (c) 2015 ITEAD Intelligent Systems Co., Ltd. \n\n
* 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. \n\n
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __ESP8266_H__
#define __ESP8266_H__
#include "Arduino.h"
#define ESP8266_USE_SOFTWARE_SERIAL
#ifdef ESP8266_USE_SOFTWARE_SERIAL
#include "SoftwareSerial.h"
#endif
#define VERSION_18 0X18
#define VERSION_22 0X22
#define DEFAULT_PATTERN 3
/**
* You can modify the macro to choose a different version
*/
#define USER_SEL_VERSION VERSION_18
/**
* Provide an easy-to-use way to manipulate ESP8266.
*/
class ESP8266 {
public:
#ifdef ESP8266_USE_SOFTWARE_SERIAL
/*
* Constuctor.
*
* @param uart - an reference of SoftwareSerial object.
* @param baud - the buad rate to communicate with ESP8266(default:9600).
*
* @warning parameter baud depends on the AT firmware. 9600 is an common value.
*/
#if (USER_SEL_VERSION == VERSION_22)
ESP8266(SoftwareSerial &uart, uint32_t baud = 115200);
#elif (USER_SEL_VERSION == VERSION_18)
ESP8266(SoftwareSerial &uart, uint32_t baud = 9600);
#endif /* #if(USER_SEL_VERSION==VERSION_22) */
#else /* HardwareSerial */
/*
* Constuctor.
*
* @param uart - an reference of HardwareSerial object.
* @param baud - the buad rate to communicate with ESP8266(default:9600).
*
* @warning parameter baud depends on the AT firmware. 9600 is an common value.
*/
#if (USER_SEL_VERSION == VERSION_22)
ESP8266(HardwareSerial &uart, uint32_t baud = 115200);
#elif (USER_SEL_VERSION == VERSION_18)
ESP8266(HardwareSerial &uart, uint32_t baud = 9600);
#endif /* #if(USER_SEL_VERSION == VERSION_22) */
#endif /* #ifdef ESP8266_USE_SOFTWARE_SERIAL */
/**
* Verify ESP8266 whether live or not.
*
* Actually, this method will send command "AT" to ESP8266 and waiting for "OK".
*
* @retval true - alive.
* @retval false - dead.
*/
bool kick(void);
/**
* Restart ESP8266 by "AT+RST".
*
* This method will take 3 seconds or more.
*
* @retval true - success.
* @retval false - failure.
*/
bool restart(void);
/**
* Get the version of AT Command Set.
*
* @return the string of version.
*/
String getVersion(void);
/**
* Start function of deep sleep.
*
* @param time - the sleep time.
* @retval true - success.
* @retval false - failure.
* @note the feature requires hardware support.
*/
bool deepSleep(uint32_t time);
/**
* Switch the echo function.
*
* @param mode - 1 start echo -0 stop echo
* @retval true - success.
* @retval false - failure.
*
*/
bool setEcho(uint8_t mode);
/**
* Restore factory.
* @retval true - success.
* @retval false - failure.
* @note The operation can lead to restart the machine.
*/
bool restore(void);
/**
* Set up a serial port configuration.
*
* @param pattern -1 send "AT+UART=", -2 send "AT+UART_CUR=", -3 send "AT+UART_DEF=".
* @param baudrate - the uart baudrate.
* @retval true - success.
* @retval false - failure.
* @note Only allows baud rate design, for the other parameters:databits- 8,stopbits -1,parity -0,flow control -0 .
*/
bool setUart(uint32_t baudrate,uint8_t pattern);
/**
* Set operation mode to station.
*
* @param pattern1 -1, send "AT+CWMODE_DEF?",-2,send "AT+CWMODE_CUR?",-3,send "AT+CWMODE?".
* @param pattern2 -1, send "AT+CWMODE_DEF=",-2,send "AT+CWMODE_CUR=",-3,send "AT+CWMODE=".
* @retval true - success.
* @retval false - failure.
*
*/
bool setOprToStation(uint8_t pattern1=DEFAULT_PATTERN,uint8_t pattern2=DEFAULT_PATTERN);
/**
* Get the model values list.
*
* @return the list of model.
*/
String getWifiModeList(void);
/**
* Set operation mode to softap.
* @param pattern1 -1, send "AT+CWMODE_DEF?",-2,send "AT+CWMODE_CUR?",-3,send "AT+CWMODE?".
* @param pattern2 -1, send "AT+CWMODE_DEF=",-2,send "AT+CWMODE_CUR=",-3,send "AT+CWMODE=".
*
* @retval true - success.
* @retval false - failure.
*/
bool setOprToSoftAP(uint8_t pattern1=DEFAULT_PATTERN,uint8_t pattern2=DEFAULT_PATTERN);
/**
* Set operation mode to station + softap.
* @param pattern1 -1, send "AT+CWMODE_DEF?",-2,send "AT+CWMODE_CUR?",-3,send "AT+CWMODE?".
* @param pattern2 -1, send "AT+CWMODE_DEF=",-2,send "AT+CWMODE_CUR=",-3,send "AT+CWMODE=".
*
* @retval true - success.
* @retval false - failure.
*/
bool setOprToStationSoftAP(uint8_t pattern1=DEFAULT_PATTERN,uint8_t pattern2=DEFAULT_PATTERN);
/**
* Get the operation mode.
* @param pattern1 -1, send "AT+CWMODE_DEF?",-2,send "AT+CWMODE_CUR?",-3,send "AT+CWMODE?".
*
* @retval 0 - failure.
* @retval 1 - mode Station.
* @retval 2 - mode AP.
* @retval 3 - mode AP + station.
*/
uint8_t getOprMode(uint8_t pattern1=DEFAULT_PATTERN);
/**
* Search available AP list and return it.
*
* @return the list of available APs.
* @note This method will occupy a lot of memeory(hundreds of Bytes to a couple of KBytes).
* Do not call this method unless you must and ensure that your board has enough memery left.
*/
String getAPList(void);
/**
* Search and returns the current connect AP.
*
* @param pattern -1, send "AT+CWJAP_DEF?",-2,send "AT+CWJAP_CUR?",-3,send "AT+CWJAP?".
* @return the ssid of AP connected now.
*/
String getNowConecAp(uint8_t pattern=DEFAULT_PATTERN);
/**
* Join in AP.
*
* @param pattern -1 send "AT+CWJAP_DEF=" -2 send "AT+CWJAP_CUR=" -3 send "AT+CWJAP=".
* @param ssid - SSID of AP to join in.
* @param pwd - Password of AP to join in.
* @retval true - success.
* @retval false - failure.
* @note This method will take a couple of seconds.
*/
bool joinAP(String ssid, String pwd,uint8_t pattern=DEFAULT_PATTERN);
/**
* Leave AP joined before.
*
* @retval true - success.
* @retval false - failure.
*/
bool leaveAP(void);
/**
* Set SoftAP parameters.
*
* @param pattern -1 send "AT+CWSAP_DEF=" -2 send "AT+CWSAP_CUR=" -3 send "AT+CWSAP=".
* @param ssid - SSID of SoftAP.
* @param pwd - PASSWORD of SoftAP.
* @param chl - the channel (1 - 13, default: 7).
* @param ecn - the way of encrypstion (0 - OPEN, 1 - WEP,
* 2 - WPA_PSK, 3 - WPA2_PSK, 4 - WPA_WPA2_PSK, default: 4).
* @retval true - success.
* @retval false - failure.
* @note This method should not be called when station mode.
*/
bool setSoftAPParam(String ssid, String pwd, uint8_t chl = 7, uint8_t ecn = 4,uint8_t pattern=DEFAULT_PATTERN);
/**
* get SoftAP parameters.
*
* @param pattern -1 send "AT+CWSAP_DEF?" -2 send "AT+CWSAP_CUR?" -3 send "AT+CWSAP?".
* @note This method should not be called when station mode.
*/
String getSoftAPParam(uint8_t pattern=DEFAULT_PATTERN);
/**
* Get the IP list of devices connected to SoftAP.
*
* @return the list of IP.
* @note This method should not be called when station mode.
*/
String getJoinedDeviceIP(void);
/**
* Get the current state of DHCP.
*
* @param pattern -1 send "AT+CWDHCP_DEF?" -2 send "AT+CWDHCP_CUR?" -3 send "AT+CWDHCP?".
* @return the state of DHCP.
*
*/
String getDHCP(uint8_t pattern=DEFAULT_PATTERN);
/**
* Set the state of DHCP.
* @param pattern -1 send "AT+CWDHCP_DEF=" -2 send "AT+CWDHCP_CUR=" -3 send "AT+CWDHCP=".
* @param mode - set ap or set station or set ap + station.
* @param en - 0 disable DHCP - 1 enable DHCP.
* @retval true - success.
* @retval false - failure.
*/
bool setDHCP(uint8_t mode, uint8_t en, uint8_t pattern=DEFAULT_PATTERN);
/**
* make boot automatically connected.
* @param en -1 enable -0 disable.
* @retval true - success.
* @retval false - failure.
*/
bool setAutoConnect(uint8_t en);
/**
* Get the station's MAC address.
* @param pattern -1 send "AT+CIPSTAMAC_DEF?=" -2 send "AT+CIPSTAMAC_CUR?" -3 send "AT+CIPSTAMAC?".
* @return mac address.
* @note This method should not be called when ap mode.
*/
String getStationMac(uint8_t pattern=DEFAULT_PATTERN);
/**
* Set the station's MAC address.
* @param pattern -1 send "AT+CIPSTAMAC_DEF=" -2 send "AT+CIPSTAMAC_CUR=" -3 send "AT+CIPSTAMAC=".
* @param mac - the mac address of station.
* @retval true - success.
* @retval false - failure.
*/
bool setStationMac(String mac,uint8_t pattern=DEFAULT_PATTERN);
/**
* Get the station's IP.
* @param pattern -1 send "AT+CIPSTA_DEF?" -2 send "AT+CIPSTA_CUR?" -3 send "AT+CIPSTA?".
* @return the station's IP.
* @note This method should not be called when ap mode.
*/
String getStationIp(uint8_t pattern=DEFAULT_PATTERN);
/**
* Set the station's IP.
* @param pattern -1 send "AT+CIPSTA_DEF=" -2 send "AT+CIPSTA_CUR=" -3 send "AT+CIPSTA=".
* @param ip - the ip of station.
* @param gateway -the gateway of station.
* @param netmask -the netmask of station.
* @retval true - success.
* @retval false - failure.
* @note This method should not be called when ap mode.
*/
bool setStationIp(String ip,String gateway,String netmask,uint8_t pattern=DEFAULT_PATTERN);
/**
* Get the AP's IP.
* @param pattern -1 send "AT+CIPAP_DEF?" -2 send "AT+CIPAP_CUR?" -3 send "AT+CIPAP?".
* @return ap's ip.
* @note This method should not be called when station mode.
*
*/
String getAPIp(uint8_t pattern=DEFAULT_PATTERN);
/**
* Set the AP IP.
* @param pattern -1 send "AT+CIPAP_DEF=" -2 send "AT+CIPAP_CUR=" -3 send "AT+CIPAP=".
* @param ip - the ip of AP.
* @retval true - success.
* @retval false - failure.
* @note This method should not be called when station mode.
*/
bool setAPIp(String ip,uint8_t pattern=DEFAULT_PATTERN);
/**
* start smartconfig.
* @param type -1:ESP_TOUCH -2:AirKiss.
* @retval true - success.
* @retval false - failure.
*/
bool startSmartConfig(uint8_t type);
/**
* stop smartconfig.
*
* @retval true - success.
* @retval false - failure.
*/
bool stopSmartConfig(void);
/**
* Get the current status of connection(UDP and TCP).
*
* @return the status.
*/
String getIPStatus(void);
/**
* Get the IP address of ESP8266.
*
* @return the IP list.
*/
String getLocalIP(void);
/**
* Enable IP MUX(multiple connection mode).
*
* In multiple connection mode, a couple of TCP and UDP communication can be builded.
* They can be distinguished by the identifier of TCP or UDP named mux_id.
*
* @retval true - success.
* @retval false - failure.
*/
bool enableMUX(void);
/**
* Disable IP MUX(single connection mode).
*
* In single connection mode, only one TCP or UDP communication can be builded.
*
* @retval true - success.
* @retval false - failure.
*/
bool disableMUX(void);
/**
* Create TCP connection in single mode.
*
* @param addr - the IP or domain name of the target host.
* @param port - the port number of the target host.
* @retval true - success.
* @retval false - failure.
*/
bool createTCP(String addr, uint32_t port);
/**
* Release TCP connection in single mode.
*
* @retval true - success.
* @retval false - failure.
*/
bool releaseTCP(void);
/**
* Register UDP port number in single mode.
*
* @param addr - the IP or domain name of the target host.
* @param port - the port number of the target host.
* @retval true - success.
* @retval false - failure.
*/
bool registerUDP(String addr, uint32_t port);
/**
* Unregister UDP port number in single mode.
*
* @retval true - success.
* @retval false - failure.
*/
bool unregisterUDP(void);
/**
* Create TCP connection in multiple mode.
*
* @param mux_id - the identifier of this TCP(available value: 0 - 4).
* @param addr - the IP or domain name of the target host.
* @param port - the port number of the target host.
* @retval true - success.
* @retval false - failure.
*/
bool createTCP(uint8_t mux_id, String addr, uint32_t port);
/**
* Release TCP connection in multiple mode.
*
* @param mux_id - the identifier of this TCP(available value: 0 - 4).
* @retval true - success.
* @retval false - failure.
*/
bool releaseTCP(uint8_t mux_id);
/**
* Register UDP port number in multiple mode.
*
* @param mux_id - the identifier of this TCP(available value: 0 - 4).
* @param addr - the IP or domain name of the target host.
* @param port - the port number of the target host.
* @retval true - success.
* @retval false - failure.
*/
bool registerUDP(uint8_t mux_id, String addr, uint32_t port);
/**
* Unregister UDP port number in multiple mode.
*
* @param mux_id - the identifier of this TCP(available value: 0 - 4).
* @retval true - success.
* @retval false - failure.
*/
bool unregisterUDP(uint8_t mux_id);
/**
* Set the timeout of TCP Server.
*
* @param timeout - the duration for timeout by second(0 ~ 28800, default:180).
* @retval true - success.
* @retval false - failure.
*/
bool setTCPServerTimeout(uint32_t timeout = 180);
/**
* Start TCP Server(Only in multiple mode).
*
* After started, user should call method: getIPStatus to know the status of TCP connections.
* The methods of receiving data can be called for user's any purpose. After communication,
* release the TCP connection is needed by calling method: releaseTCP with mux_id.
*
* @param port - the port number to listen(default: 333).
* @retval true - success.
* @retval false - failure.
*
* @see String getIPStatus(void);
* @see uint32_t recv(uint8_t *coming_mux_id, uint8_t *buffer, uint32_t len, uint32_t timeout);
* @see bool releaseTCP(uint8_t mux_id);
*/
bool startTCPServer(uint32_t port = 333);
/**
* Stop TCP Server(Only in multiple mode).
*
* @retval true - success.
* @retval false - failure.
*/
bool stopTCPServer(void);
/**
*Set the module transfer mode
*
* @retval true - success.
* @retval false - failure.
*/
bool setCIPMODE(uint8_t mode);
/**
* Start Server(Only in multiple mode).
*
* @param port - the port number to listen(default: 333).
* @retval true - success.
* @retval false - failure.
*
* @see String getIPStatus(void);
* @see uint32_t recv(uint8_t *coming_mux_id, uint8_t *buffer, uint32_t len, uint32_t timeout);
*/
bool startServer(uint32_t port = 333);
/**
* Stop Server(Only in multiple mode).
*
* @retval true - success.
* @retval false - failure.
*/
bool stopServer(void);
/**
* Save the passthrough links
*
* @retval true - success.
* @retval false - failure.
*/
bool saveTransLink (uint8_t mode,String ip,uint32_t port);
/**
* PING COMMAND.
*
* @retval true - success.
* @retval false - failure.
*/
bool setPing(String ip);
/**
* Send data based on TCP or UDP builded already in single mode.
*
* @param buffer - the buffer of data to send.
* @param len - the length of data to send.
* @retval true - success.
* @retval false - failure.
*/
bool send(const uint8_t *buffer, uint32_t len);
/**
* Send data based on one of TCP or UDP builded already in multiple mode.
*
* @param mux_id - the identifier of this TCP(available value: 0 - 4).
* @param buffer - the buffer of data to send.
* @param len - the length of data to send.
* @retval true - success.
* @retval false - failure.
*/
bool send(uint8_t mux_id, const uint8_t *buffer, uint32_t len);
/**
* Send data based on TCP or UDP builded already in single mode.
*
* @param buffer - the buffer of data to send from flash memeory.
* @param len - the length of data to send.
* @retval true - success.
* @retval false - failure.
*/
bool sendFromFlash(const uint8_t *buffer, uint32_t len);
/**
* Send data based on one of TCP or UDP builded already in multiple mode.
*
* @param mux_id - the identifier of this TCP(available value: 0 - 4).
* @param buffer - the buffer of data to send from flash memeory.
* @param len - the length of data to send.
* @retval true - success.
* @retval false - failure.
*/
bool sendFromFlash(uint8_t mux_id, const uint8_t *buffer, uint32_t len);
/**
* Receive data from TCP or UDP builded already in single mode.
*
* @param buffer - the buffer for storing data.
* @param buffer_size - the length of the buffer.
* @param timeout - the time waiting data.
* @return the length of data received actually.
*/
uint32_t recv(uint8_t *buffer, uint32_t buffer_size, uint32_t timeout = 1000);
/**
* Receive data from one of TCP or UDP builded already in multiple mode.
*
* @param mux_id - the identifier of this TCP(available value: 0 - 4).
* @param buffer - the buffer for storing data.
* @param buffer_size - the length of the buffer.
* @param timeout - the time waiting data.
* @return the length of data received actually.
*/
uint32_t recv(uint8_t mux_id, uint8_t *buffer, uint32_t buffer_size, uint32_t timeout = 1000);
/**
* Receive data from all of TCP or UDP builded already in multiple mode.
*
* After return, coming_mux_id store the id of TCP or UDP from which data coming.
* User should read the value of coming_mux_id and decide what next to do.
*
* @param coming_mux_id - the identifier of TCP or UDP.
* @param buffer - the buffer for storing data.
* @param buffer_size - the length of the buffer.
* @param timeout - the time waiting data.
* @return the length of data received actually.
*/
uint32_t recv(uint8_t *coming_mux_id, uint8_t *buffer, uint32_t buffer_size, uint32_t timeout = 1000);
private:
/*
* Empty the buffer or UART RX.
*/
void rx_empty(void);
/*
* Recvive data from uart. Return all received data if target found or timeout.
*/
String recvString(String target, uint32_t timeout = 1000);
/*
* Recvive data from uart. Return all received data if one of target1 and target2 found or timeout.
*/
String recvString(String target1, String target2, uint32_t timeout = 1000);
/*
* Recvive data from uart. Return all received data if one of target1, target2 and target3 found or timeout.
*/
String recvString(String target1, String target2, String target3, uint32_t timeout = 1000);
/*
* Recvive data from uart and search first target. Return true if target found, false for timeout.
*/
bool recvFind(String target, uint32_t timeout = 1000);
/*
* Recvive data from uart and search first target and cut out the substring between begin and end(excluding begin and end self).
* Return true if target found, false for timeout.
*/
bool recvFindAndFilter(String target, String begin, String end, String &data, uint32_t timeout = 1000);
/*
* Receive a package from uart.
*
* @param buffer - the buffer storing data.
* @param buffer_size - guess what!
* @param data_len - the length of data actually received(maybe more than buffer_size, the remained data will be abandoned).
* @param timeout - the duration waitting data comming.
* @param coming_mux_id - in single connection mode, should be NULL and not NULL in multiple.
*/
uint32_t recvPkg(uint8_t *buffer, uint32_t buffer_size, uint32_t *data_len, uint32_t timeout, uint8_t *coming_mux_id);
bool eAT(void);
bool eATRST(void);
bool eATGMR(String &version);
bool eATGSLP(uint32_t time);
bool eATE(uint8_t mode);
bool eATRESTORE(void);
bool eATSETUART(uint32_t baudrate,uint8_t pattern);
bool qATCWMODE(uint8_t *mode,uint8_t pattern=3);
bool eATCWMODE(String &list) ;
bool sATCWMODE(uint8_t mode,uint8_t pattern=3);
bool qATCWJAP(String &ssid,uint8_t pattern=3) ;
bool sATCWJAP(String ssid, String pwd,uint8_t pattern=3);
bool eATCWLAP(String &list);
bool eATCWQAP(void);
bool qATCWSAP(String &List,uint8_t pattern=3);
bool sATCWSAP(String ssid, String pwd, uint8_t chl, uint8_t ecn,uint8_t pattern=3);
bool eATCWLIF(String &list);
bool qATCWDHCP(String &List,uint8_t pattern=3);
bool sATCWDHCP(uint8_t mode, uint8_t en, uint8_t pattern=3);
bool eATCWAUTOCONN(uint8_t en);
bool qATCIPSTAMAC(String &mac,uint8_t pattern=3);
bool eATCIPSTAMAC(String mac,uint8_t pattern=3);
bool qATCIPSTAIP(String &ip,uint8_t pattern=3);
bool eATCIPSTAIP(String ip,String gateway,String netmask,uint8_t pattern=3);
bool qATCIPAP(String &ip,uint8_t pattern=3);
bool eATCIPAP(String ip,uint8_t pattern=3);
bool eCWSTARTSMART(uint8_t type);
bool eCWSTOPSMART(void);
bool eATCIPSTATUS(String &list);
bool sATCIPSTARTSingle(String type, String addr, uint32_t port);
bool sATCIPSTARTMultiple(uint8_t mux_id, String type, String addr, uint32_t port);
bool sATCIPSENDSingle(const uint8_t *buffer, uint32_t len);
bool sATCIPSENDMultiple(uint8_t mux_id, const uint8_t *buffer, uint32_t len);
bool sATCIPSENDSingleFromFlash(const uint8_t *buffer, uint32_t len);
bool sATCIPSENDMultipleFromFlash(uint8_t mux_id, const uint8_t *buffer, uint32_t len);
bool sATCIPCLOSEMulitple(uint8_t mux_id);
bool eATCIPCLOSESingle(void);
bool eATCIFSR(String &list);
bool sATCIPMUX(uint8_t mode);
bool sATCIPSERVER(uint8_t mode, uint32_t port = 333);
bool sATCIPMODE(uint8_t mode);
bool eATSAVETRANSLINK(uint8_t mode,String ip,uint32_t port);
bool eATPING(String ip);
bool sATCIPSTO(uint32_t timeout);
/*
* +IPD,len:data
* +IPD,id,len:data
*/
#ifdef ESP8266_USE_SOFTWARE_SERIAL
SoftwareSerial *m_puart; /* The UART to communicate with ESP8266 */
#else
HardwareSerial *m_puart; /* The UART to communicate with ESP8266 */
#endif
};
#endif /* #ifndef __ESP8266_H__ */
| [
"970943222@qq.com"
] | 970943222@qq.com |
54683f1a8fe3559b9faeb3e34937ce9e89507163 | 7392076e8104a58ff40e14c2b301fbcb74da9bcb | /.svn/pristine/0c/0c10641f428f606ce4c687c6816a45f10df462c2.svn-base | 403b390c0dd6ee221a6b8c64ed3b369f4924259e | [] | no_license | mengxuxin/lotter | 58414d4707dcf517f479f26e5ed6a0c2b925e3e6 | 785102eb077ef398aea9edae2ab54856db49422d | refs/heads/master | 2021-01-20T14:34:53.105135 | 2017-02-22T04:13:22 | 2017-02-22T04:13:22 | 82,759,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,392 | #ifndef CLOADLOTTERYDATA_H
#define CLOADLOTTERYDATA_H
#include <QByteArray>
#include <QVector>
#include <QMutex>
#include <QImage>
/*!
人员信息类 主要是人名和照片
*/
struct SPeopleInfo
{
public:
QString m_strName; //人员名字
QByteArray m_pictureba; //人员照片二进制流
int m_lotteryGrade = -1; //几等奖 持久化考虑,存储中奖人员名单, 默认为-1 未中奖
QImage m_image;
};
/*!
奖池人员类:总共人员,待抽奖人员,已抽奖人员
已抽奖人员的持久化
对外接口:
获取待抽奖人员列表
*/
class CLotteryData
{
public:
static CLotteryData *instance();
static void releaseInstance();
void removeOnePeople(const SPeopleInfo &people);
/**
* @brief 加载人员信息
*/
void loadData();
/**
* @brief 获取待抽奖人员列表
* 返回之前做一次洗牌
* @return 待抽奖人员列表
*/
QVector<SPeopleInfo> &getWaitLotteryPeoples();
SPeopleInfo p;
private:
CLotteryData();
private:
static QMutex mutex;
static CLotteryData* s_Instance;
private:
QVector<SPeopleInfo> m_lotteryPeoples; //全部抽奖人员
QVector<SPeopleInfo> m_waitLotteryPeoples; //待抽奖人员
QVector<SPeopleInfo> m_lotteryedPeoples; //已中奖人员
};
#endif // CLOADLOTTERYDATA_H
| [
"mengxuxin@163.com"
] | mengxuxin@163.com | |
7e165a784e494154d2c77f6e0eee68b286d65045 | 4ab8222ddf686742de4ea5fc18a8ea0a37072661 | /Engine/Engine/Player.cpp | 9efb07c9dbdb127a2843a9a8280a716f00f29eb5 | [] | no_license | ParkSunW00/DroppingCat | e1be609fbe3df4cdb862efcbe6c4c7873ccf26bd | 6ad3a29de1288c4188fd38489d18011b4ba8392d | refs/heads/master | 2023-01-14T13:13:11.101546 | 2020-11-09T04:45:43 | 2020-11-09T04:45:43 | 288,142,691 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 710 | cpp | #include "stdafx.h"
#include "Player.h"
Player::Player() {
isClick = false;
playerAnimation = new Animation(2);
playerAnimation->AddFrame("Resource/cat1.png");
playerAnimation->AddFrame("Resource/cat2.png");
AddChild(playerAnimation);
rect = playerAnimation->getRect();
}
Player::~Player() {
}
void Player::Render() {
Object::Render();
playerAnimation->Render();
}
void Player::Update(float dTime) {
if (isClick) {
playerAnimation->Update(dTime);
if (playerAnimation->getIsFinalSrite()) {
isClick = false;
playerAnimation->setIsFinalSprite(false);
}
}
}
void Player::setIsClicked(bool isClicked) {
this->isClick = isClicked;
}
bool Player::getIsClicked() {
return isClick;
} | [
"jinwon11022@naver.com"
] | jinwon11022@naver.com |
1adb38ebf42597c19e081587a4cd2c5c4e00e207 | b7d8ed5e3c607d2530f6a7752d9c916587c0374a | /扎实基础训练/啤酒与饮料.cpp | 282f831b5da25cd98373ac31ecb9e3a1e417196b | [] | no_license | small-Qing/lanqiaobei | 8c38b16e861116ae05fcc20c4927d2c81908b0fd | 09e60eba65a95a8cce802074b3574c07e888c784 | refs/heads/master | 2020-04-27T23:55:18.690593 | 2019-03-10T08:39:07 | 2019-03-10T08:39:07 | 174,796,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | cpp | #include<bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
const double eps=3e-8;
const int mod=10;
const int maxn=2e5;
bool vis[11];
const double mon=82.3;
int main(){
for(int i=0;i<=35;i++){
double y=(mon-2.3*i)/1.9;
if(i>=y)continue;
if(fabs(y-(int)y)<eps)cout<<i<<endl;
}
return 0;
}
| [
"13055200916@163.com"
] | 13055200916@163.com |
1b8a248cb1679c0a0fd945016a1aa3f90b7e8233 | b0d4af85e212e852d8307ffde7dde41878d16d49 | /forloop.cpp | b5930c1e537071b159e6123c74e678bed2e532e9 | [] | no_license | Ankur-Kumar-Gupta/Programming_Practice | 0e608cbd006a579777981b9bd98731790fdf14bd | 9fe95bc4096fee4726d88a5c9e6a5afac4fc973b | refs/heads/main | 2023-02-01T07:42:44.805858 | 2020-12-20T20:51:44 | 2020-12-20T20:51:44 | 323,158,711 | 5 | 2 | null | 2020-12-20T20:51:46 | 2020-12-20T20:27:30 | C++ | UTF-8 | C++ | false | false | 224 | cpp | #include<iostream>
using namespace std;
int main()
{
int n,i;
cout<<"Enter the number till you want to print: ";
cin>>n;
for(i=0;i<=n;i++)
{
cout<<i<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | Ankur-Kumar-Gupta.noreply@github.com |
2ecb6e0b420a06fb6da555507e63907253744ed6 | 40e1027a911cfbdea24d933d90d7038d3242b8f7 | /CPP Projects/RAND.CPP | d8c9701720994d0f00bcb549a65b6cfdffd83c38 | [] | no_license | vinodkotiya/Basics-of-C-for-Beginners | 3f8154fa59f34e480480e9d4d0d391339ef41faa | d4be50ab9796c789e76bbffaa79475838b1316e0 | refs/heads/main | 2023-06-03T06:44:32.426242 | 2021-06-19T05:39:27 | 2021-06-19T05:39:27 | 378,332,591 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 263 | cpp | #include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<dos.h>
void main()
{
clrscr();
char s;
while(!kbhit()){s = 65+ random(8);
if(s == 'B') s = 'S';
else if(s == 'C') s= 'J';
else if(s == 'E') s ='K';
cout<<s; delay(500);}
getch();
} | [
"vinodkotiya@gmail.com"
] | vinodkotiya@gmail.com |
409082d4d51087b2c1dff1f9e63d99e0c95f8d08 | 204c3945a0a38786ea1717fd360bce63ff451b48 | /src/main.cpp | f1fb447f7ab9676bc097132a2f53792392c752cd | [] | no_license | valentinpi/named-chess | 4eb493c172952a29531fee22815e815b214790c3 | 45b545636797ee7075f04b2d9918380830df2eb4 | refs/heads/master | 2021-07-06T16:08:48.141963 | 2020-10-03T16:12:07 | 2020-10-03T16:12:07 | 189,845,405 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | cpp | #include "Game.hpp"
int main(int argc, char *argv[])
{
(void) argc;
(void) argv;
Game game(720, 720);
if (!game.is_initialized())
return EXIT_FAILURE;
game.run();
return EXIT_SUCCESS;
}
| [
"valentinpickel@gmx.de"
] | valentinpickel@gmx.de |
e83ed7323d709c1d2ab9c95e1eb10bb351f8c51d | 1f63dde39fcc5f8be29f2acb947c41f1b6f1683e | /Boss2D/addon/tensorflow-1.2.1_for_boss/tensorflow/compiler/xla/service/cpu/runtime_matmul.cc | 332f4216dc7b970cb985719ef82d5aa82bb86d3d | [
"Apache-2.0",
"MIT"
] | permissive | koobonil/Boss2D | 09ca948823e0df5a5a53b64a10033c4f3665483a | e5eb355b57228a701495f2660f137bd05628c202 | refs/heads/master | 2022-10-20T09:02:51.341143 | 2019-07-18T02:13:44 | 2019-07-18T02:13:44 | 105,999,368 | 7 | 2 | MIT | 2022-10-04T23:31:12 | 2017-10-06T11:57:07 | C++ | UTF-8 | C++ | false | false | 3,082 | cc | /* Copyright 2017 The TensorFlow Authors. 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 "tensorflow/compiler/xla/service/cpu/runtime_matmul.h"
#define EIGEN_USE_THREADS
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/compiler/xla/executable_run_options.h"
#include "tensorflow/core/platform/types.h"
using tensorflow::int32;
using tensorflow::int64;
namespace {
template <typename T>
void MatMul(const void* run_options_ptr, T* out, T* lhs, T* rhs, int64 m,
int64 n, int64 k, int32 transpose_lhs, int32 transpose_rhs) {
const xla::ExecutableRunOptions* run_options =
static_cast<const xla::ExecutableRunOptions*>(run_options_ptr);
int64 lhs_rows = m;
int64 lhs_cols = k;
if (transpose_lhs) {
std::swap(lhs_rows, lhs_cols);
}
int64 rhs_rows = k;
int64 rhs_cols = n;
if (transpose_rhs) {
std::swap(rhs_rows, rhs_cols);
}
const Eigen::TensorMap<Eigen::Tensor<const T, 2>, Eigen::Aligned> A(
lhs, lhs_rows, lhs_cols);
const Eigen::TensorMap<Eigen::Tensor<const T, 2>, Eigen::Aligned> B(
rhs, rhs_rows, rhs_cols);
Eigen::TensorMap<Eigen::Tensor<T, 2>, Eigen::Aligned> C(out, m, n);
typedef typename Eigen::Tensor<T, 2>::DimensionPair DimPair;
int lhs_contract_dim = transpose_lhs ? 0 : 1;
int rhs_contract_dim = transpose_rhs ? 1 : 0;
const Eigen::array<DimPair, 1> dims({
DimPair(lhs_contract_dim, rhs_contract_dim) });
// Matrix multiply is a special case of the "contract" operation where
// the contraction is performed along dimension 1 of the lhs and dimension
// 0 of the rhs.
C.device(*run_options->intra_op_thread_pool()) = A.contract(B, dims);
}
} // namespace
void __xla_cpu_runtime_EigenMatMulF32(const void* run_options_ptr, float* out,
float* lhs, float* rhs, int64 m, int64 n,
int64 k, int32 transpose_lhs,
int32 transpose_rhs) {
MatMul<float>(run_options_ptr, out, lhs, rhs, m, n, k, transpose_lhs,
transpose_rhs);
}
void __xla_cpu_runtime_EigenMatMulF64(const void* run_options_ptr, double* out,
double* lhs, double* rhs, int64 m,
int64 n, int64 k, int32 transpose_lhs,
int32 transpose_rhs) {
MatMul<double>(run_options_ptr, out, lhs, rhs, m, n, k, transpose_lhs,
transpose_rhs);
}
| [
"slacealic@gmail.com"
] | slacealic@gmail.com |
87096f38a6f60b27370e8e18dcef55c0a922d79e | 435b7d2980bbc80718e562ec78d835975dd21b20 | /include/viewpoint_interface/layouts/twinned_pip.hpp | b696913b2282413beb744ac2e82f697b003c4328 | [] | no_license | Lualmoba/camera_viewpoint_interface | e35163c44811d975623896539b32502f5d7b762d | e165270c40f52695dd3704218272a0c44b92f3d7 | refs/heads/main | 2023-07-04T21:04:16.932301 | 2021-08-19T19:33:19 | 2021-08-19T19:33:19 | 318,031,392 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,650 | hpp | #ifndef __LAYOUT_TWINNED_PIP_HPP__
#define __LAYOUT_TWINNED_PIP_HPP__
#include "viewpoint_interface/layout.hpp"
namespace viewpoint_interface
{
struct TwinnedPipParams
{
uint start_primary_display = 0;
uint start_pip_display = 1;
uint max_num_displays = 2;
int pip_window_dims[2] = { 400, 225 };
int pip_aspect_ratio[2] = { 16, 9 };
};
class TwinnedPipLayout final : public Layout
{
public:
TwinnedPipLayout(DisplayManager &displays, TwinnedPipParams params=TwinnedPipParams()) :
Layout(LayoutType::TWINNED_PIP, displays), parameters_(params), keep_aspect_ratio_(true),
pip_enabled_(true)
{
setNumDisplaysForRole(1, LayoutDisplayRole::Primary);
setNumDisplaysForRole(1, LayoutDisplayRole::Secondary);
addDisplayByIxAndRole(parameters_.start_primary_display, LayoutDisplayRole::Primary);
addDisplayByIxAndRole(parameters_.start_pip_display, LayoutDisplayRole::Secondary);
}
virtual void displayLayoutParams() override
{
drawDisplaysList(parameters_.max_num_displays);
drawDraggableRing();
ImGui::Separator();
ImGui::Text("Picture-in-Picture Settings:\n");
uint max_size(600);
int start_pip_dims[2] = { parameters_.pip_window_dims[0], parameters_.pip_window_dims[1] };
bool pip_dims_changed(ImGui::DragInt2("Dimensions", parameters_.pip_window_dims, 1.0f, 100, max_size));
bool ar_changed(ImGui::Checkbox("Keep Aspect Ratio", &keep_aspect_ratio_));
if (keep_aspect_ratio_) {
ImGui::Text("Aspect Ratio");
ImGui::SameLine();
ar_changed = ImGui::InputInt2("##PiP AR", parameters_.pip_aspect_ratio) || ar_changed;
if (pip_dims_changed || ar_changed) {
float aspect_ratio = (float)parameters_.pip_aspect_ratio[0] / parameters_.pip_aspect_ratio[1];
// Clamp both axes to max_size
int max_width(max_size), max_height(max_size);
if (aspect_ratio > 1.0) {
// Width is largest
max_height = max_size * (1.0 / aspect_ratio);
}
else {
// Height is largest or same
max_width = max_size * aspect_ratio;
}
if (parameters_.pip_window_dims[0] > max_width ||
parameters_.pip_window_dims[1] > max_height) {
parameters_.pip_window_dims[0] = max_width;
parameters_.pip_window_dims[1] = max_height;
}
else {
if (parameters_.pip_window_dims[1]-start_pip_dims[1] != 0) {
// Height changed
parameters_.pip_window_dims[0] = parameters_.pip_window_dims[1] * aspect_ratio;
}
else {
// Width changed
aspect_ratio = 1.0 / aspect_ratio;
parameters_.pip_window_dims[1] = parameters_.pip_window_dims[0] * aspect_ratio;
}
}
}
}
}
virtual void draw() override
{
addLayoutComponent(LayoutComponent::Type::Primary);
if (pip_enabled_) {
addLayoutComponent(LayoutComponent::Type::Pic_In_Pic, LayoutComponent::Spacing::Floating,
LayoutComponent::ComponentPositioning_Top_Right, (float)(parameters_.pip_window_dims[0]),
(float)(parameters_.pip_window_dims[1]));
}
drawLayoutComponents();
std::map<std::string, bool> states;
states["Robot"] = !clutching_;
states["Suction"] = grabbing_;
displayStateValues(states);
}
virtual void handleKeyInput(int key, int action, int mods) override
{
// TODO: Add function to swap active primary with active secondary
if (action == GLFW_PRESS) {
switch (key) {
case GLFW_KEY_P:
{
pip_enabled_ = !pip_enabled_;
} break;
case GLFW_KEY_RIGHT:
{
toNextDisplay(LayoutDisplayRole::Primary);
toNextDisplay(LayoutDisplayRole::Secondary);
} break;
case GLFW_KEY_LEFT:
{
toPrevDisplay(LayoutDisplayRole::Primary);
toPrevDisplay(LayoutDisplayRole::Secondary);
} break;
case GLFW_KEY_UP:
{
toPrevDisplay(LayoutDisplayRole::Secondary);
toPrevDisplay(LayoutDisplayRole::Primary);
} break;
case GLFW_KEY_DOWN:
{
toNextDisplay(LayoutDisplayRole::Secondary);
toNextDisplay(LayoutDisplayRole::Primary);
} break;
default:
{
} break;
}
}
}
virtual void handleStringInput(std::string input) override
{
LayoutCommand command(translateStringInputToCommand(input));
switch(command)
{
case LayoutCommand::TOGGLE:
{
toNextDisplay(LayoutDisplayRole::Primary);
toNextDisplay(LayoutDisplayRole::Secondary);
} break;
default:
{} break;
}
}
private:
TwinnedPipParams parameters_;
bool keep_aspect_ratio_, pip_enabled_;
};
} // viewpoint_interface
#endif //__LAYOUT_TWINNED_PIP_HPP__ | [
"lamolina@wisc.edu"
] | lamolina@wisc.edu |
12140f64c2e06e61f74e2216a41a59a796466660 | 1bbb19e305a39a046c50e046dbb574f6b321b8dd | /altimetro/altimetro.ino | 9c7cc19378d590ebbbeb1ee66b49ac0a1a579e49 | [] | no_license | car13romani/arduino | 22b36ab9be7eb8a854488727396e2b2d137dae14 | 96924dc511d0a5867b87fbdab51318a06127606f | refs/heads/master | 2019-07-11T19:22:37.895698 | 2017-11-16T17:26:01 | 2017-11-16T17:26:01 | 110,992,920 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,324 | ino | #include <LiquidCrystal.h> //Biblioteca do LCD
#include <BME280.h> // Biblioteca do Sensor
#include <Wire.h> // Biblioteca I2C
#define SERIAL_BAUD 115200
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
BME280 bme;
void printBME280Data(Stream * client);
void printBME280CalculatedData(Stream* client);
void setup(){
lcd.begin(16, 2); //Inicia o LCD com dimensões 16x2(Colunas x Linhas)
lcd.setCursor(0, 0); //Posiciona o cursor na primeira coluna(0) e na primeira linha(0) do LCD
lcd.print("Inicializando!"); //Escreve no LCD "Olá Garagista!"
while(!bme.begin()){
lcd.setCursor(0, 0); //Posiciona o cursor na primeira coluna(0) e na primeira linha(0) do LCD
lcd.print("ERRO NO SENSOR!"); //Escreve no LCD "Olá Garagista!"
}
//lcd.setCursor(0, 1); //Posiciona o cursor na primeira coluna(0) e na segunda linha(1) do LCD
//lcd.print("LabdeGaragem"); //Escreve no LCD "LabdeGaragem"
}
void loop()
{
for(int i = 0; i<2; i++){
lcd.setCursor(0, i); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD
lcd.print(" ");
}
float temp(NAN), hum(NAN), pres(NAN);
uint8_t pressureUnit(3); // unit: B000 = Pa, B001 = hPa, B010 = Hg, B011 = atm, B100 = bar, B101 = torr, B110 = N/m^2, B111 = psi
bme.ReadData(pres, temp, hum, true, pressureUnit); // Parameters: (float& pressure, float& temp, float& humidity, bool celsius = false, uint8_t pressureUnit = 0x0)
float altitude = bme.CalculateAltitude(true); //True = Sistema Metrico
lcd.setCursor(0, 0); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD
lcd.print("Temp: ");
lcd.setCursor(6, 0); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD
lcd.print(temp);
lcd.setCursor(15, 0); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD
lcd.print("C");
lcd.setCursor(0, 1); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD
lcd.print("Alti: ");
lcd.setCursor(6, 1); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD
lcd.print(altitude);
lcd.setCursor(15, 1); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD
lcd.print("m");
delay(1000);
}
| [
"car13romani@gmail.com"
] | car13romani@gmail.com |
ed66f6e732c6046f0f5936255e53bb0ab483ec85 | 5ec06dab1409d790496ce082dacb321392b32fe9 | /clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties.h | 9d4d24bdaf5e2767a4af8ecf4ae12af946ba2599 | [
"Apache-2.0",
"MIT"
] | permissive | shinesolutions/swagger-aem-osgi | e9d2385f44bee70e5bbdc0d577e99a9f2525266f | c2f6e076971d2592c1cbd3f70695c679e807396b | refs/heads/master | 2022-10-29T13:07:40.422092 | 2021-04-09T07:46:03 | 2021-04-09T07:46:03 | 190,217,155 | 3 | 3 | Apache-2.0 | 2022-10-05T03:26:20 | 2019-06-04T14:23:28 | null | UTF-8 | C++ | false | false | 1,713 | h | /**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: opensource@shinesolutions.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/*
* OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties.h
*
*
*/
#ifndef OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties_H
#define OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties_H
#include <QJsonObject>
#include "OAIConfigNodePropertyArray.h"
#include "OAIObject.h"
namespace OpenAPI {
class OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties: public OAIObject {
public:
OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties();
OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties(QString json);
~OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties() override;
void init();
QString asJson () const override;
QJsonObject asJsonObject() const override;
void fromJsonObject(QJsonObject json) override;
void fromJson(QString jsonString) override;
OAIConfigNodePropertyArray getHcTags() const;
void setHcTags(const OAIConfigNodePropertyArray &hc_tags);
virtual bool isSet() const override;
private:
OAIConfigNodePropertyArray hc_tags;
bool m_hc_tags_isSet;
};
}
#endif // OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties_H
| [
"cliffano@gmail.com"
] | cliffano@gmail.com |
23ee143f84075bd59f1b8710f36e6386b8f2c351 | 2569f88217c7087ac4266ed57bb4c85bfb20816f | /Codes/Object Oriented/Public-Protected-Private/Private_Sinifi.h | a7aa0baea16be024b604be2764673d7e88fbfebe | [] | no_license | mertsigirci11/Cpp-Calismalari | c493f7f2b4324883a1db820b7d62df5e7f10a34f | 4ba5fe68c24336225d1e050a4f4cc237e635d4ed | refs/heads/main | 2023-04-09T20:14:17.314644 | 2021-04-19T13:41:52 | 2021-04-19T13:41:52 | 343,431,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 192 | h | #pragma once
#include <iostream>
using namespace std;
class Private_Sinifi
{
private:
string mesaj_private;
void setMesaj_Private(string mesaj);
string getMesaj_Private();
};
| [
"noreply@github.com"
] | mertsigirci11.noreply@github.com |
262087a1e275b84be37f34f36905a138c2bf1500 | cff6f556d9da38e465d65145eb3f4a08115ad4bf | /main.cpp | 9ae13d8d9ab52faae9adbf96204bb4910baa1bd0 | [
"MIT"
] | permissive | bibi-the-brave/QONTAINER | 3888d1882fa6d981207939645db0d860f6ebe7c3 | 81ca5920febcff88ac1dffd75b82c89bf0e56842 | refs/heads/master | 2020-05-22T20:08:10.852813 | 2019-07-25T16:13:53 | 2019-07-25T16:13:53 | 186,504,647 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | cpp | /*
* Andrea Favero
* 1125545
* andrea.favero.8@studenti.unipd.it
*/
#include <QApplication>
#include <QIcon>
#include <QStyle>
#include <QDesktopWidget>
#include <memory>
#include "finestraprincipale.h"
#include "contenitore.h"
#include "persona.h"
#include "allenamento.h"
#include "deepptr.h"
int main(int argc, char *argv[])
{
Contenitore<std::shared_ptr<Persona>> cp;
Contenitore<DeepPtr<Allenamento>> ca;
QApplication a(argc, argv);
a.setWindowIcon(QIcon(":/immagini/logo.svg"));
FinestraPrincipale p(ca,cp);
p.show();
return a.exec();
}
| [
"andrea.favero96@gmail.com"
] | andrea.favero96@gmail.com |
191657239974ecb19d11e21ccec214f536404e33 | c53d20695965a467a68fd8c9383ef5e1d36659a1 | /base/message_pump_uv.h | 572c8cd3e667880e8636c81e4db67beb44ae8431 | [
"BSD-3-Clause"
] | permissive | abhijeetk/chromium.src | ce9313444e905875ebfa045bb5777700157914a6 | 99faa1383d1fb0d745678484fd512b5d406da191 | refs/heads/nw12 | 2021-09-30T21:57:06.633271 | 2016-03-15T15:01:49 | 2016-03-15T15:02:04 | 48,524,771 | 1 | 1 | null | 2015-12-24T04:29:46 | 2015-12-24T04:29:46 | null | UTF-8 | C++ | false | false | 1,163 | h | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_MESSAGE_PUMP_UV_H_
#define BASE_MESSAGE_PUMP_UV_H_
#pragma once
#include "base/message_loop/message_pump.h"
#include "base/time/time.h"
#include "base/base_export.h"
#include <vector>
//#include "third_party/node/deps/uv/include/uv.h"
typedef struct uv_async_s uv_async_t;
namespace base {
class BASE_EXPORT MessagePumpUV : public MessagePump {
public:
MessagePumpUV();
// MessagePump methods:
void Run(Delegate* delegate) override;
void Quit() override;
void ScheduleWork() override;
void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
private:
~MessagePumpUV() override;
// This flag is set to false when Run should return.
bool keep_running_;
// Nested loop level.
int nesting_level_;
// Handle to wake up loop.
std::vector<uv_async_t*> wakeup_events_;
uv_async_t* wakeup_event_;
TimeTicks delayed_work_time_;
DISALLOW_COPY_AND_ASSIGN(MessagePumpUV);
};
} // namespace base
#endif // BASE_MESSAGE_PUMP_UV_H_
| [
"wenrui@gmail.com"
] | wenrui@gmail.com |
99fe7313624ab0d404df9bce78f8e0be211b03ad | 7146e34d91b9df8dce7ece9c06d9622c8ad95d02 | /question_112 Path Sum.cc | 77af5596b854179a2ac801197b96f2eeb3990f57 | [] | no_license | snakeDling/LeetCode | 5dcc45b26a6532e83f98a8c900018c128feab7a1 | ecfdfe45e6987930d65150c6c7a4b1d1bf898f71 | refs/heads/master | 2021-01-15T16:29:13.372453 | 2018-06-19T07:16:00 | 2018-06-19T07:16:00 | 10,665,814 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 765 | cc | /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL)
return false;
if(root->left == NULL && root->right == NULL)
return sum - root->val == 0;
if(root->left != NULL)
if(hasPathSum(root->left, sum - root->val))
return true;
if(root->right != NULL)
return hasPathSum(root->right, sum - root->val);
else
return false;
}
}; | [
"228156980@qq.com"
] | 228156980@qq.com |
70821965864aed27b356328c67710d8dc9f23a96 | 27ea8c9a3f62e4a9daeb4b68fe911a991a0a3de0 | /espnow-slave-conf-espresso-lite1/espnow-slave-conf-espresso-lite1/espnow-slave-conf-espresso-lite1.ino | 7da7248014cb41ce89007b6b7e72d0f1ac6ba471 | [
"MIT"
] | permissive | cmmakerclub/esp-now-config-manager | 184d906f13aeae0ac3a315e45d52346fbe0dcae5 | fe2f21ab471119051c0261eb18d64a29b6a77df0 | refs/heads/master | 2021-08-31T23:44:01.954007 | 2017-12-23T15:05:23 | 2017-12-23T15:05:23 | 106,809,170 | 1 | 3 | null | 2017-10-19T07:02:58 | 2017-10-13T10:09:21 | Arduino | UTF-8 | C++ | false | false | 4,645 | ino | #define CMMC_USE_ALIAS
#include <Arduino.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <CMMC_Utils.h>
#include <CMMC_SimplePair.h>
#include <CMMC_Config_Manager.h>
#include <CMMC_ESPNow.h>
#include <CMMC_BootMode.h>
#include <CMMC_LED.h>
#include <CMMC_TimeOut.h>
#include <DHT.h>
#include "FS.h"
#include "data_type.h"
extern "C" {
#include <espnow.h>
#include <user_interface.h>
}
#define LED_PIN 5
#define DHTPIN 12
#define DEFAULT_DEEP_SLEEP_S 60
uint8_t selective_button_pin = 2;
uint32_t wait_button_pin_ms = 1;
uint8_t master_mac[6];
uint8_t self_mac[6];
int dhtType = 22;
int mode;
CMMC_SimplePair simplePair;
CMMC_Config_Manager configManager;
CMMC_ESPNow espNow;
CMMC_LED led(LED_PIN, LOW);
DHT *dht;
bool sp_flag_done = false;
void evt_callback(u8 status, u8* sa, const u8* data) {
if (status == 0) {
char buf[13];
Serial.printf("[CSP_EVENT_SUCCESS] STATUS: %d\r\n", status);
Serial.printf("WITH KEY: ");
CMMC::dump(data, 16);
Serial.printf("WITH MAC: ");
CMMC::dump(sa, 6);
CMMC::macByteToString(data, buf);
CMMC::printMacAddress((uint8_t*)buf);
configManager.add_field("mac", buf);
configManager.commit();
Serial.println("DONE...");
sp_flag_done = true;
}
else {
Serial.printf("[CSP_EVENT_ERROR] %d: %s\r\n", status, (const char*)data);
}
}
void load_config() {
configManager.load_config([](JsonObject * root) {
Serial.println("[user] json loaded..");
if (root->containsKey("mac")) {
String macStr = String((*root)["mac"].as<const char*>());
Serial.printf("Loaded mac %s\r\n", macStr.c_str());
CMMC::convertMacStringToUint8(macStr.c_str(), master_mac);
CMMC::printMacAddress(master_mac);
Serial.println();
}
});
}
void init_espnow() {
uint8_t* slave_addr = CMMC::getESPNowSlaveMacAddress();
memcpy(self_mac, slave_addr, 6);
espNow.init(NOW_MODE_SLAVE);
espNow.on_message_sent([](uint8_t *macaddr, u8 status) {
led.toggle();
Serial.println(millis());
Serial.printf("sent status %lu\r\n", status);
});
espNow.on_message_recv([](uint8_t * macaddr, uint8_t * data, uint8_t len) {
led.toggle();
Serial.printf("GOT sleepTime = %lu\r\n", data[0]);
if (data[0] == 0) data[0] = 30;
goSleep(data[0]);
});
}
void init_simple_pair() {
simplePair.begin(SLAVE_MODE, evt_callback);
simplePair.start();
CMMC_TimeOut ct;
ct.timeout_ms(3000);
while (1) {
if (ct.is_timeout()) {
if (sp_flag_done && digitalRead(selective_button_pin) == LOW) {
ct.yield();
Serial.println("YIELDING...");
}
else {
Serial.println("timeout");
ESP.reset();
}
}
led.toggle();
delay(50L + (250 * sp_flag_done));
}
}
void setup()
{
Serial.begin(57600);
led.init();
configManager.init("/config98.json");
selective_button_pin = 2;
wait_button_pin_ms = 1;
dhtType = 11;
dht = new DHT(DHTPIN, dhtType);
dht->begin();
CMMC_BootMode bootMode(&mode, selective_button_pin);
bootMode.init();
bootMode.check([](int mode) {
if (mode == BootMode::MODE_CONFIG) {
init_simple_pair();
}
else if (mode == BootMode::MODE_RUN) {
load_config();
init_espnow();
}
else {
// unhandled
}
}, wait_button_pin_ms);
}
CMMC_SENSOR_T packet;
void read_sensor() {
packet.battery = analogRead(A0);
memcpy(packet.to, master_mac, 6);
memcpy(packet.from, self_mac, 6);
//CMMC::printMacAddress(packet.from);
//CMMC::printMacAddress(packet.to);
packet.sum = CMMC::checksum((uint8_t*) &packet,
sizeof(packet) - sizeof(packet.sum));
float h = dht->readHumidity();
float t = dht->readTemperature();
if (isnan(h) || isnan(t)) {
h = 0.0;
t = 0.0;
} else {
packet.temperature = t * 100;
packet.humidity = h * 100;
}
packet.ms = millis();
// Serial.printf("%lu - %02x\r\n", packet.battery, packet.battery);
// Serial.printf("%lu - %02x\r\n", packet.temperature, packet.temperature);
// Serial.printf("%lu - %02x\r\n", packet.humidity, packet.humidity);
}
auto timeout_cb = []() {
Serial.println("TIMEOUT...");
goSleep(DEFAULT_DEEP_SLEEP_S);
};
void loop()
{
read_sensor();
if (master_mac[0] == 0x00 && master_mac[1] == 0x00) {
goSleep(DEFAULT_DEEP_SLEEP_S);
}
else {
espNow.enable_retries(true);
Serial.println(millis());
espNow.send(master_mac, (u8*)&packet, sizeof (packet), timeout_cb, 3000);
}
delay(100);
}
void goSleep(uint32_t deepSleepS) {
//Serial.printf("\r\nGo sleep for .. %lu seconds. \r\n", deepSleepS);
ESP.deepSleep(deepSleepS * 1e6);
}
| [
"nat@cmmc.io"
] | nat@cmmc.io |
e80e76e1d786272e8b603e2687fece8a0f409912 | 0bc95dbc9650afb1d8f6b194c447679553342e12 | /model/DnaMetaData.h | cf9d1787eefbb3d81eaa186ad4102cd59468f9a2 | [] | no_license | chanismile/Dna-project | f40e52aa8dd2546a257329550a2cd21a05833e4f | d02f1de75f9eeef746e151cfb8b2496e7ecb6f65 | refs/heads/master | 2020-04-15T14:08:17.495543 | 2019-02-07T09:39:45 | 2019-02-07T09:39:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 571 | h | //
// Created by cglick on 12/29/18.
//
#ifndef UNTITLED1_DNAMETADATA_H
#define UNTITLED1_DNAMETADATA_H
#include "DnaSequence.h"
#include <glob.h>
#include <string>
enum Status{ Up_TO_DATE, MODIFIED, NEW };
class DnaMetaData
{
public:
DnaMetaData(const std::string & seq, size_t id, const std::string & name);
DnaMetaData(DnaSequence seq, size_t id, const std::string & name);
IDna * getm_IDna();
std::string getm_name();
private:
size_t m_id;
std::string m_name;
IDna * m_IDna;
Status m_status;
};
#endif //UNTITLED1_DNAMETADATA_H
| [
"37192892+chanismile@users.noreply.github.com"
] | 37192892+chanismile@users.noreply.github.com |
b23202a42e8ef90d059fb78b56b775fb6d8dc129 | acd27324a6c44314cadbdeccdf04bda4ac13eef9 | /src/main.cpp | 8ef67afd9afcfe9a3aa41c0794dc69869bf7f8ab | [] | no_license | sumanthratna/vegetable-rush | 8d4536bd27b0bb582159f2a1d128aceab400ea83 | a760d95642c10ff6b558781ac2ce2aa1c0860e51 | refs/heads/master | 2020-04-29T09:44:28.941712 | 2019-03-31T01:39:19 | 2019-03-31T01:39:19 | 176,036,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | cpp | #include <QApplication>
#include <QMainWindow>
#include <QSurfaceFormat>
#include <QFontDatabase>
#include "mainwindow.hpp"
#include "file_settings.hpp"
int main(int argc, char ** argv)
{
QApplication a(argc, argv);
Settings::programPath = a.applicationDirPath().toStdString();
QSurfaceFormat format;
format.setDepthBufferSize(24);
format.setStencilBufferSize(8);
QSurfaceFormat::setDefaultFormat(format);
QFontDatabase::addApplicationFont(":/data/fonts/arcade.regular.ttf");
MainWindow mw;
// a.setApplicationName("SUMANTH RATNA, ADITYA MENACHERY, STEVEN LI (Period 5)");
mw.show();
return a.exec();
}
| [
"sumanthratna@gmail.com"
] | sumanthratna@gmail.com |
9b0ecbcb547d8306ec6de464d9e846a568031e27 | f421bcf931dc3073e4c9b3e3e747f18f6fe617a2 | /test/cts/reporter_test_cts.cc | f9294f4e5b534266302557dee05e7fe0528063c1 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | Evervolv/android_external_perfetto | 9063868f2e8dd8446f079615b4427a4591603124 | b4ea495f96c2aa70e49431dea2770403d27f23ca | refs/heads/t-13.1 | 2023-04-10T08:35:04.318754 | 2020-09-26T14:57:04 | 2022-12-08T01:39:15 | 145,198,818 | 0 | 1 | Apache-2.0 | 2022-12-11T18:29:48 | 2018-08-18T07:13:50 | C++ | UTF-8 | C++ | false | false | 4,074 | cc | /*
* Copyright (C) 2022 The Android Open Source Project
*
* 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 <sys/system_properties.h>
#include <random>
#include "test/gtest_and_gmock.h"
#include "perfetto/ext/base/android_utils.h"
#include "perfetto/ext/base/uuid.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "src/base/test/test_task_runner.h"
#include "test/android_test_utils.h"
#include "test/test_helper.h"
#include "protos/perfetto/config/test_config.gen.h"
#include "protos/perfetto/trace/test_event.gen.h"
#include "protos/perfetto/trace/trace.gen.h"
#include "protos/perfetto/trace/trace_packet.gen.h"
namespace perfetto {
namespace {
TEST(PerfettoReporterTest, TestEndToEndReport) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.ConnectFakeProducer();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(1024);
trace_config.set_duration_ms(200);
trace_config.set_allow_user_build_tracing(true);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.perfetto.FakeProducer");
ds_config->set_target_buffer(0);
base::Uuid uuid = base::Uuidv4();
trace_config.set_trace_uuid_lsb(uuid.lsb());
trace_config.set_trace_uuid_msb(uuid.msb());
static constexpr uint32_t kRandomSeed = 42;
static constexpr uint32_t kEventCount = 1;
static constexpr uint32_t kMessageSizeBytes = 2;
ds_config->mutable_for_testing()->set_seed(kRandomSeed);
ds_config->mutable_for_testing()->set_message_count(kEventCount);
ds_config->mutable_for_testing()->set_message_size(kMessageSizeBytes);
ds_config->mutable_for_testing()->set_send_batch_on_register(true);
auto* report_config = trace_config.mutable_android_report_config();
report_config->set_reporter_service_package("android.perfetto.cts.reporter");
report_config->set_reporter_service_class(
"android.perfetto.cts.reporter.PerfettoReportService");
report_config->set_use_pipe_in_framework_for_testing(true);
// We have to construct all the processes we want to fork before we start the
// service with |StartServiceIfRequired()|. this is because it is unsafe
// (could deadlock) to fork after we've spawned some threads which might
// printf (and thus hold locks).
auto perfetto_proc = Exec("perfetto",
{
"--upload",
"-c",
"-",
},
trace_config.SerializeAsString());
std::string stderr_str;
EXPECT_EQ(0, perfetto_proc.Run(&stderr_str)) << stderr_str;
static constexpr char kPath[] =
"/sdcard/Android/data/android.perfetto.cts.reporter/files/";
std::string path = kPath + uuid.ToPrettyString();
static constexpr uint32_t kIterationSleepMs = 500;
static constexpr uint32_t kIterationCount =
kDefaultTestTimeoutMs / kIterationSleepMs;
for (size_t i = 0; i < kIterationCount; ++i) {
if (!base::FileExists(path)) {
base::SleepMicroseconds(kIterationSleepMs * 1000);
continue;
}
std::string trace_str;
ASSERT_TRUE(base::ReadFile(path, &trace_str));
protos::gen::Trace trace;
ASSERT_TRUE(trace.ParseFromString(trace_str));
int for_testing = 0;
for (const auto& packet : trace.packet()) {
for_testing += packet.has_for_testing();
}
ASSERT_EQ(for_testing, kEventCount);
return;
}
FAIL() << "Timed out waiting for trace file";
}
} // namespace
} // namespace perfetto
| [
"lalitm@google.com"
] | lalitm@google.com |
4edabc48c38c7b88cdd2e24670a8837e16ed3a84 | 382eb97bb79478130f83d50877148188ec7ff51a | /interface/src/ui/ChatMessageArea.h | 57199538fdd8dd566a8341f607c5c0011ce2ea28 | [
"Apache-2.0"
] | permissive | rabedik/hifi | d6cb72e9426d69714b06a3f842b2a4919f52ed18 | 08986dcb17ece932f567ab27cf1f0b1fdecf41e1 | refs/heads/master | 2021-01-16T20:55:40.135499 | 2015-08-28T23:36:00 | 2015-08-28T23:36:00 | 41,653,396 | 1 | 0 | null | 2015-08-31T03:17:57 | 2015-08-31T03:17:56 | null | UTF-8 | C++ | false | false | 821 | h | //
// ChatMessageArea.h
// interface/src/ui
//
// Created by Ryan Huffman on 4/11/14.
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#ifndef hifi_ChatMessageArea_h
#define hifi_ChatMessageArea_h
#include <QTextBrowser>
const int CHAT_MESSAGE_LINE_HEIGHT = 130;
class ChatMessageArea : public QTextBrowser {
Q_OBJECT
public:
ChatMessageArea(bool useFixedHeight = true);
virtual void setHtml(const QString& html);
public slots:
void updateLayout();
void setSize(const QSize& size);
signals:
void sizeChanged(QSize newSize);
protected:
virtual void wheelEvent(QWheelEvent* event);
bool _useFixedHeight;
};
#endif // hifi_ChatMessageArea_h
| [
"ryanhuffman@gmail.com"
] | ryanhuffman@gmail.com |
b15cb2412b7e95050c331f008feadcee292db42a | 98db7c4cd61029506aa7add98f1082d53844d7bb | /main.cpp | d3cf1bc6a9602ceafc6c7a6d98fc13753a42f509 | [] | no_license | wolf088/git_Calculation | acd91c39c51ecdf436bca8655c334a9281c98fd3 | c0038de0a818c358b636b60779c4e15fb9c519d8 | refs/heads/master | 2020-07-26T07:16:58.723366 | 2019-09-23T09:58:42 | 2019-09-23T09:58:42 | 208,575,814 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | cpp | #include <iostream>
#include "calc.hpp"
using namespace std;
int main(){
Calculation ins;
int num;
char mark; //演算子
//1つ目の数の入力
cout << "1つ目の数を入力してください:";
cin >> num;
ins.setNum1(num);
//演算子の入力
cout << "演算子を入力してください(+:加算、-:減算、*:乗算、/:除算):";
cin >> mark;
//2つ目の数の入力
cout << "2つ目の数を入力してください:";
cin >> num;
ins.setNum2(num);
//演算
if (mark == '+'){
cout << "答:" << ins.add() << endl;
}
else if (mark == '-'){
cout << "答:" << ins.sub() << endl;
}
else if (mark == '*'){
cout << "答:" << ins.mul() << endl;
}
else if (mark == '/'){
cout << "答:" << ins.div() << endl;
}
return 0;
} | [
"takayoshi-jean@akane.waseda.jp"
] | takayoshi-jean@akane.waseda.jp |
bba45e20d658a086c03d2709df0a7d8d4711a9e4 | a081002197d091f1c387576894a160ececb69497 | /activemq-cpp/src/main/decaf/security/cert/CertificateParsingException.cpp | 08e1cde3bf079e4636c7f20c62d125538eef8ea5 | [
"Apache-2.0"
] | permissive | greatyang/activemq-cpp | 357fe087c839ed0d535ad7e3d987db2dc0badf1e | 4f5d0847552d6a5e206cc54c4354ebd8b0bb8fe3 | refs/heads/master | 2021-03-03T09:53:20.887464 | 2020-03-09T05:34:59 | 2020-03-09T05:34:59 | 245,951,764 | 0 | 0 | Apache-2.0 | 2020-03-09T05:31:25 | 2020-03-09T05:31:25 | null | UTF-8 | C++ | false | false | 2,723 | cpp | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "CertificateParsingException.h"
using namespace decaf;
using namespace decaf::security;
using namespace decaf::security::cert;
////////////////////////////////////////////////////////////////////////////////
CertificateParsingException::CertificateParsingException() : CertificateException() {
}
////////////////////////////////////////////////////////////////////////////////
CertificateParsingException::CertificateParsingException(const Exception& ex) : CertificateException() {
*(Exception*) this = ex;
}
////////////////////////////////////////////////////////////////////////////////
CertificateParsingException::CertificateParsingException(const CertificateParsingException& ex) : CertificateException() {
*(Exception*) this = ex;
}
////////////////////////////////////////////////////////////////////////////////
CertificateParsingException::CertificateParsingException(const char* file, const int lineNumber, const std::exception* cause, const char* msg, ...) : CertificateException(cause) {
va_list vargs;
va_start(vargs, msg);
buildMessage(msg, vargs);
// Set the first mark for this exception.
setMark(file, lineNumber);
}
////////////////////////////////////////////////////////////////////////////////
CertificateParsingException::CertificateParsingException(const std::exception* cause) : CertificateException(cause) {
}
////////////////////////////////////////////////////////////////////////////////
CertificateParsingException::CertificateParsingException(const char* file, const int lineNumber, const char* msg, ...) : CertificateException() {
va_list vargs;
va_start(vargs, msg);
buildMessage(msg, vargs);
// Set the first mark for this exception.
setMark(file, lineNumber);
}
////////////////////////////////////////////////////////////////////////////////
CertificateParsingException::~CertificateParsingException() throw () {
}
| [
"tabish@apache.org"
] | tabish@apache.org |
609e00ffb0cc18d37e002fac3f940e5685e2e563 | a585dc37a6db31f54fc9d9861406827cc40007b7 | /gravity/gravity.cpp | 56a5cacc8baaaa908a006806b08f37318b87102f | [] | no_license | kybr/mat201b-1 | 4a3eeac858af0377680b84aa0015ce98285b4cf6 | 08a1f33feff18cedd183af27c0cbca5c1d62052b | refs/heads/master | 2021-04-06T11:46:57.465490 | 2018-03-20T00:16:57 | 2018-03-20T00:16:57 | 125,356,187 | 0 | 0 | null | 2018-03-15T11:18:10 | 2018-03-15T11:18:10 | null | UTF-8 | C++ | false | false | 4,421 | cpp | //ariella gilmore
//MAT 201B
//sublime
//ariellalgilmore@gmail.com
//2/7/18
#include "allocore/io/al_App.hpp"
using namespace al;
using namespace std;
// some of these must be carefully balanced; i spent some time turning them.
// change them however you like, but make a note of these settings.
unsigned particleCount = 50; // try 2, 5, 50, and 500
double maximumAcceleration = 30; // prevents explosion, loss of particles
double initialRadius = 50; // initial condition
double initialSpeed = 50; // initial condition
double gravityFactor = 1e6; // see Gravitational Constant
double timeStep = 0.0625; // keys change this value for effect
double scaleFactor = 0.1; // resizes the entire scene
double sphereRadius = 3; // increase this to make collisions more frequent
Mesh sphere; // global prototype; leave this alone
// helper function: makes a random vector
Vec3f r() { return Vec3f(rnd::uniformS(), rnd::uniformS(), rnd::uniformS()); }
struct Particle {
Vec3f position, velocity, acceleration;
Color c;
Particle() {
position = r() * initialRadius;
velocity =
// this will tend to spin stuff around the y axis
Vec3f(0, 1, 0).cross(position).normalize(initialSpeed);
c = HSV(rnd::uniform(), 0.7, 1);
}
void draw(Graphics& g) {
g.pushMatrix();
g.translate(position);
g.color(c);
g.draw(sphere);
g.popMatrix();
}
};
struct Phasor { //saw//ramp phasors go from 0 to 1
float phase = 0, increment = 0.001;
float getNextSample(){
float returnValue = phase;
phase += increment;
if(phase > 1){
phase -=1;
}
return returnValue;
}
};
struct MyApp : App {
Material material;
Light light;
bool simulate = true;
vector<Particle> particle;
MyApp() {
addSphere(sphere, sphereRadius);
sphere.generateNormals();
light.pos(0, 0, 0); // place the light
nav().pos(0, 0, 30); // place the viewer
lens().far(400); // set the far clipping plane
particle.resize(particleCount); // make all the particles
background(Color(0.07));
initWindow();
initAudio();
}
void onAnimate(double dt) {
if (!simulate)
// skip the rest of this function
return;
//
// Detect Collisions Here
//
for (unsigned i = 0; i < particle.size(); ++i){
Particle& a = particle[i];
for (unsigned j = 1 + i; j < particle.size(); ++j) {
Particle& b = particle[j];
if(a.position-b.position < 6){
a.velocity = -a.velocity;
b.velocity = -b.velocity;
//cout << "collide" << endl;
}
}
}
for (unsigned i = 0; i < particle.size(); ++i){
for (unsigned j = 1 + i; j < particle.size(); ++j) {
Particle& a = particle[i];
Particle& b = particle[j];
Vec3f difference = (b.position - a.position);
double d = difference.mag();
// F = ma where m=1
Vec3f acceleration = difference / (d * d * d) * gravityFactor;
// equal and opposite force (symmetrical)
a.acceleration += acceleration;
b.acceleration -= acceleration;
}
}
// Limit acceleration
for (auto& p : particle){
if (p.acceleration.mag() > maximumAcceleration)
p.acceleration.normalize(maximumAcceleration);
}
// Euler's Method; Keep the time step small
for (auto& p : particle) p.position += p.velocity * timeStep;
for (auto& p : particle) p.velocity += p.acceleration * timeStep;
for (auto& p : particle) p.acceleration.zero();
}
void onDraw(Graphics& g) {
material();
light();
g.scale(scaleFactor);
for (auto p : particle) p.draw(g);
}
void onSound(AudioIO& io) {
io.out(0) = 1; //left
io.out(1) = 1; //right
while (io()) {
io.out(0) = 1;
io.out(1) = 1;
}
}
void onKeyDown(const ViewpointWindow&, const Keyboard& k) {
switch (k.key()) {
default:
case '1':
// reverse time
timeStep *= -1;
break;
case '2':
// speed up time
if (timeStep < 1) timeStep *= 2;
break;
case '3':
// slow down time
if (timeStep > 0.0005) timeStep /= 2;
break;
case '4':
// pause the simulation
simulate = !simulate;
break;
}
}
};
int main() { MyApp().start(); }
| [
"noreply@github.com"
] | kybr.noreply@github.com |
f16a1b1a11f7a96b5c35c70ce9d50d4f1e777945 | e03c4081a9bcf19815f6931cc9417a640a99046f | /opencv7/main.cpp | e2b569d51dbbcfaf15013c627ba550e86e2c2a73 | [] | no_license | Longxiaoze/Machine_vision_with_opencv | df4f4699bcfc35200ffe24733903d3d36c10c987 | 6a2b625997c26dc2a9488cbd8a5754bbed6746bf | refs/heads/main | 2023-01-09T03:40:16.159502 | 2020-11-05T05:58:33 | 2020-11-05T05:58:33 | 301,421,879 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,647 | cpp | /*creat by 龙笑泽 date:2020.10.02
* 文件说明:使用opencv库读取三通道彩色图
* 输入平移量,对图像进行平移操作
* 显示原图片和平移后的图片
* trick: 1.图片输入和输出应为完整路径(可能是我建项目在桌面的原因),仅输入输出文件名无法打开和保存
* 2.命名显示窗口不能有汉字,否则无法显示标题
* 软件及环境:clion opencv3 gcc-9 g++-9
* */
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main() {
Mat srcImage, dstImage;
int xOffset, yOffset; //x和y方向的平移量
srcImage = imread("/Users/hiyoshikei/Desktop/code_all/opencv_4/test.jpg");//读取图片
if (!srcImage.data) {
cout << "读入图片错误!" << endl;
return -1;
}
dstImage.create(srcImage.size(), srcImage.type());
cout << "请输入x方向和y方向的平移量:";
cin >> xOffset >> yOffset;
int rowNumber = srcImage.rows;
int colNumber = srcImage.cols;
//进行遍历图像
for (int i = 0; i < rowNumber; i++) {
for (int j = 0; j < colNumber; j++) {
//平移变换
int x = j - xOffset;
int y = i - yOffset;
//判断边界情况
if (x >= 0 && y >= 0 && x < colNumber && y < rowNumber)
dstImage.at<Vec3b>(i, j) = srcImage.at<Vec3b>(y, x);
}
}
imshow("test", srcImage);
imshow("remove_img", dstImage);
waitKey();
return 0;
}
| [
"noreply@github.com"
] | Longxiaoze.noreply@github.com |
8d733824e3474161deee788ba670a4d4f621f445 | c209d7cf2f49e21ddf5071c4b9a2dfc7b268c44d | /Tugas 2/Tugas 2/Tugas 2.cpp | 6fa5e78bdd91a7755630cbf1fb3ccfc1edef4161 | [] | no_license | Zaidannzzz/GrafikaKomputer | 697d3d4435ae81fbdd75fefd00ff5ba5cab775b5 | 4bc505908d304be00d20d3eaeb2a0c0c26adb468 | refs/heads/main | 2023-03-19T14:31:23.215352 | 2021-03-16T04:20:38 | 2021-03-16T04:20:38 | 341,642,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,100 | cpp | #include <GL/glut.h> //pemanggilan pustaka glut.h sekaligus gl.h milik OpenGL
#include <windows.h>
#include <math.h>
const double PI = 3.142857143;
int i, jari, jumlah_titik, x_tengah, y_tengah, r;
void display() //fungsi display() salah satu fungsi terpenting dalam program OpenGL
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1, 1, 0);//untuk warna lingkaran
glBegin(GL_POLYGON);
jari = 6;
jumlah_titik = 60;
x_tengah = 0;
y_tengah = 0;
y_tengah = r;
r = 6;
for (i = 0;i <= 360;i++)
{
float sudut = i * (2 * PI / jumlah_titik);
float x = x_tengah + jari * cos(sudut);
float y = y_tengah + jari * sin(sudut);
glVertex2f(x / 100, y / 100);
}
glEnd();
glFlush();
}
int main(int argc, char** argv) //fungsi utama seluruh program C++
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(600,600);
glutCreateWindow("Lingkaran");
glutDisplayFunc(display);
glutMainLoop();
return 0;
} | [
"noreply@github.com"
] | Zaidannzzz.noreply@github.com |
5f6cfa93e3e8854f48c09d7e833360430a9e8530 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14443/function14443_schedule_36/function14443_schedule_36.cpp | 89f65e4824854b3475f3002883257543c8271e41 | [] | 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 | 765 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14443_schedule_36");
constant c0("c0", 64), c1("c1", 128), c2("c2", 128), c3("c3", 64);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
computation comp0("comp0", {i0, i1, i2, i3}, 8 * 3 * 8);
comp0.tile(i0, i1, i2, 64, 32, 32, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i01);
buffer buf0("buf0", {64, 128, 128, 64}, p_int32, a_output);
comp0.store_in(&buf0);
tiramisu::codegen({&buf0}, "../data/programs/function14443/function14443_schedule_36/function14443_schedule_36.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
2932e7c98d7dc83d5d62d889b33fe6a8292003e6 | 12b8d53b486019224d3cafbdf8d69e8dd4251a52 | /gcpp/classes/oCSSProperty.cpp | 29b7087dd866df7f41f1115d4739d09aae5f8868 | [
"ISC"
] | permissive | wol22/MotleyTools | 468bea011a6621480420952094fe23fb31b5475a | 221640737061d91e01d8bf769ce79e131bd79a60 | refs/heads/master | 2021-01-16T17:42:19.822564 | 2013-08-02T14:51:53 | 2013-08-02T14:51:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,771 | cpp | /*====================================================================*
*
* oCSSProperty.cpp - definition of the oCSSProperty class.
*
* symbol table containing CSS property names;
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#ifndef oCSSPROPERTY_SOURCE
#define oCSSPROPERTY_SOURCE
/*====================================================================*
* custom header files;
*--------------------------------------------------------------------*/
#include "../classes/oCSSProperty.hpp"
/*====================================================================*
*
* oCSSProperty ();
*
*
*--------------------------------------------------------------------*/
oCSSProperty::oCSSProperty ()
{
static char const * table [] =
{
"azimuth",
"background",
"background-attachment",
"background-color",
"background-image",
"background-position",
"background-repeat",
"border",
"border-bottom",
"border-bottom-color",
"border-bottom-style",
"border-bottom-width",
"border-collapse",
"border-color",
"border-left",
"border-left-color",
"border-left-style",
"border-left-width",
"border-right",
"border-right-color",
"border-right-style",
"border-right-width",
"border-spacing",
"border-style",
"border-top",
"border-top-color",
"border-top-style",
"border-top-width",
"border-width",
"bottom",
"caption-side",
"clear",
"clip",
"color",
"content",
"counter-increment",
"counter-reset",
"cue",
"cue-after",
"cue-before",
"cursor",
"direction",
"display",
"elevation",
"empty-cells",
"float",
"font",
"font-family",
"font-size",
"font-size-adjust",
"font-stretch",
"font-style",
"font-variant",
"font-weight",
"height",
"left",
"letter-spacing",
"line-height",
"list-style",
"list-style-image",
"list-style-position",
"list-style-type",
"margin",
"margin-bottom",
"margin-left",
"margin-right",
"margin-top",
"marker-offset",
"marks",
"max-height",
"max-width",
"min-height",
"min-width",
"orphans",
"outline",
"outline-color",
"outline-style",
"outline-width",
"overflow",
"padding",
"padding-bottom",
"padding-left",
"padding-right",
"padding-top",
"page",
"page-break-after",
"page-break-before",
"page-break-inside",
"pause",
"pause-after",
"pause-before",
"pitch",
"pitch-range",
"play-during",
"position",
"quotes",
"richness",
"right",
"size",
"speak",
"speak-header",
"speak-numeral",
"speak-punctuation",
"speech-rate",
"stress",
"table-layout",
"text-align",
"text-decoration",
"text-indent",
"text-shadow",
"text-transform",
"top",
"unicode-bidi",
"vertical-align",
"visibility",
"voice-family",
"volume",
"white-space",
"widows",
"width",
"word-spacing",
"z-index",
(char const *)(0)
};
okeywords::mtitle = "CSSProperty";
okeywords::mcount = sizeof (table) / sizeof (char const *) - 1;
okeywords::mtable = table;
okeywords::mcheck ();
return;
}
/*====================================================================*
*
* ~oCSSProperty ();
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
oCSSProperty::~oCSSProperty ()
{
return;
}
/*====================================================================*
* end definition;
*--------------------------------------------------------------------*/
#endif
| [
"charlesmaier@localhost"
] | charlesmaier@localhost |
b1456f6643b119c8326967ee3067a4ab2015f2e7 | d4b733f2e00b5d0ab103ea0df6341648d95c993b | /src/c-cpp/lib/sst/private/guts/generic_socket_poll_set/consolidate-windows.cpp | 367a21b1df5b02bef84b9003cad75c3c9cd4ab1e | [
"MIT"
] | permissive | stealthsoftwareinc/sst | ad6117a3d5daf97d947862674336e6938c0bc699 | f828f77db0ab27048b3204e10153ee8cfc1b2081 | refs/heads/master | 2023-04-06T15:21:14.371804 | 2023-03-24T08:30:48 | 2023-03-24T08:30:48 | 302,539,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,949 | cpp | //
// Copyright (C) 2012-2023 Stealth Software Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice (including
// the next paragraph) shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// SPDX-License-Identifier: MIT
//
// Include first to test independence.
#include <sst/private/guts/generic_socket_poll_set.hpp>
// Include twice to test idempotence.
#include <sst/private/guts/generic_socket_poll_set.hpp>
//
#include <sst/catalog/SST_WITH_WINDOWS_WS2_32.h>
#if SST_WITH_WINDOWS_WS2_32
#include <sst/catalog/windows_socket.hpp>
#include <sst/catalog/windows_socket_poll_set_entry.hpp>
#include <sst/private/guts/generic_socket_poll_set/pfd_t-windows.hpp>
namespace sst {
namespace guts {
template<>
void generic_socket_poll_set<
sst::windows_socket,
sst::windows_socket_poll_set_entry>::consolidate() {
this->template consolidate_helper<pfd_t>();
}
} // namespace guts
} // namespace sst
#endif // #if SST_WITH_WINDOWS_WS2_32
| [
"sst@stealthsoftwareinc.com"
] | sst@stealthsoftwareinc.com |
21497800dba0b90df14830c6f591c708a27de31f | ed71c7bc5e116282084713b0ec36b1370780f99e | /icu/source/test/intltest/tfsmalls.h | f62e590a36f731d36c74407a098c6cd8af31bb43 | [
"ICU",
"LicenseRef-scancode-unicode"
] | permissive | alexswider/dropup.brigade | 12e6a12f82a44e568f39b98bb0dbafee78c0c3f7 | 13fa5308c30786b5bba98564a0959b3c05343502 | refs/heads/master | 2021-01-18T22:20:51.901107 | 2016-04-25T18:46:27 | 2016-04-25T18:46:27 | 47,217,645 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 869 | h | /********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2001, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************/
#ifndef TESTFORMATSMALLCLASSES_H
#define TESTFORMATSMALLCLASSES_H
#include "intltest.h"
/**
* tests 3 smaller classes in the format library
**/
class TestFormatSmallClasses: public IntlTest {
/**
* runs tests in 4 local routines,
* performs test for API and funtionalty of 3 smaller format classes:
* ParsePosition in test_ParsePosition(),
* FieldPosition in test_FieldPosition(),
* Formattable in test_Formattable().
**/
void runIndexedTest( int32_t index, UBool exec, const char* &name, char* par = NULL );
};
#endif
| [
"marcinkozakk@gmail.com"
] | marcinkozakk@gmail.com |
18c0acb9ec18da96e976d07dbb7a3b61f89be262 | 8a84ba0834c149a739be1fffbf157d75d1a70083 | /CPP71.cpp | 616405d2880fb58383f99b7d88bb84b435d4730c | [] | no_license | nileshsethi1998/lab3 | 0fc6c09102ed92a19ec3190c274ec6f41d68d1a4 | fc9274aea918dba15ff48cd3fa4a397284ee6c97 | refs/heads/master | 2021-06-28T10:09:05.587473 | 2017-09-15T14:07:04 | 2017-09-15T14:07:04 | 103,663,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47 | cpp | # CPPAssignment3
C++ PROGRAMS FOR ASSIGNMENT 3
| [
"noreply@github.com"
] | nileshsethi1998.noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.