blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6048291360fbc3fa92ee150340e20b937801c0f3 | c251135af4c6e957c7b70d30aabb0e1da9bbe376 | /node-angular-display-server/node_modules/node-mirror/lib/pty-win/deps/winpty/agent/AgentAssert.cc | 413fcf7b2328804dcde1e592c75d6fc2c492cd73 | [
"MIT",
"BSD-3-Clause"
] | permissive | strongloop-community/node-angular-raspberry-pi-dashboard | 41999d49985baa33e01850570defcaa0f9466cda | 8ab985f41582f9a561f3fd999a3f54293164e330 | refs/heads/master | 2021-01-01T20:17:36.280716 | 2013-12-02T15:37:28 | 2013-12-02T15:37:28 | 14,508,781 | 9 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,676 | cc | // Copyright (c) 2011-2012 Ryan Prichard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include "AgentAssert.h"
#include "../shared/DebugClient.h"
#include <stdlib.h>
// Calling the standard assert() function does not work in the agent because
// the error message would be printed to the console, and the only way the
// user can see the console is via a working agent! This custom assert
// function instead sends the message to the DebugServer.
void assertFail(const char *file, int line, const char *cond)
{
trace("Assertion failed: %s, file %s, line %d",
cond, file, line);
abort();
}
| [
"matt.schmulen@gmail.com"
] | matt.schmulen@gmail.com |
5a0fcbfabd4c4042f5eee05b7ed9919c90c8a8f3 | 6d262e1e3f104f316cb8c3b3c9cfd5ddbb5cc6e3 | /Source/Common/Game/Enemy.h | b52b325c564e302144f82c7eca0b759f0ed7590f | [] | no_license | doug0102/GAM1514FinalProject | 594819061bb10dcb19a4a59ac8cb5f4e241882c5 | d2c693648607f48610a59e52726fa10076bed302 | refs/heads/master | 2020-06-06T02:35:08.380462 | 2013-12-12T20:15:27 | 2013-12-12T20:15:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 399 | h | #include "Player.h"
class Enemy : public Player
{
public:
Enemy(Level* level, float speed);
virtual ~Enemy();
const char* getType();
void update(double delta);
void paint();
void reset();
void fireProjectile(float x, float y);
void slowEnemy(double length, float power);
protected:
void handlePlayerCollision(Projectile* projectile);
double m_SlowTimer;
double m_PreviousSpeed;
}; | [
"doug0102@algonquincollege.com"
] | doug0102@algonquincollege.com |
b8cd780b6f5f3b7901c1dce488160cf1ebf878ea | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.002/PC4H9O | 4d2ccc5f551a17b22996f1625d18e2313bb42046 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 838 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.002";
object PC4H9O;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 3.44885e-19;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
ebfb60a5243b44bb7316068da1b5fc612ee26e3d | b4bdcc68d17958d7175c9f7742594b1a33be2c79 | /CaffeMac/caffe/blob.hpp | 1ca17113b6751818d895c74cba4ed3825582cf92 | [] | no_license | panda-lab/CaffeXcode | bc844a53f0eafb38636bb047c18d997f324ea9c1 | 5747d94a2e3917771a2fef2023d37736b299a4bd | refs/heads/master | 2022-09-09T08:10:42.899473 | 2017-08-21T09:46:37 | 2017-08-21T09:46:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,533 | hpp | #ifndef CAFFE_BLOB_HPP_
#define CAFFE_BLOB_HPP_
#include <algorithm>
#include <string>
#include <vector>
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/syncedmem.hpp"
const int kMaxBlobAxes = 32;
namespace caffe {
/**
* @brief A wrapper around SyncedMemory holders serving as the basic
* computational unit through which Layer%s, Net%s, and Solver%s
* interact.
*
* TODO(dox): more thorough description.
*/
template <typename Dtype>
class Blob {
public:
Blob()
: data_(), diff_(), count_(0), capacity_(0) {}
/// @brief Deprecated; use <code>Blob(const vector<int>& shape)</code>.
explicit Blob(const int num, const int channels, const int height,
const int width);
explicit Blob(const vector<int>& shape);
/// @brief Deprecated; use <code>Reshape(const vector<int>& shape)</code>.
void Reshape(const int num, const int channels, const int height,
const int width);
/**
* @brief Change the dimensions of the blob, allocating new memory if
* necessary.
*
* This function can be called both to create an initial allocation
* of memory, and to adjust the dimensions of a top blob during Layer::Reshape
* or Layer::Forward. When changing the size of blob, memory will only be
* reallocated if sufficient memory does not already exist, and excess memory
* will never be freed.
*
* Note that reshaping an input blob and immediately calling Net::Backward is
* an error; either Net::Forward or Net::Reshape need to be called to
* propagate the new input shape to higher layers.
*/
void Reshape(const vector<int>& shape);
void Reshape(const BlobShape& shape);
void ReshapeLike(const Blob& other);
inline string shape_string() const {
ostringstream stream;
for (int i = 0; i < shape_.size(); ++i) {
stream << shape_[i] << " ";
}
stream << "(" << count_ << ")";
return stream.str();
}
inline const vector<int>& shape() const { return shape_; }
/**
* @brief Returns the dimension of the index-th axis (or the negative index-th
* axis from the end, if index is negative).
*
* @param index the axis index, which may be negative as it will be
* "canonicalized" using CanonicalAxisIndex.
* Dies on out of range index.
*/
inline int shape(int index) const {
return shape_[CanonicalAxisIndex(index)];
}
inline int num_axes() const { return shape_.size(); }
inline int count() const { return count_; }
/**
* @brief Compute the volume of a slice; i.e., the product of dimensions
* among a range of axes.
*
* @param start_axis The first axis to include in the slice.
*
* @param end_axis The first axis to exclude from the slice.
*/
inline int count(int start_axis, int end_axis) const {
CHECK_LE(start_axis, end_axis);
CHECK_GE(start_axis, 0);
CHECK_GE(end_axis, 0);
CHECK_LE(start_axis, num_axes());
CHECK_LE(end_axis, num_axes());
int count = 1;
for (int i = start_axis; i < end_axis; ++i) {
count *= shape(i);
}
return count;
}
/**
* @brief Compute the volume of a slice spanning from a particular first
* axis to the final axis.
*
* @param start_axis The first axis to include in the slice.
*/
inline int count(int start_axis) const {
return count(start_axis, num_axes());
}
/**
* @brief Returns the 'canonical' version of a (usually) user-specified axis,
* allowing for negative indexing (e.g., -1 for the last axis).
*
* @param axis_index the axis index.
* If 0 <= index < num_axes(), return index.
* If -num_axes <= index <= -1, return (num_axes() - (-index)),
* e.g., the last axis index (num_axes() - 1) if index == -1,
* the second to last if index == -2, etc.
* Dies on out of range index.
*/
inline int CanonicalAxisIndex(int axis_index) const {
CHECK_GE(axis_index, -num_axes())
<< "axis " << axis_index << " out of range for " << num_axes()
<< "-D Blob with shape " << shape_string();
CHECK_LT(axis_index, num_axes())
<< "axis " << axis_index << " out of range for " << num_axes()
<< "-D Blob with shape " << shape_string();
if (axis_index < 0) {
return axis_index + num_axes();
}
return axis_index;
}
/// @brief Deprecated legacy shape accessor num: use shape(0) instead.
inline int num() const { return LegacyShape(0); }
/// @brief Deprecated legacy shape accessor channels: use shape(1) instead.
inline int channels() const { return LegacyShape(1); }
/// @brief Deprecated legacy shape accessor height: use shape(2) instead.
inline int height() const { return LegacyShape(2); }
/// @brief Deprecated legacy shape accessor width: use shape(3) instead.
inline int width() const { return LegacyShape(3); }
inline int LegacyShape(int index) const {
CHECK_LE(num_axes(), 4)
<< "Cannot use legacy accessors on Blobs with > 4 axes.";
CHECK_LT(index, 4);
CHECK_GE(index, -4);
if (index >= num_axes() || index < -num_axes()) {
// Axis is out of range, but still in [0, 3] (or [-4, -1] for reverse
// indexing) -- this special case simulates the one-padding used to fill
// extraneous axes of legacy blobs.
return 1;
}
return shape(index);
}
inline int offset(const int n, const int c = 0, const int h = 0,
const int w = 0) const {
CHECK_GE(n, 0);
CHECK_LE(n, num());
CHECK_GE(channels(), 0);
CHECK_LE(c, channels());
CHECK_GE(height(), 0);
CHECK_LE(h, height());
CHECK_GE(width(), 0);
CHECK_LE(w, width());
return ((n * channels() + c) * height() + h) * width() + w;
}
inline int offset(const vector<int>& indices) const {
CHECK_LE(indices.size(), num_axes());
int offset = 0;
for (int i = 0; i < num_axes(); ++i) {
offset *= shape(i);
if (indices.size() > i) {
CHECK_GE(indices[i], 0);
CHECK_LT(indices[i], shape(i));
offset += indices[i];
}
}
return offset;
}
/**
* @brief Copy from a source Blob.
*
* @param source the Blob to copy from
* @param copy_diff if false, copy the data; if true, copy the diff
* @param reshape if false, require this Blob to be pre-shaped to the shape
* of other (and die otherwise); if true, Reshape this Blob to other's
* shape if necessary
*/
void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false,
bool reshape = false);
inline Dtype data_at(const int n, const int c, const int h,
const int w) const {
return cpu_data()[offset(n, c, h, w)];
}
inline Dtype diff_at(const int n, const int c, const int h,
const int w) const {
return cpu_diff()[offset(n, c, h, w)];
}
inline Dtype data_at(const vector<int>& index) const {
return cpu_data()[offset(index)];
}
inline Dtype diff_at(const vector<int>& index) const {
return cpu_diff()[offset(index)];
}
inline const shared_ptr<SyncedMemory>& data() const {
CHECK(data_);
return data_;
}
inline const shared_ptr<SyncedMemory>& diff() const {
CHECK(diff_);
return diff_;
}
const Dtype* cpu_data() const;
void set_cpu_data(Dtype* data);
const int* gpu_shape() const;
const Dtype* gpu_data() const;
void set_gpu_data(Dtype* data);
const Dtype* cpu_diff() const;
const Dtype* gpu_diff() const;
Dtype* mutable_cpu_data();
Dtype* mutable_gpu_data();
Dtype* mutable_cpu_diff();
Dtype* mutable_gpu_diff();
void Update();
void FromProto(const BlobProto& proto, bool reshape = true);
void ToProto(BlobProto* proto, bool write_diff = false) const;
/// @brief Compute the sum of absolute values (L1 norm) of the data.
Dtype asum_data() const;
/// @brief Compute the sum of absolute values (L1 norm) of the diff.
Dtype asum_diff() const;
/// @brief Compute the sum of squares (L2 norm squared) of the data.
Dtype sumsq_data() const;
/// @brief Compute the sum of squares (L2 norm squared) of the diff.
Dtype sumsq_diff() const;
/// @brief Scale the blob data by a constant factor.
void scale_data(Dtype scale_factor);
/// @brief Scale the blob diff by a constant factor.
void scale_diff(Dtype scale_factor);
/**
* @brief Set the data_ shared_ptr to point to the SyncedMemory holding the
* data_ of Blob other -- useful in Layer%s which simply perform a copy
* in their Forward pass.
*
* This deallocates the SyncedMemory holding this Blob's data_, as
* shared_ptr calls its destructor when reset with the "=" operator.
*/
void ShareData(const Blob& other);
/**
* @brief Set the diff_ shared_ptr to point to the SyncedMemory holding the
* diff_ of Blob other -- useful in Layer%s which simply perform a copy
* in their Forward pass.
*
* This deallocates the SyncedMemory holding this Blob's diff_, as
* shared_ptr calls its destructor when reset with the "=" operator.
*/
void ShareDiff(const Blob& other);
bool ShapeEquals(const BlobProto& other);
void SetDiffStorage(shared_ptr<SyncedMemory>& storage);
void SetDataStorage(shared_ptr<SyncedMemory>& storage);
protected:
shared_ptr<SyncedMemory> data_;
shared_ptr<SyncedMemory> diff_;
shared_ptr<SyncedMemory> shape_data_;
vector<int> shape_;
int count_;
int capacity_;
DISABLE_COPY_AND_ASSIGN(Blob);
}; // class Blob
} // namespace caffe
#endif // CAFFE_BLOB_HPP_
| [
"lisiyuan@oneniceapp.com"
] | lisiyuan@oneniceapp.com |
d3884a1f91d6aa9e9cdadd6f810953f026a76c54 | e41e78cc4b8d010ebdc38bc50328e7bba2d5a3fd | /SDK/Mordhau_BP_Executioner_katzbalger_classes.hpp | ad6fdbe71887f8d84fd22b22f2ed735ada101486 | [] | no_license | Mentos-/Mordhau_SDK | a5e4119d60988dca9063e75e2563d1169a2924b8 | aacf020e6d4823a76787177eac2f8f633f558ec2 | refs/heads/master | 2020-12-13T10:36:47.589320 | 2020-01-03T18:06:38 | 2020-01-03T18:06:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,117 | hpp | #pragma once
// Mordhau (Dumped by Hinnie) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_Executioner_katzbalger.BP_Executioner_katzbalger_C
// 0x0008 (0x0080 - 0x0078)
class UBP_Executioner_katzbalger_C : public UBP_MordhauEquipmentPart_C
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0078(0x0008) (Transient, DuplicateTransient)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_Executioner_katzbalger.BP_Executioner_katzbalger_C");
return ptr;
}
void UserConstructionScript();
void ReceiveBeginPlay();
void ReceiveActorBeginOverlap(class AActor* OtherActor);
void ReceiveTick(float DeltaSeconds);
void ExecuteUbergraph_BP_Executioner_katzbalger(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"hsibma02@gmail.com"
] | hsibma02@gmail.com |
8335f948cf048b2f8efc5ffa25e416c7c79a8649 | 1b264f5b419e7fca9fb6304a0961aed604366878 | /NonOptimal.cpp | c62a0537fc949413ac79d6de558a23419f311d80 | [] | no_license | yuvalmizrahi2/Reduced-Huffman-Trees | 16b26d5e17431877375e7d61a6ade5c1d2580148 | 036f0032b42c5c1b30f6b780ad3b60e76a133e44 | refs/heads/master | 2020-05-19T22:57:26.903631 | 2019-09-02T15:48:19 | 2019-09-02T15:48:19 | 185,256,454 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,107 | cpp | #include "NonOptimal.hpp"
NonOptimal::NonOptimal(vector<int> l){
copy(l.begin(), l.end(), back_inserter(this->leaves));
for(unsigned int i = 0; i < leaves.size(); i++)
numberOfNode.push_back(0);
}
NonOptimal::~NonOptimal(){
}
int NonOptimal::numberAfterReduce(int high, int low){
int count = 0;
if(low % 2 == 1)
low--;
count += low;
high += low/2;
if(high == 0)
high = 1;
high = pow(2, floor(log2(high))) ;
while(high != 1){
count += high;
high /= 2;
}
return count;
}
bool NonOptimal::isBetterReduce(int high, int middle, int low){
return numberAfterReduce(high, middle) > numberAfterReduce(middle, low);
}
bool NonOptimal::chooseReduce(int& index){
int low, high , indexLow;
if(isBetterReduce(leaves.at(index-1),leaves.at(index),leaves.at(index+1))){
high = leaves.at(index-1);
low = leaves.at(index);
indexLow = index;
index-=2;
}
else{
high = leaves.at(index);
low = leaves.at(index+1);
indexLow = index + 1;
index-=1;
}
int count = 0;
if(low % 2 == 1)
low--;
leaves.at(indexLow) -= low;
count += 1;
high += low/2;
if(high == 0)
return false;
high = pow(2, floor(log2(high))) ;
leaves.at(indexLow - 1) = leaves.at(indexLow - 1) - high + low/2;
while(high != 1){
count += 1;
high /= 2;
}
numberOfNode.at(indexLow - count) ++;
return true;
}
void NonOptimal::reduceNonOptimal(){
bool flag = true;
while(flag){
flag = false;
for(int i = leaves.size() - 2; i > 0; i = i - 1){
flag = chooseReduce(i) || flag;
}
}
for(unsigned i = leaves.size() - 1; i > 0; i--){
numberOfNode.at(i - 1) = numberOfNode.at(i - 1) + (numberOfNode.at(i) + leaves.at(i))/2;
}
cout << "number of nodes after reduce and the new idea for ordering the tree: " <<
accumulate(numberOfNode.begin(), numberOfNode.end(), 0.0) + accumulate(leaves.begin(), leaves.end(), 0.0) + 1
<< endl;
} | [
"yuvalmiz9@gmail.com"
] | yuvalmiz9@gmail.com |
14cfcc2881749d9a5d7e7d0646d011235b3dc746 | e28e5e34a399c49ec61409dfb66a33d3c033498f | /10869-fourop/10869-fourop.cpp | 126104aba2ec7ffe73b67c78438c8605de6f0ad4 | [] | no_license | rupc/boj | e72f2e8ec1a69da7d735ac1723273b977cf2155e | 281ce9561c152a7330acc31ded83198a1d0c34c7 | refs/heads/master | 2020-07-02T08:07:00.618675 | 2017-01-24T05:56:32 | 2017-01-24T05:56:32 | 66,392,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,437 | cpp | // input, output
#include <iostream>
#include <iomanip>
// container
#include <vector>
#include <array>
#include <list>
#include <map>
#include <set>
#include <string>
// container adaper
#include <stack>
#include <queue>
// STL algorithm related
#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>
#include <memory>
#include <utility>
// C standard library
#include <cmath>
#include <cstdlib>
//
// #define DEBUG
using namespace std;
// Declaration of variables
// Declaration of auxiliary function
class genProbSolver {
public:
genProbSolver(string s) : name(s) {}
void process_input(istream &);
void process_solution();
void process_output(ostream &);
void echo_input();
private:
string name;
};
void genProbSolver::process_input(istream &pin) {
int A, B;
pin >> A >> B;
cout << A + B << endl;
std::cout <<A-B << std::endl;
std::cout << A*B << std::endl;
std::cout << A/B << std::endl;
std::cout << A%B << std::endl;
}
void genProbSolver::echo_input() {
}
void genProbSolver::process_solution() {
}
void genProbSolver::process_output(ostream &pout) {
}
int main(int argc, const char *argv[]) {
genProbSolver probsolver("");
probsolver.process_input(std::cin);
probsolver.echo_input();
probsolver.process_solution();
probsolver.process_output(std::cout);
return 0;
}
| [
"neurosilver@gmail.com"
] | neurosilver@gmail.com |
29f03c1284e414292c37b74d8dedfd87a28c10c6 | 0b9e0845b93c3759ffcbf9abb12413088fdfbe10 | /Manibus2.0/Manibus-VE-group/VE_DLL/Peripheral/MGpio/MGpio/MGpio.h | 7669352966c84eacd0dd9df2210d43b6d10808e4 | [] | no_license | MyLinkiio/Manibus | b4e95752e51a04245e2ba5881455c928802c3a38 | 2a57e97731dc61b56c8c6469b59978758f5a8098 | refs/heads/master | 2020-03-28T09:09:20.911179 | 2018-08-19T07:59:09 | 2018-08-19T07:59:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,417 | h | #include "stdafx.h"
#include <iostream>
#include <utility>
#include <string>
#define MGPIO_API __declspec(dllexport)
#define GPIO_Check 0xFE
#define pPinInit__ID 0xE1
#define pPinDeInit__ID 0xE2
#define pPinOutPut__ID 0xE3
#define pPinReadBit__ID 0xE4
#define GPIORIGHT 0xFE
typedef enum {
GPIOA = 0x08,
GPIOB = 0x0C,
GPIOC = 0x10,
GPIOD = 0x14,
GPIOE = 0x18,
GPIOF = 0x1C,
GPIOG = 0x20
}GPIOIO_Type;
typedef enum {
GPIO_Pin_0 = 0x01,
GPIO_Pin_1 = 0x02,
GPIO_Pin_2 = 0x04,
GPIO_Pin_3 = 0x08,
GPIO_Pin_4 = 0x41,
GPIO_Pin_5 = 0x42,
GPIO_Pin_6 = 0x44,
GPIO_Pin_7 = 0x48,
GPIO_Pin_8 = 0x81,
GPIO_Pin_9 = 0x82,
GPIO_Pin_10 = 0x84,
GPIO_Pin_11 = 0x88,
GPIO_Pin_12 = 0xC1,
GPIO_Pin_13 = 0xC2,
GPIO_Pin_14 = 0xC4,
GPIO_Pin_15 = 0xC8,
}GPIOPIN_Type;
typedef enum {
GPIO_Mode_AIN = 0x00,
GPIO_Mode_IN_FLOATING = 0x04,
GPIO_Mode_IPD = 0x28,
GPIO_Mode_IPU = 0x48,
GPIO_Mode_Out_OD = 0x14,
GPIO_Mode_Out_PP = 0x10,
GPIO_Mode_AF_OD = 0x1C,
GPIO_Mode_AF_PP = 0x18
}GPIOMODE_Type;
typedef enum
{
GPIO_Speed_10MHz = 1,
GPIO_Speed_2MHz,
GPIO_Speed_50MHz
}GPIOSpeed_Type;
typedef enum
{
Bit_LOW= 0,
Bit_HIGH
}BitAction;
class MGPIO_API MGPIO {
public:
MGPIO();
~MGPIO();
virtual std::pair<unsigned short, unsigned char*> PinInit(GPIOIO_Type IO, GPIOPIN_Type Pin, GPIOMODE_Type Mode, GPIOSpeed_Type Speed);
virtual std::pair<unsigned short, unsigned char*> PinDeInit(GPIOIO_Type IO);
virtual std::pair<unsigned short, unsigned char*> PinOutPut(GPIOIO_Type IO, GPIOPIN_Type Pin, BitAction Level);
virtual std::pair<unsigned short, unsigned char*> PinReadBit(GPIOIO_Type IO, GPIOPIN_Type Pin);
virtual std::pair<unsigned short, unsigned char*> MGPIOSerialFeedBack();
virtual std::pair<unsigned short, unsigned char*> MGPIOWifiFeedBack(unsigned char ID);
virtual bool GPIO_FeedBack(unsigned char ID, unsigned char *Msg);
virtual bool GPIO_FeedBack(unsigned char ID, unsigned char *Msg,unsigned char * readback);
unsigned char GPIO_RIGHT = 0x00;
private:
unsigned char *sendout_;
bool GPIO_ID_CHECK_ = false;
bool GPIO_PARAM_CHECK_ = false;
bool GPIO_CHECK_ = false;
unsigned char continue_count = 0;
#define GPIO_FBInit() GPIO_ID_CHECK_ = false;GPIO_CHECK_ = false;GPIO_PARAM_CHECK_ = false;continue_count=0;
#define IS_GPIO_SPEED(SPEED) (((SPEED) == GPIO_Speed_10MHz) || ((SPEED) == GPIO_Speed_2MHz) || \
((SPEED) == GPIO_Speed_50MHz))
#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_Mode_AIN) || ((MODE) == GPIO_Mode_IN_FLOATING) || \
((MODE) == GPIO_Mode_IPD) || ((MODE) == GPIO_Mode_IPU) || \
((MODE) == GPIO_Mode_Out_OD) || ((MODE) == GPIO_Mode_Out_PP) || \
((MODE) == GPIO_Mode_AF_OD) || ((MODE) == GPIO_Mode_AF_PP))
#define IS_GPIO_BIT_ACTION(ACTION) (((ACTION) == Bit_LOW) || ((ACTION) == Bit_HIGH))
#define IS_GET_GPIO_PIN(PIN) (((PIN) == GPIO_Pin_0) || \
((PIN) == GPIO_Pin_1) || \
((PIN) == GPIO_Pin_2) || \
((PIN) == GPIO_Pin_3) || \
((PIN) == GPIO_Pin_4) || \
((PIN) == GPIO_Pin_5) || \
((PIN) == GPIO_Pin_6) || \
((PIN) == GPIO_Pin_7) || \
((PIN) == GPIO_Pin_8) || \
((PIN) == GPIO_Pin_9) || \
((PIN) == GPIO_Pin_10) || \
((PIN) == GPIO_Pin_11) || \
((PIN) == GPIO_Pin_12) || \
((PIN) == GPIO_Pin_13) || \
((PIN) == GPIO_Pin_14) || \
((PIN) == GPIO_Pin_15))
#define IS_GPIO_ALL_PERIPH(PERIPH) (((PERIPH) == GPIOA) || \
((PERIPH) == GPIOB) || \
((PERIPH) == GPIOC) || \
((PERIPH) == GPIOD) || \
((PERIPH) == GPIOE) || \
((PERIPH) == GPIOF) || \
((PERIPH) == GPIOG))
bool IS_PARAMS(bool JUDGE);
bool IS_RIGHT(unsigned char param1, unsigned char param2);
};
| [
"33600719+JameScottX@users.noreply.github.com"
] | 33600719+JameScottX@users.noreply.github.com |
24d560bce905db7299b5526edbd5e302dc48f9dc | abc4cd2f20e873ae23b969252813987ff028d0df | /Labs/lab09/main.cpp | bc4b41158e2579201ccee2f844dde2d4b5877d34 | [] | no_license | Reido50/CSE-232 | 7b291440d4c733336464bb4513aca28a5e978dd3 | 6bd6af37a4ed85d5d854b09fb64d2de27072eba2 | refs/heads/master | 2022-04-24T17:32:05.725968 | 2020-04-26T18:19:09 | 2020-04-26T18:19:09 | 233,287,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 979 | cpp | #include<iostream>
#include<string>
using std::cout; using std::endl;
using std::string;
#include "math_vector.h"
int main (){
MathVector v1;
MathVector v2(3,2);
MathVector v3(10,12);
cout << "V1:" << vec_to_str(v1)
<< ", V2:" << vec_to_str(v2)
<< ", V3:" << vec_to_str(v3)
<< endl;
MathVector add_result = v1.add(v2);
cout << "Sum of v1 and v2 is: " << vec_to_str(add_result) << endl;
MathVector add_result2 = v2.add(v3);
cout << "Sum of v2 and v3 is: " << vec_to_str(add_result2) << endl;
long scalar=20;
MathVector mult_result = v2.mult(scalar);
cout << "mult of v2 and " << scalar << " is: " << vec_to_str(mult_result) << endl;
long long_result = v1.mult(v2);
cout << "mult of v1 and v2 is: " << long_result << endl;
long long_result2 = v2.mult(v3);
cout << "mult of v2 and v3 is: " << long_result2 << endl;
double dbl_result = v2.magnitude();
cout << "magnitude of v2 is: " << dbl_result << endl;
}
| [
"reidoharry50@gmail.com"
] | reidoharry50@gmail.com |
71ad8926f751b5cde1ba559705235ef061cf1ca7 | 6b68d51a5e78f09ac3c0ce618c22f3d94a9ba4d8 | /src/rpcdump.cpp | 4077bd1a976163a72e435a3ba087ea61d2249ddf | [
"LicenseRef-scancode-other-permissive"
] | permissive | systemgregorypc/a1xcoin | f9e5f883fa33a3e6a427c306547d1ba2a32f9370 | e64dbf3d7220161ccbc58d9b600e222de4bd2df0 | refs/heads/master | 2021-05-09T11:12:11.036599 | 2018-09-10T05:44:50 | 2018-09-10T05:44:50 | 118,985,262 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,623 | cpp | // Copyright (c) 2009-2012 Bitcoin Developers
// Copyright (c) 2012-2015 The Peercoin developers
// Copyright (c) 2018 The a1xcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h" // for pwalletMain
#include "bitcoinrpc.h"
#include "ui_interface.h"
#include "base58.h"
#include <boost/lexical_cast.hpp>
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#define printf OutputDebugStringF
using namespace json_spirit;
using namespace std;
extern Object JSONRPCError(int code, const string& message);
class CTxDump
{
public:
CBlockIndex *pindex;
int64 nValue;
bool fSpent;
CWalletTx* ptx;
int nOut;
CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
{
pindex = NULL;
nValue = 0;
fSpent = false;
this->ptx = ptx;
this->nOut = nOut;
}
};
Value importprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"importprivkey <paycoinprivkey> [label]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(-5,"Invalid private key");
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockMintOnly) // a1xcoin: no importprivkey in mint-only mode
throw JSONRPCError(-102, "Wallet is unlocked for minting only (unlock with walletpassphrase).");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
CKeyID vchAddress = key.GetPubKey().GetID();
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->SetAddressBookName(vchAddress, strLabel);
if (!pwalletMain->AddKey(key))
throw JSONRPCError(-4,"Error adding key to wallet");
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
}
MainFrameRepaint();
return Value::null;
}
Value dumpprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey <a1xcoinaddress>\n"
"Reveals the private key corresponding to <a1xcoinaddress>.");
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(-5, "Invalid a1xcoin address");
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockMintOnly) // paycoin: no dumpprivkey in mint-only mode
throw JSONRPCError(-102, "Wallet is unlocked for minting only (unlock with walletpassphrase).");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(-3, "Address does not refer to a key");
CSecret vchSecret;
bool fCompressed;
if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed))
throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret, fCompressed).ToString();
}
| [
"noreply@github.com"
] | noreply@github.com |
08591be038a2027e9bea529d273d58e8b43156d9 | 8f4678d6c0ba8ec98a6bd5ecef800a3f51751937 | /Demo/BulletPhysics.cpp | eddde90c1bc5a8ae9981c31c3547e00d7ea07d28 | [] | no_license | Lateks/physics-demo | a01858b5781b4f6d5993ce7b0bd4534e41ec4b92 | 24e655744b66ca7c7af2b37afb075f3e3d853dfa | refs/heads/master | 2021-01-22T03:13:35.295427 | 2013-05-26T08:23:55 | 2013-05-26T08:23:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,081 | cpp | #include "BulletPhysics.h"
#include "BulletPhysicsObject.h"
#include "GameActor.h"
#include "WorldTransformComponent.h"
#include "GameData.h"
#include "IEventManager.h"
#include "XMLPhysicsData.h"
#include "Events.h"
#include "BulletConversions.h"
#include "BSPConverter.h"
#include <btBulletCollisionCommon.h>
#include <btBulletDynamicsCommon.h>
#include <LinearMath\btGeometryUtil.h>
#include <cassert>
#include <vector>
#include <memory>
#include <algorithm>
#include <cmath>
#include <set>
#include <stdexcept>
#include <iostream> // used for error output
using std::shared_ptr;
using std::weak_ptr;
using std::unique_ptr;
namespace GameEngine
{
namespace Physics
{
typedef std::pair<const btRigidBody *, const btRigidBody *> CollisionPair;
typedef std::set<CollisionPair> CollisionPairs;
struct CollisionObject;
struct BulletPhysicsData
{
// CONSTRUCTORS / DESTRUCTORS:
BulletPhysicsData(float worldScale, float contactThreshold, float collisionMargin)
: m_worldScaleFactor(worldScale), m_contactThreshold(contactThreshold * m_worldScaleFactor),
m_collisionMargin(collisionMargin * m_worldScaleFactor), m_initialized(false), m_constraintIdCounter(0) { }
virtual ~BulletPhysicsData();
// MEMBERS:
float m_worldScaleFactor;
float m_contactThreshold;
float m_collisionMargin;
bool m_initialized;
ConstraintID m_constraintIdCounter;
// Bullet-related:
unique_ptr<btDynamicsWorld> m_pDynamicsWorld; // - manages the other required components (declared below)
unique_ptr<btBroadphaseInterface> m_pCollisionBroadPhase; // - manages the first (rough) phase of collision detection
unique_ptr<btCollisionDispatcher> m_pCollisionDispatcher; // - manages the more accurate second phase of collision detection
unique_ptr<btConstraintSolver> m_pConstraintSolver; // - manages objects' freedom of motion
unique_ptr<btDefaultCollisionConfiguration> m_pCollisionConfig; // - memory usage configuration
unique_ptr<XMLPhysicsData> m_physicsMaterialData;
/* Store the rigid bodies related to game actors.
* Several rigid bodies can be related to a single actor, but each
* rigid body may only have one actor related to it. At the moment
* only "static" actors (basically map elements in the demo) can
* own several rigid bodies.
*/
std::map<ActorID, std::shared_ptr<BulletPhysicsObject>> m_actorToBulletPhysicsObjectMap;
std::map<const btRigidBody*, ActorID> m_rigidBodyToActorMap;
std::map<ConstraintID, btTypedConstraint*> m_constraintMap;
// Stores the Bullet collision flags associated with each object type.
std::map<IPhysicsEngine::PhysicsObjectType, int> m_collisionFlags;
std::shared_ptr<BulletPhysicsObject> GetPhysicsObject(ActorID id) const;
ActorID GetActorID(const btRigidBody *pBody) const;
CollisionPairs m_previousTickCollisions;
// METHODS:
bool VInitializeSystems(const std::string& materialFileName);
void AddShape(ActorPtr pActor, btCollisionShape *shape, CollisionObject& object);
void AddSingleBodyShape(ActorPtr pActor, btCollisionShape *shape, CollisionObject& object);
void AddMultiBodyShape(ActorPtr pActor, btCollisionShape *shape, CollisionObject& object);
void SendNewCollisionEvent(const btPersistentManifold *manifold,
const btRigidBody *pBody1, const btRigidBody *pBody2);
void SendSeparationEvent(const btRigidBody *pBody1, const btRigidBody *pBody2);
void RemoveCollisionObject(btCollisionObject *pObj);
void RemoveCollisionPairsFor(btCollisionObject *pObj);
void RemoveConstraintsFor(btRigidBody *pBody);
void CreateRigidBody(ActorPtr pActor, btCollisionShape *shape, CollisionObject& object);
float CalculateMass(CollisionObject& object);
btMotionState *GetMotionStateFrom(const WorldTransformComponent& transform);
// Bullet callbacks.
static void BulletInternalTickCallback(btDynamicsWorld * const pWorld, const btScalar timeStep);
void HandleCallback();
void HandleNewCollisions(CollisionPairs& currentTickCollisions);
void HandleRemovedCollisions(CollisionPairs& currentTickCollisions);
// Applies a function over the rigid bodies of a non-static object.
// (No-op if the actor is a static object.)
void ApplyOnNonStaticBodies(ActorID id, std::function<void(btRigidBody *pBody)>& func);
void SetupSystems();
void CleanUpRigidBodies();
};
// These are temporary objects used passing parameters related to
// building a rigid body.
struct CollisionObject
{
CollisionObject(IPhysicsEngine::PhysicsObjectType type,
const std::string& material,
const std::string& density,
const std::function<float()>& volumeCalculationStrategy,
const std::function<float(float)>& rollingFrictionCalculationStrategy = [] (float friction) { return friction / 3.f; })
: m_objectType(type),
m_calculateVolume(volumeCalculationStrategy),
m_calculateRollingFriction(rollingFrictionCalculationStrategy),
m_material(material), m_density(density) { }
const IPhysicsEngine::PhysicsObjectType m_objectType;
const std::function<float()> m_calculateVolume;
const std::function<float(float)> m_calculateRollingFriction;
const std::string m_material;
const std::string m_density;
};
/****************************************************
* Implementation of the BulletPhysicsFactory class *
****************************************************/
BulletPhysicsFactory::BulletPhysicsFactory(const std::string& materialFilePath,
float worldScale, float contactThreshold, float collisionMargin)
: m_materialFilePath(materialFilePath), m_worldScale(worldScale),
m_contactThreshold(contactThreshold), m_collisionMargin(collisionMargin) { }
std::shared_ptr<IPhysicsEngine> BulletPhysicsFactory::CreatePhysicsEngine() const
{
auto pPhysics = std::shared_ptr<IPhysicsEngine>(
new BulletPhysics(m_worldScale, m_contactThreshold, m_collisionMargin));
if (pPhysics && !pPhysics->VInitEngine(m_materialFilePath))
{
pPhysics.reset();
}
return pPhysics;
}
/********************************************
* Functions for calculating object volumes *
********************************************/
inline float SphereVolume(float radius)
{
return (4.f/3.f) * 3.14159f * pow(radius, 3);
}
inline float BoxVolume(const btVector3& dimensions)
{
return dimensions.x() * dimensions.y() * dimensions.z();
}
// Calculates the axis-aligned bounding box of the given shape
// and the volume for it.
float AABBVolume(btCollisionShape *shape)
{
btVector3 aabbMin, aabbMax;
shape->getAabb(btTransform::getIdentity(), aabbMin, aabbMax);
const btVector3 dimensions = aabbMax - aabbMin;
return BoxVolume(dimensions);
}
/************************************************
* Implementation of the BulletPhysics class. *
************************************************/
BulletPhysics::BulletPhysics(float worldScale, float contactThreshold, float collisionMargin)
: m_pData(new BulletPhysicsData(worldScale, contactThreshold, collisionMargin))
{
std::cerr << "BulletPhysics (info): world scale is " << m_pData->m_worldScaleFactor
<< ", contact threshold is set to " << m_pData->m_contactThreshold
<< ", collision margin is " << m_pData->m_collisionMargin << "."
<< std::endl;
}
BulletPhysics::~BulletPhysics() { }
bool BulletPhysics::VInitEngine(const std::string& materialFileName)
{
std::cerr << "BulletPhysics (info): using material file '" << materialFileName << "'." << std::endl;
return m_pData->VInitializeSystems(materialFileName);
}
/* Updates an actor's world transform with the new position and rotation.
Note that synchronization is always only done from BulletPhysics to
the actor's global world transform, not the other way around. That meand
that with this implementation, no one else can move these actors.
Note, however, that the only actors moving in this implementation are
dynamic, and therefore are supposed to be fully controlled by the
physics system (unless user controlled constraints are in place).
Other user or AI movable objects would need to be implemented as kinematic
objects.
*/
void UpdateWorldTransform(ActorPtr pActor, const Vec3& pos, const Quaternion& rot)
{
shared_ptr<GameData> pGame = GameData::GetInstance();
WorldTransformComponent& worldTrans = pActor->GetWorldTransform();
bool changed = false;
if (worldTrans.GetRotation() != rot)
{
worldTrans.SetRotation(rot);
changed = true;
}
if (worldTrans.GetPosition() != pos)
{
worldTrans.SetPosition(pos);
changed = true;
}
if (changed)
{
auto pEventManager = pGame->GetEventManager();
if (pEventManager)
{
std::shared_ptr<Events::IEventData> event =
std::make_shared<Events::ActorMoveEvent>(pGame->CurrentTimeMs(), pActor->GetID());
pEventManager->VQueueEvent(event);
}
}
}
// Update the locations of all actors involved in the physics
// simulation and signal changes in location with events.
void BulletPhysics::VSyncScene()
{
std::shared_ptr<GameData> pGame = GameData::GetInstance();
for (auto it = m_pData->m_actorToBulletPhysicsObjectMap.begin();
it != m_pData->m_actorToBulletPhysicsObjectMap.end(); it++)
{
ActorID id = it->first;
std::shared_ptr<BulletPhysicsObject> pObject = it->second;
assert(pObject);
auto pActor = pGame->GetActor(id);
if (!pActor || pObject->IsStatic() || pObject->GetNumBodies() == 0)
continue;
btRigidBody *pBody = pObject->GetRigidBodies()[0];
const Quaternion rot = btQuaternion_to_Quaternion(pBody->getOrientation());
const Vec3 pos = btVector3_to_Vec3(pBody->getCenterOfMassPosition(), m_pData->m_worldScaleFactor);
UpdateWorldTransform(pActor, pos, rot);
}
}
void BulletPhysics::VUpdateSimulation(float deltaSec)
{
m_pData->m_pDynamicsWorld->stepSimulation(deltaSec, 4);
}
void BulletPhysics::VAddSphere(ActorPtr pActor, float radius,
IPhysicsEngine::PhysicsObjectType type, const std::string& density,
const std::string& material)
{
if (!pActor)
return;
float btRadius = m_pData->m_worldScaleFactor * radius;
btSphereShape * const sphereShape = new btSphereShape(btRadius);
CollisionObject object(type, material, density,
[btRadius] () { return SphereVolume(btRadius); },
[] (float friction) { return friction / 5.f; });
m_pData->AddShape(pActor, sphereShape, object);
}
void BulletPhysics::VAddBox(ActorPtr pActor, const Vec3& dimensions,
IPhysicsEngine::PhysicsObjectType type, const std::string& density, const std::string& material)
{
if (!pActor)
return;
btVector3 btDimensions = Vec3_to_btVector3(dimensions, m_pData->m_worldScaleFactor);
btBoxShape * const boxShape = new btBoxShape(0.5f * btDimensions);
CollisionObject object(type, material, density,
[btDimensions] () { return BoxVolume(btDimensions); });
m_pData->AddShape(pActor, boxShape, object);
}
void BulletPhysics::VAddConvexMesh(ActorPtr pActor, std::vector<Vec3>& vertices,
IPhysicsEngine::PhysicsObjectType type, const std::string& density, const std::string& material)
{
if (!pActor || vertices.empty())
return;
// Compute the convex hull of the given vertex cloud.
btConvexHullShape * const convexShape = new btConvexHullShape();
for(Vec3& vertex : vertices)
{
convexShape->addPoint(Vec3_to_btVector3(vertex, this->m_pData->m_worldScaleFactor));
}
CollisionObject object(type, material, density,
[convexShape] () { return AABBVolume(convexShape); });
m_pData->AddShape(pActor, convexShape, object);
}
void BulletPhysics::VAddConvexMesh(ActorPtr pActor, std::vector<Vec4>& planeEquations,
IPhysicsEngine::PhysicsObjectType type, const std::string& density, const std::string& material)
{
if (!pActor || planeEquations.empty())
return;
btAlignedObjectArray<btVector3> vertices;
btAlignedObjectArray<btVector3> btPlaneEquations;
float scaling = m_pData->m_worldScaleFactor;
for(Vec4& eq : planeEquations)
{
btVector3 btEq = Vec4_to_btVector3(eq);
btEq[3] *= scaling;
btPlaneEquations.push_back(btEq);
}
btGeometryUtil::getVerticesFromPlaneEquations(btPlaneEquations, vertices);
btConvexHullShape *convexShape = new btConvexHullShape(&(vertices[0].getX()), vertices.size());
CollisionObject object(type, material, density,
[convexShape] () { return AABBVolume(convexShape); });
m_pData->AddShape(pActor, convexShape, object);
}
void BulletPhysics::VLoadBspMap(ActorPtr pActor, BspLoader& bspLoad, const std::string& material)
{
if (!pActor)
return;
Utils::ConvertBsp(bspLoad,
[this, pActor, &material] (std::vector<Vec4> planeEquations)
{
this->VAddConvexMesh(pActor, planeEquations,
IPhysicsEngine::PhysicsObjectType::STATIC, "", material);
});
}
void BulletPhysics::VRemoveActor(ActorID id)
{
auto pObject = m_pData->GetPhysicsObject(id);
if (pObject)
{
std::vector<btRigidBody*> bodies = pObject->GetRigidBodies();
if (bodies.size() > 0)
{
for(btRigidBody *pBody : bodies)
{
this->m_pData->RemoveCollisionObject(pBody);
this->m_pData->m_rigidBodyToActorMap.erase(pBody);
}
m_pData->m_actorToBulletPhysicsObjectMap.erase(id);
}
}
}
void BulletPhysics::VApplyForce(ActorID id, const Vec3& direction, float magnitude)
{
const btVector3 forceVector = Vec3_to_btVector3(direction).normalized()
* magnitude * m_pData->m_worldScaleFactor;
m_pData->ApplyOnNonStaticBodies(id, std::function<void(btRigidBody *pBody)>(
[&forceVector] (btRigidBody *pBody)
{
pBody->applyCentralImpulse(forceVector);
}));
}
void BulletPhysics::VApplyTorque(ActorID id, const Vec3& direction, float magnitude)
{
const btVector3 torqueVector = Vec3_to_btVector3(direction).normalized()
* magnitude * -1.f * m_pData->m_worldScaleFactor;
m_pData->ApplyOnNonStaticBodies(id, std::function<void(btRigidBody *pBody)>(
[&torqueVector] (btRigidBody *pBody)
{
pBody->applyTorqueImpulse(torqueVector);
}));
}
void BulletPhysics::VStopActor(ActorID id)
{
VSetLinearVelocity(id, Vec3(1, 0, 0), 0.f);
VSetAngularVelocity(id, Vec3(1, 0, 0), 0.f);
}
void BulletPhysics::VSetLinearVelocity(ActorID id, const Vec3& direction, float magnitude)
{
const btVector3 velocity = Vec3_to_btVector3(direction).normalized()
* magnitude * m_pData->m_worldScaleFactor;
m_pData->ApplyOnNonStaticBodies(id, std::function<void(btRigidBody *pBody)>(
[&velocity] (btRigidBody *pBody)
{
pBody->setLinearVelocity(velocity);
}));
}
void BulletPhysics::VSetAngularVelocity(ActorID id, const Vec3& rotationAxis, float radiansPerSecond)
{
// Multiply radians by -1 to make rotations work according to the "right hand rule"
// (same as for torque).
const btVector3 velocity =
Vec3_to_btVector3(rotationAxis).normalized() * radiansPerSecond * -1.f;
m_pData->ApplyOnNonStaticBodies(id, std::function<void(btRigidBody *pBody)>(
[&velocity] (btRigidBody *pBody)
{
pBody->setAngularVelocity(velocity);
}));
}
void BulletPhysics::VSetGlobalGravity(Vec3& gravity)
{
assert(m_pData && m_pData->m_pDynamicsWorld);
if (m_pData && m_pData->m_pDynamicsWorld)
{
m_pData->m_pDynamicsWorld->setGravity(
Vec3_to_btVector3(gravity, m_pData->m_worldScaleFactor));
}
else
{
std::cerr << "BulletPhysics (warning): Cannot set gravity. Dynamics world not present." << std::endl;
}
}
Vec3 BulletPhysics::VGetGlobalGravity()
{
assert(m_pData && m_pData->m_pDynamicsWorld);
if (m_pData && m_pData->m_pDynamicsWorld)
{
return btVector3_to_Vec3(
m_pData->m_pDynamicsWorld->getGravity(), m_pData->m_worldScaleFactor);
}
else
{
std::cerr << "BulletPhysics (warning): Cannot get gravity. Dynamics world not present. Returning zero vector." << std::endl;
return Vec3(0, 0, 0);
}
}
// Use a raycast to get the first non-static body that was hit (for picking objects).
ActorID BulletPhysics::VGetClosestActorHit(Vec3& rayFrom, Vec3& rayTo, Vec3& hitPosition) const
{
btVector3 btRayFrom = Vec3_to_btVector3(rayFrom, m_pData->m_worldScaleFactor);
btVector3 btRayTo = Vec3_to_btVector3(rayTo, m_pData->m_worldScaleFactor);
btCollisionWorld::AllHitsRayResultCallback rayCallback(btRayFrom, btRayTo);
m_pData->m_pDynamicsWorld->rayTest(btRayFrom, btRayTo, rayCallback);
ActorID actorHit = 0;
float closestHitDistance = FLT_MAX;
btVector3 btPickPosition;
if (rayCallback.hasHit())
{
/* The collection of collision objects in the raycallback does not appear
* to be ordered by distance, so we need to keep track of the closest
* hit so far. Triggers are ignored and picking is not possible through
* walls or other static non-trigger objects.
*
* btCollisionWorld::ClosestRayResultCallback cannot be used here because we
* want to be able to pick objects that are inside trigger bodies, in which
* case the ClosestRayResultCallback would only detect a collision with the
* trigger body, which is unpickable.
*/
for (int i = 0; i < rayCallback.m_collisionObjects.size(); i++)
{
const btRigidBody *pBody = btRigidBody::upcast(rayCallback.m_collisionObjects[i]);
assert(pBody);
if (pBody)
{
auto actorId = m_pData->m_rigidBodyToActorMap[pBody];
auto hitPosition = rayCallback.m_hitPointWorld[i];
float objectDistance = (hitPosition - btRayFrom).length();
if (pBody->isStaticObject())
{
if (!m_pData->GetPhysicsObject(actorId)->IsTrigger() && objectDistance < closestHitDistance)
{
actorHit = 0;
closestHitDistance = objectDistance;
}
}
else if (objectDistance < closestHitDistance)
{
actorHit = actorId;
btPickPosition = hitPosition;
closestHitDistance = objectDistance;
}
}
}
}
if (actorHit)
{
hitPosition = btVector3_to_Vec3(btPickPosition, m_pData->m_worldScaleFactor);
}
return actorHit;
}
Vec3 BulletPhysics::VGetLinearVelocity(ActorID id)
{
std::shared_ptr<BulletPhysicsObject> pObject = m_pData->GetPhysicsObject(id);
if (!pObject || !pObject->IsDynamic() || pObject->GetNumBodies() != 1)
return Vec3(0, 0, 0);
return btVector3_to_Vec3(pObject->GetRigidBodies()[0]->getLinearVelocity(), m_pData->m_worldScaleFactor);
}
Vec3 BulletPhysics::VGetAngularVelocity(ActorID id)
{
std::shared_ptr<BulletPhysicsObject> pObject = m_pData->GetPhysicsObject(id);
if (!pObject || !pObject->IsDynamic() || pObject->GetNumBodies() != 1)
return Vec3(0, 0, 0);
// No scaling here, value is in radians per second.
// Invert sign again to take the right-hand rule into account.
return btVector3_to_Vec3(-1.f * pObject->GetRigidBodies()[0]->getAngularVelocity());
}
void BulletPhysics::VSetAngularFactor(ActorID id, const Vec3& factor)
{
std::shared_ptr<BulletPhysicsObject> pObject = m_pData->GetPhysicsObject(id);
if (!pObject || !pObject->IsDynamic() || pObject->GetNumBodies() != 1)
return;
pObject->GetRigidBodies()[0]->setAngularFactor(Vec3_to_btVector3(factor, m_pData->m_worldScaleFactor));
}
Vec3 BulletPhysics::VGetAngularFactor(ActorID id)
{
std::shared_ptr<BulletPhysicsObject> pObject = m_pData->GetPhysicsObject(id);
if (!pObject || !pObject->IsDynamic() || pObject->GetNumBodies() != 1)
return Vec3(0, 0, 0);
return btVector3_to_Vec3(pObject->GetRigidBodies()[0]->getAngularFactor(), m_pData->m_worldScaleFactor);
}
// I could not find documentation for the parameters of DOF6 constraints,
// (e.g. BT_CONSTRAINT_STOP_CFM - these are not mentioned in the Bullet
// user manual as far as I can see) so the code in this function is
// basically from the Bullet examples, refactored for parameterisation and commented.
btGeneric6DofConstraint *CreateUniformDOF6Constraint(
btRigidBody* pBody, btTransform *pTransform,
float constraintForceMix, float constraintForceErrorMargin)
{
btGeneric6DofConstraint* dof6 = new btGeneric6DofConstraint(*pBody, *pTransform, false);
btVector3 zeroVector(0,0,0);
dof6->setLinearLowerLimit(zeroVector);
dof6->setLinearUpperLimit(zeroVector);
dof6->setAngularLowerLimit(zeroVector);
dof6->setAngularUpperLimit(zeroVector);
/* Apparently this is the "constraint force mixing factor when
* joint is at limit" (?). From testing, it appears that the value
* should be between 0 and 1 or unexpected bad things (TM) will happen.
* At 1.0 the constraint gets very wonky but I can barely
* notice any difference between 0.1 and 0.8.
*/
dof6->setParam(BT_CONSTRAINT_STOP_CFM, constraintForceMix, 0);
dof6->setParam(BT_CONSTRAINT_STOP_CFM, constraintForceMix, 1);
dof6->setParam(BT_CONSTRAINT_STOP_CFM, constraintForceMix, 2);
dof6->setParam(BT_CONSTRAINT_STOP_CFM, constraintForceMix, 3);
dof6->setParam(BT_CONSTRAINT_STOP_CFM, constraintForceMix, 4);
dof6->setParam(BT_CONSTRAINT_STOP_CFM, constraintForceMix, 5);
// Set the error margins for the six degrees of freedom (?)
dof6->setParam(BT_CONSTRAINT_STOP_ERP, constraintForceErrorMargin, 0);
dof6->setParam(BT_CONSTRAINT_STOP_ERP, constraintForceErrorMargin, 1);
dof6->setParam(BT_CONSTRAINT_STOP_ERP, constraintForceErrorMargin, 2);
dof6->setParam(BT_CONSTRAINT_STOP_ERP, constraintForceErrorMargin, 3);
dof6->setParam(BT_CONSTRAINT_STOP_ERP, constraintForceErrorMargin, 4);
dof6->setParam(BT_CONSTRAINT_STOP_ERP, constraintForceErrorMargin, 5);
return dof6;
}
ConstraintID BulletPhysics::VAddDOF6Constraint(ActorID actorID, const Vec3& pivotPosition)
{
std::shared_ptr<BulletPhysicsObject> pObject = m_pData->GetPhysicsObject(actorID);
if (!pObject || !pObject->IsDynamic()) // cannot create constraint for static or kinematic objects
{
std::cerr << "BulletPhysics: Failed to create constraint. Invalid physics object given." << std::endl;
return 0;
}
assert(pObject->GetNumBodies() == 1);
if (pObject->GetNumBodies() == 1)
{
btRigidBody *pBody = pObject->GetRigidBodies()[0];
pBody->setActivationState(DISABLE_DEACTIVATION);
btVector3 btPivotPosition = Vec3_to_btVector3(pivotPosition, m_pData->m_worldScaleFactor);
btVector3 objectSpacePivot = pBody->getCenterOfMassTransform().inverse() * btPivotPosition;
btTransform transform;
transform.setIdentity();
transform.setOrigin(objectSpacePivot);
btGeneric6DofConstraint* btPickConstraint =
CreateUniformDOF6Constraint(pBody, &transform, 0.8f, 0.1f);
m_pData->m_pDynamicsWorld->addConstraint(btPickConstraint, true);
ConstraintID constraintId = ++m_pData->m_constraintIdCounter;
m_pData->m_constraintMap.insert(std::make_pair(constraintId, btPickConstraint));
auto map = m_pData->m_constraintMap;
return constraintId;
}
return 0;
}
void BulletPhysics::VUpdateDOF6PivotPoint(ConstraintID constraintId, const Vec3& pivotPosition)
{
auto iter = m_pData->m_constraintMap.find(constraintId);
if (iter != m_pData->m_constraintMap.end() && iter->second->getConstraintType() == D6_CONSTRAINT_TYPE)
{
btGeneric6DofConstraint* pDof6PickConstraint =
static_cast<btGeneric6DofConstraint*>(iter->second);
if (pDof6PickConstraint)
{
btVector3 newPivot = Vec3_to_btVector3(pivotPosition, m_pData->m_worldScaleFactor);
pDof6PickConstraint->getFrameOffsetA().setOrigin(newPivot);
}
}
}
void ReactivateBody(btRigidBody &pBody)
{
pBody.forceActivationState(ACTIVE_TAG);
pBody.setDeactivationTime(0.f);
}
void BulletPhysics::VRemoveConstraint(ConstraintID constraintId)
{
auto iter = m_pData->m_constraintMap.find(constraintId);
if (iter != m_pData->m_constraintMap.end())
{
btTypedConstraint *pConstraint = iter->second;
ReactivateBody(pConstraint->getRigidBodyA());
ReactivateBody(pConstraint->getRigidBodyB());
m_pData->m_pDynamicsWorld->removeConstraint(pConstraint);
m_pData->m_constraintMap.erase(iter);
delete pConstraint;
}
}
/*******************************************************
* Implementation of the BulletPhysicsData struct. *
*******************************************************/
std::shared_ptr<BulletPhysicsObject> BulletPhysicsData::GetPhysicsObject(ActorID id) const
{
auto it = m_actorToBulletPhysicsObjectMap.find(id);
if (it != m_actorToBulletPhysicsObjectMap.end())
return it->second;
return std::shared_ptr<BulletPhysicsObject>(nullptr);
}
ActorID BulletPhysicsData::GetActorID(const btRigidBody *pBody) const
{
auto it = m_rigidBodyToActorMap.find(pBody);
assert(it != m_rigidBodyToActorMap.end());
if (it != m_rigidBodyToActorMap.end())
return it->second;
return 0;
}
bool BulletPhysicsData::VInitializeSystems(const std::string& materialFileName)
{
if (m_initialized)
{
std::cerr << "BulletPhysics (warning): Systems already initialized." << std::endl;
return false;
}
m_physicsMaterialData.reset(new XMLPhysicsData());
if (!m_physicsMaterialData->LoadDataFromXML(materialFileName))
{
return false; // XML parsing failed
}
SetupSystems();
if (!m_pCollisionConfig || !m_pCollisionDispatcher ||
!m_pCollisionBroadPhase || !m_pConstraintSolver ||
!m_pDynamicsWorld)
{
return false;
}
m_pDynamicsWorld->setInternalTickCallback(BulletInternalTickCallback);
m_pDynamicsWorld->setWorldUserInfo(this);
m_collisionFlags[IPhysicsEngine::PhysicsObjectType::DYNAMIC] = 0;
m_collisionFlags[IPhysicsEngine::PhysicsObjectType::STATIC] = btRigidBody::CF_STATIC_OBJECT;
m_collisionFlags[IPhysicsEngine::PhysicsObjectType::TRIGGER] =
btRigidBody::CF_STATIC_OBJECT | btRigidBody::CF_NO_CONTACT_RESPONSE;
m_initialized = true;
return true;
}
BulletPhysicsData::~BulletPhysicsData()
{
CleanUpRigidBodies();
}
void BulletPhysicsData::SetupSystems()
{
m_pCollisionConfig.reset(new btDefaultCollisionConfiguration());
m_pCollisionDispatcher.reset(new btCollisionDispatcher(m_pCollisionConfig.get()));
m_pCollisionBroadPhase.reset(new btDbvtBroadphase());
m_pConstraintSolver.reset(new btSequentialImpulseConstraintSolver());
m_pDynamicsWorld.reset(new btDiscreteDynamicsWorld(
m_pCollisionDispatcher.get(), m_pCollisionBroadPhase.get(),
m_pConstraintSolver.get(), m_pCollisionConfig.get()));
}
void BulletPhysicsData::CleanUpRigidBodies()
{
// Iterate backwards to avoid linear-time deletes.
auto collisionObjects = m_pDynamicsWorld->getCollisionObjectArray();
int idx = m_pDynamicsWorld->getNumCollisionObjects() - 1;
while (idx >= 0)
{
RemoveCollisionObject(collisionObjects[idx]);
--idx;
}
}
void BulletPhysicsData::RemoveCollisionPairsFor(btCollisionObject *pObj)
{
// Remove the collision pairs that contain the given collision object.
for (auto it = m_previousTickCollisions.begin(); it != m_previousTickCollisions.end(); )
{
if ((*it).first == pObj || (*it).second == pObj)
{
m_previousTickCollisions.erase(it++);
}
else
{
++it;
}
}
}
void BulletPhysicsData::RemoveConstraintsFor(btRigidBody *pBody)
{
if (pBody)
{
delete pBody->getMotionState();
delete pBody->getCollisionShape();
// destroy related constraints
for (int i = pBody->getNumConstraintRefs()-1; i >= 0; i--)
{
btTypedConstraint *pConstraint = pBody->getConstraintRef(i);
m_pDynamicsWorld->removeConstraint(pConstraint);
delete pConstraint;
}
}
}
void BulletPhysicsData::RemoveCollisionObject(btCollisionObject *pObj)
{
RemoveCollisionPairsFor(pObj);
btRigidBody* pBody = btRigidBody::upcast(pObj);
RemoveConstraintsFor(pBody);
m_pDynamicsWorld->removeCollisionObject(pObj);
delete pObj;
}
void BulletPhysicsData::BulletInternalTickCallback(
btDynamicsWorld * const pWorld, const btScalar timeStep)
{
assert(pWorld);
assert(pWorld->getWorldUserInfo());
if (pWorld && pWorld->getWorldUserInfo())
{
BulletPhysicsData * const pBulletPhysics =
static_cast<BulletPhysicsData*>(pWorld->getWorldUserInfo());
pBulletPhysics->HandleCallback();
}
else
{
std::cerr << "BulletPhysics (warning): Internal tick callback called with invalid parameters." << std::endl;
}
}
void BulletPhysicsData::HandleCallback()
{
CollisionPairs currentTickCollisions;
HandleNewCollisions(currentTickCollisions);
HandleRemovedCollisions(currentTickCollisions);
m_previousTickCollisions = currentTickCollisions;
}
void BulletPhysicsData::HandleNewCollisions(CollisionPairs& currentTickCollisions)
{
// Find the collisions that are new (did not exist on previous tick).
for (int manifoldIdx = 0; manifoldIdx < m_pCollisionDispatcher->getNumManifolds(); ++manifoldIdx)
{
const btPersistentManifold * const pContactManifold =
m_pCollisionDispatcher->getManifoldByIndexInternal(manifoldIdx);
assert(pContactManifold);
if (!pContactManifold)
continue;
const btRigidBody * body1 =
static_cast<const btRigidBody *>(pContactManifold->getBody0());
const btRigidBody * body2 =
static_cast<const btRigidBody *>(pContactManifold->getBody1());
// Keep rigid body pointers always in the same order to make
// comparisons between collision pairs easier.
if (body1 > body2)
{
std::swap(body1, body2);
}
for (int i = 0; i < pContactManifold->getNumContacts(); ++i)
{
/* Bullet registers the collision slightly before it actually happens
(regardless of collision margins etc.), so check the actual contact
point distance to see whether the objects are touching.
Note that this reports collisions between rigid bodies. If an actor
(say, the world map) has multiple rigid bodies, a collision or separation
event may be reported several times in a row for the same pair of actors
(but not rigid bodies).
*/
if (pContactManifold->getContactPoint(i).getDistance() < m_contactThreshold)
{
const CollisionPair newPair = std::make_pair(body1, body2);
currentTickCollisions.insert(newPair);
if (m_previousTickCollisions.find(newPair) == m_previousTickCollisions.end())
{
SendNewCollisionEvent(pContactManifold, body1, body2);
}
break; // found contact, no need to search this manifold further
}
}
}
}
void BulletPhysicsData::HandleRemovedCollisions(CollisionPairs& currentTickCollisions)
{
// Find the collisions that existed on the last tick but not on this tick.
CollisionPairs removedCollisions;
std::set_difference(m_previousTickCollisions.begin(),
m_previousTickCollisions.end(),
currentTickCollisions.begin(), currentTickCollisions.end(),
std::inserter(removedCollisions, removedCollisions.end()));
for(auto &pair : removedCollisions)
{
const btRigidBody * const body1 = pair.first;
const btRigidBody * const body2 = pair.second;
this->SendSeparationEvent(body1, body2);
}
}
void BulletPhysicsData::ApplyOnNonStaticBodies(ActorID id,
std::function<void(btRigidBody *pBody)>& func)
{
std::shared_ptr<BulletPhysicsObject> pObject = GetPhysicsObject(id);
assert(pObject);
if (pObject && !pObject->IsStatic() && pObject->GetNumBodies() > 0)
{
auto &bodies = pObject->GetRigidBodies();
std::for_each(bodies.begin(), bodies.end(), func);
}
else
{
std::cerr << "BulletPhysics (warning): Rigid body dynamics altering method called for invalid physics object." << std::endl;
}
}
void BulletPhysicsData::AddShape(ActorPtr pActor, btCollisionShape *shape, CollisionObject& object)
{
assert (pActor);
if (!pActor)
{
delete shape;
return;
}
switch (object.m_objectType)
{
case IPhysicsEngine::PhysicsObjectType::DYNAMIC:
AddSingleBodyShape(pActor, shape, object);
break;
case IPhysicsEngine::PhysicsObjectType::STATIC:
AddMultiBodyShape(pActor, shape, object);
break;
case IPhysicsEngine::PhysicsObjectType::TRIGGER:
AddSingleBodyShape(pActor, shape, object);
break;
default: // Note: Kinematic objects are not supported.
delete shape;
throw std::domain_error("BulletPhysics: Unsupported physics object type given.");
}
}
void BulletPhysicsData::AddSingleBodyShape(ActorPtr pActor, btCollisionShape *shape, CollisionObject& object)
{
ActorID id = pActor->GetID();
auto iter = m_actorToBulletPhysicsObjectMap.find(id);
assert(iter == m_actorToBulletPhysicsObjectMap.end());
if (iter != m_actorToBulletPhysicsObjectMap.end())
{
std::cerr << "BulletPhysics (warning): Trying to add a multi-body non-static or trigger object or "
<< "a non-static or trigger body to a static object. Remove existing bodies before adding a new "
<< "non-static body for actor " << id << "." << std::endl;
delete shape;
return;
}
m_actorToBulletPhysicsObjectMap[id].reset(new BulletPhysicsObject(id, object.m_objectType));
CreateRigidBody(pActor, shape, object);
}
// Note: (currently) in this implementation, only static non-trigger objects may have
// several rigid bodies.
void BulletPhysicsData::AddMultiBodyShape(ActorPtr pActor, btCollisionShape *shape, CollisionObject& object)
{
assert(object.m_objectType == IPhysicsEngine::PhysicsObjectType::STATIC);
ActorID id = pActor->GetID();
auto objectIt = m_actorToBulletPhysicsObjectMap.find(id);
if (objectIt == m_actorToBulletPhysicsObjectMap.end())
{
m_actorToBulletPhysicsObjectMap[id].reset(
new BulletPhysicsObject(id, object.m_objectType));
}
else if (objectIt->second->GetPhysicsType() != object.m_objectType)
{
std::cerr << "BulletPhysics (warning): Cannot add a static body for an existing non-static actor." << std::endl;
delete shape;
return;
}
CreateRigidBody(pActor, shape, object);
}
float BulletPhysicsData::CalculateMass(CollisionObject& object)
{
if (object.m_objectType == IPhysicsEngine::PhysicsObjectType::STATIC ||
object.m_objectType == IPhysicsEngine::PhysicsObjectType::TRIGGER)
{
return 0.f; // objects with zero mass are regarded as immovable by bullet
}
else
{
float density = object.m_density.empty() ?
0.f : m_physicsMaterialData->LookupDensity(object.m_density);
float mass = density > 0.f ? object.m_calculateVolume() * density : 0.f;
if (mass == 0.f)
{
std::cerr << "BulletPhysics (warning): non-static object with 0 mass created. Is the density identifier valid?" << std::endl;
}
return mass;
}
}
void BulletPhysicsData::CreateRigidBody(ActorPtr pActor, btCollisionShape *shape, CollisionObject& object)
{
static MaterialData defaultMaterial(0.f, 0.f);
float mass = CalculateMass(object);
btMotionState *motionState = GetMotionStateFrom(pActor->GetWorldTransform());
btVector3 localInertia(0, 0, 0);
if (mass > 0.f)
shape->calculateLocalInertia(mass, localInertia);
shape->setMargin(m_collisionMargin);
btRigidBody::btRigidBodyConstructionInfo rbInfo(
mass, motionState, shape, localInertia);
if (object.m_objectType != IPhysicsEngine::PhysicsObjectType::TRIGGER) // triggers have no use for these properties
{
const MaterialData& matData = object.m_material.empty() ?
defaultMaterial : m_physicsMaterialData->LookupMaterial(object.m_material);
rbInfo.m_restitution = matData.m_restitution;
rbInfo.m_friction = matData.m_friction; // this is the sliding friction (as opposed to rolling friction)
rbInfo.m_rollingFriction = object.m_calculateRollingFriction(matData.m_friction);
}
btRigidBody * const pBody = new btRigidBody(rbInfo);
if (pBody->getRollingFriction() > 0.f)
{
pBody->setAnisotropicFriction(shape->getAnisotropicRollingFrictionDirection(),
btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
}
pBody->setCollisionFlags(pBody->getCollisionFlags() | m_collisionFlags[object.m_objectType]);
m_pDynamicsWorld->addRigidBody(pBody);
ActorID id = pActor->GetID();
m_actorToBulletPhysicsObjectMap[id]->AddRigidBody(pBody);
m_rigidBodyToActorMap[pBody] = id;
}
btMotionState *BulletPhysicsData::GetMotionStateFrom(const WorldTransformComponent& worldTransform)
{
btQuaternion rotation(Quaternion_to_btQuaternion(worldTransform.GetRotation()));
btVector3 translation(Vec3_to_btVector3(worldTransform.GetPosition(), m_worldScaleFactor));
btTransform transform(rotation, translation);
return new btDefaultMotionState(transform);
}
void BulletPhysicsData::SendNewCollisionEvent(const btPersistentManifold * manifold,
const btRigidBody * pBody1, const btRigidBody * pBody2)
{
auto pGameData = GameData::GetInstance();
auto pEventManager = pGameData->GetEventManager();
assert(pEventManager);
ActorID id1 = GetActorID(pBody1);
ActorID id2 = GetActorID(pBody2);
assert(id1 != 0 || id2 != 0);
if (id1 == 0 || id2 == 0)
{
std::cerr << "BulletPhysics (warning): Collision detected with an unknown actor. "
<< "This implies that there is a rigid body without an owner in the dynamics world."
<< std::endl;
return;
}
std::shared_ptr<Events::IEventData> event;
bool firstIsTrigger;
if ((firstIsTrigger = m_actorToBulletPhysicsObjectMap[id1]->IsTrigger()) ||
m_actorToBulletPhysicsObjectMap[id2]->IsTrigger())
{
ActorID triggerId = firstIsTrigger ? GetActorID(pBody1) : GetActorID(pBody2);
ActorID actorId = firstIsTrigger ? GetActorID(pBody2) : GetActorID(pBody1);
event.reset(new Events::TriggerEntryEvent(pGameData->CurrentTimeMs(),
triggerId, actorId));
pEventManager->VQueueEvent(event);
}
else // not a trigger event
{
std::vector<Vec3> collisionPoints;
btVector3 sumNormalForce;
btVector3 sumFrictionForce;
for (int i = 1; i < manifold->getNumContacts(); ++i)
{
const btManifoldPoint &point = manifold->getContactPoint(i);
collisionPoints.push_back(btVector3_to_Vec3(point.getPositionWorldOnB(), m_worldScaleFactor));
sumNormalForce += point.m_combinedRestitution * point.m_normalWorldOnB;
sumFrictionForce += point.m_combinedFriction * point.m_lateralFrictionDir1;
}
event.reset(new Events::ActorCollideEvent(pGameData->CurrentTimeMs(),
id1, id2, collisionPoints, btVector3_to_Vec3(sumNormalForce, m_worldScaleFactor),
btVector3_to_Vec3(sumFrictionForce, m_worldScaleFactor)));
pEventManager->VQueueEvent(event);
}
}
void BulletPhysicsData::SendSeparationEvent(const btRigidBody * pBody1, const btRigidBody * pBody2)
{
auto pGameData = GameData::GetInstance();
auto pEventManager = pGameData->GetEventManager();
assert(pEventManager);
ActorID id1 = GetActorID(pBody1);
ActorID id2 = GetActorID(pBody2);
if (id1 == 0 || id2 == 0)
return;
std::shared_ptr<Events::IEventData> event;
bool firstIsTrigger;
if ((firstIsTrigger = m_actorToBulletPhysicsObjectMap[id1]->IsTrigger()) ||
m_actorToBulletPhysicsObjectMap[id2]->IsTrigger())
{
ActorID triggerId = firstIsTrigger ? GetActorID(pBody1) : GetActorID(pBody2);
ActorID actorId = firstIsTrigger ? GetActorID(pBody2) : GetActorID(pBody1);
event.reset(new Events::TriggerExitEvent(pGameData->CurrentTimeMs(),
triggerId, actorId));
pEventManager->VQueueEvent(event);
}
else
{
event.reset(new Events::ActorSeparationEvent(
pGameData->CurrentTimeMs(), id1, id2));
pEventManager->VQueueEvent(event);
}
}
}
} | [
"laura.leppanen@iki.fi"
] | laura.leppanen@iki.fi |
416eaad698e2a70d433b265a1bedcf44318ba2dd | 786ee5ec2863154dd194f2144850a0abdca5947b | /src/njli/graphics/opengl_es_3.0/Geometry.cpp | 034256925ab903934a0442d6f09a965564233dd8 | [
"MIT"
] | permissive | njligames/Engine | c36076fcf79784354cb75ea23fab461340b084a2 | 899c7b79cea33a72fc34f159134f721b56715d3d | refs/heads/master | 2020-05-20T18:56:30.287559 | 2017-04-06T23:06:18 | 2017-04-06T23:06:18 | 84,506,545 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,037 | cpp | //
// Geometry.cpp
// JLIGameEngineTest
//
// Created by James Folk on 11/22/14.
// Copyright (c) 2014 James Folk. All rights reserved.
//
#include "Geometry.h"
#include "JLIFactoryTypes.h"
#include "World.h"
#include "LevelOfDetail.h"
#include "Material.h"
#include "ShaderProgram.h"
#include "MaterialProperty.h"
#include "GLPlatform.h"
#include "Node.h"
#include "Log.h"
#define TAG "Geometry.cpp"
#define FORMATSTRING "{\"njli::Geometry\":[]}"
#include "btPrint.h"
#include "Image.h"
static const u32 MAX_SPRITES = NUMBER_OF_MESHES;
static const GLfloat IDENTITYMATRIX[] =
{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
};
namespace njli
{
f32 Geometry::s_PointSize = 1;
f32 Geometry::s_LineWidth = 1;
Geometry::Geometry():
AbstractFactoryObject(this),
// m_Name("MyGeometry"),
m_Material(NULL),
m_ShaderProgram(NULL),
m_projectionMatrixUniform(-1),
m_modelViewMatrixUniform(-1),
m_ModelviewTransform(NULL),
modelviewBufferID(-1),
m_InTransformAttrib(-1),
// m_CurrentMeshCount(-1),
verticesID(-1),
indexBufferID(-1),
vertexArrayID(-1),
m_InPositionAttrib(-1),
m_InTexCoordAttrib(-1),
m_InColorAttrib(-1),
m_blendFuncSource(GL_SRC_ALPHA),
m_blendFuncDestination(GL_ONE_MINUS_SRC_ALPHA),
_opacityModifyRGB(false),
m_enableBlend(true),
m_enableDepthTest(true),
m_enableStencilTest(false),
m_TransformDirty(true),
// m_StartCopyTransform(std::numeric_limits<u64>::max()),
m_LoadGPU(false),
m_setupOpacity_Material(NULL),
m_setupOpacity_Image(NULL),
m_setupOpacity(false),
m_UnLoadGPU(false),
// m_setupShader(false),
m_bufferModified(true),
m_vertexAttribChanged(false),
m_MatrixBuffer(new float[16])
{
enableRenderObject();
}
Geometry::Geometry(const AbstractBuilder &builder):
AbstractFactoryObject(this),
// m_Name("MyGeometry"),
m_Material(NULL),
m_ShaderProgram(NULL),
m_projectionMatrixUniform(-1),
m_modelViewMatrixUniform(-1),
m_ModelviewTransform(NULL),
modelviewBufferID(-1),
m_InTransformAttrib(-1),
// m_CurrentMeshCount(-1),
verticesID(-1),
indexBufferID(-1),
vertexArrayID(-1),
m_InPositionAttrib(-1),
m_InTexCoordAttrib(-1),
m_InColorAttrib(-1),
m_blendFuncSource(GL_SRC_ALPHA),
m_blendFuncDestination(GL_ONE_MINUS_SRC_ALPHA),
_opacityModifyRGB(false),
m_enableBlend(true),
m_enableDepthTest(true),
m_enableStencilTest(false),
m_TransformDirty(true),
// m_StartCopyTransform(std::numeric_limits<u64>::max()),
m_LoadGPU(false),
m_setupOpacity_Material(NULL),
m_setupOpacity_Image(NULL),
m_setupOpacity(false),
m_UnLoadGPU(false),
// m_setupShader(false),
m_bufferModified(true),
m_vertexAttribChanged(false),
m_MatrixBuffer(new float[16])
{
enableRenderObject();
}
Geometry::Geometry(const Geometry ©):
AbstractFactoryObject(this),
// m_Name("MyGeometry"),
m_Material(NULL),
m_ShaderProgram(NULL),
m_projectionMatrixUniform(-1),
m_modelViewMatrixUniform(-1),
m_ModelviewTransform(NULL),
modelviewBufferID(-1),
m_InTransformAttrib(-1),
// m_CurrentMeshCount(-1),
verticesID(-1),
indexBufferID(-1),
vertexArrayID(-1),
m_InPositionAttrib(-1),
m_InTexCoordAttrib(-1),
m_InColorAttrib(-1),
m_InOpacityAttrib(-1),
m_InHiddenAttrib(-1),
m_blendFuncSource(GL_SRC_ALPHA),
m_blendFuncDestination(GL_ONE_MINUS_SRC_ALPHA),
_opacityModifyRGB(false),
m_enableBlend(true),
m_enableDepthTest(true),
m_enableStencilTest(false),
m_TransformDirty(true),
// m_StartCopyTransform(std::numeric_limits<u64>::max()),
m_LoadGPU(false),
m_setupOpacity_Material(NULL),
m_setupOpacity_Image(NULL),
m_setupOpacity(false),
m_UnLoadGPU(false),
// m_setupShader(false),
m_bufferModified(true),
m_vertexAttribChanged(false),
m_MatrixBuffer(new float[16])
{
enableRenderObject();
}
Geometry::~Geometry()
{
delete [] m_MatrixBuffer; m_MatrixBuffer = NULL;
unLoadGPU_Internal();
}
Geometry &Geometry::operator=(const Geometry &rhs)
{
if(this != &rhs)
{
}
return *this;
}
s32 Geometry::calculateSerializeBufferSize() const
{
//TODO: calculateSerializeBufferSize
return 0;
}
void Geometry::serialize(void* dataBuffer, btSerializer* serializer) const
{
//TODO: serialize
}
const char *Geometry::getClassName()const
{
return "Geometry";
}
s32 Geometry::getType()const
{
return Geometry::type();
}
Geometry::operator std::string() const
{
return njli::JsonJLI::parse(string_format("%s", FORMATSTRING).c_str());
}
Geometry *Geometry::create(u32 type)
{
DEBUG_ASSERT(type == JLI_OBJECT_TYPE_Plane);
return dynamic_cast<Geometry*>(World::getInstance()->getWorldFactory()->create(type));
}
void Geometry::destroy(Geometry *object)
{
if(object)
{
object->removeMaterial();
object->removeShaderProgram();
object->removeAllLevelOfDetails();
World::getInstance()->getWorldFactory()->destroy(object);
}
}
void Geometry::load(Geometry &object, lua_State *L, int index)
{
// Push another reference to the table on top of the stack (so we know
// where it is, and this function can work for negative, positive and
// pseudo indices
lua_pushvalue(L, index);
// stack now contains: -1 => table
lua_pushnil(L);
// stack now contains: -1 => nil; -2 => table
while (lua_next(L, -2))
{
// stack now contains: -1 => value; -2 => key; -3 => table
// copy the key so that lua_tostring does not modify the original
lua_pushvalue(L, -2);
// stack now contains: -1 => key; -2 => value; -3 => key; -4 => table
const char *key = lua_tostring(L, -1);
const char *value = lua_tostring(L, -2);
if(lua_istable(L, -2))
{
Geometry::load(object, L, -2);
}
else
{
if(lua_isnumber(L, index))
{
double number = lua_tonumber(L, index);
printf("%s => %f\n", key, number);
}
else if(lua_isstring(L, index))
{
const char *v = lua_tostring(L, index);
printf("%s => %s\n", key, v);
}
else if(lua_isboolean(L, index))
{
bool v = lua_toboolean(L, index);
printf("%s => %d\n", key, v);
}
else if(lua_isuserdata(L, index))
{
// swig_lua_userdata *usr;
// swig_type_info *type;
// assert(lua_isuserdata(L,index));
// usr=(swig_lua_userdata*)lua_touserdata(L,index); /* get data */
// type = usr->type;
// njli::AbstractFactoryObject *object = static_cast<njli::AbstractFactoryObject*>(usr->ptr);
// printf("%s => %d:%s\n", key, object->getType(), object->getClassName());
}
}
// pop value + copy of key, leaving original key
lua_pop(L, 2);
// stack now contains: -1 => key; -2 => table
}
// stack now contains: -1 => table (when lua_next returns 0 it pops the key
// but does not push anything.)
// Pop table
lua_pop(L, 1);
// Stack is now the same as it was on entry to this function
}
u32 Geometry::type()
{
return JLI_OBJECT_TYPE_Geometry;
}
void Geometry::addLevelOfDetail(LevelOfDetail *lod)
{
DEBUG_ASSERT(NULL != lod);
std::vector<LevelOfDetail*>::const_iterator iter = std::find(m_LevelOfDetailList.begin(), m_LevelOfDetailList.end(), lod);
if(iter == m_LevelOfDetailList.end())
{
std::vector<LevelOfDetail*>::iterator iter = std::find(m_LevelOfDetailList.begin(), m_LevelOfDetailList.end(), lod);
if(iter != m_LevelOfDetailList.end())
removeLevelOfDetail(lod);
m_LevelOfDetailList.push_back(lod);
addChild(lod);
}
}
bool Geometry::removeLevelOfDetail(LevelOfDetail *lod)
{DEBUG_ASSERT(NULL != lod);
std::vector<LevelOfDetail*>::iterator iter = std::find(m_LevelOfDetailList.begin(), m_LevelOfDetailList.end(), lod);
if(iter != m_LevelOfDetailList.end())
{
removeChild(*iter);
m_LevelOfDetailList.erase(iter);
return true;
}
return false;
}
void Geometry::removeAllLevelOfDetails()
{
for(std::vector<LevelOfDetail*>::iterator iter = m_LevelOfDetailList.begin();
iter != m_LevelOfDetailList.end();
++iter)
{
removeChild(*iter);
}
m_LevelOfDetailList.clear();
}
void Geometry::getLevelOfDetails(std::vector<LevelOfDetail*> &particleEmitters)const
{
for(std::vector<LevelOfDetail*>::const_iterator iter = m_LevelOfDetailList.begin();
iter != m_LevelOfDetailList.end();
++iter)
{
if(getChildIndex(*iter) != -1)
particleEmitters.push_back(*iter);
}
}
LevelOfDetail *Geometry::getLevelOfDetail(const u32 index)
{
if (index < m_LevelOfDetailList.size())
{
s32 idx = getChildIndex(m_LevelOfDetailList.at(index));
if(idx != -1)
return dynamic_cast<LevelOfDetail*>(getChild(idx));
}
return NULL;
}
const LevelOfDetail *Geometry::getLevelOfDetail(const u32 index)const
{
if (index < m_LevelOfDetailList.size())
{
s32 idx = getChildIndex(m_LevelOfDetailList.at(index));
if(idx != -1)
return dynamic_cast<const LevelOfDetail*>(getChild(idx));
}
return NULL;
}
void Geometry::addMaterial(Material *material, Image *img)
{
DEBUG_ASSERT(material != NULL);
removeMaterial();
m_Material = material;
addChild(m_Material);
if(img)
{
bool hasAlpha = img->getNumberOfComponents() == 4 || img->getNumberOfComponents() == 2;
bool premultiplied = img->getNumberOfComponents() != 1 && hasAlpha;
_opacityModifyRGB = false;
if (m_blendFuncSource == GL_ONE && m_blendFuncDestination == GL_ONE_MINUS_SRC_ALPHA)
{
if (premultiplied)
_opacityModifyRGB = true;
else {
m_blendFuncSource = GL_SRC_ALPHA;
m_blendFuncDestination = GL_ONE_MINUS_SRC_ALPHA;
}
}
if(premultiplied)
img->preMultiplyAlpha();
}
}
void Geometry::removeMaterial()
{
if(getMaterial())
{
removeChild(getMaterial());
}
m_Material = NULL;
}
Material *Geometry::getMaterial()
{
s32 idx = getChildIndex(m_Material);
if(idx != -1)
return dynamic_cast<Material*>(getChild(idx));
return NULL;
}
const Material *Geometry::getMaterial() const
{
s32 idx = getChildIndex(m_Material);
if(idx != -1)
return dynamic_cast<const Material*>(getChild(idx));
return NULL;
}
void Geometry::addShaderProgram(ShaderProgram *shader)
{
DEBUG_ASSERT(shader != NULL);
removeShaderProgram();
m_ShaderProgram = shader;
addChild(m_ShaderProgram);
// setupShader();
setupShader_Internal();
}
void Geometry::removeShaderProgram()
{
ShaderProgram *shader = getShaderProgram();
if(NULL != shader)
{
removeChild(shader);
}
m_ShaderProgram = NULL;
}
ShaderProgram *Geometry::getShaderProgram()
{
s32 idx = getChildIndex(m_ShaderProgram);
if(idx != -1)
return dynamic_cast<ShaderProgram*>(getChild(idx));
return NULL;
}
const ShaderProgram *Geometry::getShaderProgram() const
{
s32 idx = getChildIndex(m_ShaderProgram);
if(idx != -1)
return dynamic_cast<const ShaderProgram*>(getChild(idx));
return NULL;
}
u32 Geometry::getMaxMeshes()const
{
return MAX_SPRITES;
}
void Geometry::setBlendSource(s32 source)
{
m_blendFuncSource = source;
}
void Geometry::setBlendDestination(s32 dest)
{
m_blendFuncDestination = dest;
}
void Geometry::setupOpacity(Material *material, Image *img)
{
m_setupOpacity_Material = material;
m_setupOpacity_Image = img;
m_setupOpacity = true;
}
void Geometry::loadGPU()
{
m_LoadGPU = true;
}
void Geometry::unLoadGPU()
{
m_UnLoadGPU = true;
}
bool Geometry::isLoadedGPU()const
{
return (verticesID != -1);
}
void Geometry::setTransform(const u64 index, const btTransform &transform)
{
if (index < getMaxMeshes())
{
const GLuint STRIDE = 64;
// static GLfloat m[16];
// GLfloat *m = new GLfloat[16];
transform.getOpenGLMatrix(m_MatrixBuffer);
// m_StartCopyTransform = btMin<u64>(m_StartCopyTransform, (index * STRIDE));
m_TransformDirty = true;
for (int currentVertex = 0; currentVertex < numberOfVertices(); currentVertex++)
{
memcpy(m_ModelviewTransform + ((index * STRIDE) + (16 * currentVertex)), m_MatrixBuffer, sizeof(f32) * 16);
}
}
}
void Geometry::sort(const btVector3 &cameraOrigin)
{
quickSort(0, m_maxindice, cameraOrigin);
}
void Geometry::quickSort(signed long left, signed long right, const btVector3 &cameraOrigin)
{
DEBUG_ASSERT(left >= 0 && left < getMaxMeshes());
DEBUG_ASSERT(right >= 0 && right < getMaxMeshes());
signed long i = left, j = right;
signed long pivot = (left + right) / 2;
while (i <= j)
{
while (lessThan(i, pivot, cameraOrigin))
++i;
while(greaterThan(j, pivot, cameraOrigin))
--j;
if (i <= j)
{
swapTransformData(i, j);
// swapVertexData(i, j);
++i;
--j;
}
}
if (left < j)
quickSort(left, j, cameraOrigin);
if (i < right)
quickSort(i, right, cameraOrigin);
}
void Geometry::swapTransformData(const size_t idx1, const size_t idx2)
{
btTransform temp(getTransform(idx1));
setTransform(idx1, getTransform(idx2));
setTransform(idx2, temp);
}
bool Geometry::lessThan(const size_t idx1, const size_t idx2, const btVector3 &cameraOrigin)
{
btVector3 object1(getTransform(idx1).getOrigin());
btVector3 object2(getTransform(idx2).getOrigin());
return cameraOrigin.distance2(object1) < cameraOrigin.distance2(object2);
}
bool Geometry::greaterThan(const size_t idx1, const size_t idx2, const btVector3 &cameraOrigin)
{
btVector3 object1(getTransform(idx1).getOrigin());
btVector3 object2(getTransform(idx2).getOrigin());
return cameraOrigin.distance2(object1) > cameraOrigin.distance2(object2);
}
btTransform Geometry::getTransform(const u64 index)
{
btTransform transform(btTransform::getIdentity());
if (index < getMaxMeshes())
{
const GLuint STRIDE = 64;
// static GLfloat m[16];
// GLfloat *m = new GLfloat[16];
for (int currentVertex = 0; currentVertex < numberOfVertices(); currentVertex++)
{
memcpy(m_MatrixBuffer, m_ModelviewTransform + ((index * STRIDE) + (16 * currentVertex)), sizeof(f32) * 16);
}
transform.setFromOpenGLMatrix(m_MatrixBuffer);
// delete [] m;m=NULL;
}
return transform;
}
void Geometry::getAabb(Node *node, btVector3& aabbMin,btVector3& aabbMax) const
{
aabbMin = btVector3(0,0,0);
aabbMax = btVector3(0,0,0);
}
void Geometry::enableBlend(const bool enable)
{
m_enableBlend = enable;
}
void Geometry::enableDepthTest(const bool enable)
{
m_enableDepthTest = enable;
}
void Geometry::enableStencilTest(const bool enable)
{
m_enableStencilTest = enable;
}
void Geometry::load()
{
unLoad();
m_ModelviewTransform = new f32[MAX_SPRITES * numberOfVertices() * 16];
memset(m_ModelviewTransform, 0, sizeof(f32) * MAX_SPRITES * numberOfVertices() * 16);
m_TransformDirty = true;
// m_StartCopyTransform = 0;
for (int i = 0; i < MAX_SPRITES * numberOfVertices() * 16; i += 16)
{
memcpy(m_ModelviewTransform + i, IDENTITYMATRIX, sizeof(IDENTITYMATRIX));
}
m_References.reset();
// std::string ids = m_References.to_string();
// DEBUG_LOG_V("", "reset\t%s", ids.c_str());
}
void Geometry::unLoad()
{
if(m_ModelviewTransform)
delete [] m_ModelviewTransform;
m_ModelviewTransform=NULL;
}
void Geometry::render(Camera *camera, s32 mode)
{
Material *material = getMaterial();
ShaderProgram *shader = getShaderProgram();
if (m_UnLoadGPU)
unLoadGPU_Internal();
if (m_setupOpacity)
setupOpacity_Internal(m_setupOpacity_Material, m_setupOpacity_Image);
glLineWidth(s_LineWidth);
if (m_LoadGPU)
loadGPU_Internal();
// if(m_setupShader)
// setupShader_Internal();
if (m_enableBlend)
glEnable(GL_BLEND);
else
glDisable(GL_BLEND);
if (m_enableDepthTest)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);
if (m_enableStencilTest)
glEnable(GL_STENCIL_TEST);
else
glDisable(GL_STENCIL_TEST);
glBlendFunc(m_blendFuncSource, m_blendFuncDestination);
if(NULL != shader)
shader->use();
if(NULL != material && NULL != shader)
material->bind(shader);
glUniformMatrix4fv(m_modelViewMatrixUniform, 1, 0, camera->getModelViewMatrixArray());
glUniformMatrix4fv(m_projectionMatrixUniform, 1, 0, camera->getProjectionMatrixArray());
glUniform1i(u_opacityModifyRGB, _opacityModifyRGB);
glBindVertexArrayAPPLE(vertexArrayID);
if(!isLoadedGPU())
{
m_LoadGPU = true;
loadGPU_Internal();
}
bindTransform();
glBindBuffer(GL_ARRAY_BUFFER, verticesID);
if(isBufferModified())
{
glBufferSubData(GL_ARRAY_BUFFER, 0, (GLsizeiptr)getArrayBufferSize(), getArrayBuffer());
m_bufferModified = false;
// printf("buffer");
}
if (m_vertexAttribChanged)
{
// m_vertexAttribChanged = false;
glEnableVertexAttribArray(m_InPositionAttrib);
glVertexAttribPointer(m_InPositionAttrib,
3,
GL_FLOAT,
GL_FALSE,
sizeof(TexturedColoredVertex),
(const GLvoid*) offsetof(TexturedColoredVertex, vertex));
glEnableVertexAttribArray(m_InTexCoordAttrib);
glVertexAttribPointer(m_InTexCoordAttrib,
2,
GL_FLOAT,
GL_FALSE,
sizeof(TexturedColoredVertex),
(const GLvoid*) offsetof(TexturedColoredVertex, texture));
glEnableVertexAttribArray(m_InColorAttrib);
glVertexAttribPointer(m_InColorAttrib,
4,
GL_FLOAT,
GL_FALSE,
sizeof(TexturedColoredVertex),
(const GLvoid*) offsetof(TexturedColoredVertex, color));
glEnableVertexAttribArray(m_InOpacityAttrib);
glVertexAttribPointer(m_InOpacityAttrib,
1,
GL_FLOAT,
GL_FALSE,
sizeof(TexturedColoredVertex),
(const GLvoid*)offsetof(TexturedColoredVertex, opacity));
glEnableVertexAttribArray(m_InHiddenAttrib);
glVertexAttribPointer(m_InHiddenAttrib,
1,
GL_FLOAT,
GL_FALSE,
sizeof(TexturedColoredVertex),
(const GLvoid*)offsetof(TexturedColoredVertex, hidden));
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
glDrawElements(mode, static_cast<GLsizei>((getMaxMeshes()) * numberOfIndices()), GL_UNSIGNED_SHORT, (const GLvoid*)0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
if(material)
material->unBind();
}
// void Geometry::setupShader()
// {
// m_setupShader = true;
//
// }
void Geometry::bindTransform()
{
if(m_TransformDirty)
{
const GLuint STRIDE = 64;
glBindBuffer(GL_ARRAY_BUFFER, modelviewBufferID);
GLsizei size = sizeof(GLfloat) * getMaxMeshes() * numberOfVertices() * 16;
glBufferSubData(GL_ARRAY_BUFFER, 0, size, m_ModelviewTransform);
if (m_vertexAttribChanged)
{
glEnableVertexAttribArray(m_InTransformAttrib + 0);
glEnableVertexAttribArray(m_InTransformAttrib + 1);
glEnableVertexAttribArray(m_InTransformAttrib + 2);
glEnableVertexAttribArray(m_InTransformAttrib + 3);
glVertexAttribPointer(m_InTransformAttrib + 0, 4, GL_FLOAT, 0, STRIDE, (GLvoid*)0);
glVertexAttribPointer(m_InTransformAttrib + 1, 4, GL_FLOAT, 0, STRIDE, (GLvoid*)16);
glVertexAttribPointer(m_InTransformAttrib + 2, 4, GL_FLOAT, 0, STRIDE, (GLvoid*)32);
glVertexAttribPointer(m_InTransformAttrib + 3, 4, GL_FLOAT, 0, STRIDE, (GLvoid*)48);
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
m_TransformDirty = false;
// DEBUG_LOG_V(TAG, "%llu\n", m_StartCopyTransform);
// m_StartCopyTransform = std::numeric_limits<u64>::max();
}
}
// void Geometry::resetMeshCount()
// {
// m_CurrentMeshCount = -1;
// }
Node *Geometry::getParent()
{
return dynamic_cast<Node*>(AbstractDecorator::getParent());
}
const Node *Geometry::getParent()const
{
return dynamic_cast<const Node*>(AbstractDecorator::getParent());
}
void Geometry::addReference(Node *node)
{
for (s32 i = 0; i < m_References.size(); ++i)
{
if (!m_References[i])
{
m_References[i] = 1;
// std::string ids = m_References.to_string();
// DEBUG_LOG_V("", "add\t%s", ids.c_str());
node->setGeometryIndex(i);
return;
}
}
}
void Geometry::removeReference(Node *node)
{
size_t index = node->getGeometryIndex();
if(index < m_References.size())
{
m_References[index] = 0;
// std::string ids = m_References.to_string();
// DEBUG_LOG_V("", "remove\t%s", ids.c_str());
hideGeometry(node);
}
}
void Geometry::enableBufferModified(bool modified)
{
m_bufferModified = modified;
}
bool Geometry::isBufferModified()const
{
return m_bufferModified;
}
void Geometry::setPointSize(const f32 s)
{
s_PointSize = s;
}
f32 Geometry::getPointSize()
{
return s_PointSize;
}
void Geometry::setLineWidth(const f32 s)
{
DEBUG_ASSERT(s >= 0.0);
s_LineWidth = s;
}
f32 Geometry::getLineWidth()
{
return s_LineWidth;
}
s32 Geometry::numberOfReferences()const
{
return m_References.size();
}
void Geometry::loadGPU_Internal()
{
DEBUG_ASSERT(m_LoadGPU);
DEBUG_ASSERT(vertexArrayID == -1);
glGenVertexArraysAPPLE(1, &vertexArrayID);
glBindVertexArrayAPPLE(vertexArrayID);
DEBUG_ASSERT(modelviewBufferID == -1);
glGenBuffers(1, &modelviewBufferID);
glBindBuffer(GL_ARRAY_BUFFER, modelviewBufferID);
GLsizei size = sizeof(GLfloat) * getMaxMeshes() * numberOfVertices() * 16;
glBufferData(GL_ARRAY_BUFFER, size, m_ModelviewTransform, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
DEBUG_ASSERT(verticesID == -1);
glGenBuffers(1, &verticesID);
glBindBuffer(GL_ARRAY_BUFFER, verticesID);
glBufferData(GL_ARRAY_BUFFER, (long)getArrayBufferSize(), getArrayBuffer(), GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
DEBUG_ASSERT(indexBufferID == -1);
glGenBuffers(1, &indexBufferID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (long)getElementArrayBufferSize(), getElementArrayBuffer(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArrayAPPLE(0);
m_LoadGPU = false;
}
void Geometry::setupOpacity_Internal(Material *material, Image *img)
{
DEBUG_ASSERT(m_setupOpacity);
bool hasAlpha = img->getNumberOfComponents() == 4 || img->getNumberOfComponents() == 2;
bool premultiplied = img->getNumberOfComponents() != 1 && hasAlpha;
_opacityModifyRGB = false;
if (m_blendFuncSource == GL_ONE && m_blendFuncDestination == GL_ONE_MINUS_SRC_ALPHA)
{
if (premultiplied)
_opacityModifyRGB = true;
else {
m_blendFuncSource = GL_SRC_ALPHA;
m_blendFuncDestination = GL_ONE_MINUS_SRC_ALPHA;
}
}
if(premultiplied)
img->preMultiplyAlpha();
material->getDiffuse()->loadGPU(*img);
m_setupOpacity = false;
}
void Geometry::unLoadGPU_Internal()
{
DEBUG_ASSERT(m_UnLoadGPU);
if(modelviewBufferID == -1)
{
glDeleteBuffers(1, &modelviewBufferID);
modelviewBufferID = -1;
}
if(indexBufferID == -1)
{
glDeleteBuffers(1, &indexBufferID);
indexBufferID = -1;
}
if(verticesID == -1)
{
glDeleteBuffers(1, &verticesID);
verticesID = -1;
}
if(vertexArrayID == -1)
{
glDeleteVertexArraysAPPLE(1, &vertexArrayID);
vertexArrayID = -1;
}
m_UnLoadGPU = false;
}
void Geometry::setupShader_Internal()
{
// DEBUG_ASSERT(m_setupShader);
ShaderProgram *shader = getShaderProgram();
DEBUG_ASSERT(shader);
if (!shader->isLinked())
{
if(!shader->link())
{
DEBUG_LOG_PRINT_E(TAG, "%s", "Linking failed");
DEBUG_LOG_PRINT_E(TAG, "Program log: %s", shader->programLog());
DEBUG_LOG_PRINT_E(TAG, "Vertex log: %s", shader->vertexShaderLog());
DEBUG_LOG_PRINT_E(TAG, "Fragment log: %s", shader->fragmentShaderLog());
}
}
// ... and add the attributes the shader needs for the vertex position, color and texture st information
shader->bindAttribute("inPosition");
shader->bindAttribute("inTexCoord");
shader->bindAttribute("inColor");
shader->bindAttribute("inOpacity");
shader->bindAttribute("inHidden");
shader->bindAttribute("inTransform");
// Setup the index pointers into the shader for our attributes
m_InPositionAttrib = shader->getAttributeIndex("inPosition");
m_InTexCoordAttrib = shader->getAttributeIndex("inTexCoord");
m_InColorAttrib = shader->getAttributeIndex("inColor");
m_InOpacityAttrib = shader->getAttributeIndex("inOpacity");
m_InHiddenAttrib = shader->getAttributeIndex("inHidden");
shader->use();
m_InTransformAttrib = shader->getAttributeIndex("inTransform");
m_modelViewMatrixUniform = shader->getUniformIndex("modelView");
m_projectionMatrixUniform = shader->getUniformIndex("projection");
u_opacityModifyRGB = shader->getUniformIndex("u_opacityModifyRGB");
// u_pointSize = shader->getUniformIndex("u_pointSize");
// m_setupShader = false;
m_vertexAttribChanged = true;
}
}
| [
"jamesfolk1@gmail.com"
] | jamesfolk1@gmail.com |
eee27e3f3a417ff94b388c34d8037828333b5d89 | feb916f1dadbbb91a1ba710a471bc0a267f3255f | /source/Jigsaw3D/PuzzlePiece.h | e855a2223a159da9751c9bd010900c2b856626fa | [] | no_license | DaanNiphuis/Jigsaw3D | b4475ad78faac08a445507db4aa94302bc81e1fd | f10238d5b5572668c4a0dbb3683080d92ea317b7 | refs/heads/master | 2020-05-30T16:33:05.614082 | 2013-01-23T19:22:43 | 2013-01-23T19:22:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,050 | h | #ifndef PUZZLEPIECE_H_
#define PUZZLEPIECE_H_
#include <iostream>
#include <vector>
#include "common.h"
class PuzzlePiece {
const uint _gridwidth;
std::vector<uint> _piece_shape;
uint get_point_index(uint row_number, uint col_number) const;
uint get_flippable_point(bool flipped, uint row_number, uint col_number) const;
char get_point_char(uint orientation, bool flipped, uint row_number, uint col_number) const;
std::string get_field_str(uint orientation, bool flipped) const;
PuzzlePiece& operator=(const PuzzlePiece&) {return *this;}
public:
PuzzlePiece(uint gridwidth, const std::vector<uint> & piece_shape);
virtual ~PuzzlePiece(void);
uint get_nr_of_edge_bits(void) const;
uint get_nr_of_corner_bits(void) const;
uint get_point(uint orientation, bool flipped, uint row_number, uint col_number) const;
std::string get_row_str(uint orientation, bool flipped, uint row_number) const;
friend std::ostream &operator<<(std::ostream &out, const PuzzlePiece &P);
};
#endif /* PUZZLEPIECE_H_ */
| [
"dniphuis@gmail.com"
] | dniphuis@gmail.com |
f3b01d90130add0e78bd1688f4c0b8e76fe620d4 | d29ff768a0f7c0a21e497271ae6bb3a9510c0c41 | /DesktopToys/Shooter2Mark.cpp | 12f40f868732078887762485f407ae6276274fcc | [] | no_license | imcy/DesktopToys | e2544512574d6b2e8d2575611538b41173604216 | 98d281fb3b8021869b664eb3bcf5afd153da72a8 | refs/heads/master | 2021-08-15T02:52:37.391784 | 2017-11-17T08:00:30 | 2017-11-17T08:00:30 | 110,933,217 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,893 | cpp | #include "stdafx.h"
#include "Shooter2Mark.h"
CShooter2Mark::CShooter2Mark(float x, float y)
{
SetCenterPos(x, y);
// 生成[1,5]之间的随机数
int i = 1 + rand() % 5;
TCHAR szFilename[MAX_PATH] = { 0 };
_stprintf_s(szFilename, _T("images/The Toolbox Mark %02d.png"), i);
m_img = Image::FromFile(szFilename);
for (int i = 0; i < (1 + rand() % 3); ++i) {
SDynamic dy;
// 下落物体
dy.m_img2 = Image::FromFile(_T("images/The Toolbox Mark 06.png"));
// 速度(包含方向) [-5, 4 / -5, 4]
dy.m_speed = PointF(float(rand() % 10 - 5), float(rand() % 10 - 5));
// 位置
dy.m_pos.X = x + float(rand() % 80 - 40);
dy.m_pos.Y = y + float(rand() % 80 - 40);
// 当前角度(用于自射旋转)
dy.m_dir = Degree2Radian(rand() % 360);
// 是否显示
dy.m_bShow = true;
m_vD.push_back(dy);
}
}
CShooter2Mark::~CShooter2Mark()
{
}
static void DrawImageRotate(PointF mousePt, Graphics &gh, Image *img, float degree)
{
//旋转绘图平面
PointF center = mousePt;
center.X += img->GetWidth() / 2.0f;
center.Y += img->GetHeight() / 2.0f;
// 1.平移变换 : 移动坐标点到 坦克中心
gh.TranslateTransform(center.X, center.Y);
// 2.旋转变换 : 使作标系,跟坐标旋转"degree"度
gh.RotateTransform(degree);
// 3.恢复原点
gh.TranslateTransform(-center.X, -center.Y);
// 方法退出时恢复对坐标系和平移的转换
ON_SCOPE_EXIT([&]() {
// 重置坐标变换 : 精度是否够呢?
// 1.移动到中心点
gh.TranslateTransform(center.X, center.Y);
// 2.逆向转
gh.RotateTransform(-degree);
// 3.再移动回去
gh.TranslateTransform(-center.X, -center.Y);
//ScaleTransform : 缩放
});
// 画出图像
{
RectF rc;
rc.X = mousePt.X;
rc.Y = mousePt.Y;
rc.Width = (float)img->GetWidth();
rc.Height = (float)img->GetHeight();
gh.DrawImage(img, rc);
}
}
void CShooter2Mark::Draw(Gdiplus::Graphics & gh)
{
// 主图片
gh.DrawImage(m_img, GetCenterPos());
// 画下落物体
for (auto &dy : m_vD) {
if (dy.m_bShow) {
// 判断是否落出到外面
if (!g_game->GetRectF().Contains(dy.m_pos)) {
continue;
}
// 没有落到外面
// 画出来
DrawImageRotate(dy.m_pos, gh, dy.m_img2, Radian2Degree(dy.m_dir));
//
{
// 调整位置
dy.m_pos.X += dy.m_speed.X;
dy.m_pos.Y += dy.m_speed.Y;
// 调整速度:y方向符合重力加速度
dy.m_speed.Y += 1.0f;
//调整当前的角度
dy.m_dir += PI(0.1f);
if (dy.m_dir >= PI(2.0f)) {
dy.m_dir = 0.0f;
}
}
}
}
// 移除落出游戏窗口外的对象
m_vD.erase(std::remove_if(m_vD.begin(),
m_vD.end(),
[&](auto & lhs)->bool {
// 不包含在窗口中的全部移除要
return (!g_game->GetRectF().Contains(lhs.m_pos));
}), m_vD.end());
}
bool CShooter2Mark::IsChanging() const
{
// 没有空,说明还有动态对象
return !m_vD.empty();
} | [
"393632272@qq.com"
] | 393632272@qq.com |
5da6769bbda4777f0ff4458d511321aeb9832597 | e769bb7386f31ee347accee1ccbb421dfd9c42d1 | /Assignments/Assignment 2/A2/A2/LevelOneState (copy).cpp | 69dd76d89962021b7f88e00d71fc053dd07a9c1c | [] | no_license | neytjieb1/Software-Modelling | 5cf0bbdf5411b7b6006aa02113ee493fe077f65f | 907fc4dc2f1fac9b6b0ce62e840b17a7b6604a72 | refs/heads/master | 2023-02-07T18:53:14.187438 | 2020-10-23T04:30:22 | 2020-10-23T04:30:22 | 287,204,960 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 501 | cpp | //
// Created by jo on 2020/08/26.
//
#include "NoLevelState.h"
#include "LevelOneState.h"
#include "LevelTwoState.h"
#include <iostream>
using namespace std;
LevelOneState::LevelOneState() : LevelState("level1") {}
void LevelOneState::handle() {
cout << "The country is at level1: Very few cases" << endl;
}
LevelState *LevelOneState::changePandemicLevel(bool increase) {
if (increase==1) {
return new LevelTwoState();
}
else {
return new NoLevelState;
}
}
| [
"u17091820@tuks.co.za"
] | u17091820@tuks.co.za |
843c1d0855f5f4b7057454d5fec5a14def31f95d | ba10da4be74ba4e472bbe4b51d411627fc07bdbf | /build/iOS/Preview/include/Fuse.UserEvent.h | 92659f0b13d2a814041d20cd3fbb6a011c9ec526 | [] | no_license | ericaglimsholt/gadden | 80f7c7b9c3c5c46c2520743dc388adbad549c679 | daef25c11410326f067c896c242436ff1cbd5df0 | refs/heads/master | 2021-07-03T10:07:58.451759 | 2017-09-05T18:11:47 | 2017-09-05T18:11:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,173 | h | // This file was generated based on '/Users/ericaglimsholt/Library/Application Support/Fusetools/Packages/Fuse.UserEvents/1.0.5/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Behavior.h>
#include <Fuse.Binding.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
namespace g{namespace Fuse{namespace Scripting{struct Context;}}}
namespace g{namespace Fuse{struct Node;}}
namespace g{namespace Fuse{struct UserEvent;}}
namespace g{namespace Fuse{struct UserEventDispatch;}}
namespace g{namespace Fuse{struct Visual;}}
namespace g{namespace Uno{namespace Collections{struct Dictionary;}}}
namespace g{namespace Uno{namespace UX{struct Selector;}}}
namespace g{
namespace Fuse{
// public partial sealed class UserEvent :354
// {
::g::Fuse::Node_type* UserEvent_typeof();
void UserEvent__ctor_3_fn(UserEvent* __this);
void UserEvent__New2_fn(UserEvent** __retval);
void UserEvent__OnRooted_fn(UserEvent* __this);
void UserEvent__OnUnrooted_fn(UserEvent* __this);
void UserEvent__raise_fn(::g::Fuse::Scripting::Context* c, UserEvent* n, uArray* args);
void UserEvent__Raise_fn(UserEvent* __this, ::g::Uno::Collections::Dictionary* args);
void UserEvent__RaiseEvent_fn(::g::Fuse::Visual* from, ::g::Uno::UX::Selector* name, ::g::Uno::Collections::Dictionary* args);
void UserEvent__ScanTree_fn(::g::Fuse::Node* at, ::g::Uno::UX::Selector* name, ::g::Fuse::Visual** visual, UserEvent** __retval);
struct UserEvent : ::g::Fuse::Behavior
{
uStrong< ::g::Fuse::UserEventDispatch*> Dispatch;
void ctor_3();
void Raise(::g::Uno::Collections::Dictionary* args);
static UserEvent* New2();
static void raise(::g::Fuse::Scripting::Context* c, UserEvent* n, uArray* args);
static void RaiseEvent(::g::Fuse::Visual* from, ::g::Uno::UX::Selector name, ::g::Uno::Collections::Dictionary* args);
static UserEvent* ScanTree(::g::Fuse::Node* at, ::g::Uno::UX::Selector name, ::g::Fuse::Visual** visual);
};
// }
}} // ::g::Fuse
| [
"ericaglimsholt@hotmail.com"
] | ericaglimsholt@hotmail.com |
138980fbb4e3563a20203f8baef32f94d8c5450f | 8c4ad8d91bdd5cc1c0cf2f7b2766d804a21e0ff8 | /chef/SPOON.cpp | 950f1fd49ad65da86da9c4dcc0594b4af018649e | [] | no_license | gabrieltepin/programming-contests | c4da797a80a77ee02b99a74b8469cb77677fd94c | 9dcf56c4b77c5426dd987ebf1f0536aa14fd4858 | refs/heads/master | 2023-03-23T11:36:39.908248 | 2021-03-19T13:43:43 | 2021-03-19T13:43:43 | 349,437,506 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | cpp | #include <iostream>
#define fori(x, y) for(int i = x; i < y; ++i)
#define forj(x, y) for(int j = x; j < y; ++j)
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int T, R, C;
char tab[102][102], str[5] = {'s', 'p','o', 'o', 'n'};
cin >> T;
while(T--){
bool isfound=0;
cin >> R >> C;
fori(0, R){
forj(0, C){
cin >> tab[i][j];
int d = tab[i][j]-'A';
if(d<=26 && d>=0)
tab[i][j]='a'+d;
}
}
fori(0, R){
int k = 0;
forj(0, C-4){//no need to look later j>C-5
while(tab[i][j+k]==str[k] && k<5){
k++;
}
if(k==5) {
isfound=1;
j=C;i=R;//break
}
else k=0;
}
}
if(isfound==0){
forj(0, C){
int k =0;
fori(0, R-4){
while(tab[i+k][j]==str[k] && k<5){
k++;
}
if(k==5) {
isfound=1;
j=C;i=R;//break
}
else k=0;
}
}
}
if(isfound) cout << "There is a spoon!\n";
else cout << "There is indeed no spoon!\n";
}
return 0;
} | [
"gabrieltepin@gmail.com"
] | gabrieltepin@gmail.com |
6539ce6c96c7172e4a38acbf268469f033b3fdba | 03ba325820c997599beff5add437d35347a953aa | /source/editor/Editor.h | 26d849327caaed3be993996657619bec63b20798 | [
"MIT"
] | permissive | simplerr/UtopianEngine | cc13a43279bd49f55136120cf75c8c8d5fcff705 | b7c38df663a4b6b2fa1d7c9f1f83dfc661de1a9a | refs/heads/master | 2022-10-12T12:03:19.166812 | 2022-09-28T05:48:31 | 2022-09-28T05:48:31 | 77,483,702 | 64 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 2,412 | h | #pragma once
#include "utopian/vulkan/VulkanPrerequisites.h"
#include "utopian/utility/Common.h"
#include "utopian/ui/Console.h"
#include <vector>
#include <string>
#include <glm/glm.hpp>
namespace Utopian
{
class World;
class Actor;
class ActorInspector;
class Terrain;
class TerrainTool;
class FoliageTool;
class PrototypeTool;
class ImGuiRenderer;
enum ActorTemplate
{
STATIC_MODEL,
STATIC_POINT_LIGHT,
RIGID_BOX,
RIGID_SPHERE,
RIGID_SPHERE_LIGHT,
SPAWN_POINT,
FINISH_POINT,
PBR_SPHERE
};
enum SelectionType
{
OBJECT_SELECTION,
FACE_SELECTION,
EDGE_SELECTION
};
class Editor
{
public:
Editor(ImGuiRenderer* imGuiRenderer, World* world, Terrain* terrain);
~Editor();
void Update(double deltaTime);
void UpdateUi();
void Draw();
void PreFrame();
void CreateActor(std::string modelPath, ActorTemplate actorTemplate, glm::vec3 position);
void AddActorCreation(std::string modelPath, ActorTemplate actorTemplate = STATIC_MODEL);
private:
void UpdateSelectionType();
void DrawGizmo();
void SelectActor();
void AddActorToScene();
void RemoveActorFromScene();
void ScaleSelectedActor();
bool IsActorSelected();
void OnActorSelected(Actor* actor);
void DeselectActor();
void RenderActorCreationUi();
void RenderActorSelectionUi();
void RenderLoadSaveUi();
void SaveTerrain();
void LoadTerrain();
void AddPaths();
World* mWorld;
Terrain* mTerrain;
ImGuiRenderer* mImGuiRenderer;
ActorInspector* mActorInspector;
SharedPtr<TerrainTool> mTerrainTool;
SharedPtr<FoliageTool> mFoliageTool;
SharedPtr<PrototypeTool> mPrototypeTool;
Actor* mSelectedActor;
Console mConsole;
SelectionType mSelectionType = OBJECT_SELECTION;
int mSelectedActorIndex = 0;
std::vector<const char*> mModelPaths;
/*
* The editor supports creating Actors from different templates consisting
* of different default components. For example STATIC_MODEL is an actor with
* a CTransfrom + CRenderable. Todo: Note: This should be improved.
*/
std::vector<ActorTemplate> mTemplateTypes;
int mSelectedModel = 0;
const float MWHEEL_SCALE_FACTOR = 0.0025f;
};
}
| [
"axel.blackert@gmail.com"
] | axel.blackert@gmail.com |
06a26f81a362ac0c8ac92d50232c94665e86aca3 | 9324cb559c509753d3a2f6467ccb6616de58af05 | /fboss/lib/RingBuffer.h | 011615227269d6ed854f9b34ad14d1f8b86dcfd1 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | rsunkad/fboss | 4b39eefa3851bd9e415403d28a28290838dea22f | 760255f88fdaeb7f12d092a41362acf1e9a45bbb | refs/heads/main | 2023-07-24T10:39:48.865411 | 2021-09-08T18:58:30 | 2021-09-08T18:59:40 | 404,465,680 | 0 | 0 | NOASSERTION | 2021-09-08T19:09:20 | 2021-09-08T19:09:19 | null | UTF-8 | C++ | false | false | 721 | h | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <stddef.h>
#include <list>
namespace facebook::fboss {
template <typename T, size_t length>
class RingBuffer {
public:
using iterator = typename std::list<T>::iterator;
void write(T val);
const T last() const;
bool empty() const;
iterator begin();
iterator end();
size_t size();
size_t maxSize();
private:
std::list<T> buf;
};
} // namespace facebook::fboss
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
9a3043a6ac568c4db92972b8a6174282fa50757c | ef9692ecde7874511d0e82338cdbeca0bbb18c68 | /include/rcnn/config/paths_catalog.h | 5e2e5b5c372bcd7b9ca1037a080d3ad4008abf88 | [
"MIT"
] | permissive | conanhung/maskrcnn_benchmark.cpp | f364dae01be21d289c6e7034f0a2070c9c0cb909 | eab9787d3140e003662a31a8e01f7ae39469e9a0 | refs/heads/master | 2020-09-29T17:29:04.957348 | 2019-11-10T12:50:05 | 2019-11-10T12:50:05 | 227,083,634 | 1 | 0 | MIT | 2019-12-10T09:53:59 | 2019-12-10T09:53:59 | null | UTF-8 | C++ | false | false | 871 | h | #pragma once
#include <map>
#include <string>
namespace rcnn{
namespace config{
using args = std::map<std::string, std::string>;
class DatasetCatalog{
public:
DatasetCatalog(){};
std::tuple<std::string, std::string, std::string> operator[](std::string name);
static const std::string DATA_DIR;
static const std::map<std::string, args> DATASETS;
//no keypoints and voc
};
class ModelCatalog{
public:
ModelCatalog(){};
static const std::string S3_C2_DETECTRON_URL;
static const std::map<std::string, std::string> C2_IMAGENET_MODELS;
static const std::string C2_DETECTRON_SUFFIX;
static const std::map<std::string, std::string> C2_DETECTRON_MODELS;
static std::string get(std::string name);
static std::string get_c2_imagenet_pretrained(std::string name);
static std::string get_c2_detectron_12_2017_baselines(std::string name);
};
}
} | [
"lsrock1@naver.com"
] | lsrock1@naver.com |
3c071a227c48141295f4eff86e748589891056e3 | 120eb6e3eefd4083d719ab90ed288c88fcedfaed | /guichan/sdl/OpenGLImage.cpp | 0e72ff8872076a60256db2f6738033751e781248 | [] | no_license | AspidT/Zerlight | b111d6c874033b1bccef1780d8479f216d0239b0 | 2fb6d713580f4b93217274ee8f655b5af0682a07 | refs/heads/master | 2020-04-18T18:59:39.029017 | 2019-01-28T16:47:29 | 2019-01-28T16:48:51 | 167,700,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,164 | cpp | //
// Created by tatiana on 28.09.18.
//
#include "OpenGLImage.h"
#include "guichan/gui/Exception.h"
namespace sdl_interface
{
OpenGLImage::OpenGLImage(const unsigned int* pixels, int width, int height, bool convertToDisplayFormat)
{
mAutoFree = true;
mWidth = width;
mHeight = height;
mTextureWidth = 1, mTextureHeight = 1;
while(mTextureWidth < mWidth)
{
mTextureWidth *= 2;
}
while(mTextureHeight < mHeight)
{
mTextureHeight *= 2;
}
// Create a new pixel array and copy the pixels into it
mPixels = new unsigned int[mTextureWidth * mTextureHeight];
#ifdef __BIG_ENDIAN__
const unsigned int magicPink = 0xff00ffff;
#else
const unsigned int magicPink = 0xffff00ff;
#endif
int x, y;
for (y = 0; y < mTextureHeight; y++)
{
for (x = 0; x < mTextureWidth; x++)
{
if (x < mWidth && y < mHeight)
{
unsigned int c = pixels[x + y * mWidth];
// Magic pink to transparent
if (c == magicPink)
{
c = 0x00000000;
}
mPixels[x + y * mTextureWidth] = c;
}
else
{
mPixels[x + y * mTextureWidth] = 0x00000000;
}
}
}
if (convertToDisplayFormat)
{
OpenGLImage::convertToDisplayFormat();
}
}
OpenGLImage::OpenGLImage(GLuint textureHandle, int width, int height, bool autoFree)
{
mTextureHandle = textureHandle;
mAutoFree = autoFree;
mPixels = NULL;
mWidth = width;
mHeight = height;
mTextureWidth = 1, mTextureHeight = 1;
while(mTextureWidth < mWidth)
{
mTextureWidth *= 2;
}
while(mTextureHeight < mHeight)
{
mTextureHeight *= 2;
}
}
OpenGLImage::~OpenGLImage()
{
if (mAutoFree)
{
free();
}
}
GLuint OpenGLImage::getTextureHandle() const
{
return mTextureHandle;
}
int OpenGLImage::getTextureWidth() const
{
return mTextureWidth;
}
int OpenGLImage::getTextureHeight() const
{
return mTextureHeight;
}
void OpenGLImage::free()
{
if (mPixels == NULL)
{
glDeleteTextures(1, &mTextureHandle);
}
else
{
delete[] mPixels;
mPixels = NULL;
}
}
int OpenGLImage::getWidth() const
{
return mWidth;
}
int OpenGLImage::getHeight() const
{
return mHeight;
}
gui::ZColor OpenGLImage::getPixel(int x, int y)
{
if (mPixels == NULL)
{
throw GCN_EXCEPTION("Image has been converted to display format");
}
if (x < 0 || x >= mWidth || y < 0 || y >= mHeight)
{
throw GCN_EXCEPTION("Coordinates outside of the image");
}
unsigned int c = mPixels[x + y * mTextureWidth];
#ifdef __BIG_ENDIAN__
unsigned char r = (unsigned char) ((c >> 24) & 0xff);
unsigned char g = (unsigned char) ((c >> 16) & 0xff);
unsigned char b = (unsigned char) ((c >> 8) & 0xff);
unsigned char a = (unsigned char) (c & 0xff);
#else
unsigned char a = (unsigned char) ((c >> 24) & 0xff);
unsigned char b = (unsigned char) ((c >> 16) & 0xff);
unsigned char g = (unsigned char) ((c >> 8) & 0xff);
unsigned char r = (unsigned char) (c & 0xff);
#endif
return gui::ZColor(r, g, b, a);
}
void OpenGLImage::putPixel(int x, int y, const gui::ZColor& color)
{
if (mPixels == NULL)
{
throw GCN_EXCEPTION("Image has been converted to display format");
}
if (x < 0 || x >= mWidth || y < 0 || y >= mHeight)
{
throw GCN_EXCEPTION("Coordinates outside of the image");
}
#ifdef __BIG_ENDIAN__
unsigned int c = color.a | color.b << 8 | color.g << 16 | color.r << 24;
#else
unsigned int c = color.r | color.g << 8 | color.b << 16 | color.a << 24;
#endif
mPixels[x + y * mTextureWidth] = c;
}
void OpenGLImage::convertToDisplayFormat()
{
if (mPixels == NULL)
{
throw GCN_EXCEPTION("Image has already been converted to display format");
}
glGenTextures(1, &mTextureHandle);
glBindTexture(GL_TEXTURE_2D, mTextureHandle);
glTexImage2D(GL_TEXTURE_2D,
0,
4,
mTextureWidth,
mTextureHeight,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
mPixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
delete[] mPixels;
mPixels = NULL;
GLenum error = glGetError();
if (error)
{
std::string errmsg;
switch (error)
{
case GL_INVALID_ENUM:
errmsg = "GL_INVALID_ENUM";
break;
case GL_INVALID_VALUE:
errmsg = "GL_INVALID_VALUE";
break;
case GL_INVALID_OPERATION:
errmsg = "GL_INVALID_OPERATION";
break;
case GL_STACK_OVERFLOW:
errmsg = "GL_STACK_OVERFLOW";
break;
case GL_STACK_UNDERFLOW:
errmsg = "GL_STACK_UNDERFLOW";
break;
case GL_OUT_OF_MEMORY:
errmsg = "GL_OUT_OF_MEMORY";
break;
}
throw GCN_EXCEPTION(std::string("Unable to convert to OpenGL display format, glGetError said: ") + errmsg);
}
}
} | [
"hx03@yandex.ru"
] | hx03@yandex.ru |
db8cd4233081687773b81880a18f3e63823a1ea6 | dcb6cb3bf5d34a9d16394172fa7a19a0f5eee2f9 | /Offline 3/nachos_64bit/code/userprog/spaceid_generator.h | cc20d870f700ad767178e9a01d33a89ff2297180 | [] | no_license | Rafid013/Nachos_Offline | 4ba530de20a45004eaaf43ac338555c073b7e034 | 5158a3b84144af887b3f4a970fb3d578060fd1e5 | refs/heads/master | 2023-06-24T17:42:48.475770 | 2021-07-27T18:58:46 | 2021-07-27T18:58:46 | 115,601,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 428 | h | //
// Created by rafid on 12/31/17.
//
#ifndef SPACEID_GENERATOR_H
#define SPACEID_GENERATOR_H
#include "../threads/synch.h"
#include <queue>
using namespace std;
typedef int SpaceId;
class SpaceIdGenerator {
queue<SpaceId> *freeIds;
Lock *lock;
public:
explicit SpaceIdGenerator(int maxId);
~SpaceIdGenerator();
SpaceId generate();
void releaseId(SpaceId spaceId);
};
#endif //SPACEID_GENERATOR_H
| [
"1405013.ahmr@ugrad.cse.buet.ac.bd"
] | 1405013.ahmr@ugrad.cse.buet.ac.bd |
da725655e550f6513f7acdb796f587e0a273fe38 | 404547b1ec3237f02342fe65e957f32851ce1495 | /Game/ge_stategrapheventfilterisplayer.h | dd3a127845e597b37298a833c6e753bcca5e8e43 | [] | no_license | Adanos-Gotoman/GenomeSDK-R | c5e3a5d57c4fb721b15bb7f572454f2a3021561a | cf87f21fca83b37d2e186fb69b083b72932f9c8c | refs/heads/master | 2023-03-16T07:05:00.799421 | 2021-02-19T16:07:09 | 2021-02-19T16:07:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 651 | h | #ifndef GE_STATEGRAPHEVENTFILTERISPLAYER_H_INCLUDED
#define GE_STATEGRAPHEVENTFILTERISPLAYER_H_INCLUDED
class GE_DLLIMPORT gCStateGraphEventFilterIsPlayer :
public gCStateGraphEventFilter
{
GE_DECLARE_PROPERTY_OBJECT( gCStateGraphEventFilterIsPlayer, gCStateGraphEventFilter )
public: virtual bEResult Create( void );
protected: virtual void Destroy( void );
public: virtual ~gCStateGraphEventFilterIsPlayer( void );
public: virtual GEBool FilterEvent( gEStateGraphEventType, eCEntity *, eCEntity *, GELPVoid );
protected:
void Invalidate( void );
};
GE_ASSERT_SIZEOF( gCStateGraphEventFilterIsPlayer, 0x0008 )
#endif
| [
"gothicgame29@gmail.com"
] | gothicgame29@gmail.com |
46f1bc43d18b99d033da5132c0a530a3b7214cbf | d11776e8f2e823d9c4095e7f10e8bf7dce8d33eb | /Oscilloscope.cpp | e74df89f3b923403fc1142aa6f5246f98b2b9b37 | [
"MIT",
"BSD-3-Clause",
"LGPL-2.1-only"
] | permissive | jfchapman/VUPlayer | c71968c27c042301ad570f22cc46ee012eb1f6fb | dfbf9764c387aaf97aad01d98721e0abe598b3ce | refs/heads/master | 2023-08-23T18:26:35.383957 | 2023-08-12T12:02:23 | 2023-08-12T12:02:23 | 89,956,372 | 78 | 7 | MIT | 2023-05-18T06:01:53 | 2017-05-01T19:38:47 | C | UTF-8 | C++ | false | false | 5,527 | cpp | #include "Oscilloscope.h"
// Render thread millisecond interval.
static const DWORD s_RenderThreadInterval = 15;
DWORD WINAPI Oscilloscope::RenderThreadProc( LPVOID lpParam )
{
Oscilloscope* oscilloscope = reinterpret_cast<Oscilloscope*>( lpParam );
if ( nullptr != oscilloscope ) {
oscilloscope->RenderThreadHandler();
}
return 0;
}
Oscilloscope::Oscilloscope( WndVisual& wndVisual ) :
Visual( wndVisual ),
m_RenderThread( NULL ),
m_RenderStopEvent( CreateEvent( NULL /*attributes*/, TRUE /*manualReset*/, FALSE /*initialState*/, L"" /*name*/ ) ),
m_Colour( nullptr ),
m_BackgroundColour( nullptr ),
m_Weight( 2.0f )
{
}
Oscilloscope::~Oscilloscope()
{
StopRenderThread();
CloseHandle( m_RenderStopEvent );
CloseHandle( m_RenderThread );
FreeResources();
}
int Oscilloscope::GetHeight( const int width )
{
return width;
}
void Oscilloscope::Show()
{
StartRenderThread();
}
void Oscilloscope::Hide()
{
StopRenderThread();
}
void Oscilloscope::StartRenderThread()
{
if ( nullptr == m_RenderThread ) {
ResetEvent( m_RenderStopEvent );
m_RenderThread = CreateThread( NULL /*attributes*/, 0 /*stackSize*/, RenderThreadProc, reinterpret_cast<LPVOID>( this ), 0 /*flags*/, NULL /*threadId*/ );
}
}
void Oscilloscope::StopRenderThread()
{
if ( nullptr != m_RenderThread ) {
SetEvent( m_RenderStopEvent );
WaitForSingleObject( m_RenderThread, INFINITE );
CloseHandle( m_RenderThread );
m_RenderThread = nullptr;
}
}
void Oscilloscope::RenderThreadHandler()
{
DWORD result = 0;
do {
DoRender();
result = WaitForSingleObject( m_RenderStopEvent, s_RenderThreadInterval );
} while ( WAIT_OBJECT_0 != result );
}
void Oscilloscope::OnPaint()
{
ID2D1DeviceContext* deviceContext = BeginDrawing();
if ( nullptr != deviceContext ) {
LoadResources( deviceContext );
const D2D1_SIZE_F targetSize = deviceContext->GetSize();
if ( ( targetSize.height > 0 ) && ( targetSize.height > 0 ) ) {
if ( nullptr != m_BackgroundColour ) {
const D2D1_RECT_F rect = D2D1::RectF( 0 /*left*/, 0 /*top*/, targetSize.width, targetSize.height );
deviceContext->FillRectangle( rect, m_BackgroundColour );
}
if ( nullptr != m_Colour ) {
std::vector<float> sampleData;
long channelCount = 0;
const long scale = 4;
const long width = static_cast<long>( scale * targetSize.width );
GetOutput().GetSampleData( width, sampleData, channelCount );
if ( channelCount > 0 ) {
const FLOAT meterHeight = targetSize.height / channelCount;
const long sampleDataWidth = static_cast<long>( sampleData.size() / channelCount );
for ( long channelIndex = 0; channelIndex < channelCount; channelIndex++ ) {
const FLOAT halfHeight = meterHeight / 2;
const FLOAT centrePoint = channelIndex * meterHeight + halfHeight;
if ( width <= sampleDataWidth ) {
ID2D1Factory* factory = nullptr;
deviceContext->GetFactory( &factory );
if ( nullptr != factory ) {
ID2D1PathGeometry* pathGeometry = nullptr;
if ( SUCCEEDED( factory->CreatePathGeometry( &pathGeometry ) ) ) {
ID2D1GeometrySink* sink = nullptr;
if ( SUCCEEDED( pathGeometry->Open( &sink ) ) ) {
sink->SetFillMode( D2D1_FILL_MODE_ALTERNATE );
D2D1_POINT_2F point = D2D1::Point2F( 0 /*x*/, centrePoint - halfHeight * sampleData.at( channelIndex ) /*y*/ );
sink->BeginFigure( point, D2D1_FIGURE_BEGIN_HOLLOW );
for ( long pos = 1; ( pos < width / scale ); pos++ ) {
point = D2D1::Point2F( static_cast<FLOAT>( pos ) /*x*/,
centrePoint - halfHeight * sampleData.at( scale * pos * channelCount + channelIndex ) /*y*/ );
sink->AddLine( point );
}
sink->EndFigure( D2D1_FIGURE_END_OPEN );
sink->Close();
sink->Release();
deviceContext->DrawGeometry( pathGeometry, m_Colour, m_Weight );
}
pathGeometry->Release();
}
factory->Release();
}
} else {
const D2D1_POINT_2F startPoint = D2D1::Point2F( 0 /*x*/, centrePoint );
const D2D1_POINT_2F endPoint = D2D1::Point2F( static_cast<FLOAT>( width ) /*x*/, centrePoint );
deviceContext->DrawLine( startPoint, endPoint, m_Colour, m_Weight );
}
}
}
}
}
EndDrawing();
}
}
void Oscilloscope::OnSettingsChange()
{
FreeResources();
}
void Oscilloscope::OnSysColorChange()
{
}
void Oscilloscope::LoadResources( ID2D1DeviceContext* deviceContext )
{
if ( nullptr != deviceContext ) {
if ( ( nullptr == m_Colour ) && ( nullptr == m_BackgroundColour ) ) {
const COLORREF colour = GetSettings().GetOscilloscopeColour();
deviceContext->CreateSolidColorBrush( D2D1::ColorF(
static_cast<FLOAT>( GetRValue( colour ) ) / 0xff,
static_cast<FLOAT>( GetGValue( colour ) ) / 0xff,
static_cast<FLOAT>( GetBValue( colour ) ) / 0xff,
0xff ), &m_Colour );
const COLORREF background = GetSettings().GetOscilloscopeBackground();
deviceContext->CreateSolidColorBrush( D2D1::ColorF(
static_cast<FLOAT>( GetRValue( background ) ) / 0xff,
static_cast<FLOAT>( GetGValue( background ) ) / 0xff,
static_cast<FLOAT>( GetBValue( background ) ) / 0xff,
0xff ), &m_BackgroundColour );
m_Weight = GetSettings().GetOscilloscopeWeight();
}
}
}
void Oscilloscope::FreeResources()
{
if ( nullptr != m_Colour ) {
m_Colour->Release();
m_Colour = nullptr;
}
if ( nullptr != m_BackgroundColour ) {
m_BackgroundColour->Release();
m_BackgroundColour = nullptr;
}
}
| [
"james@vuplayer.com"
] | james@vuplayer.com |
ef6de0aad6dacc292ad14b410346e27e6f5ae621 | 4dd4f58ed9dbb5c0f93a63f2edec20e06bd66539 | /packages/thirdParty/wxWidgets/wxWidgets-2.9.4/include/wx/os2/combobox.h | 37eceeb791d2a8f06c3b5ba679acb274b2fb50f0 | [] | no_license | iokto/newton-dynamics | 042e46c5d7ea38252ad2ec7b26d537b4f148d502 | cf43da56760e53dbd19e9c25092ab28559f79f39 | refs/heads/master | 2021-01-19T07:33:50.459594 | 2015-07-19T01:58:05 | 2015-07-19T01:58:05 | 39,357,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,962 | h | /////////////////////////////////////////////////////////////////////////////
// Name: wx/os2/combobox.h
// Purpose: wxComboBox class
// Author: David Webster
// Modified by:
// Created: 10/13/99
// RCS-ID: $Id$
// Copyright: (c) David Webster
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_COMBOBOX_H_
#define _WX_COMBOBOX_H_
#include "wx/choice.h"
#include "wx/textentry.h"
#if wxUSE_COMBOBOX
// Combobox item
class WXDLLIMPEXP_CORE wxComboBox : public wxChoice,
public wxTextEntry
{
public:
inline wxComboBox() {}
inline wxComboBox( wxWindow* pParent
,wxWindowID vId
,const wxString& rsValue = wxEmptyString
,const wxPoint& rPos = wxDefaultPosition
,const wxSize& rSize = wxDefaultSize
,int n = 0
,const wxString asChoices[] = NULL
,long lStyle = 0
,const wxValidator& rValidator = wxDefaultValidator
,const wxString& rsName = wxComboBoxNameStr
)
{
Create( pParent
,vId
,rsValue
,rPos
,rSize
,n
,asChoices
,lStyle
,rValidator
,rsName
);
}
inline wxComboBox( wxWindow* pParent
,wxWindowID vId
,const wxString& rsValue
,const wxPoint& rPos
,const wxSize& rSize
,const wxArrayString& asChoices
,long lStyle = 0
,const wxValidator& rValidator = wxDefaultValidator
,const wxString& rsName = wxComboBoxNameStr
)
{
Create( pParent
,vId
,rsValue
,rPos
,rSize
,asChoices
,lStyle
,rValidator
,rsName
);
}
bool Create( wxWindow* pParent
,wxWindowID vId
,const wxString& rsValue = wxEmptyString
,const wxPoint& rPos = wxDefaultPosition
,const wxSize& rSize = wxDefaultSize
,int n = 0
,const wxString asChoices[] = NULL
,long lStyle = 0
,const wxValidator& rValidator = wxDefaultValidator
,const wxString& rsName = wxComboBoxNameStr
);
bool Create( wxWindow* pParent
,wxWindowID vId
,const wxString& rsValue
,const wxPoint& rPos
,const wxSize& rSize
,const wxArrayString& asChoices
,long lStyle = 0
,const wxValidator& rValidator = wxDefaultValidator
,const wxString& rsName = wxComboBoxNameStr
);
// See wxComboBoxBase discussion of IsEmpty().
bool IsListEmpty() const { return wxItemContainer::IsEmpty(); }
bool IsTextEmpty() const { return wxTextEntry::IsEmpty(); }
// resolve ambiguities among virtual functions inherited from both base
// classes
virtual void Clear();
virtual wxString GetValue() const;
virtual void SetValue(const wxString& value);
virtual wxString GetStringSelection() const
{ return wxChoice::GetStringSelection(); }
inline virtual void SetSelection(int n) { wxChoice::SetSelection(n); }
virtual void SetSelection(long from, long to)
{ wxTextEntry::SetSelection(from, to); }
virtual int GetSelection() const { return wxChoice::GetSelection(); }
virtual void GetSelection(long *from, long *to) const
{ wxTextEntry::GetSelection(from, to); }
virtual bool IsEditable() const;
virtual bool OS2Command( WXUINT uParam
,WXWORD wId
);
bool ProcessEditMsg( WXUINT uMsg
,WXWPARAM wParam
,WXLPARAM lParam
);
private:
// implement wxTextEntry pure virtual methods
virtual wxWindow *GetEditableWindow() { return this; }
virtual WXHWND GetEditHWND() const { return m_hWnd; }
DECLARE_DYNAMIC_CLASS(wxComboBox)
}; // end of CLASS wxComboBox
#endif // wxUSE_COMBOBOX
#endif
// _WX_COMBOBOX_H_
| [
"jerezjulio0@gmail.com"
] | jerezjulio0@gmail.com |
2c4aee2a0bf7ce2ae023bd965ffd7492b5e5e8d5 | 3abc173c09536289842c3a249967060ca6bfb8f8 | /1097.cpp | b2cabc4c1de611a689705fb8f4e9af3ec3accda8 | [] | no_license | Frank980908/51NOD | 2e06ff5e7f295c5c13272214b79b8634deafc567 | 3efd360183a7c2edeca332f6d29f9ea0a1214bcd | refs/heads/master | 2020-03-30T16:39:18.656851 | 2018-10-03T13:50:35 | 2018-10-03T13:50:35 | 151,414,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | #include <bits/stdc++.h>
using namespace std;
const int AX = 1e4+6;
string a[AX];
bool cmp(const string x , const string y ){
string x1 = x + y ; string x2 = y + x;
return x1 < x2;
}
int main(){
int n ;
cin >> n;
for( int i = 0 ; i < n ; i++ ){
cin >> a[i];
}
sort( a , a + n , cmp );
int tot = 0;
for( int i = 0 ; i < n ; i++ ){
int len = a[i].size();
for( int j = 0 ; j < len ; j++ ){
cout << a[i][j];
tot ++ ;
if( tot == 1000 ) { tot -= 1000; puts("");}
}
}
puts("");
return 0 ;
} | [
"1045000428@qq.com"
] | 1045000428@qq.com |
794762a6db1b5965187d221515c37a138aec2741 | 0ac4fb044735c1d8db0276834f4728980655be57 | /WrenCommon/Source/EventHandling/Events/ChangeActiveLayerEvent.h | 7f4b71c8a161e8a35a64b3f63e05e89c8a6681fe | [] | no_license | ericbfriday/wren | 87d0bc21f090d46f3bce40b70a495c82615861df | 5010309a705b7016c546215da01cb5f66e8910dd | refs/heads/master | 2020-12-08T20:38:15.428673 | 2019-12-01T06:52:41 | 2019-12-01T06:52:41 | 233,088,842 | 1 | 0 | null | 2020-01-10T16:40:05 | 2020-01-10T16:40:04 | null | UTF-8 | C++ | false | false | 244 | h | #pragma once
#include "Event.h"
#include "../../Layer.h"
class ChangeActiveLayerEvent : public Event
{
public:
ChangeActiveLayerEvent(const Layer layer)
: Event(EventType::ChangeActiveLayer),
layer{ layer }
{
}
const Layer layer;
}; | [
"drew.kestell@gmail.com"
] | drew.kestell@gmail.com |
478de40eaf1276711e23d07e2e2b40c8b918888c | fe265101e3b799864268427b0633a098f15683c8 | /Operaciones basicas.cpp | 8b1455cfcef51dbc1ab9725981b6c3670dff5a7b | [] | no_license | vladyslavTokmak/UTN-Curso-de-verano-2017 | 298b7a4cc0a0412e76fe2dfa5918969d3c2c1758 | 0b53e0da9d089841bed79542ecc752e4b5c7926c | refs/heads/master | 2021-01-18T13:08:43.665747 | 2017-02-10T21:59:33 | 2017-02-10T21:59:33 | 80,733,803 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,167 | cpp | /*
Id.Programa: Operaciones basicas
Autor......: Tokmak Vladyslav
Fecha......: Fedrero - 2017
Comentario.: Suma-resta-multiplicacion-division, curso de verano 2017
*/
#include <iostream>
using namespace std;
int main() {
int x,y;
int opcion;
float division = 0;
cout<<"Ingrese el primer numero(x): ";
cin>>x;
cout<<endl<<"Ingrese el segundo numero(y): ";
cin>>y;
cout<<endl<<"--- Menu ---"<<endl;
cout<<"1- Suma"<<endl;
cout<<"2- Resta"<<endl;
cout<<"3- Multiplicacion"<<endl;
cout<<"4- Division"<<endl;
cout<<"Que opcion elige?: ";
cin>>opcion;
switch(opcion){
case 1:
cout<<"Resultado de la suma: "<< x+y << endl;
break;
case 2:
cout<<"Resultado de x - y = "<< x-y << endl;
cout<<"Resultado de y - x = "<< y-x << endl;
break;
case 3:
cout<<"Resultado de la multiplicacion: "<< x*y << endl;
break;
case 4:
division = float(x) / float(y);
cout<<"Resultado de x / y = "<< division << endl;
division = float(y) / float(x);
cout<<"Resultado de y / x = "<< division << endl;
break;
default:
break;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
40c52c2d1edf1f2140187bfb3f08cf033284b2ae | 0d094ff96f957ad70882b5206eeedce7400a1980 | /Host_client/Server/Dealer.cpp | 40f9cf0cdb1a9f7297c217865df37fa1a45de8d9 | [] | no_license | Glowny/Korttipelimoottori | 28bc6c75e707fbe98004c68a597dc8b93bde60f0 | eb0945bb40a40f8bb91b1b034d4f559dd4f0e46c | refs/heads/master | 2021-01-20T07:50:58.371432 | 2014-07-28T04:42:55 | 2014-07-28T04:42:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 805 | cpp | #include "Dealer.h"
Dealer::Dealer(void)
{
std::srand(unsigned(std::time(NULL)));
initialize();
}
Dealer::~Dealer(void)
{
}
void Dealer::initialize()
{
deck.clear();
for(int i = 1; i <= 13; i++)
{
Card h(i, Hearts);
Card d(i, Diamonds);
Card c(i, Clubs);
Card s(i, Spades);
deck.push_back(h);
deck.push_back(d);
deck.push_back(c);
deck.push_back(s);
}
}
void Dealer::shuffle()
{
std::random_shuffle(deck.hand.begin(), deck.hand.end());
}
Hand Dealer::deal(int i)
{
Hand temp;
if(deck.hand.size() > 0)
{
for(int j = 0; j < i; j++)
{
if(deck.hand.size() > 0)
{
temp.push_back(deck.hand[0]);
deck.hand.erase(deck.hand.begin());
}
else
std::cout<<"Deck is empty"<<std::endl;
}
}
else
std::cout<<"Deck is empty"<<std::endl;
return temp;
} | [
"alluoma@outlook.com"
] | alluoma@outlook.com |
c14fd780da0e81aa5f47ba3bdaffcb9207100e98 | 95251dfb465d951dd8ce64c2f9b9625e458df315 | /Lab3_Circuit/Node.cpp | 388cce2d743e2758fdc0cc8dadf66d7aa4df5d44 | [] | no_license | zhangjingwei07/ece244_lab3 | 9063b3c5dbe45d7c5674c8368e25ef63718e6f43 | 9a1d0f22cc0140b361bc34267db3639c12550421 | refs/heads/master | 2020-03-21T15:19:16.645554 | 2017-10-18T01:09:06 | 2017-10-18T01:09:06 | 138,706,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,799 | cpp | //
// Node.cpp
// Lab3_Circuit
//
// Created by 张经纬 on 2017/10/11.
// Copyright © 2017年 Jingwei Zhang. All rights reserved.
//
#include <cstdlib>
#include <iomanip>
#include <string>
#include <iostream>
#include "Node.h"
#include "Rparser.h"
#include "Resistor.h"
// The node constructor
Node::Node(){
}
// The default node destructor
Node::~Node(){
}
// The function to determine whether the resistor array is full
bool Node::canAddResistor(int rIndex){
if (rIndex == maxResistor){
cout << "Error: resistor array is full" << endl;
return false;
}
return true;
}
// The function to determine whether the node array is full
bool Node::canAddNode(){
if(numRes == MAX_RESISTORS_PER_NODE){
cout << "Error: node is full" << endl;
return false;
}
return true;
}
// The function to add the resistor
void Node::addResistor (int rIndex){
resIDArray[numRes] = rIndex;
numRes++;
}
// The member function to print the node connection
void Node:: print (int nodeIndex){
if (numRes == 0)
cout << "Connections at node "<< nodeIndex << ": 0 resistor(s)" << endl;
else{
cout << "Connections at node " << nodeIndex <<": " <<numRes<<" resistor(s)"<< endl;
for(int i = 0; i< numRes ; i++){
cout <<" ";
cout.width(21);
cout << left << pResistorArray[resIDArray[i]]->getName();
cout.width(8);
cout << right << setiosflags(ios::fixed)
<< setprecision(2) << pResistorArray[resIDArray[i]]->getResistance()
<< " Ohms "
<< pResistorArray[resIDArray[i]]-> firstEnd()<< " -> "
<< pResistorArray[resIDArray[i]]->secondEnd() << endl;
}
}
}
| [
"danielzhang@s-MacBook-Pro.local"
] | danielzhang@s-MacBook-Pro.local |
c73f4dcef810e3ca386100f80164d9bb62d17f5f | c04366db4f98cf4c24db04bb512ff418e2bc57dc | /aws-cpp-sdk-ssm/include/aws/ssm/model/MaintenanceWindowTaskParameterValueExpression.h | 5b0bdb051b1cddf0b2ca858dba620bf368e3d2d3 | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | margomw/aws-sdk-cpp | 409259eb891162389bb6a1481fc0787c349252d3 | 5f60ff49d323c117eb1992aa059d8214a26d1506 | refs/heads/master | 2021-01-11T12:17:27.791797 | 2016-12-14T22:51:13 | 2016-12-14T22:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,534 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/ssm/SSM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace SSM
{
namespace Model
{
/**
* <p>Defines the values for a task parameter.</p>
*/
class AWS_SSM_API MaintenanceWindowTaskParameterValueExpression
{
public:
MaintenanceWindowTaskParameterValueExpression();
MaintenanceWindowTaskParameterValueExpression(const Aws::Utils::Json::JsonValue& jsonValue);
MaintenanceWindowTaskParameterValueExpression& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>This field contains an array of 0 or more strings, each 1 to 255 characters
* in length.</p>
*/
inline const Aws::Vector<Aws::String>& GetValues() const{ return m_values; }
/**
* <p>This field contains an array of 0 or more strings, each 1 to 255 characters
* in length.</p>
*/
inline void SetValues(const Aws::Vector<Aws::String>& value) { m_valuesHasBeenSet = true; m_values = value; }
/**
* <p>This field contains an array of 0 or more strings, each 1 to 255 characters
* in length.</p>
*/
inline void SetValues(Aws::Vector<Aws::String>&& value) { m_valuesHasBeenSet = true; m_values = value; }
/**
* <p>This field contains an array of 0 or more strings, each 1 to 255 characters
* in length.</p>
*/
inline MaintenanceWindowTaskParameterValueExpression& WithValues(const Aws::Vector<Aws::String>& value) { SetValues(value); return *this;}
/**
* <p>This field contains an array of 0 or more strings, each 1 to 255 characters
* in length.</p>
*/
inline MaintenanceWindowTaskParameterValueExpression& WithValues(Aws::Vector<Aws::String>&& value) { SetValues(value); return *this;}
/**
* <p>This field contains an array of 0 or more strings, each 1 to 255 characters
* in length.</p>
*/
inline MaintenanceWindowTaskParameterValueExpression& AddValues(const Aws::String& value) { m_valuesHasBeenSet = true; m_values.push_back(value); return *this; }
/**
* <p>This field contains an array of 0 or more strings, each 1 to 255 characters
* in length.</p>
*/
inline MaintenanceWindowTaskParameterValueExpression& AddValues(Aws::String&& value) { m_valuesHasBeenSet = true; m_values.push_back(value); return *this; }
/**
* <p>This field contains an array of 0 or more strings, each 1 to 255 characters
* in length.</p>
*/
inline MaintenanceWindowTaskParameterValueExpression& AddValues(const char* value) { m_valuesHasBeenSet = true; m_values.push_back(value); return *this; }
private:
Aws::Vector<Aws::String> m_values;
bool m_valuesHasBeenSet;
};
} // namespace Model
} // namespace SSM
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
4dcc5caa33532f7302707445cd1cb6326ca9847f | dbaf0bc1ee749efa2aa1405259c6d8e3f5c4eebf | /pocheng_HW3/pocheng_HW3/pocheng_Problem3.cpp | c292c574c09fa88efa36d1b72d32be7aa6d17c1a | [
"Apache-2.0"
] | permissive | dpocheng/CPP-Practice-Projects | 78a19e5ae6c87ecfb6c924b58ef3e6e4f33dddbf | 2695ea7c78f439e1d4334378b66d4cd2c3ce1922 | refs/heads/master | 2021-01-20T01:43:47.753096 | 2017-04-25T06:01:53 | 2017-04-25T06:01:53 | 89,322,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,643 | cpp | #include "pocheng_Problem3.h"
#include "pocheng_Hw3Stack.h"
#include <iostream>
#include <string>
using namespace std;
void Problem3() {
cout << "Problem 3" << endl;
// Case 1:
// Create a stack and print out the correct size / capacity based on user input
cout << "Case 1:" << endl;
Hw3Stack s;
cout << "Stack's Size : " << s.getSize() << endl;
cout << "Stack's Capacity: " << s.getCapacity() << endl;
cout << endl;
// Case2:
// Test the push, pop, top, isEmpty, and getSize functions for a stack with 0 items
// and 2 items in order to demonstrate the current behavior
cout << "Case2:" << endl;
stackItem item1 = { "someItem1" };
stackItem item2 = { "someItem2" };
// isEmpty() test for stack with 0 items
if (s.isEmpty() == true && s.getSize() == 0) {
cout << "isEmpty() test passed for stack with 0 items" << endl;
}
else {
cout << "isEmpty() test failed for stack with 0 items" << endl;
}
// top() test for stack with 0 items
if (s.top().name == "") {
cout << "top() test passed for stack with 0 items" << endl;
}
else {
cout << "top() test failed for stack with 0 items" << endl;
}
// pop() test for stack with 0 items
if (s.pop() == false && s.getSize() == 0) {
cout << "pop() test passed for stack with 0 items" << endl;
}
else {
cout << "pop() test failed for stack with 0 items" << endl;
}
// push() test
s.push(item1);
s.push(item2);
if (s.isEmpty() == false && s.getSize() == 2){
cout << "push() test passed for stack with 0 items" << endl;
}
else {
cout << "push() test failed for stack with 0 items" << endl;
}
// isEmpty() test for stack with 2 items
if (s.isEmpty() == false && s.getSize() != 0) {
cout << "isEmpty() test passed for stack with 2 items" << endl;
}
else {
cout << "isEmpty() test failed for stack with 2 items" << endl;
}
// top() test for stack with 2 items
if (s.top().name == "someItem2") {
cout << "top() test passed for stack with 2 items" << endl;
}
else {
cout << "top() test failed for stack with 2 items" << endl;
}
// pop() test for stack with 2 items
if (s.pop() == true && s.pop() == true && s.isEmpty() == true && s.getSize() == 0 && s.top().name == "") {
cout << "pop() test passed for stack with 2 items" << endl;
}
else {
cout << "pop() test failed for stack with 2 items" << endl;
}
cout << endl;
// Case 3:
// Test the case where push creates a new array with double the capacity
// double capacity test
cout << "Case 3:" << endl;
int beforeCapacity = s.getCapacity();
for (int num = 0; num < beforeCapacity; num++) {
if (num % 2 == 0)
s.push(item1);
else
s.push(item2);
}
int afterCapacity = s.getCapacity();
if (afterCapacity == beforeCapacity * 2) {
cout << "Double capacity test passed for stack" << endl;
}
else {
cout << "Double capacity test failed for stack" << endl;
}
cout << endl;
// Case 4:
// Test the copy constructor by creating a copy of a current Hw3Stack object and printing the
// elements, size, and capacity.
cout << "Case 4:" << endl;
Hw3Stack copiedStack(s);
if (s.getSize() == copiedStack.getSize() && s.getCapacity() == copiedStack.getCapacity()) {
cout << "Copy constructor test passed for stack" << endl;
}
else {
cout << "Copy constructor test failed for stack" << endl;
}
cout << "Stack's Size : " << copiedStack.getSize() << endl;
cout << "Stack's Capacity: " << copiedStack.getCapacity() << endl;
cout << "Stack's elements:" << endl;
copiedStack.printStack();
} | [
"noreply@github.com"
] | noreply@github.com |
99ca66817d7510bf9c90aba9391586aaa9ae4f4b | bc92c058b0c2dd2877648e30156245e36ee571a4 | /source/solution_zoo/video_box/include/mediapipemanager/basicmediamoudle.h | dd1068d29d989f77373235a548251bf460cc8b20 | [
"BSD-2-Clause"
] | permissive | robort-yuan/AI-EXPRESS | c1783f5f155b918dcc6da11956c842ae5467de8e | 56f86d03afbb09f42c21958c8cd9f2f1c6437f48 | refs/heads/master | 2023-02-09T03:51:44.775020 | 2021-01-02T15:15:37 | 2021-01-02T15:15:37 | 309,591,131 | 0 | 0 | BSD-2-Clause | 2020-12-08T07:48:54 | 2020-11-03T06:11:06 | null | UTF-8 | C++ | false | false | 1,107 | h | /**
* Copyright (c) 2020, Horizon Robotics, Inc.
* All rights reserved.
* @Author:
* @Mail: @horizon.ai
*/
#ifndef INCLUDE_BASICMEDIAMODULE_H_
#define INCLUDE_BASICMEDIAMODULE_H_
#include <cstdint>
#include <cstring>
#include "hb_vio_interface.h"
namespace horizon {
namespace vision {
typedef enum {
RTSP_Payload_NONE,
RTSP_Payload_H264,
RTSP_Payload_H265,
RTSP_Payload_PCMU,
RTSP_Payload_PCMA,
RTSP_Payload_AAC,
} RTSPPayloadType;
struct PipeModuleInfo {
void *attr;
uint32_t input_width;
uint32_t input_height;
uint32_t output_width;
uint32_t output_height;
uint32_t frame_depth;
uint16_t input_encode_type;
};
class BasicMediaModule {
public:
virtual int Init(uint32_t group_id, const PipeModuleInfo *module_info) = 0;
virtual int Start() = 0;
virtual int Input(void *data) = 0;
virtual int Output(void **data) = 0;
virtual int OutputBufferFree(void *data) = 0;
virtual int Stop() = 0;
virtual int DeInit() = 0;
BasicMediaModule(){};
~BasicMediaModule(){};
};
} // namespace vision
} // namespace horizon
#endif // INCLUDE_BASICMEDIAMODULE_H_ | [
"qingpeng.liu@horizon.ai"
] | qingpeng.liu@horizon.ai |
882321add7002d796f893730480d3f7ef9411138 | c5707dba79b69ed3080d452a1fe37840254f5de5 | /src/ParticleSystem.cpp | aefb3a136efc8108c5a3e174eab9fea1b5ae8ade | [] | no_license | August1s/Heart-Pool | 3903358a0fc58aefdacaf0f5dba9472cf58b908f | 8d45ea7951d0396ef5045b936d1850e79d011bb1 | refs/heads/master | 2023-07-23T22:35:21.377787 | 2021-08-28T10:46:31 | 2021-08-28T10:46:31 | 326,929,443 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,380 | cpp | #include "ParticleSystem.h"
ParticleSystem::ParticleSystem(float radius, int num, float width, float height, Curve& c)
:H(radius), HSQ(radius*radius), particles_num(num),
POLY6(315.f / (65.f * M_PI * pow(radius, 9.f))), SPIKY_GRAD(-45.f / (M_PI * pow(radius, 6.f))), VISC_LAP(45.f / (M_PI * pow(radius, 6.f))),
EPS(radius), VIEW_WIDTH(1.5 * width), VIEW_HEIGHT(1.5 * height),
curve(c)
{
int count = 0;
for (float y = VIEW_HEIGHT / 3; y < VIEW_HEIGHT - EPS * 2.f; y += H)
{
for (float x = VIEW_WIDTH / 4; x <= VIEW_WIDTH / 2; x += H)
{
if (particles.size() >= particles_num)
break;
float jitter = static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
particles.push_back(Particle(x + jitter, y));
count++;
}
}
std::cout << "initializing with " << count << " particles" << std::endl;
}
void ParticleSystem::Integrate()
{
for (auto& p : particles)
{
// forward Euler integration
p.v += DT * p.f / p.rho;
p.x += DT * p.v;
Collision(p);
}
}
void ParticleSystem::ComputeDensityPressure()
{
for (auto& pi : particles)
{
pi.rho = 0.f;
for (auto& pj : particles)
{
Eigen::Vector2d rij = pj.x - pi.x;
float r2 = rij.squaredNorm();
if (r2 < HSQ)
{
// this computation is symmetric
pi.rho += MASS * POLY6 * pow(HSQ - r2, 3.f);
}
}
pi.p = GAS_CONST * (pi.rho - REST_DENS);
}
}
void ParticleSystem::ComputeForces()
{
for (auto& pi : particles)
{
Eigen::Vector2d fpress(0.f, 0.f);
Eigen::Vector2d fvisc(0.f, 0.f);
for (auto& pj : particles)
{
if (&pi == &pj)
continue;
Eigen::Vector2d rij = pj.x - pi.x;
float r = rij.norm();
if (r < H)
{
// compute pressure force contribution
fpress += -rij.normalized() * MASS * (pi.p + pj.p) / (2.f * pj.rho) * SPIKY_GRAD * pow(H - r, 2.f);
// compute viscosity force contribution
fvisc += VISC * MASS * (pj.v - pi.v) / pj.rho * VISC_LAP * (H - r);
}
}
Eigen::Vector2d fgrav = G * pi.rho;
pi.f = fpress + fvisc + fgrav;
}
}
void ParticleSystem::Update()
{
ComputeDensityPressure();
ComputeForces();
Integrate();
}
void ParticleSystem::Restart()
{
particles.clear();
for (float y = VIEW_HEIGHT / 3; y < VIEW_HEIGHT - EPS * 2.f; y += H)
{
for (float x = VIEW_WIDTH / 4; x <= VIEW_WIDTH / 2; x += H)
{
if (particles.size() >= particles_num)
break;
float jitter = static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
particles.push_back(Particle(x + jitter, y));
}
}
}
void ParticleSystem::Collision(Particle& p)
{
/* 视口矩形作为边界 */
//if (p.x(0) - EPS < 0.0f)
//{
// p.v(0) *= -BOUND_DAMPING;
// p.x(0) = EPS;
//}
//if (p.x(0) + EPS > VIEW_WIDTH)
//{
// p.v(0) *= -BOUND_DAMPING;
// p.x(0) = VIEW_WIDTH - EPS;
//}
//if (p.x(1) - EPS < 0.0f)
//{
// p.v(1) *= -BOUND_DAMPING;
// p.x(1) = EPS;
//}
//if (p.x(1) + EPS > VIEW_HEIGHT)
//{
// p.v(1) *= -BOUND_DAMPING;
// p.x(1) = VIEW_HEIGHT - EPS;
//}
if (curve.Style == "circle")
{
/* 使用圆形作为边界*/
float R = curve.GetR(p.x(0), p.x(1));
float CurveR = curve.GetCurveR(p.x(0), p.x(1));
if (R + EPS / 2 > CurveR)
{
Eigen::Vector2d n = (Eigen::Vector2d(curve.Xoffset, curve.Yoffset) - p.x).normalized(); // 归一化法向量,指向圆心
Eigen::Vector2d Vn = -(p.v.dot(n)) * n; // 速度的法向分量
Eigen::Vector2d Vt = p.v + Vn; // 速度的切向分量
p.v = Vt + Vn; // 边界碰撞后的速度
//p.v(0) *= BOUND_DAMPING;
//p.v(1) *= BOUND_DAMPING;
//p.x = Eigen::Vector2d(curve.Xoffset, curve.Yoffset) - (CurveR - EPS / 2) * n;
p.x += n * EPS / 2;
}
}
else if (curve.Style == "heart")
{
/* 使用心形线作为边界 */
float R = curve.GetR(p.x(0), p.x(1));
float CurveR = curve.GetCurveR(p.x(0), p.x(1));
if (R + EPS / 2 > CurveR)
{
float delta = 0.00001;
float theta = curve.GetTheta(p.x(0), p.x(1));
Eigen::Vector2d t = curve.GetXY(theta + delta) - curve.GetXY(theta - delta);// 近似的切向向量
Eigen::Vector2d n = Eigen::Vector2d(-t(1), t(0));
n.normalize(); // 近似的单位法向量
Eigen::Vector2d Vn = -(p.v.dot(n)) * n;
Eigen::Vector2d Vt = p.v + Vn;
p.v = Vt + Vn;
//p.v(0) *= BOUND_DAMPING;
//p.v(1) *= BOUND_DAMPING;
//p.x = curve.GetXY(theta) + n * EPS / 2 ;
p.x += n * EPS / 2;
}
}
}
| [
"154010273@qq.com"
] | 154010273@qq.com |
369258f8d4885f00459cc1bc699e97099cfc2898 | 443416bab5d7c258936dae678feb27de6c537758 | /applications/ContactStructuralMechanicsApplication/custom_utilities/interface_preprocess.h | 1d8adae89f71a270bd9a4f8751c8ff66676e7409 | [
"BSD-3-Clause"
] | permissive | pyfsi/Kratos | b941e12594ec487eafcd5377b869c6b6a44681f4 | 726aa15a04d92c958ba10c8941ce074716115ee8 | refs/heads/master | 2020-04-27T17:10:10.357084 | 2019-11-22T09:05:35 | 2019-11-22T09:05:35 | 174,507,074 | 2 | 0 | NOASSERTION | 2020-03-27T16:38:28 | 2019-03-08T09:22:47 | C++ | UTF-8 | C++ | false | false | 8,578 | h | // KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: StructuralMechanicsApplication/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
#if !defined(KRATOS_INTERFACE_PREPROCESS_CONDITION_H_INCLUDED )
#define KRATOS_INTERFACE_PREPROCESS_CONDITION_H_INCLUDED
// System includes
#include <iostream>
// External includes
// Project includes
#include "includes/model_part.h"
#include "includes/define.h"
#include "includes/kratos_parameters.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @ingroup ContactStructuralMechanicsApplication
* @class InterfacePreprocessCondition
* @brief Creates Model Parts containing the interface
* @todo Add parallelization
* @author Vicente Mataix Ferrandiz
*/
class KRATOS_API(CONTACT_STRUCTURAL_MECHANICS_APPLICATION) InterfacePreprocessCondition
{
public:
///@name Type Definitions
///@{
/// Geometric definitions
typedef Point PointType;
typedef Node<3> NodeType;
typedef Geometry<NodeType> GeometryType;
typedef Geometry<PointType> GeometryPointType;
/// The index type
typedef std::size_t IndexType;
/// The size type
typedef std::size_t SizeType;
/// Definition of the entities container
typedef ModelPart::NodesContainerType NodesArrayType;
typedef ModelPart::ElementsContainerType ElementsArrayType;
typedef ModelPart::ConditionsContainerType ConditionsArrayType;
/// Pointer definition of ExactMortarIntegrationUtility
KRATOS_CLASS_POINTER_DEFINITION(InterfacePreprocessCondition);
///@}
///@name Life Cycle
///@{
/// Constructor
/**
* @brief This is the default constructor
* @param rMainModelPrt The model part to consider
*/
InterfacePreprocessCondition(ModelPart& rMainModelPrt)
:mrMainModelPart(rMainModelPrt)
{
}
/// Destructor.
virtual ~InterfacePreprocessCondition() = default;
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief Generate a new ModelPart containing only the interface. It will contain the conditions addressed in the call
* @param rInterfacePart The interface model part
* @param ThisParameters The configuration parameters
*/
void GenerateInterfacePart(
ModelPart& rInterfacePart,
Parameters ThisParameters = Parameters(R"({})")
);
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
ModelPart& mrMainModelPart; /// The main model part storing all the information
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
/**
* @brief Check if the existing conditions have properties and if doesn't it creates it
* @param rInterfacePart The interface model part
*/
void CheckAndCreateProperties(ModelPart& rInterfacePart);
/**
* @brief Check if the existing combination exists on the geometry
* @param IndexVector The vector containing the indexes of the nodes in the condition
* @param rElementGeometry The element geometry
*/
bool CheckOnTheFace(
const std::vector<std::size_t>& rIndexVector,
GeometryType& rElementGeometry
);
/**
* @brief Creates a new properties (contaning just values related with contact)
* @details These values are removed from the original property (in order to reduce overload of properties on the original elements)
* @return A map containing new properties
*/
std::unordered_map<IndexType, Properties::Pointer> CreateNewProperties();
/**
* @brief Copies a value from the original property to the new one
* @param pOriginalProperty The original property
* @param pNewProperty The new property
* @param rVariable The variable to copy an erase
*/
template<class TClass>
void CopyProperties(
Properties::Pointer pOriginalProperty,
Properties::Pointer pNewProperty,
const Variable<TClass>& rVariable,
const bool AssignZero = true
)
{
if(pOriginalProperty->Has(rVariable)) {
const TClass& value = pOriginalProperty->GetValue(rVariable);
pNewProperty->SetValue(rVariable, value);
} else if (AssignZero) {
KRATOS_INFO("InterfacePreprocessCondition") << "Property " << rVariable.Name() << " not available. Assigning zero value" << std::endl;
pNewProperty->SetValue(rVariable, rVariable.Zero());
}
}
/**
* @brief Creates a new condition with a giving name
* @param prThisProperties The pointer to the element
* @param rGeometry The geometry considered
* @param ConditionId The Id of the condition
* @param rCondition The base condition
*/
void CreateNewCondition(
Properties::Pointer prThisProperties,
const GeometryType& rGeometry,
const IndexType ConditionId,
Condition const& rCondition
);
/**
* @brief This method assign the corresponding master/slave flag to the condition in function of its nodes
* @param pCond The pointer to the condition
*/
void AssignMasterSlaveCondition(Condition::Pointer pCond);
/**
* @brief It prints the nodes and conditions in the interface, gives an error otherwise there are not
* @param NodesCounter Number of nodes in the interface
* @param rCondCounter Number of conditions in the interface
*/
void PrintNodesAndConditions(
const IndexType NodesCounter,
const IndexType rCondCounter
);
/**
* @brief It reorders the Ids of the conditions
* @return cond_id: The Id from the last condition
*/
IndexType ReorderConditions();
/**
* @brief This method creates the conditions for the edges
* @param rInterfacePart The model part of the interface
* @param prThisProperties The properties of the base element
* @param rEdgeGeometry Geometry considered
* @param SimplestGeometry If consider or not the simplest geometry
* @param rCondCounter The counter of conditions
* @param rConditionId The condition id
*/
inline void GenerateEdgeCondition(
ModelPart& rInterfacePart,
Properties::Pointer prThisProperties,
const GeometryType& rEdgeGeometry,
const bool SimplestGeometry,
IndexType& rCondCounter,
IndexType& rConditionId
);
/**
* @brief This method creates the conditions for the faces
* @param rInterfacePart The model part of the interface
* @param prThisProperties The properties of the base element
* @param rFaceGeometry Geometry considered
* @param SimplestGeometry If consider or not the simplest geometry
* @param rCondCounter The counter of conditions
* @param rConditionId The condition id
*/
inline void GenerateFaceCondition(
ModelPart& rInterfacePart,
Properties::Pointer prThisProperties,
const GeometryType& rFaceGeometry,
const bool SimplestGeometry,
IndexType& rCondCounter,
IndexType& rConditionId
);
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
///@name Private Inquiry
///@{
///@}
///@name Unaccessible methods
///@{
///@}
}; // Class InterfacePreprocessCondition
}
#endif /* KRATOS_INTERFACE_PREPROCESS_CONDITION_H_INCLUDED defined */
| [
"vmataix@cimne.upc.edu"
] | vmataix@cimne.upc.edu |
879c23629a6ef0e6ecf686675ee9df1f248d3e93 | ac48dc874f5550d03648c28b1eda5720202eb55c | /prebuilt_HY11/target/product/msm8937_64/obj/include/mare/mare/internal/synchronization/barrier.hh | 102978b8b5fbd1ba9eb47fe4edf2c32918c92557 | [] | no_license | difr/msm8937-8953_qcom_vendor | 464e478cae4a89de34ac79f4d615e5141c40cbcb | 6cafff53eca7f0c28fa9c470b5211423cf47fd40 | refs/heads/master | 2020-03-20T09:58:48.935110 | 2018-05-27T04:13:22 | 2018-05-27T04:13:22 | 137,355,108 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,410 | hh | // --~--~--~--~----~--~--~--~----~--~--~--~----~--~--~--~----~--~--~--~--
// Copyright 2013-2015 Qualcomm Technologies, Inc.
// All rights reserved.
// Confidential and Proprietary – Qualcomm Technologies, Inc.
// --~--~--~--~----~--~--~--~----~--~--~--~----~--~--~--~----~--~--~--~--
#pragma once
#include <atomic>
#include <cstdlib>
#include <mare/internal/legacy/task.hh>
#include <mare/internal/synchronization/mutex.hh>
namespace mare{
namespace internal{
class sense_barrier{
private:
std::atomic<size_t> _count;
size_t _total;
std::atomic<bool> _sense;
task_shared_ptr _wait_task[2];
size_t _delta;
public:
static const int WAIT_TASK_SPIN_THRESHOLD = 1000;
static const int SPIN_THRESHOLD = 10000;
void wait();
explicit sense_barrier(size_t count) : _count(count), _total(count),
_sense(false), _wait_task(),
_delta(_total / (4))
{
_wait_task[0] = nullptr;
_wait_task[1] = nullptr;
}
MARE_DELETE_METHOD(sense_barrier(sense_barrier&));
MARE_DELETE_METHOD(sense_barrier(sense_barrier&&));
MARE_DELETE_METHOD(sense_barrier& operator=(sense_barrier const&));
MARE_DELETE_METHOD(sense_barrier& operator=(sense_barrier&&));
private:
bool volatile_read_sense(){
return _sense.load(mare::mem_order_relaxed);
}
void create_wait_task(bool local_sense);
};
};
};
| [
"adithya.r02@outlook.com"
] | adithya.r02@outlook.com |
7a29fd17ead86c96b928ed44abec265df875b790 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE78_OS_Command_Injection/s03/CWE78_OS_Command_Injection__char_environment_w32_spawnlp_81.h | 8add8d3ad4d6449e5cfff2efb9e238a70a2bfba7 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,734 | h | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_environment_w32_spawnlp_81.h
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-81.tmpl.h
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: environment Read input from an environment variable
* GoodSource: Fixed string
* Sinks: w32_spawnlp
* BadSink : execute command with spawnlp
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "ls"
#define COMMAND_ARG2 "-la"
#define COMMAND_ARG3 data
#endif
namespace CWE78_OS_Command_Injection__char_environment_w32_spawnlp_81
{
class CWE78_OS_Command_Injection__char_environment_w32_spawnlp_81_base
{
public:
/* pure virtual function */
virtual void action(char * data) const = 0;
};
#ifndef OMITBAD
class CWE78_OS_Command_Injection__char_environment_w32_spawnlp_81_bad : public CWE78_OS_Command_Injection__char_environment_w32_spawnlp_81_base
{
public:
void action(char * data) const;
};
#endif /* OMITBAD */
#ifndef OMITGOOD
class CWE78_OS_Command_Injection__char_environment_w32_spawnlp_81_goodG2B : public CWE78_OS_Command_Injection__char_environment_w32_spawnlp_81_base
{
public:
void action(char * data) const;
};
#endif /* OMITGOOD */
}
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
36ffbe6246edc32860d2c1bafa50b76a6062fafb | e7de4d463001ae5523579c43d2a23949d1a1dcf0 | /src/main/cpp/native-lib.cpp | 6612cbfc5cef61369bd6d6934ba9a8708255cb55 | [] | no_license | Silver-Official/DexLoader | bb75bb9859f6bdcf5563ad0f997473fecb0b41be | fbce19fcdd620a51d8afe953f6d0d273bf845edd | refs/heads/master | 2023-05-24T20:46:56.564973 | 2019-12-26T02:36:39 | 2019-12-26T02:36:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,700 | cpp | #include <jni.h>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/inotify.h>
#include<pthread.h>
#include<sys/wait.h>
#include <signal.h>
#include <sys/select.h>
#include <stdio.h>
#include <sys/ptrace.h>
#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <assert.h>
#include <android/log.h>
jstring Check(
JNIEnv *env,
jobject,
jstring s) {
return env->NewStringUTF("Tql");
}
static const char *gClassName = "com/example/administrator/crackme/MainActivity";
static int registerNativeMethods(JNIEnv *env, const char *className,
JNINativeMethod *gMethods, int numMethods) {
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
return JNI_FALSE;
}
return JNI_TRUE;
}
static JNINativeMethod gMethods[] = {
{"Check", "(Ljava/lang/String;)Ljava/lang/String;", (void*)Check},
};
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env = NULL;
jint result = -1;
if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
else{
gMethods->fnPtr=(void*)Check;
}
if (registerNativeMethods(env, gClassName, gMethods,
sizeof(gMethods) / sizeof(gMethods[0])) == JNI_FALSE) {
return -1;
}
return JNI_VERSION_1_6;
} | [
"noreply@github.com"
] | noreply@github.com |
e38211388a21bbffced4cedfc331c3b2dfce3a9f | ccfbf5a9ee9c00282c200945bbe36b387eb38b19 | /Codeforces Solutions/codeforces 584D.cpp | ec6aab0dc206158f6b2270243a629c420401f22b | [] | no_license | sakiib/OnlineJudge-Solutions | e070d4b255d036cdefaf087e9f75b69db708406c | b024352aa99efe548b48ef74c492cb69c1fa89f9 | refs/heads/master | 2023-01-07T20:57:04.259395 | 2020-11-16T08:41:27 | 2020-11-16T08:41:27 | 288,191,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,050 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int LL;
typedef unsigned long long uLL;
typedef pair < int , int > ii;
const int inf = 1e9;
const LL INF = 1e18;
const int N = 1e5 + 5;
const int mod = 1000000007;
const double eps = 1e-8;
const double pi = acos( -1.0 );
bool ok( int n ) {
for( int i = 2; i*i <= n; i++ ) {
if( n%i == 0 ) return false;
}
return true;
}
vector <bool> isprime( N , true );
vector <int> prime;
void sieve( ) {
isprime[0] = isprime[1] = false;
prime.push_back( 2 );
int sq = sqrt( N );
for( int i = 4; i <= N; i += 2 ) isprime[i] = false;
for( int i = 3; i <= sq; i += 2 ) {
if( isprime[i] ) {
for( int j = i*i; j <= N; j+= 2*i ) {
isprime[j] = false;
}
}
}
for( int i = 3; i <= N; i+= 2 ) if( isprime[i] ) prime.push_back( i );
}
void brute( int n ) {
bool f = false;
for( int i = 0; i < prime.size() && prime[i] <= n; i++ ) {
for( int j = 0; j < prime.size() && prime[j] <= n; j++ ) {
for( int k = 0; k < prime.size() && prime[k] <= n; k++ ) {
if( prime[i]%2 == 0 || prime[j]%2 == 0 || prime[k]%2 == 0 ) continue;
if( prime[i]+prime[j]+prime[k] == n ) {
f = true;
cout <<n <<": "<< prime[i] << " " << prime[j] << " " << prime[k] << endl;
}
}
}
}
getchar();
if( !f ) cout << "Not Found " << endl;
}
int main( int argc , char const *argv[] ) {
ios_base :: sync_with_stdio(false); cin.tie(NULL);
sieve();
for( int i = 99999; i <= 99999; i+= 2 ) brute( i );
int n;
cin >> n;
if( ok(n) ) return cout << 1 << "\n" << n << endl,0;
return 0;
}
| [
"sakibalamin162@gmail.com"
] | sakibalamin162@gmail.com |
bb858117361b7700b1318da0b7cb51a5d30a30bb | 10ab53a980d7abac380b4e6cef7a113d5bc54330 | /tools/IIItest/Renderer.h | b11145ced83d88f7c35bbb7ab6c068147e633997 | [] | no_license | MonteHeights/librwgta | 0cce73b7649d43f8720f251416bcc943323c6b25 | dae35cbe16f8ad54f47f4b6e5abd29a056030b55 | refs/heads/master | 2021-04-27T12:07:33.127422 | 2018-01-15T15:46:14 | 2018-01-15T15:46:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 747 | h | class CRenderer
{
public:
static int ms_nNoOfVisibleEntities;
static int ms_nNoOfInVisibleEntities;
static CEntity *ms_aVisibleEntityPtrs[2000];
static CVector ms_vecCameraPosition;
public:
static void ConstructRenderList(void);
static void ScanSectorPoly(rw::V2d *poly, int numVerts, void (*f)(CSector*));
static void ScanWorld(void);
static void ScanBigBuildingList(CPtrList *list);
static void ScanSectorList(CSector *sec);
static bool SetupBigBuildingVisibility(CEntity *ent);
static int SetupEntityVisibility(CEntity *ent);
static void RenderOneNonRoad(CEntity *ent);
static void RenderEverything(void);
static void RenderEverythingBarRoads(void);
static void RenderRoads(void);
static void RenderFadingInEntities(void);
};
| [
"aap@papnet.eu"
] | aap@papnet.eu |
923e8d223732fe41dc7197ac294464dc03bf960c | 878a0c7a89ec5ef6c937eb79b57d64e4bfd73760 | /include/panoramagrid/uvmaterial.hpp | d952f2a8f3e3b6d609a35707d7ece79fb57eb090 | [] | no_license | krystiancha/panoramagrid | aa634a4bcfed1503177cf611a72445587958b8d9 | 23b454c9189dee4c409824c9cf9032f2438e0b42 | refs/heads/master | 2021-06-25T14:14:55.079134 | 2020-11-30T16:36:27 | 2020-11-30T16:40:38 | 174,722,347 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 426 | hpp | #ifndef PANORAMAGRID_UVMATERIAL_HPP
#define PANORAMAGRID_UVMATERIAL_HPP
#include <panoramagrid/material.hpp>
namespace panoramagrid {
class UvMaterial : public Material {
public:
const cv::Mat &getTexture() const override;
void setTexture(const cv::Mat &texture) override;
bool isCubemap() override;
private:
cv::Mat texture;
};
}
#endif //PANORAMAGRID_UVMATERIAL_HPP
| [
"krystiancha@gmail.com"
] | krystiancha@gmail.com |
29c55aff6392b7a620567fe70b03730a99658e9b | b483f26702813245c008530f1376d6446aaf8113 | /Dependencies/include/EventHandler.h | 1ea2542c2f9efb75ce31bf5d5adc7c9942bbddc5 | [] | no_license | bennybroseph/2D-OpenGL-Engine | c553dfa2b44e95f0720fcacfa289de2ef7025d05 | 8cfe480726aeb3d54a0c9166292f9662128582d5 | refs/heads/master | 2021-01-10T14:08:32.520575 | 2015-12-15T21:23:56 | 2015-12-15T21:23:56 | 43,943,477 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,520 | h | //////////////////////////////////////////////////////////////
// File: EventHandler.h
// Author: Ben Odom
// Brief: You're not meant to create an object of this class
// This class is created to simply be inherited by
// 'Loop'. By making all virtual, each object of
// 'Loops' (or its children) can redefine what
// happens on that event
//////////////////////////////////////////////////////////////
#ifndef _EVENTHANDLER_H_
#define _EVENTHANDLER_H_
#include <stdio.h>
#include <SDL.h>
class EventHandler
{
protected:
//////Constructor - Destructor//////
EventHandler();
//This should be virtual if any member function is virtual
virtual ~EventHandler();
//////Functions//////
//Takes in the event, and then calls the appropriate function
virtual void OnEvent(const SDL_Event& ac_sdlEvent);
//Deals with window focus (alt-tab)
virtual void OnInputFocus();
virtual void OnInputBlur();
//Takes in sym (The enum naming the key) the mod (if any, like shift), and unicode (in case of typing)
virtual void OnKeyDown(const SDL_Keycode ac_sdlSym, const Uint16 ac_uiMod, const SDL_Scancode ac_sdlScancode);
virtual void OnKeyUp(const SDL_Keycode ac_sdlSym, const Uint16 ac_uiMod, const SDL_Scancode ac_sdlScancode);
//Deals with window focus (clicking in and out)
virtual void OnMouseFocus();
virtual void OnMouseBlur();
//Passes mouse_x mouse_y x_velocity y_velocity buttonL, buttonR, buttonM (scroll wheel)
virtual void OnMouseMove(const Sint32 ac_iMouseX, const Sint32 ac_iMouseY, const Sint32 ac_iVelX, const Sint32 ac_VelY, const bool ac_bLeft, const bool ac_bRight, const bool ac_bMiddle);
//Passes which way the mouse wheel is spun
virtual void OnMouseWheel(const Sint32 ac_iVelX, const Sint32 ac_iVelY);
//If mouse buttons down/up
virtual void OnLButtonDown(const Sint32 ac_MouseX, const Sint32 ac_MouseY);
virtual void OnLButtonUp(const Sint32 ac_MouseX, const Sint32 ac_MouseY);
virtual void OnRButtonDown(const Sint32 ac_MouseX, const Sint32 ac_MouseY);
virtual void OnRButtonUp(const Sint32 ac_MouseX, const Sint32 ac_MouseY);
virtual void OnMButtonDown(const Sint32 ac_MouseX, const Sint32 ac_MouseY);
virtual void OnMButtonUp(const Sint32 ac_MouseX, const Sint32 ac_MouseY);
//Checks for joystick events, but there's an SDL_Joystick object which is much better
virtual void OnJoyAxis(const Uint8 ac_uiWhich, const Uint8 ac_uiAxis, const Sint16 ac_uiValue);
virtual void OnJoyButtonDown(const Uint8 ac_uiWhich, const Uint8 ac_uiButton);
virtual void OnJoyButtonUp(const Uint8 ac_uiWhich, const Uint8 ac_uiButton);
virtual void OnJoyHat(const Uint8 ac_uiWhich, const Uint8 ac_uiHat, const Uint8 ac_uiValue);
virtual void OnJoyBall(const Uint8 ac_uiWhich, const Uint8 ac_uiBall, const Sint16 ac_uiRelX, const Sint16 ac_uiRelY);
//Minimize and maximize of window
virtual void OnMinimize();
virtual void OnRestore();
//When the window gets resized, returns the new W and H
virtual void OnResize(const Sint32 ac_iWidth, const Sint32 ac_iHeight);
//Most likely when the window is restored from being minimized?
virtual void OnExpose();
//Can be different for each class that defines it
virtual void OnExit();
//No clue
virtual void OnUser(const Uint32 ac_uiType, const Sint32 ac_iCode, const void* ac_pData1, const void* ac_pData2);
};
//Renames EventHandler as EH
//With this, instead of doing EventHandler* handle = new EventHandler,
//You can do EH* handle = new EH
typedef EventHandler EH;
#endif // _EVENTHANDLER_H_
| [
"bennybroseph@gmail.com"
] | bennybroseph@gmail.com |
e52a84754e93075f8a32a34cca26e84f69b5ea54 | 38c75ea38cab758b96236fb01e77ae504491de37 | /PGML-BL/OpenFoam_Laminar/laminarFlatPlate/1/p | d6baf53bce27452a645b125e8208d6dd7e6cc28c | [
"Apache-2.0"
] | permissive | zuokuijun/PGML | afa4ea49cc2d6e3249fada1000b813730ea5e6e6 | 2b919d65e6467b2afdd9f58b9a72f1d5ec74132f | refs/heads/main | 2023-07-16T18:17:29.166672 | 2021-08-23T01:39:42 | 2021-08-23T01:39:42 | 435,793,580 | 1 | 0 | Apache-2.0 | 2021-12-07T08:05:32 | 2021-12-07T08:05:31 | null | UTF-8 | C++ | false | false | 28,752 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 5.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1";
object p;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -2 0 0 0 0];
internalField nonuniform List<scalar>
2475
(
0.034029
0.0299698
0.0238076
0.0179469
0.0122219
0.00629415
0.000633414
-0.00334281
-0.00467451
-0.00393542
-0.00244223
-0.00109232
-0.000205661
0.000251604
0.000430887
0.000469951
0.000460913
0.000444109
0.000431097
0.000414859
0.000396966
0.000370344
0.000327511
0.000274155
0.000225778
0.000173107
0.000123456
7.56247e-05
2.91997e-05
-1.88277e-05
-6.2994e-05
-8.85246e-05
-0.000113288
-8.74536e-05
-9.57384e-05
0.0306734
0.028564
0.0233699
0.0176976
0.0120864
0.00638625
0.00095456
-0.00295489
-0.00438743
-0.00375812
-0.00232809
-0.00101485
-0.000152494
0.000290118
0.000460901
0.000494709
0.000481927
0.000462272
0.000446855
0.000428663
0.000409078
0.000381199
0.000337132
0.0002828
0.00023348
0.000180123
0.000129669
8.13619e-05
3.42751e-05
-1.40774e-05
-5.88587e-05
-8.45415e-05
-0.000109888
-8.40333e-05
-9.2833e-05
0.0280573
0.0272143
0.0230137
0.0175917
0.0120705
0.00663622
0.00157165
-0.00220616
-0.00383404
-0.00346659
-0.00218655
-0.00094143
-0.000103749
0.000330158
0.000496474
0.000526616
0.000510072
0.000486497
0.000467417
0.000445972
0.000423642
0.00039355
0.000347641
0.000291863
0.000241385
0.000187109
0.000135788
8.68658e-05
3.9107e-05
-9.67959e-06
-5.50481e-05
-8.09767e-05
-0.000106836
-8.12146e-05
-9.04595e-05
0.0260183
0.025837
0.0225419
0.0175137
0.0121355
0.00695651
0.00225514
-0.00134781
-0.00313407
-0.0030646
-0.00198918
-0.000829588
-1.99039e-05
0.000401264
0.000556943
0.000577703
0.000553019
0.000522085
0.000496835
0.000470369
0.00044411
0.000410842
0.000362481
0.00030463
0.000252444
0.000196694
0.000144151
9.42091e-05
4.54835e-05
-4.08219e-06
-5.02469e-05
-7.67039e-05
-0.000103145
-7.83387e-05
-8.76713e-05
0.0242779
0.0244252
0.0218937
0.0173872
0.012244
0.00730369
0.00291853
-0.000501971
-0.0023971
-0.00260913
-0.0017578
-0.000697929
8.24419e-05
0.000493336
0.000638402
0.000647734
0.000612233
0.000571265
0.000537614
0.000504558
0.000473014
0.0004353
0.000383558
0.000322873
0.000268193
0.000210246
0.000155891
0.000104462
5.43655e-05
3.66502e-06
-4.3657e-05
-7.1012e-05
-9.81865e-05
-7.50504e-05
-8.37516e-05
0.0227105
0.0230316
0.0211059
0.0171942
0.0123833
0.00767731
0.00355369
0.000306949
-0.00165375
-0.00211506
-0.00149556
-0.000552325
0.000192847
0.000596115
0.00073338
0.000731312
0.000683335
0.000630529
0.000587071
0.000546661
0.000509026
0.000466199
0.000410528
0.000346696
0.000288915
0.000228285
0.000171455
0.000118117
6.61307e-05
1.40623e-05
-3.48741e-05
-6.34933e-05
-9.16276e-05
-7.11076e-05
-7.82635e-05
0.0212801
0.0217221
0.0202635
0.0169383
0.0125326
0.00807222
0.00416243
0.00106948
-0.000919215
-0.00158954
-0.00119963
-0.0003899
0.000310345
0.000706441
0.000839213
0.000826568
0.000764582
0.000697847
0.000642921
0.000594317
0.00054995
0.000501663
0.000441685
0.000374686
0.000313483
0.0002501
0.000190299
0.000134858
8.04742e-05
2.70487e-05
-2.39092e-05
-5.40237e-05
-8.34111e-05
-6.62982e-05
-7.12302e-05
0.0200075
0.0205614
0.0194551
0.0166379
0.0126638
0.00846866
0.00474434
0.00178565
-0.000202619
-0.00103956
-0.000867846
-0.000205809
0.000436319
0.000822315
0.000953424
0.00093222
0.000855503
0.000772739
0.000704357
0.000646433
0.00059473
0.00054067
0.000476028
0.00040578
0.000340895
0.00027474
0.000211635
0.000153981
9.67869e-05
4.20573e-05
-1.11635e-05
-4.29033e-05
-7.38027e-05
-6.06174e-05
-6.32361e-05
0.0189304
0.0196002
0.0187368
0.0163196
0.0127586
0.008849
0.00530385
0.00246577
0.0004945
-0.000471887
-0.00050069
4.35726e-06
0.000573858
0.000943184
0.00107426
0.00104769
0.000956712
0.000856098
0.00077196
0.00070319
0.000643353
0.000583075
0.000513407
0.00043972
0.00037088
0.000301791
0.000235124
0.000175071
0.000114783
5.86164e-05
3.04538e-06
-3.05481e-05
-6.3095e-05
-5.42384e-05
-5.50002e-05
0.0180065
0.0188089
0.0181212
0.0160017
0.012809
0.00919676
0.00583717
0.00311143
0.00116679
0.000102565
-0.000104392
0.000242228
0.000726114
0.00106955
0.00120013
0.0011718
0.00106835
0.000948739
0.000846457
0.000764968
0.00069595
0.000628906
0.000553894
0.000476517
0.000403455
0.000331146
0.000260701
0.00019796
0.00013443
7.65051e-05
1.86016e-05
-1.72368e-05
-5.14539e-05
-4.73146e-05
-4.69665e-05
0.0171572
0.0181079
0.0175825
0.0156966
0.0128159
0.00949635
0.00633186
0.00371619
0.00180635
0.000673246
0.000312835
0.000506817
0.000895997
0.00120297
0.00132963
0.00130212
0.00118914
0.00105072
0.0009284
0.000832166
0.000752676
0.000678153
0.000597463
0.000516136
0.000438647
0.00036278
0.000288385
0.000222593
0.000155755
9.56536e-05
3.54852e-05
-3.08112e-06
-3.89729e-05
-3.99041e-05
-3.93256e-05
0.0163412
0.0174552
0.017099
0.0154146
0.0127938
0.00974354
0.00677923
0.00427746
0.0024108
0.00123416
0.00074651
0.000797817
0.00108722
0.00134719
0.00146288
0.00143691
0.00131805
0.00116255
0.00101901
0.00090587
0.000814209
0.000731114
0.000644245
0.000558671
0.000476621
0.000396844
0.000318351
0.000249088
0.000178875
0.000116123
5.37306e-05
1.19497e-05
-2.56988e-05
-3.19763e-05
-3.21174e-05
0.0155458
0.0168368
0.0166585
0.0151617
0.0127606
0.00994619
0.00717727
0.00479479
0.00297889
0.00178056
0.00119221
0.00111333
0.00130153
0.00150556
0.00160134
0.0015753
0.00145405
0.00128422
0.00111909
0.000986956
0.000881224
0.000788176
0.000694488
0.000604309
0.000517574
0.000433498
0.000350752
0.000277577
0.000203909
0.00013804
7.33839e-05
2.7944e-05
-1.16745e-05
-2.34767e-05
-2.53334e-05
0.0147763
0.0162539
0.0162581
0.0149404
0.0127282
0.0101151
0.00752703
0.00526629
0.00350739
0.00230536
0.0016427
0.00144858
0.00153774
0.00168055
0.00174806
0.00171742
0.00159564
0.00141459
0.00122866
0.00107611
0.00095446
0.000849784
0.000748362
0.00065307
0.000561543
0.000472846
0.000385737
0.000308215
0.000230945
0.000161507
9.44561e-05
4.49977e-05
3.06195e-06
-1.43701e-05
-1.89604e-05
0.0140439
0.0157106
0.0158944
0.0147461
0.012699
0.0102567
0.00782975
0.00568915
0.00399272
0.00280058
0.002089
0.00179876
0.00179449
0.00187428
0.00190625
0.00186349
0.00174082
0.00155178
0.00134715
0.00117382
0.00103475
0.000916553
0.000806112
0.000705015
0.000608548
0.000514953
0.000423382
0.00034114
0.000260075
0.000186659
0.000116961
6.3192e-05
1.8483e-05
-4.64411e-06
-1.29673e-05
0.0133526
0.0152036
0.0155584
0.014569
0.0126707
0.0103746
0.00808837
0.00606214
0.00443225
0.0032598
0.00252243
0.00215934
0.00206971
0.00208632
0.00207778
0.00201473
0.00188862
0.00169452
0.00147387
0.00128014
0.00112259
0.000989054
0.000868076
0.000760307
0.000658669
0.000559919
0.000463758
0.000376486
0.000291373
0.000213627
0.000140928
8.26087e-05
3.45774e-05
5.69096e-06
-7.33594e-06
0.0126982
0.0147252
0.015243
0.0144036
0.0126423
0.0104733
0.00830843
0.00638666
0.00482539
0.00368083
0.00293583
0.00252323
0.0023591
0.00231404
0.00226364
0.0021741
0.00203976
0.00184194
0.00160782
0.00139462
0.00121827
0.00106803
0.000934903
0.000819279
0.000711979
0.000607841
0.00050698
0.000414467
0.000324989
0.000242585
0.000166424
0.000103349
5.14023e-05
1.66483e-05
-1.85014e-06
0.0120793
0.014273
0.0149463
0.0142474
0.0126122
0.0105549
0.00849303
0.00666375
0.00517178
0.0040628
0.00332212
0.00288045
0.00265723
0.00255503
0.00246417
0.00234422
0.00219499
0.00199241
0.00174705
0.001516
0.00132161
0.00115397
0.00100707
0.00088218
0.000768494
0.000658648
0.000552935
0.000455057
0.000360922
0.000273605
0.00019348
0.000125397
6.89358e-05
2.8142e-05
3.39751e-06
0.0115054
0.0138514
0.0146684
0.0140976
0.0125772
0.0106192
0.00864466
0.00689689
0.00547321
0.00440583
0.0036774
0.00322283
0.00295937
0.00280754
0.00267813
0.0025262
0.00235564
0.00214549
0.00189086
0.00164359
0.00143213
0.00124697
0.0010848
0.000949229
0.000828385
0.00071247
0.000601671
0.000498346
0.000399228
0.000306717
0.000222111
0.000148784
8.72161e-05
4.01248e-05
8.33084e-06
0.0109775
0.0134585
0.0144044
0.0139497
0.0125329
0.010665
0.00876746
0.00709231
0.0057336
0.00471155
0.00400237
0.00354583
0.00325932
0.00306795
0.00290221
0.0027191
0.00252331
0.00230206
0.00203897
0.00177657
0.00154895
0.00134716
0.00116894
0.00102124
0.000892088
0.000769485
0.000653217
0.000544413
0.000440091
0.000342214
0.000252562
0.000173645
0.000106372
5.26895e-05
1.36614e-05
0.0104793
0.0130835
0.014146
0.0137973
0.0124746
0.0106896
0.0088622
0.00725081
0.00595133
0.00497585
0.00429284
0.00384274
0.0035471
0.00332872
0.00313147
0.00292082
0.0026991
0.00246244
0.00219007
0.00191314
0.00166996
0.00145296
0.00125881
0.00109785
0.000959346
0.000829486
0.00070742
0.000593029
0.000483236
0.000379732
0.000284636
0.000199819
0.000126343
6.56377e-05
1.87146e-05
0.0100108
0.0127278
0.0138952
0.0136427
0.0124055
0.0106967
0.00893378
0.00737739
0.00613019
0.0052003
0.00454913
0.00411285
0.00381742
0.0035848
0.00336356
0.00312935
0.00288221
0.00262599
0.00234282
0.00205247
0.00179461
0.00156372
0.00135419
0.00117932
0.00103054
0.000892562
0.000764044
0.000643906
0.00052859
0.000419357
0.000318421
0.000227247
0.000147074
7.89219e-05
2.33332e-05
0.00958553
0.012402
0.0136613
0.0134928
0.0123312
0.0106901
0.00898506
0.0074767
0.00627583
0.00539006
0.00477443
0.00435799
0.00406797
0.00383086
0.00359501
0.00334157
0.00307102
0.00279395
0.00249895
0.00219562
0.00192277
0.00167872
0.00145471
0.00126564
0.00110588
0.000959213
0.000823657
0.000697534
0.000576441
0.000461211
0.000354035
0.000256217
0.000168859
9.28491e-05
2.88207e-05
0.00919198
0.0120979
0.0134381
0.013342
0.0122456
0.0106628
0.00900975
0.00754634
0.00638852
0.00554529
0.00496608
0.00457394
0.00429471
0.00406091
0.00381936
0.00355186
0.00326208
0.0029654
0.00265728
0.00234034
0.0020518
0.00179553
0.00155896
0.00135609
0.0011849
0.00102901
0.000885791
0.000753217
0.000626139
0.000504887
0.000391305
0.000286446
0.000191452
0.00010719
3.41724e-05
0.00881876
0.0118064
0.0132192
0.0131863
0.0121466
0.0106157
0.00901098
0.00759067
0.00647184
0.00566669
0.0051219
0.00475724
0.00449467
0.00426982
0.00403011
0.00375532
0.00345158
0.00313723
0.00281522
0.00248541
0.00218166
0.00191351
0.00166553
0.00144924
0.00126653
0.00110127
0.000950006
0.000810785
0.000677661
0.000550078
0.000429785
0.000317655
0.00021478
0.000121852
3.89597e-05
0.00847417
0.0115335
0.0130102
0.0130328
0.0120429
0.010558
0.00899586
0.00761352
0.00652818
0.00575647
0.00524476
0.00490992
0.00466877
0.00445698
0.00422455
0.00394943
0.00363723
0.00330715
0.00297155
0.00263086
0.0023124
0.00203138
0.00177264
0.00154415
0.00135064
0.00117634
0.00101671
0.000870216
0.000730588
0.000596652
0.000469633
0.000350044
0.000238869
0.000137029
4.4724e-05
0.00816206
0.0112831
0.0128145
0.0128841
0.0119357
0.0104888
0.00896201
0.00761264
0.00655816
0.00581823
0.00533898
0.00503448
0.00481698
0.00462072
0.00439867
0.00412856
0.0038135
0.00347139
0.00312391
0.00277395
0.00244143
0.0021477
0.00187982
0.00164039
0.00143604
0.00125267
0.00108464
0.000930889
0.000784811
0.000644357
0.00051028
0.000383063
0.000263466
0.000152477
5.06806e-05
0.00787819
0.0110522
0.0126291
0.0127371
0.0118222
0.0104065
0.00891004
0.00759073
0.00656553
0.00585503
0.00540552
0.0051293
0.00493565
0.00475692
0.00454828
0.00428723
0.00397497
0.003627
0.00327034
0.00291218
0.00256725
0.00226131
0.00198496
0.00173548
0.00152103
0.00132946
0.0011537
0.000992547
0.00083963
0.000692278
0.000551254
0.000416399
0.000288348
0.000167755
5.5456e-05
0.00761666
0.0108355
0.0124506
0.0125907
0.0117037
0.0103145
0.00884398
0.00755058
0.00655058
0.00586503
0.00544136
0.00519119
0.0050228
0.00486559
0.00467419
0.00442476
0.00411836
0.00376971
0.00340625
0.00304161
0.00268836
0.00237122
0.00208633
0.0018288
0.00160566
0.00140657
0.00122338
0.00105469
0.000895073
0.000741079
0.000592887
0.000450104
0.000313596
0.000183407
5.93588e-05
0.00736615
0.0106248
0.0122745
0.0124434
0.0115803
0.0102119
0.00876118
0.00748745
0.00650768
0.00584323
0.00544278
0.00521775
0.00507581
0.00494242
0.0047701
0.00453468
0.00423696
0.00389236
0.00352618
0.003158
0.00280074
0.00247477
0.00218223
0.0019187
0.00168798
0.00148202
0.00129273
0.00111792
0.000951773
0.000790863
0.00063541
0.000485153
0.000340182
0.000201352
6.98024e-05
0.00679993
0.0101476
0.0118746
0.012103
0.011283
0.00994804
0.00852765
0.00728516
0.00634025
0.00571631
0.00536398
0.00519258
0.00510555
0.00502378
0.00489728
0.00470217
0.00443563
0.00411069
0.00374911
0.00337746
0.00301447
0.00267492
0.00236926
0.00209595
0.00185249
0.00163512
0.00143543
0.0012478
0.00106856
0.000894472
0.000724052
0.000557198
0.000394096
0.000235107
7.99103e-05
0.0070429
0.0102903
0.0119068
0.0120241
0.0111052
0.00969331
0.0082226
0.00695599
0.00601105
0.00540832
0.00509395
0.0049721
0.00493972
0.00491153
0.00483263
0.00467767
0.00444412
0.00414595
0.00380598
0.0034499
0.0030992
0.00276876
0.00246735
0.00219676
0.00195481
0.00173592
0.00153291
0.00134013
0.001153
0.000968247
0.000784937
0.000603099
0.00042347
0.000247421
7.6924e-05
0.0055923
0.00882267
0.0104837
0.0106999
0.00991239
0.00864017
0.00729973
0.00614579
0.00529301
0.00475892
0.00448816
0.00438916
0.00437023
0.00435881
0.00430705
0.00419161
0.00401107
0.00377921
0.00351454
0.00323421
0.00295416
0.00268787
0.00244022
0.00221001
0.0019965
0.00179642
0.00160424
0.00141669
0.00123155
0.0010469
0.000861988
0.000676419
0.000489521
0.000300204
0.000106729
0.00437648
0.000949656
-0.000891655
-0.00127449
-0.000646302
0.00046692
0.00164177
0.00261777
0.00327708
0.00359991
0.00364004
0.00348889
0.00324018
0.00296954
0.00272759
0.00253928
0.00240686
0.00231792
0.00225523
0.00220214
0.00214276
0.00206447
0.00196434
0.00184406
0.00170507
0.00155244
0.00139227
0.00122807
0.00106255
0.00089749
0.000733161
0.000569189
0.000405153
0.000240879
7.69481e-05
0.00321216
-0.000246106
-0.00206655
-0.00238096
-0.00165802
-0.000448717
0.00080831
0.00184866
0.00255443
0.00290527
0.00295641
0.00280493
0.00255416
0.00228844
0.00206217
0.00190113
0.00180929
0.00177444
0.00177492
0.00178711
0.00179111
0.00177355
0.0017278
0.00165253
0.00155128
0.00143025
0.00129569
0.00115319
0.00100709
0.000859745
0.000711815
0.000562685
0.000410769
0.000253962
9.00929e-05
0.00398032
0.000392903
-0.00157591
-0.00204803
-0.001476
-0.000396486
0.000758279
0.0017234
0.00237826
0.00269853
0.00273302
0.00257197
0.00231271
0.00203576
0.00179472
0.00161676
0.00150817
0.00145951
0.00145209
0.00146438
0.00147734
0.00147677
0.0014538
0.00140523
0.00133212
0.00123808
0.00112841
0.00100847
0.00088249
0.000753325
0.000622406
0.000489846
0.000354936
0.000216597
7.38399e-05
0.00361956
1.89276e-05
-0.00196199
-0.00244516
-0.00188294
-0.000811677
0.000336678
0.00129731
0.00194954
0.00226888
0.00230382
0.00214425
0.00188724
0.00161318
0.00137583
0.00120265
0.00110026
0.00105966
0.00106262
0.00108804
0.00111688
0.0011348
0.00113305
0.00110806
0.00106025
0.000992742
0.000910036
0.000816679
0.000716527
0.000612311
0.000505585
0.000396884
0.000286128
0.000172971
5.72546e-05
0.0035806
-1.81741e-05
-0.00200059
-0.0024881
-0.00193219
-0.000868381
0.000271996
0.00122455
0.00186884
0.00218055
0.00220827
0.00204188
0.00177848
0.00149857
0.00125596
0.00107817
0.000971894
0.000928283
0.000929283
0.000953975
0.000983453
0.00100357
0.00100574
0.000986426
0.000946051
0.000887672
0.000815559
0.000734029
0.000646647
0.000555801
0.000462667
0.00036733
0.000269077
0.000166703
5.88611e-05
0.00341394
-0.000187156
-0.00217217
-0.00266271
-0.00211027
-0.00105022
8.62625e-05
0.00103492
0.00167542
0.00198353
0.00200789
0.00183847
0.00157245
0.00129033
0.001046
0.000867067
0.000760305
0.000716967
0.000719083
0.00074583
0.00077842
0.000802797
0.000810442
0.000797875
0.000765571
0.000716578
0.000655154
0.000585588
0.000511425
0.000435085
0.000357857
0.000280085
0.000201534
0.000121753
4.04574e-05
0.00324309
-0.000356721
-0.00234048
-0.00282982
-0.00227624
-0.00121505
-7.7369e-05
0.000872639
0.00151469
0.00182455
0.00185087
0.00168361
0.00141991
0.00114027
0.000898592
0.000722493
0.0006188
0.000578799
0.000584565
0.000615339
0.000652404
0.000681757
0.000694944
0.000688577
0.000663196
0.000621896
0.000568972
0.000508712
0.000444625
0.000379047
0.000313114
0.000246922
0.00017985
0.000110896
3.9049e-05
0.00310017
-0.000498059
-0.00248061
-0.002969
-0.00241455
-0.00135247
-0.000213821
0.000737255
0.00138046
0.00169156
0.00171917
0.00155324
0.00129091
0.00101273
0.00077262
0.000598232
0.000496426
0.000458542
0.000466712
0.000500222
0.000540383
0.000573229
0.000590335
0.000588306
0.000567687
0.000531603
0.000484386
0.000430381
0.00037317
0.000315174
0.000257644
0.00020084
0.000144369
8.75537e-05
2.98261e-05
0.00297555
-0.000621651
-0.00260332
-0.00309094
-0.00253575
-0.0014729
-0.000333412
0.000618599
0.00126285
0.0015751
0.00160396
0.00143937
0.00117848
0.000901842
0.00066339
0.000490804
0.000390968
0.000355245
0.000365799
0.000401944
0.000445014
0.000481075
0.000501738
0.000503654
0.000487414
0.000456195
0.000414372
0.000366337
0.000315712
0.000264955
0.000215336
0.000167114
0.000119862
7.28278e-05
2.53292e-05
0.00287347
-0.000723141
-0.00270413
-0.00319098
-0.00263496
-0.00157122
-0.000430772
0.000522263
0.00116761
0.00148104
0.00151115
0.00134791
0.00108846
0.00081335
0.000576541
0.00040572
0.000307787
0.000274126
0.000286916
0.000325492
0.000371209
0.000410155
0.000433962
0.000439305
0.000426796
0.000399629
0.000362199
0.000318907
0.000273384
0.000228096
0.000184317
0.000142311
0.000101653
6.16022e-05
2.14878e-05
0.00280071
-0.000795401
-0.00277585
-0.00326213
-0.00270549
-0.00164109
-0.000499921
0.000453892
0.00110008
0.00141441
0.0014455
0.00128328
0.00102491
0.000750955
0.000515373
0.000345861
0.000249329
0.000217175
0.000231591
0.000271923
0.000319539
0.000360536
0.00038656
0.0003943
0.000384376
0.000359997
0.00032557
0.000285513
0.000243471
0.000201927
0.000162171
0.000124487
8.84715e-05
5.34083e-05
1.8659e-05
0.00276203
-0.000833421
-0.00281338
-0.0032993
-0.00274242
-0.00167781
-0.000536441
0.000417614
0.0010641
0.0013788
0.00141032
0.00124861
0.000990811
0.000717485
0.000482586
0.000313807
0.000218052
0.00018672
0.000202008
0.000243272
0.000291886
0.000333956
0.00036114
0.000370136
0.000361576
0.000338676
0.000305853
0.000267533
0.000227368
0.000187849
0.000150276
0.000114937
8.14386e-05
4.90709e-05
1.72012e-05
0.0124201
0.010345
0.0102007
0.0100554
0.010149
0.009682
0.00997284
0.00985551
0.009907
0.0102543
0.0107312
0.0112394
0.0117507
0.0127214
0.014056
0.0158214
0.0181172
0.0210044
0.0245842
0.0287735
0.0124252
0.0103335
0.010207
0.0100345
0.0101568
0.00966467
0.00998676
0.00982661
0.00992625
0.0102029
0.0107501
0.0111397
0.0117765
0.0126703
0.0140772
0.0157505
0.0180833
0.0207266
0.0238684
0.0271426
0.012426
0.0103196
0.0102131
0.0100136
0.0101624
0.00964686
0.00999796
0.0097975
0.0099427
0.0101506
0.0107628
0.0110656
0.0117895
0.0126255
0.0140643
0.015656
0.0179045
0.0202342
0.0228396
0.0254216
0.0124209
0.0103051
0.0102195
0.00999233
0.0101637
0.00963198
0.010006
0.00977333
0.00995176
0.0101146
0.0107495
0.0110245
0.0117516
0.0126
0.0139846
0.015517
0.0175386
0.0195832
0.0217004
0.0238489
0.012412
0.0102908
0.0102264
0.00997139
0.0101623
0.00962304
0.0100081
0.0097604
0.00994551
0.0100965
0.0107009
0.0110011
0.0116716
0.0125517
0.0138454
0.0152929
0.0170477
0.018811
0.0205598
0.0224049
0.0124009
0.0102783
0.0102327
0.00995346
0.0101568
0.00962215
0.00999914
0.00976176
0.00991772
0.0101126
0.0106283
0.0109661
0.0115744
0.0124467
0.0136362
0.0149628
0.0164673
0.0179704
0.019442
0.021045
0.0123878
0.0102691
0.0102364
0.0099406
0.0101431
0.00963156
0.00997526
0.00977853
0.00986633
0.0101144
0.0105546
0.0109101
0.0114577
0.0122738
0.0133301
0.014504
0.015801
0.017103
0.0183653
0.0197714
0.0123718
0.0102654
0.0102352
0.00993465
0.0101179
0.00965193
0.00993544
0.009804
0.0098085
0.0101008
0.01049
0.0108299
0.0113156
0.0120464
0.0129315
0.0138778
0.0149437
0.0161412
0.0174076
0.0185922
0.0123517
0.0102695
0.0102274
0.00993585
0.0100808
0.00967929
0.00988808
0.00981897
0.00976966
0.0100681
0.0104329
0.0107293
0.0111427
0.01176
0.0124943
0.0132188
0.0140219
0.0149642
0.0160268
0.0173893
0.0123252
0.0102848
0.010212
0.00994458
0.0100315
0.00970968
0.0098417
0.00982069
0.00975078
0.0100222
0.0103672
0.0106096
0.0109299
0.0113808
0.0118867
0.0124008
0.0130056
0.0137691
0.0147935
0.0162788
0.0122898
0.0103141
0.0101884
0.00995986
0.00997315
0.00973659
0.00980899
0.00981258
0.00973024
0.00996441
0.0102703
0.0104108
0.0105907
0.0109045
0.0112406
0.0115687
0.0119942
0.0126381
0.013655
0.0152562
0.0122441
0.0103603
0.0101575
0.00997515
0.00991854
0.00974338
0.00979955
0.0097967
0.00970493
0.00986222
0.0100846
0.0101458
0.0102128
0.0103912
0.0105773
0.0107419
0.0110134
0.0115627
0.0125762
0.0142802
0.0121857
0.0104255
0.0101226
0.00998303
0.00987857
0.00973165
0.00978301
0.0097657
0.00962424
0.0097078
0.00986779
0.00985856
0.00981219
0.00985327
0.00990547
0.00992834
0.0100612
0.0105193
0.0115256
0.013325
0.0121135
0.010508
0.0100963
0.00997642
0.0098553
0.0097091
0.00972796
0.00968128
0.00951545
0.00953493
0.00962819
0.00955202
0.00939555
0.00929723
0.00921598
0.00911176
0.0091219
0.00949553
0.0104965
0.0123908
0.0120283
0.0105967
0.010089
0.0099605
0.00982626
0.00966754
0.00965215
0.00958277
0.00939034
0.00934308
0.00936715
0.00922354
0.00896121
0.00872077
0.00850031
0.00828041
0.0081908
0.00849637
0.00949987
0.0114909
0.01193
0.0106827
0.0101172
0.0099397
0.00978435
0.00961105
0.00956066
0.00946335
0.00924474
0.00913343
0.00908221
0.00886646
0.00849978
0.00811955
0.00776365
0.00744146
0.00727793
0.00753757
0.00855204
0.0106375
0.0118189
0.0107631
0.0101693
0.00991875
0.00972866
0.00953593
0.00944836
0.00932221
0.00907948
0.00890291
0.00876623
0.0084723
0.00800872
0.00750248
0.0070233
0.00661165
0.00639358
0.00662668
0.0076585
0.00983206
0.0116983
0.0108274
0.0102456
0.00990806
0.00966283
0.00943968
0.00931365
0.00915786
0.00888851
0.00864445
0.00841959
0.00804716
0.00749772
0.00688349
0.00629408
0.00580125
0.00553916
0.00576031
0.00681692
0.00907335
0.0115802
0.010866
0.0103197
0.00990963
0.00959472
0.00932681
0.00915333
0.00896187
0.00866532
0.00836267
0.00805448
0.00760436
0.00697535
0.00626514
0.0055811
0.00501744
0.00472073
0.00494261
0.0060338
0.00837099
0.0114704
0.0108926
0.0103682
0.00991967
0.0095266
0.00919077
0.00895849
0.00872761
0.00840976
0.00805924
0.00767261
0.0071447
0.00644062
0.00564838
0.00488605
0.00426582
0.00394522
0.0041774
0.00531044
0.00772624
0.0113633
0.0108579
0.0104106
0.0099955
0.00951668
0.00905071
0.00872111
0.00844698
0.00811554
0.00772635
0.00726801
0.00666638
0.005897
0.00503734
0.00421196
0.00354706
0.00320945
0.00345475
0.00463036
0.00712069
0.0112791
0.0108373
0.0103856
0.00991878
0.00946772
0.0089933
0.00853069
0.00818101
0.00781592
0.00738078
0.00685359
0.0061833
0.00535779
0.00444511
0.00357025
0.00286939
0.00251843
0.00277644
0.00399226
0.00655258
0.0112355
0.0108735
0.0103491
0.00979421
0.0092683
0.00877206
0.00834194
0.00795939
0.00753741
0.00703648
0.00643757
0.00570256
0.0048289
0.00387986
0.00296995
0.00224263
0.0018831
0.00215506
0.00340958
0.00603583
0.011181
0.010839
0.0102818
0.00966684
0.00908929
0.00858688
0.00815478
0.00773676
0.00725739
0.00668794
0.00601909
0.00522567
0.00431037
0.00333353
0.00240079
0.00165726
0.00129512
0.00158273
0.00287361
0.00555974
0.0111136
0.0107922
0.0102157
0.0095501
0.00892591
0.00839388
0.00793913
0.00748537
0.00695907
0.00633208
0.00560109
0.0047538
0.00380141
0.00280215
0.00185526
0.0011038
0.000744079
0.00104827
0.00237265
0.00511226
0.0110432
0.0107308
0.0101261
0.00941898
0.00875221
0.00818514
0.00769641
0.00720724
0.00664345
0.00597167
0.00518895
0.00429593
0.00331335
0.00229755
0.0013433
0.000590392
0.00023703
0.00055849
0.00191398
0.00470168
0.0109636
0.0106497
0.0100164
0.00927078
0.00856696
0.00796608
0.00744365
0.00692011
0.00632268
0.00561435
0.0047893
0.00386098
0.00285532
0.00182795
0.000870958
0.000121355
-0.000222444
0.000116878
0.00150121
0.00433177
0.0108681
0.0105484
0.00988713
0.00910736
0.00837051
0.00773944
0.00718733
0.006633
0.0060052
0.00526698
0.00440967
0.00345241
0.00242746
0.00139061
0.000432547
-0.00031125
-0.000642591
-0.000283998
0.00112788
0.00399716
0.010753
0.010423
0.0097393
0.00892776
0.00816262
0.00750714
0.00693161
0.00635342
0.00570039
0.00493771
0.00405631
0.00307633
0.00203493
0.000988652
2.73011e-05
-0.000713931
-0.00103317
-0.000653463
0.000785801
0.00369096
0.0106163
0.0102791
0.00956836
0.0087299
0.00794349
0.00727163
0.0066801
0.00608672
0.00541773
0.00463792
0.00373986
0.00274461
0.00169091
0.000636482
-0.000328632
-0.00106871
-0.00138389
-0.000993059
0.000469315
0.00340366
0.0102283
0.00987272
0.0091132
0.00822451
0.00740486
0.00671471
0.00610932
0.00550495
0.00482611
0.00403239
0.00312071
0.00211095
0.00104341
-2.13854e-05
-0.000994426
-0.00174292
-0.00206903
-0.00168655
-0.000217713
0.0027599
0.00923464
0.00889769
0.00818709
0.00736661
0.00663014
0.00603291
0.00552478
0.00502457
0.00446757
0.00381582
0.00305499
0.00219099
0.00125034
0.00028404
-0.000623424
-0.00133875
-0.00165965
-0.00129492
0.000139054
0.00307126
0.00818298
0.0080151
0.00751885
0.00694643
0.00645423
0.00605312
0.00566098
0.00518826
0.00457321
0.00379669
0.0028703
0.00182421
0.000703196
-0.000430359
-0.00148821
-0.00233687
-0.00277677
-0.00251715
-0.00117296
0.00168505
0.00455557
0.00468704
0.00512031
0.00561246
0.00601035
0.00630295
0.00657251
0.00691152
0.00737927
0.00799672
0.00875683
0.00963358
0.0105851
0.0115506
0.0124426
0.0131275
0.0134057
0.0129869
0.0114853
0.00846821
0.00365418
0.00396159
0.00461716
0.0053684
0.006021
0.00650991
0.00687754
0.00720712
0.0075779
0.00804355
0.00862804
0.00932838
0.0101177
0.0109433
0.0117188
0.0123082
0.0125055
0.0120145
0.0104461
0.00736714
0.0026405
0.00302912
0.00383386
0.00477646
0.00564457
0.0063579
0.00694919
0.00749981
0.00808608
0.00875208
0.0095098
0.0103464
0.0112293
0.0121041
0.0128868
0.0134473
0.0135883
0.0130247
0.011379
0.0082268
0.00215798
0.00259498
0.00346876
0.00449573
0.00545316
0.00624677
0.00689696
0.00747787
0.00806457
0.00870791
0.00942914
0.0102234
0.0110633
0.0118982
0.0126456
0.0131758
0.0132915
0.0127071
0.0110445
0.0078791
0.00176896
0.00222287
0.00312311
0.00418268
0.00517561
0.00600416
0.0066862
0.00729513
0.00790622
0.00857038
0.00930908
0.0101181
0.010971
0.0118171
0.0125739
0.0131117
0.0132333
0.0126538
0.0109958
0.00783532
0.00147811
0.00194158
0.00285739
0.00393649
0.00495082
0.00580048
0.00650168
0.00712671
0.00775043
0.00842375
0.00916835
0.00998021
0.010833
0.0116765
0.0124292
0.0129622
0.0130791
0.0124953
0.0108338
0.00767087
0.00124533
0.00171304
0.00263552
0.00372291
0.00474621
0.00560437
0.00631255
0.00694275
0.00756997
0.00824549
0.0089914
0.00980402
0.0106573
0.0115013
0.0122544
0.0127879
0.0129053
0.0123221
0.0106612
0.00749896
0.00105127
0.00152098
0.00244674
0.00353817
0.00456584
0.00542838
0.00614072
0.00677454
0.00740477
0.00808274
0.00883066
0.00964501
0.0104999
0.0113457
0.0121007
0.012636
0.0127553
0.0121739
0.0105147
0.00735423
0.000892074
0.00136295
0.00229063
0.00338444
0.00441467
0.00527981
0.00599472
0.00663111
0.00726385
0.00794422
0.00869438
0.00951075
0.0103674
0.0112146
0.0119708
0.0125071
0.0126272
0.0120466
0.0103883
0.00722862
0.00076781
0.00123953
0.00216863
0.00326416
0.00429624
0.00516324
0.00587996
0.00651807
0.00715242
0.00783426
0.00858574
0.00940327
0.0102609
0.0111091
0.0118659
0.0124029
0.0125236
0.0119434
0.0102855
0.00712613
0.000679889
0.00115215
0.00208215
0.00317877
0.00421203
0.00508019
0.00579804
0.00643721
0.00707257
0.00775535
0.00850769
0.00932601
0.0101844
0.0110331
0.0117906
0.0123281
0.0124492
0.0118695
0.0102119
0.00705295
0.000632475
0.00110487
0.00203507
0.00313201
0.00416569
0.0050344
0.00575284
0.00639263
0.00702856
0.00771187
0.00846469
0.00928346
0.0101423
0.0109914
0.0117492
0.012287
0.0124085
0.0118291
0.010172
0.0070136
)
;
boundaryField
{
top
{
type zeroGradient;
}
inlet
{
type zeroGradient;
}
outlet
{
type fixedValue;
value uniform 0;
}
plate
{
type zeroGradient;
}
symmBound
{
type zeroGradient;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"pawarsuraj92@gmail.com"
] | pawarsuraj92@gmail.com | |
eba9d099f4dd73ba4807803fade8f29fac23bfee | dc29086e666691d3d1f1371708ca860c7393fd8f | /libWorld/include/LibEngine/AutoBuffer.h | 796c500836941a115f93b37b625d7effc631b3b8 | [] | no_license | preboy/9DayGame | acb9ee02500a7a6a8b3470d4c6adbfbd517c442a | 4947b402e5e9e9cd430ea178b8bf6debc05abbf4 | refs/heads/master | 2021-01-11T14:11:59.060933 | 2017-02-10T14:46:12 | 2017-02-10T14:46:12 | 81,573,914 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,195 | h | #pragma once
#include "LibWindows/lock.h"
using namespace LibWindows;
namespace LibEngine
{
// 自动管理大小的缓冲区;
// 多线程版本;
const UINT nMaxBufferSize = 200*1024*1024; // 可分配内存的最大大小200M;
class AutoBuffer
{
public:
AutoBuffer();
~AutoBuffer();
// 获取缓冲区大小;
inline UINT GetBufferSize(){ return nSize; }
// 设置新的大小,旧的数据不会丢失;
bool SetBufferSize(UINT nNewSize);
// 获取缓冲区指针(非必要情况请勿写入数据,若非要写入的数据请注意长度不可超过nLen);
// 获取之后应该尽快在当前线程调用ReleaseBuffer,否则可能出现死锁;
// 在GetBuffer与ReleaseBuffer之间的代码,可安全的访问数据而不会出错;
void* GetBuffer();
// 释放可写入的缓冲区,只能在获取写指针的那个线程中调用才有效;
bool ReleaseBuffer();
// 拷贝数据到缓冲区;
bool SaveData(void* pBuffer_, UINT nLen_, UINT nSize_ = 0);
// 追加数据到缓冲区;
bool AddData(void* pBuffer_, UINT nLen_);
// 清除缓冲区末尾指定长度的数据,若nClearSize为0表示清除所有数据,nClearSize可能大于len;
void ClearData(UINT nClearSize = 0);
// 获取数据大小;
inline UINT GetDataLen(){ return nLen; }
// 清空数据及大小;
void Clear();
private:
void _clear();
void _wait(); // 等待ReleaseBuffer指针;
private:
void* pBuffer; // 缓冲区指针;
UINT nSize; // 缓冲区大小;
UINT nLen; // 数据大小;
lock theLock; // 安全锁;
DWORD dwUsingThreadID; // 若数据缓冲区被外界以写的方式使用中则不为0,否则为0;
};
}
| [
"preboy@126.com"
] | preboy@126.com |
82dd67233134ebf9b52e0b4f81e0b15bc7b8abf4 | 6722aa483d1b2d7b7f2c5aee8cabb41bba68cd20 | /BOJ/9457(기하학 문양).cpp | 8de08efbd8301874e1dd7e5afded86035e3752b0 | [] | no_license | oknkc8/PS | 3b28d4bb368cd5bc23623a1369ae0a3dce38c7a6 | cb27f08ef00d04dbfee5ae44e9449e4dbaa7bf10 | refs/heads/master | 2020-03-24T10:26:39.018880 | 2019-09-05T04:56:53 | 2019-09-05T04:56:53 | 142,656,302 | 0 | 1 | null | 2018-09-22T12:30:36 | 2018-07-28T07:21:33 | C++ | UTF-8 | C++ | false | false | 421 | cpp | #include<bits/stdc++.h>
using namespace std;
#define mod 10007
int dp[50005][2];
int main() {
dp[2][0] = 4, dp[2][1] = 3;
for (int i = 3; i <= 50000; i++) {
dp[i][0] = (3 * dp[i - 1][0] + dp[i - 1][1]) % mod;
dp[i][1] = (2 * dp[i - 1][0] + dp[i - 1][1]) % mod;
}
int t; scanf("%d", &t);
while (t--) {
int n; scanf("%d", &n);
printf("%d %d\n", dp[n][0], (dp[n][0] + dp[n][1] - 1)*n % mod);
}
return 0;
} | [
"oknkc8@gmail.com"
] | oknkc8@gmail.com |
0e2777b9fe092bd3851169d5a0c241ae952f0aeb | 1f9ff37c2383ea01758a486eeb9d46185c28520f | /Solved Problems/Count_Subarrays.cpp | 64fb10b8d1f2e90500a10f04476be39c28cd5a72 | [] | no_license | Manii-M/InterviewBit | 992a9fbca290052d2386536443e57f62818bdc12 | b5d735d9c22edebfbcbd2ee06532cba28f18f64d | refs/heads/master | 2022-12-15T10:31:55.391785 | 2020-09-07T13:56:44 | 2020-09-07T13:56:44 | 263,404,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 880 | cpp | /**
* Approach 1 - brute force is to take all subarray and see all the elements are unique or not
* TC - O(n^2) and to check also O(n)
* Approach 2 - we can have a frequency array.
* and based on that we'll keep counting the subarrays which has freq == 1
* as we encounter the element freq>1 we'll keep decrementing the freq and until for that element freq doesn't come down to 1
* TC - O(n) as we are traversing the array only once
* SC - O(n) for frequency array
*/
int Solution::solve(vector<int> &A)
{
map<int, int> m;
long long int l = 0, r = 0, answer = 0, mod = 1000000007;
while (l <= r && r < A.size())
{
m[A[r]]++;
while (m[A[r]] > 1)
{
m[A[l]]--;
l++;
}
answer += r - l + 1;
if (answer > mod)
answer -= mod;
r++;
}
return (int)(answer % mod);
}
| [
"manii.nitc@gmail.com"
] | manii.nitc@gmail.com |
217bec91c9f0e9854134af127dff77281bb1e610 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_2075_last_repos.cpp | 11efb7651f989b2de687509553dd412a35ea62a2 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 814 | cpp | static int diff_cache(struct rev_info *revs,
const struct object_id *tree_oid,
const char *tree_name,
int cached)
{
struct tree *tree;
struct tree_desc t;
struct unpack_trees_options opts;
tree = parse_tree_indirect(tree_oid);
if (!tree)
return error("bad tree object %s",
tree_name ? tree_name : oid_to_hex(tree_oid));
memset(&opts, 0, sizeof(opts));
opts.head_idx = 1;
opts.index_only = cached;
opts.diff_index_cached = (cached &&
!DIFF_OPT_TST(&revs->diffopt, FIND_COPIES_HARDER));
opts.merge = 1;
opts.fn = oneway_diff;
opts.unpack_data = revs;
opts.src_index = &the_index;
opts.dst_index = NULL;
opts.pathspec = &revs->diffopt.pathspec;
opts.pathspec->recursive = 1;
init_tree_desc(&t, tree->buffer, tree->size);
return unpack_trees(1, &t, &opts);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
a0ff8f6f2b039adb2f078833dbd17011a2d26fa8 | 3ac54f76223c0e6c8e61a67ff3d72775644baa01 | /1035/Main.cpp | 9b247c6197d8b25e47738d0b60644317c26d0ebd | [] | no_license | luizklitzke1/URI_CPP | ba0614023713e0102b929c527632707669d9e6cd | 88f7a1e6c4ebe866ec9f8bc8efa228aab7e1542a | refs/heads/main | 2023-05-09T08:03:42.172323 | 2021-05-25T02:04:37 | 2021-05-25T02:04:37 | 367,716,528 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp | #include <iostream>
using namespace std;
int main()
{
long lValorA = 0;
long lValorB = 0;
long lValorC = 0;
long lValorD = 0;
cin >> lValorA >> lValorB >> lValorC >> lValorD;
if (lValorB > lValorC && lValorD > lValorA && ((lValorC + lValorD) > (lValorA + lValorB)))
{
cout << "Valores aceitos" << endl;
}
else
{
cout << "Valores nao aceitos" << endl;
}
return 0;
}
| [
"49824305+luizklitzke1@users.noreply.github.com"
] | 49824305+luizklitzke1@users.noreply.github.com |
1b22979fa738a41033d1a64cf06d9f2c63c4700f | 16580255e7a63f2eb31b9f46644018a60bd61202 | /bicoloring.cpp | 873152b609941b6bdccacb707ebb7633d56b68d8 | [] | no_license | Sadeeb96/Algorithm-Implementations | 682e159def6e89d817dd937ead065316144a653a | a81a8fee32449561a09bf3e85e34fe6b6980c0d5 | refs/heads/master | 2020-06-19T20:52:32.502838 | 2019-08-02T21:30:30 | 2019-08-02T21:30:30 | 196,867,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,290 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
while(true)
{
int nodes;
int edges;
cin>>nodes;
if(nodes==0)
break;
cin>>edges;
int A[nodes][nodes];
memset(A,0,sizeof(A));
for(int i=0; i<edges; i++)
{
int x,y;
cin>>x>>y;
A[x][y]=1;
A[y][x]=1;
}
int color[nodes];
memset(color,-1,sizeof(color));
int src=0;
color[src]=1;
queue<int> q;
q.push(src);
bool bic=true;
while(!q.empty())
{
int head = q.front();
q.pop();
for(int i=0; i<nodes; i++)
{
if((A[head][i]==1 || A[i][head]==1) && color[i]==-1)
{
color[i]=1-color[head];
q.push(i);
}
else if((A[head][i]==1 || A[i][head]==1) && color[i]==color[head])
{
bic=false;
}
}
}
if(bic)
{
cout<<"BICOLORABLE."<<endl;
}
else
{
cout<<"NOT BICOLORABLE."<<endl;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
585b3819ac27225f83d2424eab3727434b28a862 | c9bb5bfc7b7adb253629c46e8b3d4ca3e5220b38 | /include/km_utils/mifsud_combinations.hpp | e1ed662573661d33638cf890312b8401f9fd0c36 | [
"Apache-2.0"
] | permissive | kartikmohta/km_utils | b3b1e323dafbf756b348ff751d44b00affdaae18 | 41fa812f3cfddcf214653081c8e4183f2b3fa543 | refs/heads/master | 2021-01-25T13:06:40.466812 | 2018-10-09T03:25:49 | 2018-10-09T03:28:12 | 123,529,982 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,530 | hpp | #pragma once
#include <cassert>
#include <vector>
namespace km
{
/**
* Generates the next combination of the integers [0,...,n-1] taken r at a time
* in lexicographical order.
*
* The algorithm is from:
* Mifsud, Charles J. "Algorithm 154: Combination in lexicographical order."
* Communications of the ACM 6.3 (1963): 103.
* http://dx.doi.org/10.1145/366274.366309
*/
class MifsudCombinations
{
public:
MifsudCombinations(unsigned int const n, unsigned int const r) : n_(n), r_(r)
{
assert(r <= n);
vec_.reserve(r);
for(unsigned int j = 0; j < r; ++j)
vec_.push_back(j);
}
/**
* Get the vector containing the combination.
*
* @return the vector which contains the current combination.
*/
std::vector<unsigned int> const &get() const { return vec_; }
/**
* Generate the next combination
*
* @return true when more combinations are possible, false when done
*/
bool next()
{
if(r_ == 0)
return false;
// Separate out the simple case for optimization
if(vec_[r_ - 1] < n_ - 1)
{
vec_[r_ - 1] += 1;
return true;
}
for(unsigned int i = 2; i <= r_; ++i)
{
unsigned int const idx = r_ - i; // Reverse index
if(vec_[idx] < n_ - i)
{
vec_[idx] += 1;
for(unsigned int j = 1; j < i; ++j)
vec_[idx + j] = vec_[idx] + j;
return true;
}
}
return false;
}
private:
std::vector<unsigned int> vec_;
unsigned int const n_;
unsigned int const r_;
};
}
| [
"kartikmohta@gmail.com"
] | kartikmohta@gmail.com |
4e094c6f71dac3690b6e0d8e7e40e1c3ffa957cb | 6a07849efd29bf8e44a75d02b45821073ab75fe8 | /Codeup/100000575B.cpp | 317618a5b82bedea17deab97dee1a1692fabe288 | [] | no_license | hsinyv/Algorithm_Exercise | 3185c971e8dc2f511a4d4e16275f38567edf29fa | fd6b0fcdfa9b94c4d52531d66a34f726eba460fb | refs/heads/main | 2023-03-22T19:25:07.857517 | 2021-03-18T16:28:54 | 2021-03-18T16:28:54 | 335,290,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | cpp | #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cctype>
#include <unordered_map>
#include <iomanip>
using namespace std;
int main() {
string s,t;
while(cin >> s){
cin >> t;
// cout <<"s: " << s << endl;
// cout <<"t: " << t << endl;
for(int i = 0; i < s.size(); i++){
if(s[i] == ',') {
s.erase(s.begin()+i);
i--;
}
}
for(int i = 0; i < t.size(); i++){
if(t[i] == ',') {
t.erase(t.begin()+i);
i--;
}
}
// cout <<"new s: " << s << endl;
// cout <<"new t: " << t << endl;
int a = stoi(s);
int b = stoi(t);
cout << a+b << endl;
}
return 0;
}
| [
"hsinyv@163.com"
] | hsinyv@163.com |
aa5141882950c4adff9f48dd17a126eeca9f109b | e76475e8405f87c154152d7e03373ea12b2da13d | /demoapps/clustering/lanczos.hpp | e825ede9fd084ad8544bf72e67619a28c176e06b | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | iivek/graphlab-cmu-mirror | dc84da0f9969ad3c8e3882f22c25a2db7ff42da6 | 028321757ea979e6a0859687e37933be375153eb | refs/heads/master | 2021-07-08T12:45:47.503395 | 2012-02-29T19:44:26 | 2012-02-29T19:44:26 | 106,104,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,369 | hpp | /**
* Copyright (c) 2009 Carnegie Mellon University.
* 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.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#ifndef __LANCZOS_HPP
#define __LANCZOS_HPP
#include "graphlab.hpp"
#include <graphlab/macros_def.hpp>
#define pvec distances
#define rmse min_distance
#define num_edges reported
using namespace std;
/**
*
* Implementation of the Lanczos algorithm, as given in:
* http://en.wikipedia.org/wiki/Lanczos_algorithm
*
* Code written by Danny Bickson, CMU, June 2011
* */
extern advanced_config ac;
extern problem_setup ps;
using namespace graphlab;
void last_iter();
double predict(const vertex_data& user, const vertex_data &movie, float rating, float & prediction);
void verify_result(double a, double b, double c);
flt_dbl* find_pvec(int pos, int i, vertex_data* data);
//LANCZOS VARIABLES
flt_dbl_vec lancbeta;
flt_dbl_vec lancalpha;
int offset, offset2, offset3;
/**
*
* [n,k] = size(A);
V = zeros(k,m+1);
V(:,2) = rand(k,1);
V(:,2)=V(:,2)/norm(V(:,2),2);
beta(2)=0;
*
* */
void init_lanczos(){
int m = ac.iter;
lancbeta = zeros(m+3);
lancalpha = zeros(m+3);
double sum = 0;
const graph_type *g = ps.g<graph_type>(TRAINING);
for (int i=ps.M; i< ps.M+ps.N; i++){
vertex_data * data = (vertex_data*)&g->vertex_data(i);
data->pvec = zeros(m+3);
data->pvec[1] = ac.debug ? 0.5 : rand();
sum += data->pvec[1]*data->pvec[1];
}
sum = sqrt(sum);
for (int i=ps.M; i< ps.M+ps.N; i++){
vertex_data * data = (vertex_data*)&g->vertex_data(i);
data->pvec[1] /= sum;
if (ac.debug && i- ps.M < 20)
cout<<"Initial V(:,2) is " << data->pvec[1] << endl;
}
}
/***
* UPDATE FUNCTION (ROWS)
*/
void Axb(gl_types::iscope &scope,
gl_types::icallback &scheduler) {
/* GET current vertex data */
vertex_data& user = scope.vertex_data();
/* print statistics */
if (ac.debug&& (scope.vertex() == 0 || ((int)scope.vertex() == ps.M-1))){
printf("Axb: entering node %u \n", (int)scope.vertex());
//debug_print_vec("V" , user.pvec, D);
}
user.rmse = 0;
if (!user.num_edges ){
return; //if this user/movie have no ratings do nothing
}
//gl_types::edge_list outs = scope.out_edge_ids();
timer t;
t.start();
// foreach(gl_types::edge_id oedgeid, outs) {
FOR_ITERATOR_(i,user.datapoint){
//edge_data & edge = scope.edge_data(oedgeid);
double weight = get_nz_data(user.datapoint, i);
int index = get_nz_index(user.datapoint, i);
//vertex_data & movie = scope.neighbor_vertex_data(scope.target(oedgeid));
assert(index >= ps.M && index < ps.M+ps.N);
vertex_data& movie = ps.g<graph_type>(TRAINING)->vertex_data(index);
//user.rmse += edge.weight * movie.pvec[offset];
user.rmse += weight * movie.pvec[offset];
}
ps.counter[SVD_MULT_A] += t.current_time();
if (ac.debug&& (scope.vertex() == 0 || ((int)scope.vertex() == ps.M-1))){
printf("Axb: computed value %u %g \n", (int)scope.vertex(), user.rmse);
}
}
/***
* UPDATE FUNCTION (COLS)
*/
void ATxb(gl_types::iscope &scope,
gl_types::icallback &scheduler) {
/* GET current vertex data */
vertex_data& user = scope.vertex_data();
int m = ac.iter;
/* print statistics */
if (ac.debug&& ((int)scope.vertex() == ps.M || ((int)scope.vertex() == ps.M+ps.N-1))){
printf("Axb: entering node %u \n", (int)scope.vertex());
//debug_print_vec("V" , user.pvec, m);
}
user.rmse = 0;
if (!user.num_edges){
return; //if this user/movie have no ratings do nothing
}
//gl_types::edge_list ins = scope.in_edge_ids();
timer t;
t.start();
//foreach(gl_types::edge_id iedgeid, ins) {
FOR_ITERATOR_(i, user.datapoint){
//edge_data & edge = scope.edge_data(iedgeid);
double weight = get_nz_data(user.datapoint, i);
int index = get_nz_index(user.datapoint, i);
//vertex_data & movie = scope.neighbor_vertex_data(scope.source(iedgeid));
vertex_data & movie = ps.g<graph_type>(TRAINING)->vertex_data(index);
//user.rmse += edge.weight * movie.rmse;
user.rmse += weight * movie.rmse;
}
assert(offset2 < m+2 && offset3 < m+2);
user.rmse -= lancbeta[offset2] * user.pvec[offset3];
ps.counter[SVD_MULT_A_TRANSPOSE] += t.current_time();
if (ac.debug&& ((int)scope.vertex() == ps.M || ((int)scope.vertex() == ps.M+ps.N-1))){
printf("Axb: computed value %u %g beta: %g v %g \n", (int)scope.vertex(), user.rmse,lancbeta[offset2], user.pvec[offset3]);
}
}
double wTV(int j){
graph_type *g = ps.g<graph_type>(TRAINING);
timer t; t.start();
double lancalpha = 0;
for (int i=ps.M; i< ps.M+ps.N; i++){
vertex_data * data = &g->vertex_data(i);
//lancalpha+= data->rmse*data->pvec[j];
lancalpha+= data->rmse* *find_pvec(j, i, data);
}
ps.counter[CALC_RMSE_Q] += t.current_time();
if (ac.debug)
cout<<"alpha: " << lancalpha<<endl;
return lancalpha;
}
double w_lancalphaV(int j){
const graph_type *g = ps.g<graph_type>(TRAINING);
timer t; t.start();
double norm = 0;
if (ac.debug)
cout << "w: " ;
for (int i=ps.M; i< ps.M+ps.N; i++){
vertex_data * data = (vertex_data*)&g->vertex_data(i);
//data->rmse -= lancalpha[j]*data->pvec[j];
data->rmse -= lancalpha[j]* *find_pvec(j, i, data);
if (ac.debug && i-ps.M<20)
cout<<data->rmse<<" ";
norm += data->rmse*data->rmse;
}
ps.counter[CALC_RMSE_Q] += t.current_time();
if (ac.debug){
cout<<endl;
cout<<"Beta: " << sqrt(norm) << endl;
}
return sqrt(norm);
}
void update_V(int j){
const graph_type *g = ps.g<graph_type>(TRAINING);
timer t; t.start();
//if (ac.debug)
//cout<<"V: ";
for (int i=ps.M; i< ps.M+ps.N; i++){
vertex_data * data = (vertex_data*)&g->vertex_data(i);
//data->pvec[j] = data->rmse / lancbeta[j];
*find_pvec(j,i,data) = data->rmse/ lancbeta[j];
//if (ac.debug && i-ps.M<20)
//cout<<*find_pvec(j,i,data)<<" ";
}
//if (ac.debug)
// cout<<endl;
ps.counter[CALC_RMSE_Q] += t.current_time();
}
void print_w(bool rows){
const graph_type *g = ps.g<graph_type>(TRAINING);
int size =rows? ps.M : ps.N;
int start=rows? 0 : ps.M;
int end = rows?ps.M : ps.M+ ps.N;
flt_dbl_vec v = zeros(size);
for (int i=start; i< end; i++){
const vertex_data * data = (vertex_data*)&g->vertex_data(i);
v[i - start] = data->rmse;
}
cout<<"w is: " << mid(v,0,20) << endl;
if (end - start > 40)
cout<<"w end is: " << mid(v, v.size()-20, 20) << endl;
}
//flt_dbl_mat calc_V(bool other_side, flt_dbl_mat& mat);
template<typename core>
void lanczos(core & glcore){
assert(false);
}
template<>
void lanczos<>(gl_types::core & glcore){
std::vector<vertex_id_t> rows,cols;
for (int i=0; i< ps.M; i++)
rows.push_back(i);
for (int i=ps.M; i< ps.M+ps.N; i++)
cols.push_back(i);
ac.iter--;
//for j=2:m+2
for (int j=1; j<= ac.iter+1; j++){
//w = A*V(:,j)
offset = j;
glcore.add_tasks(rows, Axb, 1);
glcore.start();
if (ac.debug)
print_w(true);
//w = w - lancbeta(j)*V(:,j-1);
offset2 = j;
offset3 = j-1;
glcore.add_tasks(cols, ATxb, 1);
glcore.start();
if (ac.debug)
print_w(false);
//lancalpha(j) = w'*V(:,j);
lancalpha[j] = wTV(j);
//w = w - lancalpha(j)*V(:,j);
//lancbeta(j+1)=norm(w,2);
lancbeta[j+1] = w_lancalphaV(j);
//V(:,j+1) = w/lancbeta(j+1);
update_V(j+1);
}
/*
* T=sparse(m+1,m+1);
* for i=2:m+1
* T(i-1,i-1)=lancalpha(i);
* T(i-1,i)=lancbeta(i+1);
* T(i,i-1)=lancbeta(i+1);
* end
* T(m+1,m+1)=lancalpha(m+2);
* V = V(:,2:end-1);
*/
int m = ac.iter;
mat T=fmat2mat(zeros(m+1,m+1));
for (int i=1; i<=m; i++){
set_val(T,i-1,i-1,lancalpha[i]);
set_val(T,i-1,i,lancbeta[i+1]);
set_val(T,i,i-1,lancbeta[i+1]);
}
set_val(T,m,m,lancalpha[m+1]);
if (ac.debug && m < 100){
cout<<"Matrix T is: " << T << endl;
}
/*
vec eigenvalues;
mat eigenvectors;
assert(::eig_sym(T, eigenvalues, eigenvectors));
cout << "Here are the computed eigenvalues, from larger to smaller" << endl;
for (int i=0; i< std::min((int)eigenvalues.size(),20); i++)
cout<<"eigenvalue " << i << " val: " << eigenvalues[i] << endl;
mat Vectors=fmat2mat(calc_V(false, mat2fmat(eigenvectors)));
ps.U=mat2famt(Vectors);
if (ac.debug)
cout<<"Eigen vectors are:" << ps.U << endl << "V is: " << Vectors << endl << " Eigenvectors (u) are: " << eigenvectors;
ps.V=zeros(eigenvalues.size(),1);
set_col(ps.V,0,vec2fvec(eigenvalues));
*/
if (ac.unittest > 0){
verify_result(0, 0, 0);
}
}
#include "graphlab/macros_undef.hpp"
#endif //__LANCZOS_HPP
| [
"danny.bickson@gmail.com"
] | danny.bickson@gmail.com |
2d8eb66af53a0a3a5f3269c15c43ded10d91d0f7 | fc23228bc1cbacda78c67fbe45d5a06da4bdb91e | /src/VulkanDevice.hpp | 03681773b11005b236776fa9242ac953c424accb | [] | no_license | SkaillZ/renderer | 584387b41929e9d91ede4631dcd1d4398ce45a74 | adfd2c6919b05573f888b92784be4a89f2a75e55 | refs/heads/master | 2023-02-15T20:49:56.631715 | 2021-01-15T15:57:03 | 2021-01-15T15:57:03 | 299,661,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,592 | hpp | #pragma once
#include <optional>
#include <vector>
#include <iostream>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include "VulkanBuffer.hpp"
class VulkanDevice {
public:
VulkanDevice(GLFWwindow* window);
virtual ~VulkanDevice();
GLFWwindow* window;
VkInstance instance;
VkDebugUtilsMessengerEXT debugMessenger;
VkSurfaceKHR surface;
VkPhysicalDevice physicalDevice;
VkDevice device;
VkCommandPool commandPool;
VkQueue graphicsQueue;
VkQueue presentQueue;
VkSampleCountFlagBits userRequestedMsaaSamples = VK_SAMPLE_COUNT_2_BIT;
VkSampleCountFlagBits maxMsaaSamples = VK_SAMPLE_COUNT_2_BIT;
#ifdef NDEBUG
bool enableValidationLayers = false;
#else
bool enableValidationLayers = false;
#endif
struct QueueFamilyIndices {
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool isComplete() {
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VulkanBuffer& buffer);
void freeBuffer(VulkanBuffer& buffer);
static const std::vector<const char*> validationLayers;
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData);
QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device);
VkSampleCountFlagBits getMsaaSamples();
int getUserRequestedMsaaSamples() { return (int) userRequestedMsaaSamples; }
void setUserRequestedMsaaSamples(int sampleCount) { userRequestedMsaaSamples = (VkSampleCountFlagBits) sampleCount; }
private:
static const std::vector<const char*> deviceExtensions;
void createInstance();
void createSurface();
void setupDebugMessenger();
void pickPhysicalDevice();
void createLogicalDevice();
void createCommandPool();
bool checkValidationLayerSupport();
bool isDeviceSuitable(VkPhysicalDevice device);
bool checkDeviceExtensionSupport(VkPhysicalDevice device);
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device);
VkSampleCountFlagBits getMaxMsaaSamples();
};
| [
"rene.buchmayer@gmail.com"
] | rene.buchmayer@gmail.com |
1c6d8ee058dc06366a4b118dff60729fa092a5a9 | a07e8ce8748e1c11dcb2fb4f1d8438759a791c0d | /year1/torrent/torrent_client/torrent_client/main.cpp | a05308e0adf23ed5f700c5f8648c48ecf8473f6f | [] | no_license | celidos/programming-mipt-2015-2017 | 7aef789009cf63dfe415070e6907c634a0b89c7a | cd27a7798f2f50164228b3ab0b7c3015a9c7c049 | refs/heads/master | 2021-06-16T14:22:29.455077 | 2017-05-13T15:33:58 | 2017-05-13T15:33:58 | 91,165,940 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,868 | cpp | #include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include "cpp-bencoding-master/include/Decoder.h"
#include "cpp-bencoding-master/include/Encoder.h"
#include "cpp-bencoding-master/include/PrettyPrinter.h"
#include <iomanip>
#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */
#include <fcntl.h> // File control definitions
#include <vector>
using std::string;
using std::cin;
using std::cout;
using std::endl;
using std::stringstream;
using std::ostringstream;
using std::hex;
using std::uppercase;
using std::nouppercase;
using std::vector;
using namespace bencoding;
void error(const char *msg) { perror(msg); exit(0); }
namespace {
/**
* @brief Checks if help was requested.
*/
bool helpIsRequested(int argc, char **argv) {
if (argc != 2) {
return false;
}
std::string firstArg(argv[1]);
if (firstArg == "-h" || firstArg == "--help") {
return true;
}
return false;
}
/**
* @brief Prints help to the standard output.
*/
void printHelp(const std::string &prog) {
std::cout
<< "A decoder of bencoded files.\n"
<< "\n"
<< "Usage: " << prog << " [FILE]\n"
<< "\n"
<< "If FILE is not given, the data are read from the standard input.\n"
<< "The decoded data are printed to the standard output.\n";
}
} // anonymous namespace
string url_encode(const string &value) {
ostringstream escaped;
escaped.fill('0');
escaped << hex;
for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << uppercase;
escaped << '%' << std::setw(2) << int((unsigned char) c);
escaped << nouppercase;
}
return escaped.str();
}
vector<string> getTracker(string &data, string req)
{
vector<string> res;
int pos1 = 0, pos2, pos3;
while (pos1 != string::npos && pos2 != string::npos && pos3 != string::npos)
{
string subreq = string("\"") + req + string("\"");
pos1 = data.find(subreq, pos1);
if (pos1 == string::npos)
break;
pos2 = data.find('"', pos1 + req.length()+2);
pos3 = data.find('"', pos2 + 1);
if (pos2 != string::npos && pos3 != string::npos)
{
res.push_back(data.substr(pos2+1, pos3-pos2-1));
}
pos1 = pos3+1;
}
return res;
}
vector< vector<int> > getPeers(string &data)
{
vector <vector <int> > res;
std::cout << data << std::endl;
int ndex = data.find("peers");
if (ndex != string::npos)
{
cout << "_________________________ " << ndex << endl;
ndex = data.find(':', ndex + 1);
cout << "_________________________ " << ndex << endl;
for (int i = ndex + 1; i < data.length(); ++i)
{
if (i + 6 >= data.length())
break;
res.push_back(vector<int>());
for (int j = i; j <= i + 5; ++j)
{
res[res.size()-1].push_back(data[j]);
}
}
}
}
int main(int argc, char **argv)
{
// Part1 - Parsing file -------------------------------------------------------------
string filename;
cout << "Enter filename : ";
filename = "sample.torrent";
std::shared_ptr<BItem> decodedData;
try
{
std::ifstream input(filename);
cout << "File opened, now parsing...";
decodedData = decode(input);
cout << "File parsed" << endl;
}
catch (const DecodingError &ex)
{
std::cerr << "Error: " << ex.what() << endl;
return 1;
}
string repr = getPrettyRepr(decodedData).first;
cout << repr << endl;
string infostr = encode(std::shared_ptr<BItem>(getPrettyRepr(decodedData).second));
vector <string>trackers = getTracker(repr, "announce");
cout << trackers[0] << endl;
cout << infostr << endl;
// Part2 - Server request -------------------------------------------------------------
int sock;
struct sockaddr_in client;
int PORT = 6881;
struct hostent * host = gethostbyname("tracker.tfile.me");
if ( (host == NULL) || (host->h_addr == NULL) )
{
cout << "Error retrieving DNS information." << endl;
exit(1);
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
cout << "Error creating socket." << endl;
exit(1);
}
// 6881
for (PORT = 80; PORT < 6890; ++PORT)
{
cout << "trying to connect port " << PORT << "...";
cout.flush();
bzero(&client, sizeof(client));
client.sin_family = AF_INET;
client.sin_port = htons(PORT);
memcpy(&client.sin_addr, host->h_addr, host->h_length);
if (connect(sock, (struct sockaddr *)&client, sizeof(client)) != 0 )
{
cout << "failed" << endl;
}
else
{
cout << "ok!"<<endl;
break;
}
}
if (PORT == 6890)
{
cout << "Couldn't connect" << endl;
close(sock);
exit(1);
}
// --------------------------------------
cout<< "still ok!" << endl;
stringstream ss;
ss << "GET /announce.php?"
<< //url_encode(
string("ak=11b9569798&&info_hash=%89M%19x%93%ab%d2%2b%14%5d%8b%a2Z%28%0dT%1e%e8%0d2")+
"&port=80"+
"&uploaded=0"+
"&downloaded=0"+
"&left=1273509"+
"&event=started"
<< "HTTP/1.0\r\n"
<< "Host: tracker.tfile.me\r\n"
<< "User-Agent: Transmission v.30000000\r\n"
<< "Accept: text/plain\r\n"
<< "\r\n\r\n";
string request = ss.str();
if (send(sock, request.c_str(), request.length(), 0) != (int)request.length()) {
cout << "Error sending request." << endl;
exit(1);
}
cout << "------------------ ACCEPTING RESPONSE ------------------" << endl;
char cur;
string response;
while ( read(sock, &cur, 1) > 0 ) {
response += cur;
}
cout << response << endl;
// HAND SHAKING -------------------------------------------------
vector <vector <int> > peers = getPeers(response);
}
| [
"chloroformorganic@gmail.com"
] | chloroformorganic@gmail.com |
1f8ea2a2d28cc557158d4040030f423d4866ab37 | 61447d695c11d4a76c92a4b710d8f1ee55f0f8bb | /C+Cpp/GameFrameWorkDemo/src/Graphics/Texture2D.cpp | f7f8a97f7db016ae3d56a6ed181ed4ecab91068a | [] | no_license | biyu/PlayGround | 0fede52c543c823546f726c1403aafc4a7b1524e | 403964687ba635eebfab9c174cede047418ca3e7 | refs/heads/master | 2021-01-15T19:45:08.464767 | 2013-08-11T16:13:48 | 2013-08-11T16:13:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,177 | cpp | #include "Texture2D.h"
Texture2D::Texture2D(std::string fileName)
: _gTextureTarget(GL_TEXTURE_2D),
_fileName(fileName), _pImage(0)
{
}
Texture2D::~Texture2D()
{
delete this->_pImage;
}
bool Texture2D::load()
{
if(this->_fileName.empty())
{
Debug(L"empty texture file name");
return false;
}
try {
this->_pImage = new Magick::Image(this->_fileName);
this->_pImage->write(&_blob, "RGBA");
}
catch (Magick::Error& Error) {
std::cout << "error loading texture '" << this->_fileName << "': " << Error.what() << std::endl;
return false;
}
glGenTextures(1, &(this->_gTextureObject));
glBindTexture(this->_gTextureTarget, this->_gTextureObject);
glTexImage2D(this->_gTextureTarget, 0, GL_RGBA, this->_pImage->columns(), this->_pImage->rows(), 0, GL_RGBA, GL_UNSIGNED_BYTE, this->_blob.data());
glTexParameterf(this->_gTextureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(this->_gTextureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
return true;
}
void Texture2D::bind(GLenum TextureUnit)
{
glActiveTexture(TextureUnit);
glBindTexture(this->_gTextureTarget, this->_gTextureObject);
} | [
"yubin19850822@gmail.com"
] | yubin19850822@gmail.com |
78beb1e2e1fb1b42552912638ba2cb4709c934b0 | 6857c2ef676792a4048c9c67e52dc3b64550a771 | /evita/text/marker_set_unittest.cc | 7a426efeb35bec39e1404ef21137f6b81ba50bd9 | [] | no_license | TheTypoMaster/evita | d4978ae4d332e8980d1c0da0f717d957d102dd26 | 213d542fc39736d15372dc04cd3c803806db352b | refs/heads/master | 2021-01-15T20:19:04.727264 | 2015-09-19T21:17:19 | 2015-09-19T21:17:19 | 42,788,695 | 0 | 0 | null | 2015-09-19T20:33:06 | 2015-09-19T20:33:06 | null | UTF-8 | C++ | false | false | 7,955 | cc | // Copyright (c) 1996-2014 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma warning(push)
#pragma warning(disable : 4365 4625 4626 4826)
#include "gtest/gtest.h"
#pragma warning(pop)
#include "evita/text/marker_set.h"
namespace {
using text::BufferMutationObserver;
using text::Marker;
using text::MarkerSet;
class MockBufferMutationObservee : public text::BufferMutationObservee {
private:
void AddObserver(BufferMutationObserver* observer) final {}
void RemoveObserver(BufferMutationObserver* observer) final {}
};
class MarkerSetTest : public ::testing::Test {
public:
virtual ~MarkerSetTest() {}
protected:
MarkerSetTest()
: Correct(L"Correct"),
Misspelled(L"Misspelled"),
marker_set_(&mutation_observee_) {}
MarkerSet* marker_set() { return &marker_set_; }
void DidDeleteAt(text::Posn offset, size_t length) {
static_cast<text::BufferMutationObserver*>(marker_set())
->DidDeleteAt(offset, length);
}
void RemoveMarker(text::Posn start, text::Posn end) {
marker_set()->RemoveMarkerForTesting(start, end);
}
Marker GetAt(Posn offset) {
auto const marker = marker_set_.GetMarkerAt(offset);
return marker ? *marker : Marker();
}
void InsertMarker(text::Posn start,
text::Posn end,
const common::AtomicString& type) {
marker_set()->InsertMarker(start, end, type);
}
const common::AtomicString Correct;
const common::AtomicString Misspelled;
private:
MockBufferMutationObservee mutation_observee_;
MarkerSet marker_set_;
DISALLOW_COPY_AND_ASSIGN(MarkerSetTest);
};
TEST_F(MarkerSetTest, DeleteMarker_cover) {
// before: --CC--
// insert: -____--
// after: -____--
InsertMarker(150, 250, Correct);
RemoveMarker(100, 300);
EXPECT_EQ(Marker(), GetAt(100));
EXPECT_EQ(Marker(), GetAt(125));
EXPECT_EQ(Marker(), GetAt(150));
EXPECT_EQ(Marker(), GetAt(225));
EXPECT_EQ(Marker(), GetAt(250));
}
TEST_F(MarkerSetTest, DeleteMarker_cross_left) {
// before: ---CC--
// insert: --__---
// after: --__C--
InsertMarker(200, 300, Correct);
RemoveMarker(150, 250);
EXPECT_EQ(Marker(), GetAt(150));
EXPECT_EQ(Marker(250, 300, Correct), GetAt(250));
}
TEST_F(MarkerSetTest, DeleteMarker_cross_right) {
// before: --CCCC----
// insert: ----____--
// after: --CC__----
InsertMarker(100, 250, Correct);
RemoveMarker(200, 300);
EXPECT_EQ(Marker(100, 200, Correct), GetAt(150));
EXPECT_EQ(Marker(), GetAt(200));
EXPECT_EQ(Marker(), GetAt(250));
}
TEST_F(MarkerSetTest, DeleteMarker_disjoint) {
// before: --CC--
// insert: ------__--
// after: --CC------
InsertMarker(100, 200, Correct);
RemoveMarker(300, 400);
EXPECT_EQ(Marker(100, 200, Correct), GetAt(150));
EXPECT_EQ(Marker(), GetAt(350));
}
TEST_F(MarkerSetTest, DeleteMarker_same) {
InsertMarker(100, 200, Correct);
RemoveMarker(100, 200);
auto const marker = marker_set()->GetLowerBoundMarker(100);
EXPECT_EQ(Marker(), marker ? *marker : Marker());
}
TEST_F(MarkerSetTest, DeleteMarker_split) {
// before: -CCCCCC--
// insert: ---__--
// after: -CC__CC--
InsertMarker(200, 400, Correct);
RemoveMarker(250, 350);
EXPECT_EQ(Marker(), GetAt(199));
EXPECT_EQ(Marker(200, 250, Correct), GetAt(200));
EXPECT_EQ(Marker(200, 250, Correct), GetAt(225));
EXPECT_EQ(Marker(), GetAt(300));
EXPECT_EQ(Marker(), GetAt(349));
EXPECT_EQ(Marker(350, 400, Correct), GetAt(350));
EXPECT_EQ(Marker(350, 400, Correct), GetAt(399));
EXPECT_EQ(Marker(), GetAt(400));
}
TEST_F(MarkerSetTest, DidDeleteAt) {
// before: --"foo"x--
// delete: --"foo"---
InsertMarker(0, 5, Correct);
InsertMarker(5, 6, Misspelled);
DidDeleteAt(5, 1);
EXPECT_EQ(Marker(0, 5, Correct), GetAt(0));
}
TEST_F(MarkerSetTest, GetMarkerAt) {
InsertMarker(5, 10, Correct);
EXPECT_EQ(Marker(), GetAt(0));
EXPECT_EQ(Marker(), GetAt(4));
EXPECT_EQ(Marker(5, 10, Correct), GetAt(5));
EXPECT_EQ(Marker(5, 10, Correct), GetAt(9));
EXPECT_EQ(Marker(), GetAt(10));
EXPECT_EQ(Marker(), GetAt(11));
}
TEST_F(MarkerSetTest, GetLowerBoundMarker) {
InsertMarker(5, 10, Correct);
EXPECT_EQ(Marker(), GetAt(0));
EXPECT_EQ(Marker(), GetAt(4));
EXPECT_EQ(Marker(5, 10, Correct), GetAt(5));
EXPECT_EQ(Marker(5, 10, Correct), GetAt(9));
EXPECT_EQ(Marker(), GetAt(10));
}
TEST_F(MarkerSetTest, InsertMarker_cover) {
// before: --CC--
// insert: -MMMM--
// after: -MMMM--
InsertMarker(150, 250, Correct);
InsertMarker(100, 300, Misspelled);
EXPECT_EQ(Marker(100, 300, Misspelled), GetAt(100));
EXPECT_EQ(Marker(100, 300, Misspelled), GetAt(125));
EXPECT_EQ(Marker(100, 300, Misspelled), GetAt(150));
EXPECT_EQ(Marker(100, 300, Misspelled), GetAt(225));
EXPECT_EQ(Marker(100, 300, Misspelled), GetAt(250));
}
TEST_F(MarkerSetTest, InsertMarker_cross_left) {
// before: ---MM--
// insert: --CC---
// after: --CCM--
InsertMarker(200, 300, Correct);
InsertMarker(150, 250, Misspelled);
EXPECT_EQ(Marker(150, 250, Misspelled), GetAt(150));
EXPECT_EQ(Marker(250, 300, Correct), GetAt(250));
}
TEST_F(MarkerSetTest, InsertMarker_cross_right) {
// before: --MMMM----
// insert: ----CCCC--
// after: --MMCCCC--
InsertMarker(100, 250, Misspelled);
InsertMarker(200, 300, Correct);
EXPECT_EQ(Marker(100, 200, Misspelled), GetAt(150));
EXPECT_EQ(Marker(200, 300, Correct), GetAt(200));
EXPECT_EQ(Marker(200, 300, Correct), GetAt(250));
}
TEST_F(MarkerSetTest, InsertMarker_disjoint) {
// before: --CC--
// insert: ------CC--
// after: --CC--CC--
InsertMarker(100, 200, Correct);
InsertMarker(300, 400, Correct);
EXPECT_EQ(Marker(100, 200, Correct), GetAt(150));
EXPECT_EQ(Marker(300, 400, Correct), GetAt(350));
}
TEST_F(MarkerSetTest, InsertMarker_existing) {
// before: --CCCCCCC--
// insert: ----CCCCC--
// after: --CCCCCCC--
InsertMarker(10, 30, Correct);
InsertMarker(20, 30, Correct);
EXPECT_EQ(Marker(10, 30, Correct), GetAt(10));
}
TEST_F(MarkerSetTest, InsertMarker_extend) {
// before: --CCCCCCC----
// insert: ----CCCCCCC--
// after: --CCCCCCCCC--
InsertMarker(10, 30, Correct);
InsertMarker(20, 40, Correct);
EXPECT_EQ(Marker(10, 40, Correct), GetAt(10));
}
TEST_F(MarkerSetTest, InsertMarker_merge) {
// before: --CC--CC--CC--
// insert: --MMMMMMMMMM--
// after: --MMMMMMMMMM--
InsertMarker(10, 20, Correct);
InsertMarker(40, 60, Correct);
InsertMarker(80, 90, Correct);
InsertMarker(10, 90, Misspelled);
EXPECT_EQ(Marker(10, 90, Misspelled), GetAt(10));
EXPECT_EQ(Marker(10, 90, Misspelled), GetAt(20));
EXPECT_EQ(Marker(10, 90, Misspelled), GetAt(30));
EXPECT_EQ(Marker(10, 90, Misspelled), GetAt(89));
EXPECT_EQ(Marker(), GetAt(90));
}
TEST_F(MarkerSetTest, InsertMarker_merge2) {
// before: --CCCC-CCCC--
// insert: ------C------
// after: --CCCCCCCC---
InsertMarker(0, 4, Correct);
InsertMarker(5, 9, Correct);
InsertMarker(4, 5, Correct);
EXPECT_EQ(Marker(0, 9, Correct), GetAt(1));
}
TEST_F(MarkerSetTest, InsertMarker_split) {
// before: --CCCCCC--
// insert: ----MM----
// after: --CCMMCC--
InsertMarker(200, 400, Correct);
InsertMarker(250, 350, Misspelled);
EXPECT_EQ(Marker(), GetAt(199));
EXPECT_EQ(Marker(200, 250, Correct), GetAt(200));
EXPECT_EQ(Marker(200, 250, Correct), GetAt(225));
EXPECT_EQ(Marker(250, 350, Misspelled), GetAt(300));
EXPECT_EQ(Marker(250, 350, Misspelled), GetAt(349));
EXPECT_EQ(Marker(350, 400, Correct), GetAt(350));
EXPECT_EQ(Marker(350, 400, Correct), GetAt(399));
EXPECT_EQ(Marker(), GetAt(400));
}
} // namespace
| [
"eval1749@gmail.com"
] | eval1749@gmail.com |
894dfbcb50ce6b627392422996bfa35dade8efd3 | 8726841917e4999289451334c356e97f966ee776 | /C++/256 Paint House.cpp | cab9545fc76ab7a7dd88bf069095a759621bfb20 | [] | no_license | weiho1122/LeetCode | cf890eaf3b8299897431564d811c52d1a95f6d94 | ac986cb0ccba053afbb21b7fe6ec8fa5f767da5e | refs/heads/master | 2021-01-11T02:04:40.560365 | 2016-09-13T00:09:04 | 2016-09-13T00:09:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 714 | cpp | //dp. O(3n) sub-problems, O(3) choices for each sub-problem
class Solution {
public:
int minCost(vector<vector<int>>& costs) {
if(costs.empty()) return 0;
int n = costs.size(), m = costs[0].size();
vector<vector<int>> dp(n+1,vector<int>(3, INT_MAX));
dp[0][0] = 0, dp[0][1] = 0, dp[0][2] = 0;
for(int i = 1; i < n+1; i++){
dp[i][0] = min(dp[i-1][1] + costs[i-1][0], dp[i-1][2] + costs[i-1][0]);
dp[i][1] = min(dp[i-1][0] + costs[i-1][1], dp[i-1][2] + costs[i-1][1]);
dp[i][2] = min(dp[i-1][0] + costs[i-1][2], dp[i-1][1] + costs[i-1][2]);
}
return min(min(dp.back()[0], dp.back()[1]), dp.back()[2]);
}
};
| [
"zhangweiqi357@gmail.com"
] | zhangweiqi357@gmail.com |
515dd57d72249f98ebb8bb16689e91d340125751 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /chrome/browser/ui/webui/settings/md_settings_ui.h | 6f49d402e08debbdd4f54e15c60ef26ba750007d | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 1,533 | h | // Copyright (c) 2015 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 CHROME_BROWSER_UI_WEBUI_SETTINGS_MD_SETTINGS_UI_H_
#define CHROME_BROWSER_UI_WEBUI_SETTINGS_MD_SETTINGS_UI_H_
#include <unordered_set>
#include "base/macros.h"
#include "base/time/time.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_ui_controller.h"
class GURL;
namespace settings {
class SettingsPageUIHandler;
// The WebUI handler for chrome://md-settings.
class MdSettingsUI : public content::WebUIController,
public content::WebContentsObserver {
public:
MdSettingsUI(content::WebUI* web_ui, const GURL& url);
~MdSettingsUI() override;
// content::WebContentsObserver:
void DidStartProvisionalLoadForFrame(
content::RenderFrameHost* render_frame_host,
const GURL& validated_url,
bool is_error_page,
bool is_iframe_srcdoc) override;
void DocumentLoadedInFrame(
content::RenderFrameHost *render_frame_host) override;
void DocumentOnLoadCompletedInMainFrame() override;
private:
void AddSettingsPageUIHandler(SettingsPageUIHandler* handler);
// Weak references; all |handlers_| are owned by |web_ui()|.
std::unordered_set<SettingsPageUIHandler*> handlers_;
base::Time load_start_time_;
DISALLOW_COPY_AND_ASSIGN(MdSettingsUI);
};
} // namespace settings
#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_MD_SETTINGS_UI_H_
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
5325ef1fffd494ad4dc113f7b97c7c440d9adfea | 5c4a89eae320d3297237d36c7f09e0c0c2b50722 | /mainwindow.h | d9cec7b4fc368b2f5670e4fd3adcefbc4e7a6d92 | [] | no_license | NipunaCooray/Grace | abed041b85b8b50a1b30bd82563399bc514d692a | 1b831fe777bcc0a67b15a6be2f7a1af22a0fcf9d | refs/heads/master | 2020-07-17T12:13:19.452456 | 2016-12-07T05:34:12 | 2016-12-07T05:34:12 | 73,930,157 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "edgedetect.h"
#include "serialreadwrite.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
void on_pushButton_loadStyle_clicked();
void on_btn_close_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"noreply@github.com"
] | noreply@github.com |
f956c3462f8968d651a0ceb01aa96dbf9692af4d | 3cd86ab3ce830eb0cd15cd3073e5e6c18ae54ff9 | /test/cases/c++.cpp | c32099d7a98e9a7cf8d7331516335836555a280a | [
"MIT"
] | permissive | okonet/node-language-classifier | 781c80462c6454eac3a94414f5eb6812ae5e6f0f | 2e3ac320da5f4e5b62f7424a21b0fced827ae471 | refs/heads/master | 2023-09-04T11:07:11.648972 | 2017-04-26T20:17:44 | 2017-04-26T20:17:44 | 89,521,701 | 0 | 0 | null | 2017-04-26T20:03:00 | 2017-04-26T20:03:00 | null | UTF-8 | C++ | false | false | 19,427 | cpp | /*
Copyright (c) 2007-2012 iMatix Corporation
Copyright (c) 2009-2011 250bpm s.r.o.
Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform.hpp"
#ifdef ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#else
#include <unistd.h>
#endif
#include <new>
#include <string.h>
#include "ctx.hpp"
#include "socket_base.hpp"
#include "io_thread.hpp"
#include "reaper.hpp"
#include "pipe.hpp"
#include "err.hpp"
#include "msg.hpp"
zmq::ctx_t::ctx_t () :
tag (0xabadcafe),
starting (true),
terminating (false),
reaper (NULL),
slot_count (0),
slots (NULL),
max_sockets (ZMQ_MAX_SOCKETS_DFLT),
io_thread_count (ZMQ_IO_THREADS_DFLT)
{
}
bool zmq::ctx_t::check_tag ()
{
return tag == 0xabadcafe;
}
zmq::ctx_t::~ctx_t ()
{
// Check that there are no remaining sockets.
zmq_assert (sockets.empty ());
// Ask I/O threads to terminate. If stop signal wasn't sent to I/O
// thread subsequent invocation of destructor would hang-up.
for (io_threads_t::size_type i = 0; i != io_threads.size (); i++)
io_threads [i]->stop ();
// Wait till I/O threads actually terminate.
for (io_threads_t::size_type i = 0; i != io_threads.size (); i++)
delete io_threads [i];
// Deallocate the reaper thread object.
if (reaper)
delete reaper;
// Deallocate the array of mailboxes. No special work is
// needed as mailboxes themselves were deallocated with their
// corresponding io_thread/socket objects.
if (slots)
free (slots);
// Remove the tag, so that the object is considered dead.
tag = 0xdeadbeef;
}
int zmq::ctx_t::terminate ()
{
slot_sync.lock ();
if (!starting) {
// Check whether termination was already underway, but interrupted and now
// restarted.
bool restarted = terminating;
terminating = true;
slot_sync.unlock ();
// First attempt to terminate the context.
if (!restarted) {
// First send stop command to sockets so that any blocking calls
// can be interrupted. If there are no sockets we can ask reaper
// thread to stop.
slot_sync.lock ();
for (sockets_t::size_type i = 0; i != sockets.size (); i++)
sockets [i]->stop ();
if (sockets.empty ())
reaper->stop ();
slot_sync.unlock ();
}
// Wait till reaper thread closes all the sockets.
command_t cmd;
int rc = term_mailbox.recv (&cmd, -1);
if (rc == -1 && errno == EINTR)
return -1;
errno_assert (rc == 0);
zmq_assert (cmd.type == command_t::done);
slot_sync.lock ();
zmq_assert (sockets.empty ());
}
slot_sync.unlock ();
// Deallocate the resources.
delete this;
return 0;
}
int zmq::ctx_t::set (int option_, int optval_)
{
int rc = 0;
if (option_ == ZMQ_MAX_SOCKETS && optval_ >= 1) {
opt_sync.lock ();
max_sockets = optval_;
opt_sync.unlock ();
}
else
if (option_ == ZMQ_IO_THREADS && optval_ >= 0) {
opt_sync.lock ();
io_thread_count = optval_;
opt_sync.unlock ();
}
else {
errno = EINVAL;
rc = -1;
}
return rc;
}
int zmq::ctx_t::get (int option_)
{
int rc = 0;
if (option_ == ZMQ_MAX_SOCKETS)
rc = max_sockets;
else
if (option_ == ZMQ_IO_THREADS)
rc = io_thread_count;
else {
errno = EINVAL;
rc = -1;
}
return rc;
}
zmq::socket_base_t *zmq::ctx_t::create_socket (int type_)
{
slot_sync.lock ();
if (unlikely (starting)) {
starting = false;
// Initialise the array of mailboxes. Additional three slots are for
// zmq_term thread and reaper thread.
opt_sync.lock ();
int mazmq = max_sockets;
int ios = io_thread_count;
opt_sync.unlock ();
slot_count = mazmq + ios + 2;
slots = (mailbox_t**) malloc (sizeof (mailbox_t*) * slot_count);
alloc_assert (slots);
// Initialise the infrastructure for zmq_term thread.
slots [term_tid] = &term_mailbox;
// Create the reaper thread.
reaper = new (std::nothrow) reaper_t (this, reaper_tid);
alloc_assert (reaper);
slots [reaper_tid] = reaper->get_mailbox ();
reaper->start ();
// Create I/O thread objects and launch them.
for (int i = 2; i != ios + 2; i++) {
io_thread_t *io_thread = new (std::nothrow) io_thread_t (this, i);
alloc_assert (io_thread);
io_threads.push_back (io_thread);
slots [i] = io_thread->get_mailbox ();
io_thread->start ();
}
// In the unused part of the slot array, create a list of empty slots.
for (int32_t i = (int32_t) slot_count - 1;
i >= (int32_t) ios + 2; i--) {
empty_slots.push_back (i);
slots [i] = NULL;
}
}
// Once zmq_term() was called, we can't create new sockets.
if (terminating) {
slot_sync.unlock ();
errno = ETERM;
return NULL;
}
// If max_sockets limit was reached, return error.
if (empty_slots.empty ()) {
slot_sync.unlock ();
errno = EMFILE;
return NULL;
}
// Choose a slot for the socket.
uint32_t slot = empty_slots.back ();
empty_slots.pop_back ();
// Generate new unique socket ID.
int sid = ((int) max_socket_id.add (1)) + 1;
// Create the socket and register its mailbox.
socket_base_t *s = socket_base_t::create (type_, this, slot, sid);
if (!s) {
empty_slots.push_back (slot);
slot_sync.unlock ();
return NULL;
}
sockets.push_back (s);
slots [slot] = s->get_mailbox ();
slot_sync.unlock ();
return s;
}
void zmq::ctx_t::destroy_socket (class socket_base_t *socket_)
{
slot_sync.lock ();
// Free the associated thread slot.
uint32_t tid = socket_->get_tid ();
empty_slots.push_back (tid);
slots [tid] = NULL;
// Remove the socket from the list of sockets.
sockets.erase (socket_);
// If zmq_term() was already called and there are no more socket
// we can ask reaper thread to terminate.
if (terminating && sockets.empty ())
reaper->stop ();
slot_sync.unlock ();
}
zmq::object_t *zmq::ctx_t::get_reaper ()
{
return reaper;
}
void zmq::ctx_t::send_command (uint32_t tid_, const command_t &command_)
{
slots [tid_]->send (command_);
}
zmq::io_thread_t *zmq::ctx_t::choose_io_thread (uint64_t affinity_)
{
if (io_threads.empty ())
return NULL;
// Find the I/O thread with minimum load.
int min_load = -1;
io_thread_t *selected_io_thread = NULL;
for (io_threads_t::size_type i = 0; i != io_threads.size (); i++) {
if (!affinity_ || (affinity_ & (uint64_t (1) << i))) {
int load = io_threads [i]->get_load ();
if (selected_io_thread == NULL || load < min_load) {
min_load = load;
selected_io_thread = io_threads [i];
}
}
}
return selected_io_thread;
}
int zmq::ctx_t::register_endpoint (const char *addr_, endpoint_t &endpoint_)
{
endpoints_sync.lock ();
bool inserted = endpoints.insert (endpoints_t::value_type (
std::string (addr_), endpoint_)).second;
endpoints_sync.unlock ();
if (!inserted) {
errno = EADDRINUSE;
return -1;
}
return 0;
}
void zmq::ctx_t::unregister_endpoints (socket_base_t *socket_)
{
endpoints_sync.lock ();
endpoints_t::iterator it = endpoints.begin ();
while (it != endpoints.end ()) {
if (it->second.socket == socket_) {
endpoints_t::iterator to_erase = it;
++it;
endpoints.erase (to_erase);
continue;
}
++it;
}
endpoints_sync.unlock ();
}
zmq::endpoint_t zmq::ctx_t::find_endpoint (const char *addr_)
{
endpoints_sync.lock ();
endpoints_t::iterator it = endpoints.find (addr_);
if (it == endpoints.end ()) {
endpoints_sync.unlock ();
errno = ECONNREFUSED;
endpoint_t empty = {NULL, options_t()};
return empty;
}
endpoint_t endpoint = it->second;
// Increment the command sequence number of the peer so that it won't
// get deallocated until "bind" command is issued by the caller.
// The subsequent 'bind' has to be called with inc_seqnum parameter
// set to false, so that the seqnum isn't incremented twice.
endpoint.socket->inc_seqnum ();
endpoints_sync.unlock ();
return endpoint;
}
// The last used socket ID, or 0 if no socket was used so far. Note that this
// is a global variable. Thus, even sockets created in different contexts have
// unique IDs.
zmq::atomic_counter_t zmq::ctx_t::max_socket_id;
/*
Copyright (c) 2007-2012 iMatix Corporation
Copyright (c) 2009-2011 250bpm s.r.o.
Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform.hpp"
#ifdef ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#else
#include <unistd.h>
#endif
#include <new>
#include <string.h>
#include "ctx.hpp"
#include "socket_base.hpp"
#include "io_thread.hpp"
#include "reaper.hpp"
#include "pipe.hpp"
#include "err.hpp"
#include "msg.hpp"
zmq::ctx_t::ctx_t () :
tag (0xabadcafe),
starting (true),
terminating (false),
reaper (NULL),
slot_count (0),
slots (NULL),
max_sockets (ZMQ_MAX_SOCKETS_DFLT),
io_thread_count (ZMQ_IO_THREADS_DFLT)
{
}
bool zmq::ctx_t::check_tag ()
{
return tag == 0xabadcafe;
}
zmq::ctx_t::~ctx_t ()
{
// Check that there are no remaining sockets.
zmq_assert (sockets.empty ());
// Ask I/O threads to terminate. If stop signal wasn't sent to I/O
// thread subsequent invocation of destructor would hang-up.
for (io_threads_t::size_type i = 0; i != io_threads.size (); i++)
io_threads [i]->stop ();
// Wait till I/O threads actually terminate.
for (io_threads_t::size_type i = 0; i != io_threads.size (); i++)
delete io_threads [i];
// Deallocate the reaper thread object.
if (reaper)
delete reaper;
// Deallocate the array of mailboxes. No special work is
// needed as mailboxes themselves were deallocated with their
// corresponding io_thread/socket objects.
if (slots)
free (slots);
// Remove the tag, so that the object is considered dead.
tag = 0xdeadbeef;
}
int zmq::ctx_t::terminate ()
{
slot_sync.lock ();
if (!starting) {
// Check whether termination was already underway, but interrupted and now
// restarted.
bool restarted = terminating;
terminating = true;
slot_sync.unlock ();
// First attempt to terminate the context.
if (!restarted) {
// First send stop command to sockets so that any blocking calls
// can be interrupted. If there are no sockets we can ask reaper
// thread to stop.
slot_sync.lock ();
for (sockets_t::size_type i = 0; i != sockets.size (); i++)
sockets [i]->stop ();
if (sockets.empty ())
reaper->stop ();
slot_sync.unlock ();
}
// Wait till reaper thread closes all the sockets.
command_t cmd;
int rc = term_mailbox.recv (&cmd, -1);
if (rc == -1 && errno == EINTR)
return -1;
errno_assert (rc == 0);
zmq_assert (cmd.type == command_t::done);
slot_sync.lock ();
zmq_assert (sockets.empty ());
}
slot_sync.unlock ();
// Deallocate the resources.
delete this;
return 0;
}
int zmq::ctx_t::set (int option_, int optval_)
{
int rc = 0;
if (option_ == ZMQ_MAX_SOCKETS && optval_ >= 1) {
opt_sync.lock ();
max_sockets = optval_;
opt_sync.unlock ();
}
else
if (option_ == ZMQ_IO_THREADS && optval_ >= 0) {
opt_sync.lock ();
io_thread_count = optval_;
opt_sync.unlock ();
}
else {
errno = EINVAL;
rc = -1;
}
return rc;
}
int zmq::ctx_t::get (int option_)
{
int rc = 0;
if (option_ == ZMQ_MAX_SOCKETS)
rc = max_sockets;
else
if (option_ == ZMQ_IO_THREADS)
rc = io_thread_count;
else {
errno = EINVAL;
rc = -1;
}
return rc;
}
zmq::socket_base_t *zmq::ctx_t::create_socket (int type_)
{
slot_sync.lock ();
if (unlikely (starting)) {
starting = false;
// Initialise the array of mailboxes. Additional three slots are for
// zmq_term thread and reaper thread.
opt_sync.lock ();
int mazmq = max_sockets;
int ios = io_thread_count;
opt_sync.unlock ();
slot_count = mazmq + ios + 2;
slots = (mailbox_t**) malloc (sizeof (mailbox_t*) * slot_count);
alloc_assert (slots);
// Initialise the infrastructure for zmq_term thread.
slots [term_tid] = &term_mailbox;
// Create the reaper thread.
reaper = new (std::nothrow) reaper_t (this, reaper_tid);
alloc_assert (reaper);
slots [reaper_tid] = reaper->get_mailbox ();
reaper->start ();
// Create I/O thread objects and launch them.
for (int i = 2; i != ios + 2; i++) {
io_thread_t *io_thread = new (std::nothrow) io_thread_t (this, i);
alloc_assert (io_thread);
io_threads.push_back (io_thread);
slots [i] = io_thread->get_mailbox ();
io_thread->start ();
}
// In the unused part of the slot array, create a list of empty slots.
for (int32_t i = (int32_t) slot_count - 1;
i >= (int32_t) ios + 2; i--) {
empty_slots.push_back (i);
slots [i] = NULL;
}
}
// Once zmq_term() was called, we can't create new sockets.
if (terminating) {
slot_sync.unlock ();
errno = ETERM;
return NULL;
}
// If max_sockets limit was reached, return error.
if (empty_slots.empty ()) {
slot_sync.unlock ();
errno = EMFILE;
return NULL;
}
// Choose a slot for the socket.
uint32_t slot = empty_slots.back ();
empty_slots.pop_back ();
// Generate new unique socket ID.
int sid = ((int) max_socket_id.add (1)) + 1;
// Create the socket and register its mailbox.
socket_base_t *s = socket_base_t::create (type_, this, slot, sid);
if (!s) {
empty_slots.push_back (slot);
slot_sync.unlock ();
return NULL;
}
sockets.push_back (s);
slots [slot] = s->get_mailbox ();
slot_sync.unlock ();
return s;
}
void zmq::ctx_t::destroy_socket (class socket_base_t *socket_)
{
slot_sync.lock ();
// Free the associated thread slot.
uint32_t tid = socket_->get_tid ();
empty_slots.push_back (tid);
slots [tid] = NULL;
// Remove the socket from the list of sockets.
sockets.erase (socket_);
// If zmq_term() was already called and there are no more socket
// we can ask reaper thread to terminate.
if (terminating && sockets.empty ())
reaper->stop ();
slot_sync.unlock ();
}
zmq::object_t *zmq::ctx_t::get_reaper ()
{
return reaper;
}
void zmq::ctx_t::send_command (uint32_t tid_, const command_t &command_)
{
slots [tid_]->send (command_);
}
zmq::io_thread_t *zmq::ctx_t::choose_io_thread (uint64_t affinity_)
{
if (io_threads.empty ())
return NULL;
// Find the I/O thread with minimum load.
int min_load = -1;
io_thread_t *selected_io_thread = NULL;
for (io_threads_t::size_type i = 0; i != io_threads.size (); i++) {
if (!affinity_ || (affinity_ & (uint64_t (1) << i))) {
int load = io_threads [i]->get_load ();
if (selected_io_thread == NULL || load < min_load) {
min_load = load;
selected_io_thread = io_threads [i];
}
}
}
return selected_io_thread;
}
int zmq::ctx_t::register_endpoint (const char *addr_, endpoint_t &endpoint_)
{
endpoints_sync.lock ();
bool inserted = endpoints.insert (endpoints_t::value_type (
std::string (addr_), endpoint_)).second;
endpoints_sync.unlock ();
if (!inserted) {
errno = EADDRINUSE;
return -1;
}
return 0;
}
void zmq::ctx_t::unregister_endpoints (socket_base_t *socket_)
{
endpoints_sync.lock ();
endpoints_t::iterator it = endpoints.begin ();
while (it != endpoints.end ()) {
if (it->second.socket == socket_) {
endpoints_t::iterator to_erase = it;
++it;
endpoints.erase (to_erase);
continue;
}
++it;
}
endpoints_sync.unlock ();
}
zmq::endpoint_t zmq::ctx_t::find_endpoint (const char *addr_)
{
endpoints_sync.lock ();
endpoints_t::iterator it = endpoints.find (addr_);
if (it == endpoints.end ()) {
endpoints_sync.unlock ();
errno = ECONNREFUSED;
endpoint_t empty = {NULL, options_t()};
return empty;
}
endpoint_t endpoint = it->second;
// Increment the command sequence number of the peer so that it won't
// get deallocated until "bind" command is issued by the caller.
// The subsequent 'bind' has to be called with inc_seqnum parameter
// set to false, so that the seqnum isn't incremented twice.
endpoint.socket->inc_seqnum ();
endpoints_sync.unlock ();
return endpoint;
}
// The last used socket ID, or 0 if no socket was used so far. Note that this
// is a global variable. Thus, even sockets created in different contexts have
// unique IDs.
zmq::atomic_counter_t zmq::ctx_t::max_socket_id;
| [
"tj@vision-media.ca"
] | tj@vision-media.ca |
7018514c6316c00dc1de39fd21915a1980a09535 | 650d493d6037383fe22423e00d000879fe2c580b | /node_modules/node-sass/src/libsass/src/error_handling.hpp | bcb4e808dfa207a167cbda98afaa989e48b0da1a | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | 253033688/m-boot | 6d8f06226992c98d72e32dffd98ec05717c46e0d | a424633fcfd65296868dfbdc3492b1f57c15448d | refs/heads/master | 2021-08-31T00:49:50.016040 | 2017-12-20T01:58:18 | 2017-12-20T01:58:18 | 114,828,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,434 | hpp | #ifndef SASS_ERROR_HANDLING_H
#define SASS_ERROR_HANDLING_H
#include <string>
#include <sstream>
#include <stdexcept>
#include "position.hpp"
namespace Sass {
struct Backtrace;
namespace Exception {
const std::string def_msg = "Invalid sass detected";
const std::string def_op_msg = "Undefined operation";
const std::string def_op_null_msg = "Invalid null operation";
class Base : public std::runtime_error {
protected:
std::string msg;
std::string prefix;
public:
ParserState pstate;
std::vector<Sass_Import_Entry>* import_stack;
public:
Base(ParserState pstate, std::string msg = def_msg, std::vector<Sass_Import_Entry>* import_stack = 0);
virtual const char* errtype() const { return prefix.c_str(); }
virtual const char* what() const throw() { return msg.c_str(); }
virtual ~Base() throw() {};
};
class InvalidSass : public Base {
public:
InvalidSass(ParserState pstate, std::string msg);
virtual ~InvalidSass() throw() {};
};
class InvalidParent : public Base {
protected:
Selector_Ptr parent;
Selector_Ptr selector;
public:
InvalidParent(Selector_Ptr parent, Selector_Ptr selector);
virtual ~InvalidParent() throw() {};
};
class MissingArgument : public Base {
protected:
std::string fn;
std::string arg;
std::string fntype;
public:
MissingArgument(ParserState pstate, std::string fn, std::string arg, std::string fntype);
virtual ~MissingArgument() throw() {};
};
class InvalidArgumentType : public Base {
protected:
std::string fn;
std::string arg;
std::string type;
const Value_Ptr value;
public:
InvalidArgumentType(ParserState pstate, std::string fn, std::string arg, std::string type, const Value_Ptr value = 0);
virtual ~InvalidArgumentType() throw() {};
};
class InvalidSyntax : public Base {
public:
InvalidSyntax(ParserState pstate, std::string msg, std::vector<Sass_Import_Entry>* import_stack = 0);
virtual ~InvalidSyntax() throw() {};
};
/* common virtual base class (has no pstate) */
class OperationError : public std::runtime_error {
protected:
std::string msg;
public:
OperationError(std::string msg = def_op_msg)
: std::runtime_error(msg), msg(msg)
{};
public:
virtual const char* errtype() const { return "Error"; }
virtual const char* what() const throw() { return msg.c_str(); }
virtual ~OperationError() throw() {};
};
class ZeroDivisionError : public OperationError {
protected:
const Expression& lhs;
const Expression& rhs;
public:
ZeroDivisionError(const Expression& lhs, const Expression& rhs);
virtual const char* errtype() const { return "ZeroDivisionError"; }
virtual ~ZeroDivisionError() throw() {};
};
class DuplicateKeyError : public Base {
protected:
const Map& dup;
const Expression& org;
public:
DuplicateKeyError(const Map& dup, const Expression& org);
virtual const char* errtype() const { return "Error"; }
virtual ~DuplicateKeyError() throw() {};
};
class TypeMismatch : public Base {
protected:
const Expression& var;
const std::string type;
public:
TypeMismatch(const Expression& var, const std::string type);
virtual const char* errtype() const { return "Error"; }
virtual ~TypeMismatch() throw() {};
};
class InvalidValue : public Base {
protected:
const Expression& val;
public:
InvalidValue(const Expression& val);
virtual const char* errtype() const { return "Error"; }
virtual ~InvalidValue() throw() {};
};
class StackError : public Base {
protected:
const AST_Node& node;
public:
StackError(const AST_Node& node);
virtual const char* errtype() const { return "SystemStackError"; }
virtual ~StackError() throw() {};
};
class IncompatibleUnits : public OperationError {
protected:
const Number& lhs;
const Number& rhs;
public:
IncompatibleUnits(const Number& lhs, const Number& rhs);
virtual ~IncompatibleUnits() throw() {};
};
class UndefinedOperation : public OperationError {
protected:
Expression_Ptr_Const lhs;
Expression_Ptr_Const rhs;
const std::string op;
public:
UndefinedOperation(Expression_Ptr_Const lhs, Expression_Ptr_Const rhs, const std::string& op);
// virtual const char* errtype() const { return "Error"; }
virtual ~UndefinedOperation() throw() {};
};
class InvalidNullOperation : public UndefinedOperation {
public:
InvalidNullOperation(Expression_Ptr_Const lhs, Expression_Ptr_Const rhs, const std::string& op);
virtual ~InvalidNullOperation() throw() {};
};
class AlphaChannelsNotEqual : public OperationError {
protected:
Expression_Ptr_Const lhs;
Expression_Ptr_Const rhs;
const std::string op;
public:
AlphaChannelsNotEqual(Expression_Ptr_Const lhs, Expression_Ptr_Const rhs, const std::string& op);
// virtual const char* errtype() const { return "Error"; }
virtual ~AlphaChannelsNotEqual() throw() {};
};
class SassValueError : public Base {
public:
SassValueError(ParserState pstate, OperationError& err);
virtual ~SassValueError() throw() {};
};
}
void warn(std::string msg, ParserState pstate);
void warn(std::string msg, ParserState pstate, Backtrace* bt);
void deprecated_function(std::string msg, ParserState pstate);
void deprecated(std::string msg, std::string msg2, ParserState pstate);
void deprecated_bind(std::string msg, ParserState pstate);
// void deprecated(std::string msg, ParserState pstate, Backtrace* bt);
void error(std::string msg, ParserState pstate);
void error(std::string msg, ParserState pstate, Backtrace* bt);
}
#endif
| [
"253033688@qq.com"
] | 253033688@qq.com |
adc3bee93f765d70d6d562e23a66ea6a41babcc6 | e73ba4846d69522247545ef4edd689e0c51e3958 | /include/Engine/Renderer/Renderer.h | b1e8fa3c2143b89d2e6ec4de7fc3f5f900ba016b | [] | no_license | Flinnk/Simple-Game-Engine | f11bb79a676415aa11c6243d06536ac0e6274601 | c323f9f31a6de14d75f5fd3b4303de85d0bfd615 | refs/heads/master | 2021-01-21T22:25:39.289880 | 2018-01-12T17:32:49 | 2018-01-12T17:32:49 | 102,157,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 803 | h | #pragma once
#include <string>
#include <Engine\Renderer\RenderData.h>
namespace GameEngine {
class SpriteRenderer;
class TextRenderer;
class Shader;
class Texture;
class CameraComponent;
class SpriteComponent;
struct Rect;
class Renderer {
public:
Renderer(Shader* SpriteShader, Shader* TextShader);
~Renderer();
void DrawSprite(const DrawCall2D& DrawCall) const;
void DrawText(const std::string& text, float x, float y, float scale, const Vector3& color) const;
void End();
void Release();
unsigned int GetDrawCallStats();
void ClearDebugStats();
void ClearCameraData();
void SetCamera(const CameraComponent* Camera);
private:
SpriteRenderer* SpriteRender = nullptr;
TextRenderer* TextRender = nullptr;
const CameraComponent* Camera = nullptr;
};
}
| [
"francisco.porcelparis@gmail.com"
] | francisco.porcelparis@gmail.com |
bee084a35e52186e53e971e53d484a5a2c50e113 | 9cddde271e75d4c9d5edb67475aac3566d16f68c | /include/ServerBluetooth.hpp | 544371750e15ace040b0ad431c70358d8337fe44 | [] | no_license | leandrg/Hands-Free | 0a8253fb5c2b6061152c4b1c66fd1fc7200abbf2 | ad97cba37beb513ba54df25af865f8b738a71acd | refs/heads/master | 2022-04-05T21:16:16.647965 | 2020-02-17T14:25:16 | 2020-02-17T14:25:16 | 213,389,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | hpp | //
// Created by Gaëtan Léandre on 16/02/2020.
//
#ifndef HANDS_FREE_SERVERBLUETOOTH_HPP
#define HANDS_FREE_SERVERBLUETOOTH_HPP
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include "ServerSocket.hpp"
typedef struct sockaddr SOCKADDR;
class ServerBluetooth: public ServerSocket {
public:
ServerBluetooth(int maxClients = 1);
~ServerBluetooth();
virtual const std::string getServerName() const;
protected:
virtual void socket() = 0;
virtual int bind() const = 0;
virtual ClientSocket *accept() = 0;
virtual void actionClient(ClientSocket *client, t_package &data) = 0;
};
#endif //HANDS_FREE_SERVERBLUETOOTH_HPP
| [
"gaetan.leandre@epitech.eu"
] | gaetan.leandre@epitech.eu |
847287dc39caec7ce6b9ca8f1e80c5c0e6298d06 | ab7d5ec2e40b26c33da957210b5d2da77f9b696d | /repos/arduino-sketch/contents/sketch_jul28a_seq/sketch_jul28a_seq.ino | 86d434259e4b060ea28d23927b0df353fe97cff4 | [
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | permissive | mcclure/bitbucket-backup | e49d280363ff7ef687f03473e463865a7ad8a817 | b6a02ca8decf843fa0a765c842c24e7eccf59307 | refs/heads/archive | 2023-01-24T21:15:14.875131 | 2020-02-02T20:56:23 | 2020-02-02T20:56:23 | 237,833,969 | 115 | 6 | null | 2023-01-07T14:24:14 | 2020-02-02T20:43:56 | C | UTF-8 | C++ | false | false | 3,769 | ino | #include <ctype.h>
#include <math.h>
#define PLAY 2
#define PITCH 3
#define FUNCS 26
#define STACKMAX 4
#define DEBUG 0
#define RATE 300
#define HIGHTIME 80
static int OCTAVE = 255/5;
static int ROOT = OCTAVE*3;
// Number: Play this note
// Parenthesis: Store a pattern, first letter is the label (must be uppercase letter)
// Uppercase letter: Play stored pattern
// +Number, -Number: Shift base note by semitones
// ++Number, --Number: Shift base note by octaves
const char song[] = "\
(M 0 4 7) \
(N 0 3 7) \
(R M M M M) \
(S N N N N) \
(T M M M ++1 M) \
R S R S T S R S \
";
typedef enum {
S_SCAN = 0,
S_WANTTAG,
S_WANTRPAREN
} ParenState;
struct Frame {
int at;
int root;
int pitch;
int rate;
int high;
bool on;
Frame() : at(0), root(0), pitch(0), rate(RATE), high(HIGHTIME), on(false) {}
};
struct Interp {
// PARSER
int sp;
ParenState state;
Frame stack[STACKMAX];
bool looped;
int func[FUNCS];
Interp() : sp(0), state(S_SCAN), looped(false) {
memset(func, 0, sizeof(func));
}
void reset();
void next();
Frame &frame() { return stack[sp]; }
int &at() { return frame().at; }
bool takeNumber(int n);
};
void Interp::reset() {
sp = 0; // In case of syntax error
state = S_SCAN; // Ibid
at() = 0;
looped = true;
}
bool Interp::takeNumber(int n) { // Return true if "done" with current note
frame().on = true;
frame().pitch = n;
return true;
}
void Interp::next() {
bool isbuilding = false;
int building = 0;
while (1) {
int i = at();
char ch = song[i];
#if DEBUG
Serial.print("Loop ");
Serial.print(state);
Serial.print("\n");
Serial.print(sp);
Serial.print(", ");
Serial.print(i);
Serial.print(", ");
Serial.print(ch);
Serial.print("\n");
#endif
if (ch == '\0') {
bool done = false;
if (isbuilding)
done = takeNumber(building);
reset();
building = 0;
if (done)
return;
else
continue;
} else switch (state) {
case S_WANTTAG:
if (isupper(ch))
func[ch-'A'] = i+1;
state = S_WANTRPAREN;
break;
case S_WANTRPAREN:
if (ch == ')')
state = S_SCAN;
break;
case S_SCAN:
if (isdigit(ch)) {
building *= 10;
isbuilding = true;
building += (ch - '0');
} else {
if (isbuilding) {
if (takeNumber(building))
return;
building = 0;
}
if (isupper(ch)) {
sp++;
frame() = stack[sp-1]; // Copy up
at() = func[ch-'A'];
continue;
}
switch (ch) {
case '(':
state = looped ? S_WANTRPAREN : S_WANTTAG;
break;
case ')':
sp--;
if (sp < 0)
sp = 0;
break;
default:break;
}
}
break;
}
at()++;
}
}
static Interp interp;
void setup() {
// put your setup code here, to run once:
pinMode(LED_BUILTIN, OUTPUT);
pinMode(PLAY, OUTPUT);
pinMode(PITCH, OUTPUT);
#if DEBUG
Serial.begin(9600);
#endif
}
void high() {
digitalWrite(LED_BUILTIN, HIGH);
digitalWrite(PLAY, HIGH);
}
void low() {
digitalWrite(LED_BUILTIN, LOW);
digitalWrite(PLAY, LOW);
}
void loop() {
#if DEBUG
Serial.print("Booted\n");
#endif
interp.next();
Frame note = interp.frame();
int p = (ROOT*12 + OCTAVE*(note.root + note.pitch))/12;
analogWrite(PITCH, p);
if (note.on) {
high();
if (note.high <= note.rate) {
delay(note.high);
low();
delay(note.rate-note.high);
} else {
delay(note.rate);
}
} else {
delay(note.rate);
}
}
| [
"andi.m.mcclure@gmail.com"
] | andi.m.mcclure@gmail.com |
6c951242ba5e93ab87d393bd973900e7c468ca44 | 350aa833bb2c86162a85c1c70f0cd3c51a3a1818 | /Rare/1_RK.cpp | 1d30349a472594b08ea806d7bfdeedaeeae09be2 | [] | no_license | foy4748/CPP_from_sheets | ad2a230a15483f6327c3e6572a91779352fead93 | 65ce735e07d7b6083b7f4484ecfe2a2d7cd97f75 | refs/heads/main | 2023-03-01T21:03:41.229307 | 2021-02-03T16:09:04 | 2021-02-03T16:09:04 | 335,677,503 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 798 | cpp | #include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
ofstream fout("1_RK.dat");
//Defining functions
double F(double x)
{
double omega = 4.2;
return -omega*omega*x;
}
void RK()
{
//Necessary Variables
double k1,k2,k3,k4, l1,l2,l3,l4;
//Initial Values
double x = 0, z = 1.0, t, h = 0.01;
//Labeling Data Columns
fout<<"Time"<<" "<<"Position"<<" "<<"Velocity"<<endl;
for(t=0;t<10;t+=h)
{
//Printing datas to file
fout<<t<<" "<<x<<" "<<z<<endl;
//Applying Runge-Kutta method
k1 = h*z;
l1 = h*F(x);
k2 = h*(z + l1/2);
l2 = h*F(x + k1/2);
k3 = h*(z + l2/2);
l3 = h*F(x + k2/2);
k4 = h*(z + l3);
l4 = h*F(x + k3);
x += (k1 + 2.0*k2 + 2.0*k3 + k4)/6;
z += (l1 + 2.0*l2 + 2.0*l3 + l4)/6;
}
}
int main() { RK(); } | [
"faisaljfcl@gmail.com"
] | faisaljfcl@gmail.com |
8f4c5f4ada07d924497d717701bdf71acbc20ae3 | bef429c175a2ddc77a51ee9f967e087421ea5389 | /tcpclient.h | 4b3684467cd40b11df3880ecb2161cd48ef7931b | [] | no_license | specialk74/Lexus | 774da7e1bde769982d674f86d28aedccfc3e61dd | 24f06fa2f5f3ae5a643eb795d1f03c25925816fb | refs/heads/master | 2021-03-12T23:34:41.472410 | 2014-06-06T21:47:59 | 2014-06-06T21:47:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 601 | h | #ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include <QObject>
class QTcpSocket;
class TcpClient : public QObject
{
Q_OBJECT
public:
explicit TcpClient(QObject *parent = 0);
void setSocket (QTcpSocket *socket);
void sendMsg (const QByteArray &data);
QTcpSocket * getSocket ();
void setDebug (const bool &val) { m_debug = val; }
~TcpClient();
protected slots:
void fromClientsSlot();
void send (const QByteArray &buffer);
protected:
void debug (const QString &testo);
QByteArray m_buffer;
QTcpSocket *m_socket;
bool m_debug;
};
#endif // TCPCLIENT_H
| [
"m.faletra@gmail.com"
] | m.faletra@gmail.com |
27dc1d8f9287cecbcfbcc4d41bee40f134938ba5 | 1ea7cb0f5f583d50a680c4dc600c46d986278143 | /src/synapse.cpp | 2d91c26deb5eb0fd1c8fd6500f71258dc3d34197 | [] | no_license | asuka1975/network | aa56e97993e29130f6db3977ba95666d1fc2c622 | 3a04324929e3c453dec7036fbf555f93243a054c | refs/heads/master | 2023-08-28T12:41:50.666945 | 2021-05-26T09:04:25 | 2021-05-26T09:04:25 | 282,084,832 | 4 | 0 | null | 2021-05-26T09:04:26 | 2020-07-24T00:26:09 | C++ | UTF-8 | C++ | false | false | 730 | cpp | //
// Created by hungr on 2020/07/24.
//
#include "synapse.h"
synapse::synapse(std::weak_ptr<circuitable> target, float weight) : receiver(target), weight(weight)
{
weight_update = [](auto v, auto w) -> auto { return w; };
}
void synapse::receive(float value, input_type type) {
switch (type) {
case NEURON:
send(value);
break;
case SYNAPSE:
send(value);
break;
}
}
void synapse::send(float value) {
if(auto r = receiver.lock()) {
r->receive(value * weight, SYNAPSE);
weight = weight_update(value, weight);
}
}
void synapse::add_receiver(std::weak_ptr<circuitable> target) {
receiver = target;
}
void synapse::update() {} | [
"39215088+asuka1975@users.noreply.github.com"
] | 39215088+asuka1975@users.noreply.github.com |
7cb915562c59bc3067d18fbb1bf0883eb9abbe40 | 19183c5eac81f9610d71ca035e32f7c138745531 | /src/vibration/vibration.h | 2bcdba9c5d68d0ac83a2184d646296e4009c5850 | [] | no_license | DavidM42/esp32-task-splitter | 20a6614895ae9871442fadbb05c2f641c70773fe | d95fdd05a39c9121a9527c9e2cd27f3f390e2985 | refs/heads/master | 2023-04-05T01:40:42.195401 | 2021-04-09T16:11:42 | 2021-04-09T16:11:42 | 355,705,735 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | h | #ifndef VIBRATION_H // To make sure you don't declare the function more than once by including the header multiple times.
#define VIBRATION_H
#include <Arduino.h>
class Vibration
{
private:
int vibration_pin = 22;
uint32_t vibration_length_ms = 400;
public:
void setup();
void short_vibration();
};
#endif
| [
"davidmerz@gmx.de"
] | davidmerz@gmx.de |
16e897089b07d91e4ec8efe6ffeebb6565ff3a39 | 5c406524fb7d20d0cef1456f0d12182b6c8d08ee | /hprose/io/decoders/BoolDecoder.h | 2c1e647eb99188e613e120b28da15cc74fcf030d | [
"MIT"
] | permissive | HelloKitty2022/hprose-cpp1x | 27818dffa06af91e1e1957edd52aaa1d96121cf6 | d37b3737bbf1836d68b32241c78f711051b1984c | refs/heads/master | 2023-08-25T18:10:22.934102 | 2021-11-04T13:08:25 | 2021-11-04T13:08:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,252 | h | /**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* hprose/io/decoders/BoolDecoder.h *
* *
* hprose bool decoder for cpp. *
* *
* LastModified: Oct 22, 2016 *
* Author: Chen fei <cf@hprose.com> *
* *
\**********************************************************/
#pragma once
namespace hprose {
namespace io {
class Reader;
namespace decoders {
bool BoolDecode(Reader &reader, char tag);
}
}
} // hprose::io::decoders
| [
"cf850118@163.com"
] | cf850118@163.com |
39a8fff971feee1feea368c080c07813ee4d3b42 | d167de45f960f57e72dd7da861b862e4ca0a4b3e | /rd-cpp/demo/profile.cpp | d423eb5facf5c1eedbe5fbb246d8d3af2b1f1890 | [
"Apache-2.0"
] | permissive | jmoeller93/rd | 571f8544f3f2b9babcbc8d618acda91e1632a53d | 9b59220e8c4efbadcf09776c45a770099944c70e | refs/heads/master | 2020-06-20T13:56:52.172616 | 2019-07-11T17:45:16 | 2019-07-11T17:45:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,922 | cpp | #include "DemoModel.h"
#include "ExtModel.h"
#include "Lifetime.h"
#include "SocketWire.h"
#include "Protocol.h"
#include "SimpleScheduler.h"
#include <cstdint>
using namespace rd;
using namespace demo;
int main() {
minimum_level_to_log = LogLevel::Fatal;
SimpleScheduler serverScheduler;
SimpleScheduler clientScheduler;
LifetimeDefinition server_definition(false);
Lifetime server_lifetime = server_definition.lifetime;
LifetimeDefinition server_socket_definition(false);
Lifetime server_socket_lifetime = server_definition.lifetime;
LifetimeDefinition client_definition(false);
Lifetime client_lifetime = client_definition.lifetime;
LifetimeDefinition client_socket_definition(false);
Lifetime client_socket_lifetime = client_definition.lifetime;
//region Client initialization
uint16_t port = 0;
auto serverWire = std::make_shared<SocketWire::Server>(server_socket_lifetime, &serverScheduler, port);
auto serverProtocol = std::make_unique<Protocol>(Identities::SERVER, &serverScheduler, serverWire, server_lifetime);
port = serverWire->port;
// auto clientWire = std::make_shared<SocketWire::Client>(client_socket_lifetime, &clientScheduler, port);
// auto clientProtocol = std::make_unique<Protocol>(Identities::CLIENT, &clientScheduler, clientWire, client_lifetime);
DemoModel serverModel;
// DemoModel clientModel;
serverModel.connect(server_lifetime, serverProtocol.get());
// clientModel.connect(client_lifetime, clientProtocol.get());
auto property = [&]() {
const int C = 1000;
for (int i = 0; i < C; ++i) {
serverModel.get_boolean_property().set(i % 2 == 0);
}
};
auto intern = [&]() {
const int C = 1000;
for (int i = 0; i < C; ++i) {
serverModel.get_interned_string().set(L"abacaba" + std::to_wstring(i % 2));
}
};
intern();
std::this_thread::sleep_for(std::chrono::seconds(2));
server_definition.terminate();
client_definition.terminate();
}
| [
"operasfantom@gmail.com"
] | operasfantom@gmail.com |
d9913f62af9e16b818584b33ca6f8a06728cffc7 | 63ba91de14d218aafce9b9fef4d68f072dc511d2 | /uva/solved/11057/c.cpp | 3b791da93f7bccc3dc9ab49e3806894ceae52cbd | [] | no_license | anas-didi95/programming-practices | bd1b57ea88db274f7c4b926cf2baf7360b3efe41 | cb0fb132e322b190edc11a8f71a231912c14ede5 | refs/heads/master | 2021-04-27T11:41:15.594540 | 2018-03-06T10:22:00 | 2018-03-06T10:22:00 | 122,566,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,002 | cpp | #include <bits/stdc++.h>
using namespace std;
#define dg(x) cerr<<x<<' '
#define dgl cerr<<endl
int n;
int b[10010];
int m;
string w;
int main() {
while (scanf("%d", &n)==1) {
for (int i = 0; i < n; i++) scanf("%d", &b[i]);
scanf("%d", &m);
getline(cin, w);
sort(b, b+n);
int x, y, d = INT_MAX;
for (int i = 0; i < n; i++) {
int v = m-b[i];
if (binary_search(b, b+n, v) && b[i]<=v) {
if (v == b[i]) {
int c = 0;
for (int i = 0; i < n; i++) {
if (v == b[i]) c++;
}
if (c < 2) continue;
}
if (d > abs(v-b[i])) {
x = b[i];
y = v;
d = abs(y-x);
}
}
}
printf("Peter should buy books whose prices are %d and %d.\n", x, y);
printf("\n");
}
return 0;
}
| [
"anas.didi95@gmail.com"
] | anas.didi95@gmail.com |
e83ec1d0d029ba81645323b01c073aefd952820d | 05f2045835f6d47d4f5d8e480fe33a02a49ec6d5 | /GREEDY TECHNIQUE/SOLVED EXAMPLES/jobSequencingProblem.cpp | cc0c6028af53e2995d1dc27e4c2f98de217fc376 | [] | no_license | Amanuttam1192/The-CP-Companion | b9d94abad6f35170ab8d563fe757f68f7d6457bc | e590ff4c86e7f8c18103086bbd02e9a65b8238fb | refs/heads/main | 2023-08-29T16:08:41.642937 | 2021-10-13T19:01:12 | 2021-10-13T19:01:12 | 416,994,836 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 825 | cpp | #include<iostream>
#include<algorithm>
using namespace std;
struct Job
{
char id;
int dead;
int profit;
};
bool comparison(Job a, Job b)
{
return (a.profit > b.profit);
}
void printJobScheduling(Job arr[], int n)
{
sort(arr, arr+n, comparison);
int result[n];
bool slot[n];
for (int i=0; i<n; i++)
slot[i] = false;
for (int i=0; i<n; i++)
{
for (int j=min(n, arr[i].dead)-1; j>=0; j--)
{
if (slot[j]==false)
{
result[j] = i;
slot[j] = true;
break;
}
}
}
for (int i=0; i<n; i++)
if (slot[i])
cout << arr[result[i]].id << " ";
}
int main()
{
Job arr[] = { {'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27},
{'d', 1, 25}, {'e', 3, 15}};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Following is maximum profit sequence of jobs \n";
printJobScheduling(arr, n);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
03286994146d4fea5649de228711aab15feda3c0 | 2fecdeaca0adf090ebf581e053daf9261b0cb743 | /C++基础/字符型示例.cpp | 9dbedd00e423830a577190be78a58ead32b8d959 | [] | no_license | ArvinRoad/C-Tutorial | 9aa5d98411aaf47d7698fddc68626349440e4806 | 4b1a535be496def8a37de7774b2d0adbadf7939f | refs/heads/master | 2022-12-29T02:37:17.298342 | 2020-10-20T06:48:21 | 2020-10-20T06:48:21 | 284,160,213 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 446 | cpp | #include<iostream>
using namespace std;
int main10() {
char ch = 'a';
/*
char ch2 = "b";
如果ch2为"b",系统报错。char语法为''。
char ch3 ='abc'
如果ch3为'abc',系统报错。char只支持字符,不支持字符串。
*/
cout << "ch =" << ch << endl;
cout << "char 类型的内存空间占用大小为:" << sizeof(ch) << endl;
cout << (int)ch << endl; //查看a的ASCII编码
system("pause");
return 0;
} | [
"53329456+ArvinRoad@users.noreply.github.com"
] | 53329456+ArvinRoad@users.noreply.github.com |
0fd036fed8a94c9927735e0e2516cdc8de6a26b1 | 2cf838b54b556987cfc49f42935f8aa7563ea1f4 | /aws-cpp-sdk-devicefarm/include/aws/devicefarm/model/ListTestGridSessionsRequest.h | 56cb70ff28712f703e42d31114fd0687240f3db7 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | QPC-database/aws-sdk-cpp | d11e9f0ff6958c64e793c87a49f1e034813dac32 | 9f83105f7e07fe04380232981ab073c247d6fc85 | refs/heads/main | 2023-06-14T17:41:04.817304 | 2021-07-09T20:28:20 | 2021-07-09T20:28:20 | 384,714,703 | 1 | 0 | Apache-2.0 | 2021-07-10T14:16:41 | 2021-07-10T14:16:41 | null | UTF-8 | C++ | false | false | 10,996 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/devicefarm/DeviceFarm_EXPORTS.h>
#include <aws/devicefarm/DeviceFarmRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/devicefarm/model/TestGridSessionStatus.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace DeviceFarm
{
namespace Model
{
/**
*/
class AWS_DEVICEFARM_API ListTestGridSessionsRequest : public DeviceFarmRequest
{
public:
ListTestGridSessionsRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "ListTestGridSessions"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>ARN of a <a>TestGridProject</a>.</p>
*/
inline const Aws::String& GetProjectArn() const{ return m_projectArn; }
/**
* <p>ARN of a <a>TestGridProject</a>.</p>
*/
inline bool ProjectArnHasBeenSet() const { return m_projectArnHasBeenSet; }
/**
* <p>ARN of a <a>TestGridProject</a>.</p>
*/
inline void SetProjectArn(const Aws::String& value) { m_projectArnHasBeenSet = true; m_projectArn = value; }
/**
* <p>ARN of a <a>TestGridProject</a>.</p>
*/
inline void SetProjectArn(Aws::String&& value) { m_projectArnHasBeenSet = true; m_projectArn = std::move(value); }
/**
* <p>ARN of a <a>TestGridProject</a>.</p>
*/
inline void SetProjectArn(const char* value) { m_projectArnHasBeenSet = true; m_projectArn.assign(value); }
/**
* <p>ARN of a <a>TestGridProject</a>.</p>
*/
inline ListTestGridSessionsRequest& WithProjectArn(const Aws::String& value) { SetProjectArn(value); return *this;}
/**
* <p>ARN of a <a>TestGridProject</a>.</p>
*/
inline ListTestGridSessionsRequest& WithProjectArn(Aws::String&& value) { SetProjectArn(std::move(value)); return *this;}
/**
* <p>ARN of a <a>TestGridProject</a>.</p>
*/
inline ListTestGridSessionsRequest& WithProjectArn(const char* value) { SetProjectArn(value); return *this;}
/**
* <p>Return only sessions in this state.</p>
*/
inline const TestGridSessionStatus& GetStatus() const{ return m_status; }
/**
* <p>Return only sessions in this state.</p>
*/
inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }
/**
* <p>Return only sessions in this state.</p>
*/
inline void SetStatus(const TestGridSessionStatus& value) { m_statusHasBeenSet = true; m_status = value; }
/**
* <p>Return only sessions in this state.</p>
*/
inline void SetStatus(TestGridSessionStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }
/**
* <p>Return only sessions in this state.</p>
*/
inline ListTestGridSessionsRequest& WithStatus(const TestGridSessionStatus& value) { SetStatus(value); return *this;}
/**
* <p>Return only sessions in this state.</p>
*/
inline ListTestGridSessionsRequest& WithStatus(TestGridSessionStatus&& value) { SetStatus(std::move(value)); return *this;}
/**
* <p>Return only sessions created after this time.</p>
*/
inline const Aws::Utils::DateTime& GetCreationTimeAfter() const{ return m_creationTimeAfter; }
/**
* <p>Return only sessions created after this time.</p>
*/
inline bool CreationTimeAfterHasBeenSet() const { return m_creationTimeAfterHasBeenSet; }
/**
* <p>Return only sessions created after this time.</p>
*/
inline void SetCreationTimeAfter(const Aws::Utils::DateTime& value) { m_creationTimeAfterHasBeenSet = true; m_creationTimeAfter = value; }
/**
* <p>Return only sessions created after this time.</p>
*/
inline void SetCreationTimeAfter(Aws::Utils::DateTime&& value) { m_creationTimeAfterHasBeenSet = true; m_creationTimeAfter = std::move(value); }
/**
* <p>Return only sessions created after this time.</p>
*/
inline ListTestGridSessionsRequest& WithCreationTimeAfter(const Aws::Utils::DateTime& value) { SetCreationTimeAfter(value); return *this;}
/**
* <p>Return only sessions created after this time.</p>
*/
inline ListTestGridSessionsRequest& WithCreationTimeAfter(Aws::Utils::DateTime&& value) { SetCreationTimeAfter(std::move(value)); return *this;}
/**
* <p>Return only sessions created before this time.</p>
*/
inline const Aws::Utils::DateTime& GetCreationTimeBefore() const{ return m_creationTimeBefore; }
/**
* <p>Return only sessions created before this time.</p>
*/
inline bool CreationTimeBeforeHasBeenSet() const { return m_creationTimeBeforeHasBeenSet; }
/**
* <p>Return only sessions created before this time.</p>
*/
inline void SetCreationTimeBefore(const Aws::Utils::DateTime& value) { m_creationTimeBeforeHasBeenSet = true; m_creationTimeBefore = value; }
/**
* <p>Return only sessions created before this time.</p>
*/
inline void SetCreationTimeBefore(Aws::Utils::DateTime&& value) { m_creationTimeBeforeHasBeenSet = true; m_creationTimeBefore = std::move(value); }
/**
* <p>Return only sessions created before this time.</p>
*/
inline ListTestGridSessionsRequest& WithCreationTimeBefore(const Aws::Utils::DateTime& value) { SetCreationTimeBefore(value); return *this;}
/**
* <p>Return only sessions created before this time.</p>
*/
inline ListTestGridSessionsRequest& WithCreationTimeBefore(Aws::Utils::DateTime&& value) { SetCreationTimeBefore(std::move(value)); return *this;}
/**
* <p>Return only sessions that ended after this time.</p>
*/
inline const Aws::Utils::DateTime& GetEndTimeAfter() const{ return m_endTimeAfter; }
/**
* <p>Return only sessions that ended after this time.</p>
*/
inline bool EndTimeAfterHasBeenSet() const { return m_endTimeAfterHasBeenSet; }
/**
* <p>Return only sessions that ended after this time.</p>
*/
inline void SetEndTimeAfter(const Aws::Utils::DateTime& value) { m_endTimeAfterHasBeenSet = true; m_endTimeAfter = value; }
/**
* <p>Return only sessions that ended after this time.</p>
*/
inline void SetEndTimeAfter(Aws::Utils::DateTime&& value) { m_endTimeAfterHasBeenSet = true; m_endTimeAfter = std::move(value); }
/**
* <p>Return only sessions that ended after this time.</p>
*/
inline ListTestGridSessionsRequest& WithEndTimeAfter(const Aws::Utils::DateTime& value) { SetEndTimeAfter(value); return *this;}
/**
* <p>Return only sessions that ended after this time.</p>
*/
inline ListTestGridSessionsRequest& WithEndTimeAfter(Aws::Utils::DateTime&& value) { SetEndTimeAfter(std::move(value)); return *this;}
/**
* <p>Return only sessions that ended before this time.</p>
*/
inline const Aws::Utils::DateTime& GetEndTimeBefore() const{ return m_endTimeBefore; }
/**
* <p>Return only sessions that ended before this time.</p>
*/
inline bool EndTimeBeforeHasBeenSet() const { return m_endTimeBeforeHasBeenSet; }
/**
* <p>Return only sessions that ended before this time.</p>
*/
inline void SetEndTimeBefore(const Aws::Utils::DateTime& value) { m_endTimeBeforeHasBeenSet = true; m_endTimeBefore = value; }
/**
* <p>Return only sessions that ended before this time.</p>
*/
inline void SetEndTimeBefore(Aws::Utils::DateTime&& value) { m_endTimeBeforeHasBeenSet = true; m_endTimeBefore = std::move(value); }
/**
* <p>Return only sessions that ended before this time.</p>
*/
inline ListTestGridSessionsRequest& WithEndTimeBefore(const Aws::Utils::DateTime& value) { SetEndTimeBefore(value); return *this;}
/**
* <p>Return only sessions that ended before this time.</p>
*/
inline ListTestGridSessionsRequest& WithEndTimeBefore(Aws::Utils::DateTime&& value) { SetEndTimeBefore(std::move(value)); return *this;}
/**
* <p>Return only this many results at a time.</p>
*/
inline int GetMaxResult() const{ return m_maxResult; }
/**
* <p>Return only this many results at a time.</p>
*/
inline bool MaxResultHasBeenSet() const { return m_maxResultHasBeenSet; }
/**
* <p>Return only this many results at a time.</p>
*/
inline void SetMaxResult(int value) { m_maxResultHasBeenSet = true; m_maxResult = value; }
/**
* <p>Return only this many results at a time.</p>
*/
inline ListTestGridSessionsRequest& WithMaxResult(int value) { SetMaxResult(value); return *this;}
/**
* <p>Pagination token.</p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p>Pagination token.</p>
*/
inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }
/**
* <p>Pagination token.</p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }
/**
* <p>Pagination token.</p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }
/**
* <p>Pagination token.</p>
*/
inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }
/**
* <p>Pagination token.</p>
*/
inline ListTestGridSessionsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p>Pagination token.</p>
*/
inline ListTestGridSessionsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
/**
* <p>Pagination token.</p>
*/
inline ListTestGridSessionsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}
private:
Aws::String m_projectArn;
bool m_projectArnHasBeenSet;
TestGridSessionStatus m_status;
bool m_statusHasBeenSet;
Aws::Utils::DateTime m_creationTimeAfter;
bool m_creationTimeAfterHasBeenSet;
Aws::Utils::DateTime m_creationTimeBefore;
bool m_creationTimeBeforeHasBeenSet;
Aws::Utils::DateTime m_endTimeAfter;
bool m_endTimeAfterHasBeenSet;
Aws::Utils::DateTime m_endTimeBefore;
bool m_endTimeBeforeHasBeenSet;
int m_maxResult;
bool m_maxResultHasBeenSet;
Aws::String m_nextToken;
bool m_nextTokenHasBeenSet;
};
} // namespace Model
} // namespace DeviceFarm
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
71b95b3bf5584b7237f745a6b61828022b17f453 | 8d45911e021d96c5675ea0f68c0dd97664a593f9 | /17.cpp | 89c43498606dc6b357988028f578e4c949cbe94f | [] | no_license | Arik096/L2-T1-DS-final-lab-test | 457aff1fc884ac156a4b75dc603cca3faebb54fd | d146d85e48eda31ce49d3d8e6a7b9ff25cf967d5 | refs/heads/master | 2021-01-01T15:56:17.595168 | 2017-07-19T16:03:45 | 2017-07-19T16:03:45 | 97,734,176 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 546 | cpp | #include <bits/stdc++.h>
#define MAX 5
long long int a[MAX];
long long int rear = - 1;
long long int Front = - 1;
int main ()
{
while(1)
{
long long int add;
printf("Inset the element in queue : ");
scanf("%lld", &add);
if (rear == MAX - 1)
{
printf("\nQueue Overflow \n");
}
else
{
if (Front == - 1)
Front = 0;
rear = rear + 1;
a[rear] = add;
printf("inserted element %lld\n",a[rear]);
}
}
return NULL;
}
| [
"noreply@github.com"
] | noreply@github.com |
28c53fb90282c66391f983380864c8c2e836073f | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /content/renderer/media/rtc_certificate.cc | 16a57a7545f8a5c20cef3223eb7c513a598f4dd7 | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 1,295 | cc | // Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/media/rtc_certificate.h"
#include "base/memory/ptr_util.h"
#include "url/gurl.h"
namespace content {
RTCCertificate::RTCCertificate(
const rtc::scoped_refptr<rtc::RTCCertificate>& certificate)
: certificate_(certificate) {
DCHECK(certificate_);
}
RTCCertificate::~RTCCertificate() {
}
std::unique_ptr<blink::WebRTCCertificate> RTCCertificate::shallowCopy() const {
return base::WrapUnique(new RTCCertificate(certificate_));
}
uint64_t RTCCertificate::expires() const {
return certificate_->Expires();
}
blink::WebRTCCertificatePEM RTCCertificate::toPEM() const {
rtc::RTCCertificatePEM pem = certificate_->ToPEM();
return blink::WebRTCCertificatePEM(
blink::WebString::fromUTF8(pem.private_key()),
blink::WebString::fromUTF8(pem.certificate()));
}
bool RTCCertificate::equals(const blink::WebRTCCertificate& other) const {
return *certificate_ ==
*static_cast<const RTCCertificate&>(other).certificate_;
}
const rtc::scoped_refptr<rtc::RTCCertificate>&
RTCCertificate::rtcCertificate() const {
return certificate_;
}
} // namespace content
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
35df90a1ead611a9ecb0dd7ddde07fd78e16efab | b7034de7478e196dd27e8d794f774b24238ccbde | /Week_01/reverse-only-letters.cpp | b3cf4d9f83555ea921fdd56d60d6f43999275278 | [] | no_license | NathanFreeman/algorithm008-class01 | 76c60357dac0cd2d08c613af11371162837ddedf | 75a7bcd55a089949713c7dcdc8c3ff374ed80b3b | refs/heads/master | 2022-11-18T22:40:49.479612 | 2020-07-05T10:34:51 | 2020-07-05T10:34:51 | 255,629,052 | 0 | 0 | null | 2020-04-14T14:15:29 | 2020-04-14T14:15:28 | null | UTF-8 | C++ | false | false | 525 | cpp | #include <string>
#include <iostream>
using namespace std;
class Solution {
public:
string reverseOnlyLetters(string S) {
for (int i = 0, j = S.length(); i < j;) {
if (!isalpha(S[i])) {
i++;
} else if (!isalpha(S[j])) {
j--;
} else {
swap(S[i++], S[j--]);
}
}
}
};
int main(){
string S = "abc-sc-sd";
Solution solution;
solution.reverseOnlyLetters(S);
cout << S << endl;
return 0;
} | [
"20188212e588G"
] | 20188212e588G |
e61712354cc8472dca1e1173cf887209747adb45 | 4dd1a4bb458bb8a664b4b7f57bdc5ac5a80361a7 | /chrome/browser/ui/global_media_controls/media_notification_service_unittest.cc | c32c1152dc735d82929e5d5ad42908653ed375d9 | [
"BSD-3-Clause"
] | permissive | joker2016cn/chromium | e2c74f1100b2138d54548dd8e8d1fad41f6cc9b9 | a5088d502f500bed6fa1ee1cabd0f530d2982599 | refs/heads/master | 2022-12-22T17:11:20.272822 | 2020-01-29T03:59:00 | 2020-01-29T03:59:00 | 177,708,424 | 0 | 0 | NOASSERTION | 2020-01-29T03:59:01 | 2019-03-26T03:30:16 | null | UTF-8 | C++ | false | false | 39,841 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/global_media_controls/media_notification_service.h"
#include <memory>
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/unguessable_token.h"
#include "build/build_config.h"
#include "chrome/browser/media/router/media_router_factory.h"
#include "chrome/browser/media/router/test/mock_media_router.h"
#include "chrome/browser/ui/global_media_controls/cast_media_notification_provider.h"
#include "chrome/browser/ui/global_media_controls/media_dialog_delegate.h"
#include "chrome/browser/ui/global_media_controls/media_notification_service_observer.h"
#include "chrome/browser/ui/global_media_controls/overlay_media_notification.h"
#include "chrome/test/base/testing_profile.h"
#include "components/media_message_center/media_notification_item.h"
#include "components/media_message_center/media_notification_util.h"
#include "components/media_message_center/media_session_notification_item.h"
#include "content/public/test/browser_task_environment.h"
#include "media/base/media_switches.h"
#include "services/media_session/public/mojom/audio_focus.mojom.h"
#include "services/media_session/public/mojom/media_session.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using media_session::mojom::AudioFocusRequestState;
using media_session::mojom::AudioFocusRequestStatePtr;
using media_session::mojom::MediaSessionInfo;
using media_session::mojom::MediaSessionInfoPtr;
using testing::_;
using testing::AtLeast;
using testing::Expectation;
using testing::Return;
namespace {
class MockMediaNotificationServiceObserver
: public MediaNotificationServiceObserver {
public:
MockMediaNotificationServiceObserver() = default;
MockMediaNotificationServiceObserver(
const MockMediaNotificationServiceObserver&) = delete;
MockMediaNotificationServiceObserver& operator=(
const MockMediaNotificationServiceObserver&) = delete;
~MockMediaNotificationServiceObserver() override = default;
// MediaNotificationServiceObserver implementation.
MOCK_METHOD0(OnNotificationListChanged, void());
MOCK_METHOD0(OnMediaDialogOpenedOrClosed, void());
};
class MockMediaDialogDelegate : public MediaDialogDelegate {
public:
MockMediaDialogDelegate() = default;
~MockMediaDialogDelegate() override { Close(); }
void Open(MediaNotificationService* service) {
ASSERT_NE(nullptr, service);
service_ = service;
service_->SetDialogDelegate(this);
}
void Close() {
if (!service_)
return;
service_->SetDialogDelegate(nullptr);
service_ = nullptr;
}
// MediaDialogDelegate implementation.
MOCK_METHOD2(
ShowMediaSession,
MediaNotificationContainerImpl*(
const std::string& id,
base::WeakPtr<media_message_center::MediaNotificationItem> item));
MOCK_METHOD1(HideMediaSession, void(const std::string& id));
std::unique_ptr<OverlayMediaNotification> PopOut(const std::string& id,
gfx::Rect bounds) {
return std::unique_ptr<OverlayMediaNotification>(PopOutProxy(id, bounds));
}
// Need to use a proxy since std::unique_ptr is not copyable.
MOCK_METHOD2(PopOutProxy,
OverlayMediaNotification*(const std::string& id,
gfx::Rect bounds));
private:
MediaNotificationService* service_;
DISALLOW_COPY_AND_ASSIGN(MockMediaDialogDelegate);
};
class MockOverlayMediaNotification : public OverlayMediaNotification {
public:
MockOverlayMediaNotification() = default;
MockOverlayMediaNotification(const MockOverlayMediaNotification&) = delete;
MockOverlayMediaNotification& operator=(const MockOverlayMediaNotification&) =
delete;
~MockOverlayMediaNotification() override = default;
OverlayMediaNotificationsManager* manager() { return manager_; }
// MockOverlayMediaNotification implementation.
void SetManager(OverlayMediaNotificationsManager* manager) {
manager_ = manager;
SetManagerProxy(manager);
}
MOCK_METHOD0(ShowNotification, void());
MOCK_METHOD0(CloseNotification, void());
// Use a proxy so we can add expectations on it while also storing the
// manager for future use.
MOCK_METHOD1(SetManagerProxy,
void(OverlayMediaNotificationsManager* manager));
private:
OverlayMediaNotificationsManager* manager_ = nullptr;
};
} // anonymous namespace
class MediaNotificationServiceTest : public testing::Test {
public:
MediaNotificationServiceTest()
: task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME,
base::test::TaskEnvironment::MainThreadType::UI) {}
~MediaNotificationServiceTest() override = default;
void SetUp() override {
media_router::MediaRouterFactory::GetInstance()->SetTestingFactory(
&profile_, base::BindRepeating(&media_router::MockMediaRouter::Create));
service_ = std::make_unique<MediaNotificationService>(&profile_);
service_->AddObserver(&observer_);
}
void TearDown() override { service_.reset(); }
protected:
void AdvanceClockMilliseconds(int milliseconds) {
task_environment_.FastForwardBy(
base::TimeDelta::FromMilliseconds(milliseconds));
}
void AdvanceClockMinutes(int minutes) {
AdvanceClockMilliseconds(1000 * 60 * minutes);
}
base::UnguessableToken SimulatePlayingControllableMedia() {
base::UnguessableToken id = base::UnguessableToken::Create();
SimulateFocusGained(id, true);
SimulateNecessaryMetadata(id);
return id;
}
AudioFocusRequestStatePtr CreateFocusRequest(const base::UnguessableToken& id,
bool controllable) {
MediaSessionInfoPtr session_info(MediaSessionInfo::New());
session_info->is_controllable = controllable;
AudioFocusRequestStatePtr focus(AudioFocusRequestState::New());
focus->request_id = id;
focus->session_info = std::move(session_info);
return focus;
}
void SimulateFocusGained(const base::UnguessableToken& id,
bool controllable) {
service_->OnFocusGained(CreateFocusRequest(id, controllable));
}
void SimulateFocusLost(const base::UnguessableToken& id) {
AudioFocusRequestStatePtr focus(AudioFocusRequestState::New());
focus->request_id = id;
service_->OnFocusLost(std::move(focus));
}
void SimulateNecessaryMetadata(const base::UnguessableToken& id) {
// In order for the MediaNotificationItem to tell the
// MediaNotificationService to show a media session, that session needs
// a title and artist. Typically this would happen through the media session
// service, but since the service doesn't run for this test, we'll manually
// grab the MediaNotificationItem from the MediaNotificationService and
// set the metadata.
auto item_itr = service_->sessions_.find(id.ToString());
ASSERT_NE(service_->sessions_.end(), item_itr);
media_session::MediaMetadata metadata;
metadata.title = base::ASCIIToUTF16("title");
metadata.artist = base::ASCIIToUTF16("artist");
item_itr->second.item()->MediaSessionMetadataChanged(std::move(metadata));
}
void SimulateHasArtwork(const base::UnguessableToken& id) {
auto item_itr = service_->sessions_.find(id.ToString());
ASSERT_NE(service_->sessions_.end(), item_itr);
SkBitmap image;
image.allocN32Pixels(10, 10);
image.eraseColor(SK_ColorMAGENTA);
item_itr->second.item()->MediaControllerImageChanged(
media_session::mojom::MediaSessionImageType::kArtwork, image);
}
void SimulateHasNoArtwork(const base::UnguessableToken& id) {
auto item_itr = service_->sessions_.find(id.ToString());
ASSERT_NE(service_->sessions_.end(), item_itr);
item_itr->second.item()->MediaControllerImageChanged(
media_session::mojom::MediaSessionImageType::kArtwork, SkBitmap());
}
void SimulateReceivedAudioFocusRequests(
std::vector<AudioFocusRequestStatePtr> requests) {
service_->OnReceivedAudioFocusRequests(std::move(requests));
}
bool IsSessionFrozen(const base::UnguessableToken& id) const {
auto item_itr = service_->sessions_.find(id.ToString());
EXPECT_NE(service_->sessions_.end(), item_itr);
return item_itr->second.item()->frozen();
}
bool IsSessionInactive(const base::UnguessableToken& id) const {
return base::Contains(service_->inactive_session_ids_, id.ToString());
}
bool HasActiveNotifications() const {
return service_->HasActiveNotifications();
}
bool HasFrozenNotifications() const {
return service_->HasFrozenNotifications();
}
bool HasOpenDialog() const { return service_->HasOpenDialog(); }
void SimulateDialogOpened(MockMediaDialogDelegate* delegate) {
delegate->Open(service_.get());
}
void SimulateTabClosed(const base::UnguessableToken& id) {
// When a tab is closing, audio focus will be lost before the WebContents is
// destroyed, so to simulate closer to reality we will also simulate audio
// focus lost here.
SimulateFocusLost(id);
// Now, close the tab. The session may have been destroyed with
// |SimulateFocusLost()| above.
auto item_itr = service_->sessions_.find(id.ToString());
if (item_itr != service_->sessions_.end())
item_itr->second.WebContentsDestroyed();
}
void SimulatePlaybackStateChanged(const base::UnguessableToken& id,
bool playing) {
MediaSessionInfoPtr session_info(MediaSessionInfo::New());
session_info->is_controllable = true;
session_info->playback_state =
playing ? media_session::mojom::MediaPlaybackState::kPlaying
: media_session::mojom::MediaPlaybackState::kPaused;
auto item_itr = service_->sessions_.find(id.ToString());
EXPECT_NE(service_->sessions_.end(), item_itr);
item_itr->second.MediaSessionInfoChanged(std::move(session_info));
}
void SimulateMediaSeeked(const base::UnguessableToken& id) {
auto item_itr = service_->sessions_.find(id.ToString());
EXPECT_NE(service_->sessions_.end(), item_itr);
item_itr->second.MediaSessionPositionChanged(base::nullopt);
}
void SimulateNotificationClicked(const base::UnguessableToken& id) {
service_->OnContainerClicked(id.ToString());
}
void SimulateDismissButtonClicked(const base::UnguessableToken& id) {
service_->OnContainerDismissed(id.ToString());
}
// Simulates the media notification of the given |id| being dragged out of the
// given dialog.
MockOverlayMediaNotification* SimulateNotificationDraggedOut(
const base::UnguessableToken& id,
MockMediaDialogDelegate* dialog_delegate) {
const gfx::Rect dragged_out_bounds(0, 1, 2, 3);
auto overlay_notification_unique =
std::make_unique<MockOverlayMediaNotification>();
MockOverlayMediaNotification* overlay_notification =
overlay_notification_unique.get();
// When the notification is dragged out, the dialog should be asked to
// remove the notification and return an overlay version of it.
EXPECT_CALL(*dialog_delegate,
PopOutProxy(id.ToString(), dragged_out_bounds))
.WillOnce(Return(overlay_notification_unique.release()));
// Then, that overlay notification should receive a manager and be shown.
Expectation set_manager =
EXPECT_CALL(*overlay_notification, SetManagerProxy(_));
EXPECT_CALL(*overlay_notification, ShowNotification()).After(set_manager);
// Fire the drag out.
service_->OnContainerDraggedOut(id.ToString(), dragged_out_bounds);
testing::Mock::VerifyAndClearExpectations(dialog_delegate);
testing::Mock::VerifyAndClearExpectations(overlay_notification);
return overlay_notification;
}
void ExpectHistogramCountRecorded(int count, int size) {
histogram_tester_.ExpectBucketCount(
media_message_center::kCountHistogramName, count, size);
}
void ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason reason,
int count) {
histogram_tester_.ExpectBucketCount(
"Media.GlobalMediaControls.DismissReason", reason, count);
}
void ExpectHistogramInteractionDelayAfterPause(base::TimeDelta time,
int count) {
histogram_tester_.ExpectTimeBucketCount(
"Media.GlobalMediaControls.InteractionDelayAfterPause", time, count);
}
void ExpectEmptyInteractionHistogram() {
histogram_tester_.ExpectTotalCount(
"Media.GlobalMediaControls.InteractionDelayAfterPause", 0);
}
void SimulateMediaRoutesUpdate(
const std::vector<media_router::MediaRoute>& routes) {
service_->cast_notification_provider_->OnRoutesUpdated(routes, {});
}
MockMediaNotificationServiceObserver& observer() { return observer_; }
private:
content::BrowserTaskEnvironment task_environment_;
MockMediaNotificationServiceObserver observer_;
std::unique_ptr<MediaNotificationService> service_;
base::HistogramTester histogram_tester_;
TestingProfile profile_;
};
// TODO(takumif): Remove this class once |kGlobalMediaControlsForCast| is
// enabled by default.
class MediaNotificationServiceCastTest : public MediaNotificationServiceTest {
public:
void SetUp() override {
feature_list_.InitAndEnableFeature(media::kGlobalMediaControlsForCast);
MediaNotificationServiceTest::SetUp();
}
private:
base::test::ScopedFeatureList feature_list_;
};
TEST_F(MediaNotificationServiceTest, ShowControllableOnGainAndHideOnLoss) {
// Simulate a new active, controllable media session.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
EXPECT_FALSE(HasActiveNotifications());
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_FALSE(IsSessionFrozen(id));
EXPECT_TRUE(HasActiveNotifications());
// Ensure that the observer was notified of the new notification.
testing::Mock::VerifyAndClearExpectations(&observer());
// Simulate opening a MediaDialogView.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
EXPECT_CALL(observer(), OnMediaDialogOpenedOrClosed());
EXPECT_FALSE(HasOpenDialog());
SimulateDialogOpened(&dialog_delegate);
// Ensure that the session was shown.
ExpectHistogramCountRecorded(1, 1);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
// Ensure that the observer was notified of the dialog opening.
EXPECT_TRUE(HasOpenDialog());
testing::Mock::VerifyAndClearExpectations(&observer());
// Simulate the active session ending.
EXPECT_CALL(dialog_delegate, HideMediaSession(id.ToString())).Times(0);
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
EXPECT_FALSE(HasFrozenNotifications());
SimulateFocusLost(id);
// Ensure that the session was frozen and not hidden.
EXPECT_TRUE(IsSessionFrozen(id));
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
// Ensure that the observer was notification of the frozen notification.
EXPECT_TRUE(HasFrozenNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
// Once the freeze timer fires, we should hide the media session.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
EXPECT_CALL(dialog_delegate, HideMediaSession(id.ToString()));
AdvanceClockMilliseconds(2500);
testing::Mock::VerifyAndClearExpectations(&observer());
}
TEST_F(MediaNotificationServiceTest, DoesNotShowUncontrollableSession) {
base::UnguessableToken id = base::UnguessableToken::Create();
// When focus is gained, we should not show an active session.
EXPECT_FALSE(HasActiveNotifications());
SimulateFocusGained(id, false);
SimulateNecessaryMetadata(id);
EXPECT_FALSE(HasActiveNotifications());
// When focus is lost, we should not have a frozen session.
SimulateFocusLost(id);
EXPECT_FALSE(HasFrozenNotifications());
// When focus is regained, we should still not have an active session.
SimulateFocusGained(id, false);
EXPECT_FALSE(HasActiveNotifications());
}
TEST_F(MediaNotificationServiceTest,
DoesNotShowControllableSessionThatBecomesUncontrollable) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Lose focus so the item freezes.
SimulateFocusLost(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// After 1s, the item should still be frozen.
AdvanceClockMilliseconds(1000);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// If the item regains focus but is not controllable, it should not become
// active.
SimulateFocusGained(id, false);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// And the frozen timer should still fire after the initial 2.5 seconds is
// finished.
AdvanceClockMilliseconds(1400);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
AdvanceClockMilliseconds(200);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_FALSE(HasFrozenNotifications());
}
TEST_F(MediaNotificationServiceTest, ShowsAllInitialControllableSessions) {
base::UnguessableToken controllable1_id = base::UnguessableToken::Create();
base::UnguessableToken uncontrollable_id = base::UnguessableToken::Create();
base::UnguessableToken controllable2_id = base::UnguessableToken::Create();
std::vector<AudioFocusRequestStatePtr> requests;
requests.push_back(CreateFocusRequest(controllable1_id, true));
requests.push_back(CreateFocusRequest(uncontrollable_id, false));
requests.push_back(CreateFocusRequest(controllable2_id, true));
EXPECT_FALSE(HasActiveNotifications());
// Having controllable sessions should count as active.
SimulateReceivedAudioFocusRequests(std::move(requests));
SimulateNecessaryMetadata(controllable1_id);
SimulateNecessaryMetadata(uncontrollable_id);
SimulateNecessaryMetadata(controllable2_id);
EXPECT_TRUE(HasActiveNotifications());
// If we open a dialog, it should be told to show the controllable sessions,
// but not the uncontrollable one.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate,
ShowMediaSession(controllable1_id.ToString(), _));
EXPECT_CALL(dialog_delegate,
ShowMediaSession(uncontrollable_id.ToString(), _))
.Times(0);
EXPECT_CALL(dialog_delegate,
ShowMediaSession(controllable2_id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
// Ensure that we properly recorded the number of active sessions shown.
ExpectHistogramCountRecorded(2, 1);
}
TEST_F(MediaNotificationServiceTest, HideAfterTimeoutAndActiveAgainOnPlay) {
// First, start an active session.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, stop playing media so the session is frozen, but not yet hidden.
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::
kMediaSessionStopped,
0);
SimulateFocusLost(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::
kMediaSessionStopped,
0);
// If the time hasn't elapsed yet, the session should still be frozen.
AdvanceClockMilliseconds(2400);
EXPECT_TRUE(HasFrozenNotifications());
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::
kMediaSessionStopped,
0);
// Once the time is elapsed, the session should be hidden.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
AdvanceClockMilliseconds(200);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_FALSE(HasFrozenNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::
kMediaSessionStopped,
1);
// If media starts playing again, we should show and enable the button.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
}
TEST_F(MediaNotificationServiceTest,
BecomesActiveIfMediaStartsPlayingWithinTimeout) {
// First, start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, stop playing media so the session is frozen, but hasn't been hidden
// yet.
SimulateFocusLost(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// If the time hasn't elapsed yet, we should still not be hidden.
AdvanceClockMilliseconds(2400);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// If media starts playing again, we should become active again.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
}
TEST_F(MediaNotificationServiceTest, NewMediaSessionWhileDialogOpen) {
// First, start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, open a dialog.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
ExpectHistogramCountRecorded(1, 1);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
// Then, have a new media session start while the dialog is opened. This
// should update the dialog.
base::UnguessableToken new_id = base::UnguessableToken::Create();
EXPECT_CALL(dialog_delegate, ShowMediaSession(new_id.ToString(), _));
SimulateFocusGained(new_id, true);
SimulateNecessaryMetadata(new_id);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
// If we close this dialog and open a new one, the new one should receive both
// media sessions immediately.
dialog_delegate.Close();
MockMediaDialogDelegate new_dialog;
EXPECT_CALL(new_dialog, ShowMediaSession(id.ToString(), _));
EXPECT_CALL(new_dialog, ShowMediaSession(new_id.ToString(), _));
SimulateDialogOpened(&new_dialog);
ExpectHistogramCountRecorded(1, 1);
ExpectHistogramCountRecorded(2, 1);
}
TEST_F(MediaNotificationServiceTest,
SessionIsRemovedImmediatelyWhenATabCloses) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, close the tab. The session should immediately be hidden.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::kTabClosed,
0);
SimulateTabClosed(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_FALSE(HasFrozenNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::kTabClosed,
1);
}
TEST_F(MediaNotificationServiceTest, DismissesMediaSession) {
// First, start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, open a dialog.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
// Then, click the dismiss button. This should stop and hide the session.
EXPECT_CALL(dialog_delegate, HideMediaSession(id.ToString()));
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::
kUserDismissedNotification,
0);
SimulateDismissButtonClicked(id);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::
kUserDismissedNotification,
1);
}
// TODO(https://crbug.com/1034406) Flaky on Mac10.12
#if defined(OS_MACOSX)
#define MAYBE_CountCastSessionsAsActive DISABLED_CountCastSessionsAsActive
#else
#define MAYBE_CountCastSessionsAsActive CountCastSessionsAsActive
#endif
TEST_F(MediaNotificationServiceCastTest, MAYBE_CountCastSessionsAsActive) {
media_router::MediaRoute media_route("id",
media_router::MediaSource("source_id"),
"sink_id", "description", true, true);
media_route.set_controller_type(media_router::RouteControllerType::kGeneric);
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
EXPECT_FALSE(HasActiveNotifications());
SimulateMediaRoutesUpdate({media_route});
EXPECT_TRUE(HasActiveNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
SimulateMediaRoutesUpdate({});
EXPECT_FALSE(HasActiveNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
}
// Regression test for https://crbug.com/1015903: we could end up in a situation
// where the toolbar icon was disabled indefinitely.
TEST_F(MediaNotificationServiceTest, LoseGainLoseDoesNotCauseRaceCondition) {
// First, start an active session and include artwork.
base::UnguessableToken id = SimulatePlayingControllableMedia();
SimulateHasArtwork(id);
EXPECT_TRUE(HasActiveNotifications());
// Then, stop playing media so the session is frozen, but hasn't been hidden
// yet.
SimulateFocusLost(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// Simulate no artwork, so we wait for new artwork.
SimulateHasNoArtwork(id);
// Simulate regaining focus, but no artwork yet so we wait.
SimulateFocusGained(id, true);
SimulateNecessaryMetadata(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// Then, lose focus again before getting artwork.
SimulateFocusLost(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// When the freeze timer fires, we should be hidden.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
AdvanceClockMilliseconds(2600);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_FALSE(HasFrozenNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
}
TEST_F(MediaNotificationServiceTest, ShowsOverlayForDraggedOutNotifications) {
// First, start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, open a dialog.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
// Drag out the notification.
MockOverlayMediaNotification* overlay_notification =
SimulateNotificationDraggedOut(id, &dialog_delegate);
// Now, dismiss the notification. Since the notification is an overlay
// notification, this should just close the overlay notification.
EXPECT_CALL(*overlay_notification, CloseNotification());
SimulateDismissButtonClicked(id);
testing::Mock::VerifyAndClearExpectations(overlay_notification);
// After we close, we notify our manager, and the dialog should be informed
// that it can show the notification again.
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
overlay_notification->manager()->OnOverlayNotificationClosed(id.ToString());
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
}
TEST_F(MediaNotificationServiceTest, HidesInactiveNotifications) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
// After 59 minutes, the notification should still be there.
AdvanceClockMinutes(59);
EXPECT_TRUE(HasActiveNotifications());
// But once it's been inactive for over an hour, it should disappear.
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::
kInactiveTimeout,
0);
AdvanceClockMinutes(2);
EXPECT_FALSE(HasActiveNotifications());
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::
kInactiveTimeout,
1);
// Since the user never interacted with the media before it was paused, we
// should not have recorded any post-pause interactions.
ExpectEmptyInteractionHistogram();
// If we now close the tab, then it shouldn't record that as the dismiss
// reason, since we already recorded a reason.
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::kTabClosed,
0);
SimulateTabClosed(id);
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::kTabClosed,
0);
}
TEST_F(MediaNotificationServiceTest, InactiveBecomesActive_PlayPause) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
EXPECT_FALSE(IsSessionInactive(id));
// Let the notification become inactive.
AdvanceClockMinutes(70);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(IsSessionInactive(id));
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(70),
0);
// Then, play the media. The notification should become active.
SimulatePlaybackStateChanged(id, true);
// We should have recorded an interaction even though the timer has finished.
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(70),
1);
EXPECT_TRUE(HasActiveNotifications());
EXPECT_FALSE(IsSessionInactive(id));
}
TEST_F(MediaNotificationServiceTest, InactiveBecomesActive_Seeking) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
EXPECT_FALSE(IsSessionInactive(id));
// Let the notification become inactive.
AdvanceClockMinutes(70);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(IsSessionInactive(id));
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(70),
0);
// Then, seek the media. The notification should become active.
SimulateMediaSeeked(id);
// We should have recorded an interaction even though the timer has finished.
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(70),
1);
EXPECT_TRUE(HasActiveNotifications());
EXPECT_FALSE(IsSessionInactive(id));
// If we don't interact again, the notification should become inactive again.
AdvanceClockMinutes(70);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(IsSessionInactive(id));
}
TEST_F(MediaNotificationServiceTest, DelaysHidingNotifications_PlayPause) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
// After 59 minutes, the notification should still be there.
AdvanceClockMinutes(59);
EXPECT_TRUE(HasActiveNotifications());
// If we start playing again, we should not hide the notification, even after
// an hour.
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(59),
0);
SimulatePlaybackStateChanged(id, true);
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(59),
1);
AdvanceClockMinutes(2);
EXPECT_TRUE(HasActiveNotifications());
// If we pause again, it should hide after an hour.
SimulatePlaybackStateChanged(id, false);
AdvanceClockMinutes(61);
EXPECT_FALSE(HasActiveNotifications());
}
TEST_F(MediaNotificationServiceTest, DelaysHidingNotifications_Interactions) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
// After 59 minutes, the notification should still be there.
AdvanceClockMinutes(59);
EXPECT_TRUE(HasActiveNotifications());
// If the user clicks to go back to the tab, it should reset the hide timer.
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(59),
0);
SimulateNotificationClicked(id);
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(59),
1);
AdvanceClockMinutes(50);
EXPECT_TRUE(HasActiveNotifications());
// If the user seeks the media before an hour is up, it should reset the hide
// timer.
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(50),
0);
SimulateMediaSeeked(id);
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(50),
1);
AdvanceClockMinutes(59);
EXPECT_TRUE(HasActiveNotifications());
// After the hour has passed, the notification should hide.
AdvanceClockMinutes(2);
EXPECT_FALSE(HasActiveNotifications());
}
TEST_F(MediaNotificationServiceTest,
DelaysHidingNotifications_OverlayThenPause) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, open a dialog.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
// Then, pull out the notification into an overlay notification.
MockOverlayMediaNotification* overlay_notification =
SimulateNotificationDraggedOut(id, &dialog_delegate);
// Then, pause the media.
SimulatePlaybackStateChanged(id, false);
// Since the notification is in an overlay, it should never time out as
// inactive.
AdvanceClockMinutes(61);
EXPECT_FALSE(IsSessionInactive(id));
// Now, close the overlay notification.
overlay_notification->manager()->OnOverlayNotificationClosed(id.ToString());
// The notification should become inactive now that it's not in an overlay.
AdvanceClockMinutes(61);
EXPECT_TRUE(IsSessionInactive(id));
}
TEST_F(MediaNotificationServiceTest,
DelaysHidingNotifications_PauseThenOverlay) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media.
SimulatePlaybackStateChanged(id, false);
// Then, open a dialog.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
// Then, pull out the notification into an overlay notification.
MockOverlayMediaNotification* overlay_notification =
SimulateNotificationDraggedOut(id, &dialog_delegate);
// Since the notification is in an overlay, it should never time out as
// inactive.
AdvanceClockMinutes(61);
EXPECT_FALSE(IsSessionInactive(id));
// Now, close the overlay notification.
overlay_notification->manager()->OnOverlayNotificationClosed(id.ToString());
// The notification should become inactive now that it's not in an overlay.
AdvanceClockMinutes(61);
EXPECT_TRUE(IsSessionInactive(id));
}
TEST_F(MediaNotificationServiceTest, HidingNotification_FeatureDisabled) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndDisableFeature(
media::kGlobalMediaControlsAutoDismiss);
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
// After 61 minutes, the notification should still be there.
AdvanceClockMinutes(61);
EXPECT_TRUE(HasActiveNotifications());
ExpectHistogramDismissReasonRecorded(
MediaNotificationService::GlobalMediaControlsDismissReason::
kInactiveTimeout,
0);
// Since the user never interacted with the media before it was paused, we
// should not have recorded any post-pause interactions.
ExpectEmptyInteractionHistogram();
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(61),
0);
SimulatePlaybackStateChanged(id, true);
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(61),
1);
}
TEST_F(MediaNotificationServiceTest, HidingNotification_TimerParams) {
const int kTimerInMinutes = 6;
base::test::ScopedFeatureList scoped_feature_list;
base::FieldTrialParams params;
params["timer_in_minutes"] = base::NumberToString(kTimerInMinutes);
scoped_feature_list.InitAndEnableFeatureWithParameters(
media::kGlobalMediaControlsAutoDismiss, params);
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
// After (kTimerInMinutes-1) minutes, the notification should still be there.
AdvanceClockMinutes(kTimerInMinutes - 1);
EXPECT_TRUE(HasActiveNotifications());
// If we start playing again, we should not hide the notification, even after
// kTimerInMinutes.
ExpectHistogramInteractionDelayAfterPause(
base::TimeDelta::FromMinutes(kTimerInMinutes - 1), 0);
SimulatePlaybackStateChanged(id, true);
ExpectHistogramInteractionDelayAfterPause(
base::TimeDelta::FromMinutes(kTimerInMinutes - 1), 1);
AdvanceClockMinutes(2);
EXPECT_TRUE(HasActiveNotifications());
// If we pause again, it should hide after kTimerInMinutes.
SimulatePlaybackStateChanged(id, false);
AdvanceClockMinutes(kTimerInMinutes + 1);
EXPECT_FALSE(HasActiveNotifications());
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
ae3ad53dacc0a6dc8f696fa8419e12daf6902bad | 087ec97a3db6d2c93e9d14a288e9b8683c1c3183 | /client.h | 6f5668f825702eb5db9065930df3450482307a8b | [] | no_license | laloxxx20/Network-Game | 306bed9dea4f4dc391bd5971820ae63dfc2cf6e1 | b71c26687db8185b7c0262546859ff4df6c33db2 | refs/heads/master | 2021-06-24T19:18:22.845223 | 2017-09-15T00:57:48 | 2017-09-15T00:57:48 | 103,597,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,616 | h | #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <thread>
#include <time.h> /* time */
// #include "protocol.h"
using namespace std;
typedef char const* chars;
class Client{
public:
struct sockaddr_in stSockAddr;
int Res;
int SocketFD;
int n;
int message_server;
int port;
chars ip_address;
/*char buffer[256];*/
/*char message[256];*/
char message[256];
char buffer[256];
int packet_size;
int header_size;
int width = 20;
int height = 20;
chars ship;
Protocol* protocol;
chars board[20][20] = {
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"},
{"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_"}
};
Client();
// ip, port, header_size, packet_size,
Client(chars, int, int, int);
string adding_header(string);
bool login(char*);
void read_server();
void write_server();
void get_list_online();
void start_client();
void draw_board();
void draw_ship(chars, int, int);
void draw_ship_first(chars);
};
Client::Client(){}
Client::Client(chars ip, int port, int header, int packet)
{
this->protocol = new Protocol();
/*chars message = this->protocol->envelop("simple-message", "test text lalito");
cout<<"envelop message: "<<message<<endl;
chars unwrapped_messa = this->protocol->unwrap(message);
cout<<"unwrapped message: "<<unwrapped_messa<<endl;*/
this->ip_address = ip;
this->port = port;
this->header_size = header;
this->packet_size = packet;
this->SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
// error while we try create the token
if (-1 == this->SocketFD)
{
perror("cannot create socket");
exit(EXIT_FAILURE);
}
memset(&this->stSockAddr, 0, sizeof(struct sockaddr_in));
this->stSockAddr.sin_family = AF_INET;
this->stSockAddr.sin_port = htons(this->port);
this->Res = inet_pton(AF_INET, ip_address, &this->stSockAddr.sin_addr);
if (0 > this->Res)
{
perror("error: first parameter is not a valid address family");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
else if (0 == this->Res)
{
perror("char string (second parameter does not contain valid ipaddress");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
if (-1 == connect(this->SocketFD, (const struct sockaddr *)&this->stSockAddr, sizeof(struct sockaddr_in)))
{
perror("connect failed");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
}
void Client::draw_board(){
printf(" 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9\n");
for(int i=0; i<this->width; i++){
printf("%2d| ", i);
for(int j=0; j<this->height; j++)
printf("%s ", this->board[i][j]);
printf("\n");
}
}
void Client::draw_ship(chars ship, int x, int y){
this->board[x][y] = ship;
this->board[x+1][y] = ship;
this->board[x][y+1] = ship;
this->board[x+1][y+1] = ship;
}
void Client::draw_ship_first(chars ship){
srand (time(NULL));
int x = rand() % (this->width-2) + 1;
int y = rand() % (this->height-2) + 1;
while(1){
if(this->board[x][y] == "_" && this->board[x+1][y] == "_" && this->board[x][y+1] == "_" && this->board[x+1][y+1] == "_")
break;
x = rand() % (this->width-2) + 1;
y = rand() % (this->height-2) + 1;
}
cout<<"x: "<<x<<endl;
cout<<"y: "<<y<<endl;
this->draw_ship(ship, x, y);
}
void Client::read_server()
{
int counter = 0;
for(;;)
{
chars messa = "";
if(counter < 1){
printf("Enter a letter to play (ex A): ");
scanf("%s" , this->message);
this->ship = this->message;
messa = this->protocol->envelop("simple-message", this->ship);
this->draw_ship_first(this->ship);
}
if(counter > 1){
this->draw_board();
printf("Please insert your new position to play (x enter y): ");
scanf("%s" , this->message);
system("clear");
}
if(counter==1)
this->draw_board();
system("clear");
messa = this->protocol->envelop("simple-message", this->message);
n = write(this->SocketFD, messa, 255);
if (n < 0) perror("ERROR writing to socket");
counter++;
bzero(this->buffer, 255);
this->message_server = read(this->SocketFD, this->buffer, 255);
if (this->message_server < 0) perror("ERROR reading from socket");
chars unwrapped_messa = this->protocol->unwrap(this->buffer);
printf("Message of server: << %s >>\n", unwrapped_messa);
}
shutdown(this->SocketFD, SHUT_RDWR);
close(this->SocketFD);
} | [
"eduardolalox90@gmail.com"
] | eduardolalox90@gmail.com |
e0c93b3376e1fc7faee9bb4d064f532a45bcfbc9 | be31580024b7fb89884cfc9f7e8b8c4f5af67cfa | /CTDL1/New folder/VC/VCWizards/AppWiz/MFC/Library/templates/1041/dllmain.cpp | 797a2b026d5e5c649858dd49d9e686bc896f77d7 | [] | no_license | Dat0309/CTDL-GT1 | eebb73a24bd4fecf0ddb8428805017e88e4ad9da | 8b5a7ed4f98e5d553bf3c284cd165ae2bd7c5dcc | refs/heads/main | 2023-06-09T23:04:49.994095 | 2021-06-23T03:34:47 | 2021-06-23T03:34:47 | 379,462,390 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,500 | cpp | // dllmain.cpp : DLL の初期化ルーチンを定義します。
//
#include "stdafx.h"
#include <afxwin.h>
#include <afxdllx.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
static AFX_EXTENSION_MODULE [!output SAFE_PROJECT_IDENTIFIER_NAME]DLL = { NULL, NULL };
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
// lpReserved を使う場合はここを削除してください
UNREFERENCED_PARAMETER(lpReserved);
if (dwReason == DLL_PROCESS_ATTACH)
{
TRACE0("[!output PROJECT_NAME].DLL Initializing!\n");
// 拡張 DLL を 1 回だけ初期化します。
if (!AfxInitExtensionModule([!output SAFE_PROJECT_IDENTIFIER_NAME]DLL, hInstance))
return 0;
// この DLL をリソース チェーンへ挿入します。
// メモ : この拡張 DLL が暗黙的に、MFC アプリケーションではなく
// ActiveX コントロールなどの MFC 標準 DLL によってリンクされている場合、
// 以下の行を DllMain から削除して
// から削除して、この拡張 DLL からエクスポート
// 配置してください。したがって、この拡張 DLL を使う標準 DLL は、
// その関数を明示的に呼び出して、
// を初期化するために明示的にその関数を呼び出します。
// それ以外の場合は、CDynLinkLibrary オブジェクトは
// 標準 DLL のリソース チェーンへアタッチされず、
// その結果重大な問題となります。
new CDynLinkLibrary([!output SAFE_PROJECT_IDENTIFIER_NAME]DLL);
[!if SOCKETS]
// ソケットの初期化
// メモ : この拡張 DLL が暗黙的に、MFC アプリケーションではなく
// ActiveX コントロールなどの MFC 標準 DLL によってリンクされている場合、
// 以下の行を DllMain から削除して
// この拡張 DLL からエクスポートされた別の関数に
// 配置してください。したがって、この拡張 DLL を使う標準 DLL は、
// その関数を明示的に呼び出して、
// この拡張 DLL を初期化しなければなりません。
if (!AfxSocketInit())
{
return FALSE;
}
[!endif]
}
else if (dwReason == DLL_PROCESS_DETACH)
{
TRACE0("[!output PROJECT_NAME].DLL Terminating!\n");
// デストラクターが呼び出される前にライブラリを終了します
AfxTermExtensionModule([!output SAFE_PROJECT_IDENTIFIER_NAME]DLL);
}
return 1; // OK
}
| [
"71766267+Dat0309@users.noreply.github.com"
] | 71766267+Dat0309@users.noreply.github.com |
54c258a04d621fb87b0c47c4540515d94360779c | b5eb58d11c138fe273b171a02abd42bd7d469692 | /Codechef/APRIL20B/ANSLEAK.cpp | ed1d9211e20cfa6197a450996beec6a6efaea1b0 | [] | no_license | anand2000a/Coding-Contests | da2cd80d5a2a78d5a6c8e85038a4f748336aa795 | 6feedec3204c1b5a147fdf4f9876757851e4e7e4 | refs/heads/main | 2023-03-16T14:45:18.156358 | 2021-03-09T08:04:17 | 2021-03-09T08:04:17 | 320,330,364 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,639 | cpp | //code by - anand2000
#include<bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL);
#define ll long long int
#define vll vector < ll >
#define vpll vector < pair < ll,ll > >
#define pb push_back
//#define mp make_pair
#define fr(i,a,b) for(i=a; i<b; i++)
#define fr1(i,a,b) for(i=a; i>=b; i--)
#define inf LLONG_MAX
/*-------Code Goes Here-------*/
int main()
{
fast;
ll t,i;
cin>>t;
fr(i,0,t)
{
ll n,m,k;
cin>>n>>m>>k;
ll arr[n+1][k+1];
vll v;
ll j,d;
fr(j,1,n+1)
{
map <ll,ll> mp;
fr(d,1,k+1)
{
cin>>arr[j][d];
ll num=arr[j][d];
mp[num]++;
}
ll flag=0,maxm=0;
fr(d,1,m+1)
if (maxm<=mp[d])
{
maxm=mp[d];
flag=d;
}
v.pb(flag);
}
ll p=v.size();
fr(j,0,p)
cout<<v[j]<<" ";
cout<<"\n";
}
return 0;
}
/*
!!!!!!
!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!
!!!!!!!!!!
!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!! !!!!!
!!!!!!!!!!!!!!!!!!! !!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!! ! !!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! !!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! !!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!
!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !
!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!
!!!!!!
!!!!
*/
| [
"noreply@github.com"
] | noreply@github.com |
715f266c17d404b8aed7baa13da73f4ff37e2b8a | 120f50ad80c0f60a659dafb6a09ff2cf31021c16 | /client/SWGPaymentsWalletsApi.cpp | a17f0a3bc94ca731e410a95503043432d331bb7d | [] | no_license | knetikmedia/knetikcloud-qt5cpp-client | 72dc0d1d7cbdf7536021cf546e347885497a1973 | cfad9f29a82a513941c0eb8fb2a82c18d16a24dc | refs/heads/master | 2021-01-23T06:35:36.976006 | 2017-03-27T20:52:02 | 2017-03-27T20:52:02 | 86,382,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,541 | cpp | /**
* Knetik Platform API Documentation latest
* This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com
*
* OpenAPI spec version: latest
* Contact: support@knetik.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "SWGPaymentsWalletsApi.h"
#include "SWGHelpers.h"
#include "SWGModelFactory.h"
#include <QJsonArray>
#include <QJsonDocument>
namespace Swagger {
SWGPaymentsWalletsApi::SWGPaymentsWalletsApi() {}
SWGPaymentsWalletsApi::~SWGPaymentsWalletsApi() {}
SWGPaymentsWalletsApi::SWGPaymentsWalletsApi(QString host, QString basePath) {
this->host = host;
this->basePath = basePath;
}
void
SWGPaymentsWalletsApi::getUserWallet(qint32 user_id, QString* currency_code) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/users/{user_id}/wallets/{currency_code}");
QString user_idPathParam("{"); user_idPathParam.append("user_id").append("}");
fullPath.replace(user_idPathParam, stringValue(user_id));
QString currency_codePathParam("{"); currency_codePathParam.append("currency_code").append("}");
fullPath.replace(currency_codePathParam, stringValue(currency_code));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPaymentsWalletsApi::getUserWalletCallback);
worker->execute(&input);
}
void
SWGPaymentsWalletsApi::getUserWalletCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
SWGSimpleWallet* output = static_cast<SWGSimpleWallet*>(create(json, QString("SWGSimpleWallet")));
worker->deleteLater();
emit getUserWalletSignal(output);
}
void
SWGPaymentsWalletsApi::getUserWalletTransactions(qint32 user_id, QString* currency_code, QString* filter_type, qint64 filter_max_date, qint64 filter_min_date, QString* filter_sign, qint32 size, qint32 page, QString* order) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/users/{user_id}/wallets/{currency_code}/transactions");
QString user_idPathParam("{"); user_idPathParam.append("user_id").append("}");
fullPath.replace(user_idPathParam, stringValue(user_id));
QString currency_codePathParam("{"); currency_codePathParam.append("currency_code").append("}");
fullPath.replace(currency_codePathParam, stringValue(currency_code));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_type"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_type)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_max_date"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_max_date)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_min_date"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_min_date)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_sign"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_sign)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("size"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(size)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("page"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(page)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("order"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(order)));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPaymentsWalletsApi::getUserWalletTransactionsCallback);
worker->execute(&input);
}
void
SWGPaymentsWalletsApi::getUserWalletTransactionsCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
SWGPageResource«WalletTransactionResource»* output = static_cast<SWGPageResource«WalletTransactionResource»*>(create(json, QString("SWGPageResource«WalletTransactionResource»")));
worker->deleteLater();
emit getUserWalletTransactionsSignal(output);
}
void
SWGPaymentsWalletsApi::getUserWallets(qint32 user_id) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/users/{user_id}/wallets");
QString user_idPathParam("{"); user_idPathParam.append("user_id").append("}");
fullPath.replace(user_idPathParam, stringValue(user_id));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPaymentsWalletsApi::getUserWalletsCallback);
worker->execute(&input);
}
void
SWGPaymentsWalletsApi::getUserWalletsCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QList<SWGSimpleWallet*>* output = new QList<SWGSimpleWallet*>();
QString json(worker->response);
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonArray jsonArray = doc.array();
foreach(QJsonValue obj, jsonArray) {
SWGSimpleWallet* o = new SWGSimpleWallet();
QJsonObject jv = obj.toObject();
QJsonObject * ptr = (QJsonObject*)&jv;
o->fromJsonObject(*ptr);
output->append(o);
}
worker->deleteLater();
emit getUserWalletsSignal(output);
}
void
SWGPaymentsWalletsApi::getWalletBalances() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/wallets/totals");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPaymentsWalletsApi::getWalletBalancesCallback);
worker->execute(&input);
}
void
SWGPaymentsWalletsApi::getWalletBalancesCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
SWGPageResource«WalletTotalResponse»* output = static_cast<SWGPageResource«WalletTotalResponse»*>(create(json, QString("SWGPageResource«WalletTotalResponse»")));
worker->deleteLater();
emit getWalletBalancesSignal(output);
}
void
SWGPaymentsWalletsApi::getWalletTransactions(qint32 filter_invoice, QString* filter_type, QString* filter_date, QString* filter_sign, qint32 filter_user_id, QString* filter_username, QString* filter_details, QString* filter_currency_code, qint32 size, qint32 page, QString* order) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/wallets/transactions");
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_invoice"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_invoice)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_type"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_type)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_date"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_date)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_sign"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_sign)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_user_id"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_user_id)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_username"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_username)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_details"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_details)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("filter_currency_code"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(filter_currency_code)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("size"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(size)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("page"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(page)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("order"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(order)));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPaymentsWalletsApi::getWalletTransactionsCallback);
worker->execute(&input);
}
void
SWGPaymentsWalletsApi::getWalletTransactionsCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
SWGPageResource«WalletTransactionResource»* output = static_cast<SWGPageResource«WalletTransactionResource»*>(create(json, QString("SWGPageResource«WalletTransactionResource»")));
worker->deleteLater();
emit getWalletTransactionsSignal(output);
}
void
SWGPaymentsWalletsApi::getWallets(qint32 size, qint32 page, QString* order) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/wallets");
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("size"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(size)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("page"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(page)));
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("order"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(order)));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPaymentsWalletsApi::getWalletsCallback);
worker->execute(&input);
}
void
SWGPaymentsWalletsApi::getWalletsCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
SWGPageResource«SimpleWallet»* output = static_cast<SWGPageResource«SimpleWallet»*>(create(json, QString("SWGPageResource«SimpleWallet»")));
worker->deleteLater();
emit getWalletsSignal(output);
}
void
SWGPaymentsWalletsApi::updateWalletBalance(qint32 user_id, QString* currency_code, SWGWalletAlterRequest request) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/users/{user_id}/wallets/{currency_code}/balance");
QString user_idPathParam("{"); user_idPathParam.append("user_id").append("}");
fullPath.replace(user_idPathParam, stringValue(user_id));
QString currency_codePathParam("{"); currency_codePathParam.append("currency_code").append("}");
fullPath.replace(currency_codePathParam, stringValue(currency_code));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "PUT");
QString output = request.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPaymentsWalletsApi::updateWalletBalanceCallback);
worker->execute(&input);
}
void
SWGPaymentsWalletsApi::updateWalletBalanceCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
SWGWalletTransactionResource* output = static_cast<SWGWalletTransactionResource*>(create(json, QString("SWGWalletTransactionResource")));
worker->deleteLater();
emit updateWalletBalanceSignal(output);
}
} /* namespace Swagger */
| [
"shawn.stout@knetik.com"
] | shawn.stout@knetik.com |
a57660d181271ac619b57f43bf69b06305aa1c28 | df70bc240d052a892875cc98ac7c773af4d7aac5 | /solutions/SPOJBR/BRACELMG.cpp | 2592f625b419ed68c4c310575d52e26f4dbb6c9a | [
"Unlicense"
] | permissive | jrondanv/algo | 82771e9d98d7720fb2e86f96029e4f7e07a506f6 | 01f91cb566cc6d2dadc48864d19bdaf886f23ede | refs/heads/master | 2021-01-19T07:49:58.675555 | 2015-11-17T18:11:20 | 2015-11-17T18:11:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,488 | cpp | #include <stdio.h>
#include <string.h>
#include <vector>
#include <stdlib.h>
#include <algorithm>
using namespace std;
#define pop(x) __builtin_popcount(x)
#define ind(x) __builtin_ctz(x)
#ifndef ONLINE_JUDGE
#define getchar_unlocked() getchar()
#endif
typedef unsigned long long ull;
ull B = 3409;
char p[10201], *b;
//char p[101];
//char b[10001];
int main(){
int t;
for (scanf("%d", &t), gets(p); t; t--) {
gets(p);
//scanf("%s %s", p, b);
int lp = 0;
ull search = 0;
for (; p[lp]!=' '; lp++) {
search = search*B + p[lp]-'a';
}
b=p+lp;
while (*b == ' ') b++;
//printf("search = %lld\n",search);
int lb = 0;
for (; b[lb] != '\0'; lb++) {
b[lb]-='a';
}
ull cur = 0;
int prev = 0, next = lp%lb;
int ind = 0;
for (int i = 0; i < lp; i++) {
cur = cur*B + b[ind];
ind++;
if (ind == lb) ind=0;
}
ull pot = 1;
for (int i = 0; i < lp-1; i++) pot *= B; //ull pot = B**lp;
bool found = false;
for (int i = 0; i < lb && !found; i++) {
//printf("cur = %lld\n",cur);
if (cur == search) found = true;
else {
//printf("%c %c\n",b[prev],b[next]);
cur -= pot*(b[prev]);
cur = (cur * B) + b[next];
prev++;
next++;
if (prev == lb) prev = 0;
if (next == lb) next = 0;
}
}
//printf("back:\n");
if (!found) {
cur = 0;
prev = 0; next = lp%lb;
ind = lb-1;
for (int i = 0; i < lp; i++) {
cur = cur*B + b[ind];
if (ind == 0) ind = lb-1;
else ind--;
}
for (int i = 0; i < lb && !found; i++) {
if (cur == search) found = true;
else {
cur -= pot*(b[lb-1-prev]);
cur = (cur * B) + b[lb-1-next];
prev++;
next++;
if (prev == lb) prev = 0;
if (next == lb) next = 0;
}
//printf("cur = %lld\n",cur);
}
}
if (found) printf("S\n");
else printf("N\n");
}
}
| [
"fetofs@gmail.com"
] | fetofs@gmail.com |
d481bf7c9b1a883abdce835df4083d222a9be86e | b591fbbd37b9b5e81d8f308f61d607fe7b145ed7 | /include/RE/I/ID.h | 3666f90098e188f13065d826c1d947f66ec0c324 | [
"MIT"
] | permissive | aquilae/CommonLibSSE | f6a1d321b16f2eb1e296f1154d697bd4bed549b6 | b8e6a72875b22c91dd125202dfc6a54f91cda597 | refs/heads/master | 2023-02-02T16:45:00.368879 | 2020-12-15T03:58:22 | 2020-12-15T03:58:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | h | #pragma once
#include "RE/F/FileID.h"
namespace RE
{
namespace BSResource
{
struct ID : public FileID
{
public:
// members
std::uint32_t dir; // 0
};
static_assert(sizeof(ID) == 0xC);
}
}
| [
"ryan__mckenzie@hotmail.com"
] | ryan__mckenzie@hotmail.com |
a45b1cf09a0855cd1781dcf416406062600f86d8 | b4784f7d03c278222ca697dc0a629c42d8d41e01 | /tinyxpath/xpath_static.cpp | 598b5ef65b3f99942bd0d5d3c74674d11c3534a1 | [] | no_license | guitarhua/scxml_exec | 52bf5d218dbb08aa0dcbf313ba29e73a9209acf0 | cc5cde6dd121d607e44b1203202634118eeee3ea | refs/heads/master | 2020-04-27T00:47:03.338088 | 2017-03-11T04:41:48 | 2017-03-11T04:41:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,410 | cpp | /*
www.sourceforge.net/projects/tinyxpath
Copyright (c) 2002-2004 Yves Berquin (yvesb@users.sourceforge.net)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/**
\file xpath_static.cpp
\author Yves Berquin
*/
#include "xpath_static.h"
namespace TinyXPath
{
/// Static function to compute an integer XPath expression, without an error check
int i_xpath_int (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr)
{
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
return xp_proc . i_compute_xpath ();
}
/// Static function to compute a double XPath expression, without an error check
double d_xpath_double (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr)
{
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
return xp_proc . d_compute_xpath ();
}
/// Static function to compute a bool XPath expression, without an error check
bool o_xpath_bool (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr)
{
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
return xp_proc . o_compute_xpath ();
}
/// Static function to compute a string XPath expression, without an error check
TIXML_STRING S_xpath_string (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr)
{
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
return xp_proc . S_compute_xpath ();
}
//modify by sy:add para order
/// Static function to compute a node XPath expression, without an error check
TiXmlNode * XNp_xpath_node (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr,unsigned u_order)
{
unsigned u_nb;
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
u_nb = xp_proc . u_compute_xpath_node_set ();
if (! u_nb)
return NULL;
return xp_proc . XNp_get_xpath_node (u_order);
}
//modify by sy:add para order
/// Static function to compute an attribute XPath expression, without an error check
TiXmlAttribute * XAp_xpath_attribute (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr,unsigned u_order)
{
unsigned u_nb;
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
u_nb = xp_proc . u_compute_xpath_node_set ();
if (! u_nb)
return NULL;
return xp_proc . XAp_get_xpath_attribute (u_order);
}
/// Static function to compute an integer XPath expression, with an error check
bool o_xpath_int (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr, int & i_res)
{
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
i_res = xp_proc . i_compute_xpath ();
return xp_proc . e_error == TinyXPath::xpath_processor::e_no_error;
}
/// Static function to compute a double XPath expression, without an error check
bool o_xpath_double (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr, double & d_res)
{
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
d_res = xp_proc . d_compute_xpath ();
return xp_proc . e_error == TinyXPath::xpath_processor::e_no_error;
}
/// Static function to compute a bool XPath expression, without an error check
bool o_xpath_bool (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr, bool & o_res)
{
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
o_res = xp_proc . o_compute_xpath ();
return xp_proc . e_error == TinyXPath::xpath_processor::e_no_error;
}
/// Static function to compute a string XPath expression, without an error check
bool o_xpath_string (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr, TIXML_STRING & S_res)
{
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
S_res = xp_proc . S_compute_xpath ();
return xp_proc . e_error == TinyXPath::xpath_processor::e_no_error;
}
/// Static function to compute a node XPath expression, without an error check
bool o_xpath_node (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr, const TiXmlNode * & XNp_node)
{
unsigned u_nb;
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
u_nb = xp_proc . u_compute_xpath_node_set ();
if (! u_nb)
return false;
XNp_node = xp_proc . XNp_get_xpath_node (0);
return xp_proc . e_error == TinyXPath::xpath_processor::e_no_error;
}
/// Static function to compute an attribute XPath expression, without an error check
bool o_xpath_attribute (const TiXmlNode * XNp_source_tree, const char * cp_xpath_expr, const TiXmlAttribute * & XAp_attrib)
{
unsigned u_nb;
xpath_processor xp_proc (XNp_source_tree, cp_xpath_expr);
u_nb = xp_proc . u_compute_xpath_node_set ();
if (! u_nb)
return false;
XAp_attrib = xp_proc . XAp_get_xpath_attribute (0);
return xp_proc . e_error == TinyXPath::xpath_processor::e_no_error;
}
}
| [
"suyuan1573@gmail.com"
] | suyuan1573@gmail.com |
82c9a4356ab996677531e5a8bf26d81f60d30eb6 | d30be602df8d91db95dcb4e894d729fbedf7555f | /v0.7/lib/src/SubReqMan.h | 4ee7107497f9b796bc328fdf95c9da1d1231e6a7 | [] | no_license | skhds/PA_SSD | d757ed9c2e6a7ad2ed1d94755ce0da29d3a8cfca | a51cd82b0c73646f28177bd55129140162018755 | refs/heads/master | 2020-04-05T06:49:34.613433 | 2018-12-10T06:12:02 | 2018-12-10T06:12:02 | 156,652,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,292 | h | //-------------------------------------------------------------- //%
// Important: The template for this file was generated //%
// automatically and can only be re-generated if rules //%
// are followed when editing: //%
// 1. Do not modify any line containing //% //%
// 2. Only insert your lines of code between 2 lines //%
// containing "//% user begin" and "//% user end" //%
// //%
// :generate:date: Thu Jan 09 2014 18:03:58 //%
// :generate:version: 2010.1.0-dev //%
//-------------------------------------------------------------- //%
//%
#ifndef __SUBREQMAN_H__ //%
#define __SUBREQMAN_H__ //%
//%USERBEGIN MODEL_DEBUG_ENABLE
#if defined(DEBUG) || defined(DBG_SCP)
# define DBG_SCP_SUBREQMAN
#endif
//%USEREND MODEL_DEBUG_ENABLE
#define SC_INCLUDE_DYNAMIC_PROCESSES //%
//%
#include <scml2.h> //%
#include <systemc> //%
#include "scmlinc/scml_property.h" //%
#include "scmlinc/scml_command_processor.h" //%
#include "tlm_utils/simple_target_socket.h" //%
#include "tlm.h" //%
//%USERBEGIN HEADER_H
// TODO: Insert your includes, declarations, etc. here.
#include "./header/header_SUB.h"
#include "./header/global_header.h"
using namespace std;
//%USEREND HEADER_H
//%
//------------------------ //%
// Module Interface //%
//------------------------ //%
class SubReqMan : //%
public sc_core::sc_module //%
//%USERBEGIN INHERITANCE
// TODO: Specify class inheritance here. Start each line with a , character
//%USEREND INHERITANCE
//%
{ //%
public: //%
// constructor //%
SubReqMan( const sc_core::sc_module_name & n); //%
SC_HAS_PROCESS( SubReqMan ); //%
// destructor //%
virtual ~SubReqMan(); //%
private: //%
// disable default and copy constructors by making them private //%
SubReqMan() ; //%
SubReqMan( const SubReqMan& ) ; //%
SubReqMan & operator= ( const SubReqMan& ) ; //%
public: //%
// method called at end of elaboration of design -- for initialization //%
virtual void end_of_elaboration(); //%
// initialization methods for ports & registers //%
virtual void initPorts(); //%
virtual void initRegisters(); //%
// method to handle interactive commands -- for dynamic instrumentation //%
virtual std::string commandProcessor(const std::vector<std::string>& cmd);//%
public: //%
// Port declarations //%
tlm::tlm_target_socket< 32 > WriteSlave; //%
tlm::tlm_target_socket< 32 > CmdSlave; //%
tlm::tlm_target_socket< 32 > DataSlave; //%
scml2::initiator_socket< 32 > ReadMaster; //%
scml2::initiator_socket< 32 > CmdMaster; //%
scml2::initiator_socket< 32 > DataMaster; //%
sc_core::sc_out<bool> CPU_IRQ;
sc_core::sc_out< bool > RnBMaster; //%
sc_core::sc_in< bool > rst_n; //%
protected: //%
//%
// Parameter/Property declarations //%
//%
protected: //%
//%
// Memory declarations //%
scml2::memory< unsigned int > WriteSlaveBuf; //%
scml2::memory_alias< unsigned int > WriteSlaveBuf_writeBuf;//%
//%
scml2::tlm2_gp_target_adapter< 32 > WriteSlave_WriteSlaveBuf_adapter; //%
scml2::memory< unsigned int > CmdSlaveBuf; //%
scml2::memory_alias< unsigned int > CmdSlaveBuf_writeBuf;//%
//%
scml2::tlm2_gp_target_adapter< 32 > CmdSlave_CmdSlaveBuf_adapter; //%
scml2::memory< unsigned int > DataSlaveBuf; //%
scml2::memory_alias< unsigned int > DataSlaveBuf_writeBuf;//%
//%
scml2::tlm2_gp_target_adapter< 32 > DataSlave_DataSlaveBuf_adapter; //%
//%
public: //%
// Process declarations //%
void //%
rst_nHandler(); //%
void
IRQThread();
//%
protected: //%
// Memory callback declarations //%
void //%
WriteSlaveCB( //%
tlm::tlm_generic_payload& trans, sc_core::sc_time& t); //%
void //%
CmdSlaveCB( //%
tlm::tlm_generic_payload& trans, sc_core::sc_time& t); //%
void //%
DataSlaveCB( //%
tlm::tlm_generic_payload& trans, sc_core::sc_time& t); //%
// support for message logging //%
void initMessageLogging(); //%
void REPORT_MSG(std::string sev, std::string msg); //%
void DBG_MSG(std::string msg) { REPORT_MSG("debug",msg); } //%
void WARN_MSG(std::string msg) { REPORT_MSG("warn",msg); } //%
void ERROR_MSG(std::string msg) { REPORT_MSG("error",msg); } //%
void FATAL_MSG(std::string msg) { REPORT_MSG("fatal",msg); } //%
//%USERBEGIN MEMBER_DECLS
enum DbgCategories { GENERAL = 0, PORTS, REGS } ;
bool dbgFlag[sizeof(DbgCategories)];
// TODO: Insert declarations of member data and functions here.
protected:
sc_core::sc_event eIRQThread;
sc_core::sc_event eDataReady;
sc_core::sc_event eCPUFinish;
sc_core::sc_event eNANDRead;
//hard coded for now
M_CREATEQUEUE(SubReqQueue, SubReq_t, SUBREQ_QUEUE_SIZE);
M_CREATEQUEUE(cDataQueue, PageBuf_t, DATA_QUEUE_SIZE);
Req_t reqInQueue;
bool isCPUFinish;
bool bypass_cache;
public:
// member methods
//
void split_and_queue(Req_t req);
bool CPUReadSubReq(sc_dt::uint64 adr, unsigned char* ptr, SubReq_t subreq);
bool CPUWriteSubReq(sc_dt::uint64 adr, unsigned char* ptr, SubReq_t& subreq);
void software_Init(unsigned char* ptr);
//%USEREND MEMBER_DECLS
}; //%
//%
//------------------------ //%
// Module Implementation //%
//------------------------ //%
//%USERBEGIN HEADER_CPP
// TODO: Insert your includes, declarations, etc. here.
//%USEREND HEADER_CPP
//%
SubReqMan::SubReqMan( const sc_core::sc_module_name & n) //%
: sc_core::sc_module(n) //%
, //%
WriteSlave("WriteSlave"), //%
ReadMaster("ReadMaster"), //%
CmdSlave("CmdSlave"),
CmdMaster("CmdMaster"),
DataSlave("DataSlave"),
DataMaster("DataMaster"),
RnBMaster("RnBMaster"), //%
rst_n("rst_n"), //%
WriteSlave_WriteSlaveBuf_adapter("WriteSlave_WriteSlaveBuf_adapter", WriteSlave),//%
CmdSlave_CmdSlaveBuf_adapter("CmdSlave_CmdSlaveBuf_adapter", CmdSlave),//%
DataSlave_DataSlaveBuf_adapter("DataSlave_DataSlaveBuf_adapter", DataSlave),//%
WriteSlaveBuf("WriteSlaveBuf", 524288ULL), //%
WriteSlaveBuf_writeBuf("WriteSlaveBuf_writeBuf", WriteSlaveBuf, 0LL, 524288LL ) //%
, //%
CmdSlaveBuf("CmdSlaveBuf", 524288ULL), //%
CmdSlaveBuf_writeBuf("CmdSlaveBuf_writeBuf", CmdSlaveBuf, 0LL, 524288LL )//%
, //%
DataSlaveBuf("DataSlaveBuf", 524288ULL), //%
DataSlaveBuf_writeBuf("DataSlaveBuf_writeBuf", DataSlaveBuf, 0LL, 524288LL )//%
//%
//%USERBEGIN INITIALIZER
//
// TODO: Add your class initialization here.
//m_WaitCachePossesion(1),
// m_seReadPath(1),
// m_seWaitCacheRead(1)
//%USEREND INITIALIZER
//%
{ //%
// declare processes and their sensitivities //%
SC_METHOD(rst_nHandler); //%
sensitive << rst_n.neg() ; //%
dont_initialize(); //%
SC_THREAD(IRQThread);
sensitive << eIRQThread;
dont_initialize();
//%
// bind target ports to memories //%
WriteSlave_WriteSlaveBuf_adapter(WriteSlaveBuf); //%
CmdSlave_CmdSlaveBuf_adapter(CmdSlaveBuf); //%
DataSlave_DataSlaveBuf_adapter(DataSlaveBuf); //%
//%
// setup memory callbacks //%
// - Memory: WriteSlaveBuf //%
scml2::set_callback( //%
WriteSlaveBuf_writeBuf, //%
SCML2_CALLBACK(WriteSlaveCB), //%
scml2::AUTO_SYNCING); //%
// - Memory: CmdSlaveBuf //%
scml2::set_callback( //%
CmdSlaveBuf_writeBuf, //%
SCML2_CALLBACK(CmdSlaveCB), //%
scml2::AUTO_SYNCING); //%
// - Memory: DataSlaveBuf //%
scml2::set_callback( //%
DataSlaveBuf_writeBuf, //%
SCML2_CALLBACK(DataSlaveCB), //%
scml2::AUTO_SYNCING); //%
//%
//%
//%
#ifdef SCML_COMMAND_PROCESSOR_H //%
SCML_COMMAND_PROCESSOR(commandProcessor); //%
SCML_ADD_COMMAND("debug",0,6,"debug [-+][general|regs|ports|all]", "Turn on/off debug flags");//%
#endif // SCML_COMMAND_PROCESSOR_H //%
//%
initMessageLogging(); //%
//%USERBEGIN CONSTRUCTOR
// TODO: Add constructor code here.
if ( dbgFlag[GENERAL] ) DBG_MSG("Created " + (std::string)this->basename());
if (SUB_DEBUG) cout << "subreqman constructor" << endl;
//%USEREND CONSTRUCTOR
//%
} //%
// destructor //%
SubReqMan::~SubReqMan() //%
{ //%
//%USERBEGIN DESTRUCTOR
// TODO: Add destructor code here.
//%USEREND DESTRUCTOR
} //%
// initialization method for ports //%
void //%
SubReqMan::initPorts() //%
{ //%
RnBMaster.initialize(0x1); //%
} //%
// initialization method for registers //%
void //%
SubReqMan::initRegisters() //%
{ //%
WriteSlaveBuf.initialize(0x0); //%
WriteSlaveBuf_writeBuf.initialize(0x0); //%
CmdSlaveBuf.initialize(0x0); //%
CmdSlaveBuf_writeBuf.initialize(0x0); //%
DataSlaveBuf.initialize(0x0); //%
DataSlaveBuf_writeBuf.initialize(0x0); //%
}
//%
//This method is invoked after the design is fully elaborated, but //%
// before simulation begins. //%
void //%
SubReqMan::end_of_elaboration() //%
{ //%
//%USERBEGIN END_OF_ELAB
// TODO: Add end_of_elaboration code here.
this->initRegisters();
this->initPorts();
//%USEREND END_OF_ELAB
} //%
// command processing method //%
// During simulation, this command may be called to handle //%
// interactive commands -- for dynamic instrumentation of the instance. //%
std::string //%
SubReqMan::commandProcessor(const std::vector< std::string >& cmd) //%
{ //%
//%USERBEGIN CMD_PROCESSOR
// TODO: Add commandProcessor code here.
// The default code generated here handles toggling off/on the
// default debug instrumentation flags: GENERAL, PORTS, and REGS.
std::string command = cmd[0];
std::ostringstream outs;
if (command == "debug") {
bool print_usage_flag = false;
std::string debug_cmd;
if ((cmd.size() == 1) || (cmd[1] == "?")) {
print_usage_flag = true;
} else {
int i = 1;
while (i < cmd.size()) {
bool flag = true;
if ((cmd[i] == "-") || (cmd[i] == "+")) {
if (cmd[i] == "-") {
flag = false;
}
i++;
}
debug_cmd = cmd[i];
if ((debug_cmd[0] == '+') || (debug_cmd[0] == '-')) {
if (debug_cmd[0] == '-') {
flag = false;
}
debug_cmd = debug_cmd.substr(1,debug_cmd.size()-1);
}
if (debug_cmd == "all") {
for ( int jj = 0; jj<sizeof(DbgCategories); jj++ ) {
dbgFlag[jj] = flag;
}
} else if (debug_cmd == "general") {
dbgFlag[GENERAL] = flag;
} else if (debug_cmd == "ports" || debug_cmd == "pins") {
dbgFlag[PORTS] = flag;
} else if (debug_cmd == "regs") {
dbgFlag[REGS] = flag;
} else {
DBG_MSG(std::string("ERROR: Unknown Option:") + debug_cmd);
print_usage_flag = true;
break;
}
i++;
}
}
outs << "Current debug options:"
<< (dbgFlag[GENERAL] ? " general" : "")
<< (dbgFlag[PORTS] ? " ports" : "")
<< (dbgFlag[REGS] ? " regs" : "")
<< ((dbgFlag[GENERAL] || dbgFlag[PORTS] || dbgFlag[REGS] )? "" : " Off")
<< std::endl;
if (print_usage_flag) {
outs << "Usage: debug [-+][general|ports|regs|all]" << std::endl;
outs << " Example1: 'debug -ports' toggles OFF the debug flag for ports." << std::endl;
outs << " Example2: 'debug ports regs' toggles ON the flags for ports & registers." << std::endl;
}
}
return outs.str();
//%USEREND CMD_PROCESSOR
} //%
//%
// initialization method for logging messages //%
//%
void //%
SubReqMan::initMessageLogging() //%
{ //%
//%USERBEGIN MODEL_DEBUG_INIT
// toggle on/off debugging flags
for (int i=0;i<sizeof(DbgCategories);i++) {
//#ifdef DBG_SCP_SUBREQMAN
// dbgFlag[i] = true;
//#else
// dbgFlag[i] = false;
//#endif
}
//%USEREND MODEL_DEBUG_INIT
//%
} //%
// method for logging messages //%
void //%
SubReqMan::REPORT_MSG(std::string sev, std::string msg)//%
{ //%
//%USERBEGIN REPORT_MSG
std::cout << sev << ": " << msg << " [" << this->basename() << "@" << sc_core::sc_time_stamp() << "]" << std::endl;
//%USEREND REPORT_MSG
//%
} //%
void //%
SubReqMan::rst_nHandler() //%
//%USERBEGIN rst_nHandler
{
if ( dbgFlag[PORTS] ) DBG_MSG( "rst_nHandler invoked because of event on port rst_n" );
// TODO: INSERT code for the rst_nHandler method here.
// make RnB to high for the first request
bypass_cache = false;
RnBMaster.write(1);
eIRQThread.notify();
}
//%USEREND rst_nHandler
void
SubReqMan::split_and_queue(Req_t req){
int split_count = (req.iLen-1)/SECTOR_PER_PAGE + 1;
int remaining_length = req.iLen;
assert((split_count > 0)&& (split_count <= MAX_REQ_LEN/SECTOR_PER_PAGE));
SubReq_t tmpSubReq;
for(int i = 0; i < split_count; i++){
//divide req into subreq
tmpSubReq.op = (SUB_REQ_OP)req.Op;
tmpSubReq.iId = req.iId;
tmpSubReq.iStartAddr = req.iAddr + i*SECTOR_PER_PAGE;
tmpSubReq.iLen = (remaining_length > SECTOR_PER_PAGE ) ? SECTOR_PER_PAGE : remaining_length;
assert(tmpSubReq.iLen > 0);
remaining_length -= SECTOR_PER_PAGE;
//insert subreq into queue
M_PUSH(SubReqQueue, &tmpSubReq);
}
//
}
void SubReqMan::IRQThread()
{
// This thread send the SubReq to DRAM Ctrl.
// And if subreq is write cmd, data is transmitted together.
// SubReq which should be send to the NAND is transmitted in CMD Callback.
// But this operation is not guaranteed if DRAM ctrl buffer is full.
static double time_stamp = 0;
while(1){
wait();
while(!M_CHECKEMPTY(SubReqQueue)){
if(reqInQueue.Op == HOST_WRITE ){ //write
//1. send IRQ to CPU1
if(SUB_DEBUG) cout << DEV_AND_TIME << "[IRQThread] IRQ Send, waiting for CPU... " << time_stamp << endl;
CPU_IRQ.write(1);
//2. CPU1 reads cmd (CmdCB)
//3. cmd from CPU1 (CmdCB)
if(!isCPUFinish) wait(eCPUFinish); //wait for data to arrive
isCPUFinish = false;
CPU_IRQ.write(0);
if(SUB_DEBUG) cout << DEV_AND_TIME << "[IRQThread] CPU done, waiting for data... " << endl;
//4. thread sends cmd & data
if(M_CHECKEMPTY(cDataQueue)) wait(eDataReady); //wait for data to arrive
if(!bypass_cache){ //dest cache //testing for now... must change this later
SubReq_t* tmpSubReq = &M_GETELE(SubReqQueue);
PageBuf_t* tmpDataBuf = &M_GETELE(cDataQueue);
DataMaster.write(_ADDR_DRAM_DATA_ + tmpSubReq->dst * PAGE_BYTES, (void*)tmpDataBuf, SECTOR_PER_PAGE);
#ifdef DATA_COMPARE_ON
DTCMP::writeData(DTCMP::mmDRAM, tmpSubReq->dst, tmpSubReq->iStartAddr/UNIT_OF_REQUEST, SECTOR_PER_PAGE, tmpDataBuf->buf);
#endif
if(buffer_write_count >= (uint)(0x0 - 0x200)) cout << "WARNING : POSSIBLE OVERFLOW ON COUNTING BUFFER WRITE COUNT!!!" << endl;
buffer_write_count += 512;
}
else{ //dest NAND
cache_bypass_count++;
wait(eNANDRead);
}
total_req_count++;
M_POP(SubReqQueue);
M_POP(cDataQueue);
RnBMaster.write(1);
}
else if(reqInQueue.Op == HOST_READ){ //read
//send IRQ to CPU1
//.write();
}
else{ //unknown cmd
assert(0 && "Unknown cmd");
}
wait(5, SC_NS); //this HAS to be above SC_ZERO_TIME, or IRQ write 0 will be ignored in IRQ controller...
}
}
}
void //%
SubReqMan::WriteSlaveCB( //%
tlm::tlm_generic_payload& trans, sc_core::sc_time& t) //%
{ //%
const char* dbgMsgText = "TRANSPORT handler for memory WriteSlaveBuf_writeBuf";//%
scml2::memory_alias< unsigned int >& m = this->WriteSlaveBuf_writeBuf;//%
tlm::tlm_command cmd = trans.get_command(); //%
sc_dt::uint64 adr = trans.get_address(); //%
unsigned char* ptr = trans.get_data_ptr(); //%
unsigned int len = trans.get_data_length(); //%
unsigned char* byt = trans.get_byte_enable_ptr(); //%
unsigned int wid = trans.get_streaming_width(); //%
//%USERBEGIN WriteSlaveCB
if ( dbgFlag[REGS] ) DBG_MSG( dbgMsgText );
// TODO: INSERT code for the WriteSlaveCB method here.
if (byt) { // Target unable to support byte enable attribute
trans.set_response_status( tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE );
return;
}
if (wid < len) { // Target unable to support streaming width attribute
trans.set_response_status( tlm::TLM_BURST_ERROR_RESPONSE );
return;
}
if(cmd == tlm::TLM_READ_COMMAND)
{
ERROR_MSG("Read to this port is prohibited\n");
sc_stop();
}
else if (cmd == tlm::TLM_WRITE_COMMAND){
/*if(SUB_DEBUG){
cout<< DEV_AND_TIME << "[WriteSlaveCB] data arrives on SubReqMan, current state is : " << adr <<endl;
}*/
}
Req_t newReq;
switch(adr){
case REQUEST_ADDR:
//expected to receive cmd
//divide cmd into subreq
memcpy(&newReq, ptr, sizeof(Req_t));
assert((newReq.Op == HOST_READ) || (newReq.Op == HOST_WRITE));
split_and_queue(newReq);
//notify thread
eIRQThread.notify();
break;
case DATA_ADDR:
//expected to receive data
//receive one page at a time
assert(len <= PAGE_BYTES);
//wait?
M_PUSH(cDataQueue, (PageBuf_t*)ptr);
if(M_CHECKFULL(cDataQueue)) RnBMaster.write(0);
eDataReady.notify();
//write to RnB Master
break;
default:
assert(0 && "invalid address, addr : " && adr);
break;
}
trans.set_response_status( tlm::TLM_OK_RESPONSE ); // Successful completion
//%USEREND WriteSlaveCB
}
void
SubReqMan::CmdSlaveCB( //%
tlm::tlm_generic_payload& trans, sc_core::sc_time& t) //%
{ //%
double BW_time_start = sc_time_stamp().value()/1000.0;
const char* dbgMsgText = "TRANSPORT handler for memory R_DATA"; //%
scml2::memory_alias< unsigned int >& m = this->CmdSlaveBuf_writeBuf; //%
tlm::tlm_command cmd = trans.get_command(); //%
sc_dt::uint64 adr = trans.get_address(); //%
unsigned char* ptr = trans.get_data_ptr(); //%
unsigned int len = trans.get_data_length(); //%
unsigned char* byt = trans.get_byte_enable_ptr(); //%
unsigned int wid = trans.get_streaming_width(); //%
//%USERBEGIN CPU_Callback
if ( dbgFlag[REGS] ) DBG_MSG( dbgMsgText );
// TODO: INSERT code for the CPU_Callback method here.
if (byt) { // Target unable to support byte enable attribute
trans.set_response_status( tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE );
return;
}
if (wid < len) { // Target unable to support streaming width attribute
trans.set_response_status( tlm::TLM_BURST_ERROR_RESPONSE );
return;
}
if (cmd == tlm::TLM_READ_COMMAND) {
//reads info of current cmd
if(SUB_DEBUG) cout << DEV_AND_TIME << "[CmdSlaveCB] CPU read invoked, adr : " << adr << endl;
CPUReadSubReq(adr, ptr, M_GETELE(SubReqQueue));
//note : CPU might not be able to read the full struct at once....
}
else if (cmd == tlm::TLM_WRITE_COMMAND) {
//sends dest of cmd in HOST
if((g_isFtlReady == false) ||(g_isCacheReady == false )) software_Init(ptr);
else{
//if(SUB_DEBUG) cout << DEV_AND_TIME << "[CmdSlaveCB] CPU write invoked, adr : " << adr << endl;
if(CPUWriteSubReq(adr, ptr, M_GETELE(SubReqQueue))){
isCPUFinish = true;
eCPUFinish.notify();
}
}
}
trans.set_response_status( tlm::TLM_OK_RESPONSE ); // Successful completion
//%USEREND CPU_Callback
}
bool
SubReqMan::CPUReadSubReq(sc_dt::uint64 adr, unsigned char* ptr, SubReq_t subreq){
int offset = adr;
switch (offset){
case 0 : // op
*((uint*)ptr) = subreq.op;//check
return false;
case 4 : //starting addr
*((uint*)ptr) = subreq.iStartAddr;
return false;
case 8: //length
*((uint*)ptr) = subreq.iLen;
return true;
default : //undefined
assert(0);
break;
}
}
bool
SubReqMan::CPUWriteSubReq(sc_dt::uint64 adr, unsigned char* ptr,SubReq_t& subreq){
int offset = adr - 0x1C;
switch (offset){
case 0 : // op
subreq.op = (SUB_REQ_OP)*((uint*)ptr);
return false;
case 4 : //LPA
subreq.iStartAddr = *((uint*)ptr) * SECTOR_PER_PAGE;
return false;
case 8 :
return false;
case 12 ://DRAM id (# of node)
subreq.dst = *((uint*)ptr);
return false;
case 16 :
return false;
case 20 ://everything went through
bypass_cache = *((uint*)ptr);
return true;
case 24 : //bypass cache;
if(SUB_DEBUG) cout <<DEV_AND_TIME << "[CPUWriteSubReq] bypass cache" << endl;
bypass_cache = true;
return true;
default : //undefined
assert(0);
return false;
}
}
void
SubReqMan::software_Init(unsigned char* ptr){
if(*((unsigned int *)ptr)==2){ //if Cache software initialization is completed
if(SUB_DEBUG){
cout<< "Cache software is ready"<<endl;
}
g_isCacheReady = true;
}
else if(*((unsigned int *)ptr)==3){ // if ftl software initialization is completed
if(SUB_DEBUG){
cout<< "Ftl software is ready"<<endl;
}
g_isFtlReady = true;
}
else{
assert(0);
}
}
void
SubReqMan::DataSlaveCB( //%
tlm::tlm_generic_payload& trans, sc_core::sc_time& t) //%
{ //%
double BW_time_start = sc_time_stamp().value()/1000.0;
const char* dbgMsgText = "TRANSPORT handler for memory R_DATA"; //%
scml2::memory_alias< unsigned int >& m = this->DataSlaveBuf_writeBuf; //%
tlm::tlm_command cmd = trans.get_command(); //%
sc_dt::uint64 adr = trans.get_address(); //%
unsigned char* ptr = trans.get_data_ptr(); //%
unsigned int len = trans.get_data_length()/4; //%
unsigned char* byt = trans.get_byte_enable_ptr(); //%
unsigned int wid = trans.get_streaming_width(); //%
//%USERBEGIN CPU_Callback
if ( dbgFlag[REGS] ) DBG_MSG( dbgMsgText );
// TODO: INSERT code for the CPU_Callback method here.
if (byt) { // Target unable to support byte enable attribute
trans.set_response_status( tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE );
return;
}
if (wid < len) { // Target unable to support streaming width attribute
trans.set_response_status( tlm::TLM_BURST_ERROR_RESPONSE );
return;
}
len = len*512;
if(cmd == tlm::TLM_READ_COMMAND){
if(M_CHECKEMPTY(cDataQueue)) wait(eDataReady); //wait for data to arrive
wait(len/DATA_BUS_TOTAL_BW, SC_NS);
if (SUB_DEBUG) cout << DEV_AND_TIME << "[DataSlaveCB] with cmd : " << cmd << endl;
PageBuf_t* tmpDataBuf = &M_GETELE(cDataQueue);
memcpy((void*)ptr, (void*)tmpDataBuf, len);
eNANDRead.notify();
}
else{
cout << "Unknown cmd" << endl;
assert(0);
}
trans.set_response_status( tlm::TLM_OK_RESPONSE ); // Successful completion
//%USEREND CPU_Callback
}
//%
//%
//%USERBEGIN MEMBER_DEFNS
// TODO: Insert definitions of your member functions, etc. here.
//%USEREND MEMBER_DEFNS
//%
//%
//---------------------------------------------------------------------- //%
// 'Orphaned' code section //%
// //%
// This section contains code snippets saved from previous versions of //%
// the model because they may have been user-written and they could //%
// not be associated with any tagged code sections when the //%
// code was re-generated. //%
// //%
// The most likely reason for this is that before the code was //%
// re-generated, a function name was changed. Now, the section of code //%
// that was associated with the old name cannot be re-associated with //%
// the new name. In that case, the recommended course of actions is //%
// to simply copy the relevant lines out of this section back into the //%
// function whose name has been changed. //%
#ifdef ORPHANED_CODE //%
//%USERBEGIN ORPHANED_CODE
//%USEREND ORPHANED_CODE
#endif // ORPHANED_CODE //%
//%USERBEGIN FOOTER_H
//%USEREND FOOTER_H
#endif // __SUBREQMAN_H__ //%
| [
"skhds1@daum.net"
] | skhds1@daum.net |
4319cbeeae94cc272d31d1b34ddfa96b95d63540 | 19d893b6fe80641ac38566c36c0760bf2dcff115 | /publisher.cpp | d548ab2f9637944bfe25aea9e0c07d344f0717be | [] | no_license | ewingert1/random-depo | 2b33931fbb192251ba6d9c851821acaa6f05af50 | 750d72dcb227c5a306f27699cfa37b674cf2253e | refs/heads/master | 2020-03-17T18:07:38.561943 | 2018-05-20T20:20:41 | 2018-05-20T20:20:41 | 133,815,351 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 880 | cpp | #include <ros/ros.h>
#include "std_msgs/String.h"
#include <stdlib.h>
#include <sstream>
int main(int argc, char **argv) {
//Initializes ROS, and sets up a node
ros::init(argc, argv, "PR_test");
ros::NodeHandle nh;
//Ceates the publisher, and tells it to publish
//to the husky/cmd_vel topic, with a queue size of 100
ros::Publisher pub=nh.advertise<geometry_msgs::Twist>("sensor/ultra", 100);
//Sets the loop to publish at a rate of 10Hz
ros::Rate rate(10);
while(ros::ok()) {
//Declares the message to be sent
std_msgs::String msg;
std::stringstream ss;
ss << "hello world ";
msg.data = ss.str();
//Publish the message
pub.publish(msg);
//Delays untill it is time to send another message
rate.sleep();
}
} | [
"noreply@github.com"
] | noreply@github.com |
4dbac86d55d443945526af95e7408b92d5dc3115 | 5a0dc6612e84f1152a3ad31249e0e910d3f95f3c | /HDMap/include/map_api/msg/std_msgs_Byte.h | 4287861c5b9c78920ff1a7978cb0e8a27ad11ad9 | [
"MIT"
] | permissive | 1335654481ren/autoparking | ff121043b33730544bf28dc930817e0e58365647 | a36ffaa1f787329b5e8324beb261059d6c0bd63f | refs/heads/master | 2020-04-02T05:42:56.165638 | 2018-12-05T08:28:07 | 2018-12-05T08:28:07 | 154,099,858 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 233 | h | #ifndef STD_MSGS_BYTE_H
#define STD_MSGS_BYTE_H
#include <string>
#include <vector>
using namespace std;
namespace std_msgs {
class Byte
{
public:
Byte() {};
~Byte() {};
signed char data;
};
} // namespace std_msgs
#endif
| [
"renxl@xiaoliangrendeMacBook-Pro.local"
] | renxl@xiaoliangrendeMacBook-Pro.local |
0bbdf748afb047f4a0ca581aaddd00d1b6adde9c | c286fd021537d80086c63404e9157799e8f2a59e | /cpro/assign2/q3/main.cpp | 756c1f6bc49d892a7d9070c38b78f0df6998953e | [] | no_license | bollu/IIIT-H-Code | f7bb88bff8f201a0435d648f648ccc67fd4e61d7 | e178919ab642ecfeea2ac3cdd3d668da43a2b883 | refs/heads/master | 2023-01-28T11:43:05.034342 | 2020-05-04T13:23:21 | 2020-05-04T13:23:21 | 65,584,926 | 8 | 3 | null | 2023-01-19T02:48:27 | 2016-08-12T21:37:13 | C | UTF-8 | C++ | false | false | 3,801 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define endl '\n'
typedef int digit;
typedef vector<digit> number;
template<typename T>
void printvec(vector<T> &v, string name="") {
cout<<name<<" : [";
for(auto x : v) {
cout<<x<<" ";
}
cout<<"]\n";
}
//remove leading zeroes
//00012 -> 12
//in the representation, since ones place is at "0", this will be
//[1, 2, 0, 0, 0] -> [1, 2]
number trim(number a) {
while(a[a.size() - 1] == 0 && a.size() > 1) {
a.pop_back();
}
return a;
}
number add (number as, number bs) {
number sum;
const int n = max(as.size(), bs.size());
for(int i = 0; i < n + 1; i++) {
sum.push_back(0);
}
int carry = 0;
for(int i = 0; i < n; i++) {
int s = 0;
if (i < as.size()) { s += as[i]; }
if (i < bs.size()) { s += bs[i]; }
s += carry;
int digitsum = s % 10;
carry = (s - digitsum) / 10;
sum[i] = digitsum;
//printvec(sum, "sum - " + std::to_string(i));
}
sum[n] = carry;
sum = trim(sum);
return sum;
}
number product(number as, number bs) {
number prod;
//printvec(as, "as");
//printvec(bs, "bs");
vector<vector<int>> intermediates;
for(int bi = 0; bi < bs.size(); bi++) {
intermediates.push_back(vector<int>());
for(int j = 0; j < as.size() + bs.size(); j++) {
intermediates[bi].push_back(0);
}
}
for(int i = 0; i < as.size() + bs.size(); i++) {
prod.push_back(0);
}
for(int bi = 0; bi < bs.size(); bi++) {
int digitcarry = 0;
for(int ai = 0; ai < as.size(); ai++) {
const int a = as[ai];
const int b = bs[bi];
const int totalprod = a * b + digitcarry;
const int digitprod = totalprod % 10;
digitcarry = (totalprod - digitprod) / 10;
//cout<<"digit: "<<digitprod<<" | carry: "<<digitcarry<<"\n";
intermediates[bi][ai + bi] += digitprod;
}
intermediates[bi][bi + as.size()] = digitcarry;
//printvec(intermediates[bi], "int-" + std::to_string(bi));
}
for(int bi = 0; bi < bs.size(); bi++) {
prod = add(prod, intermediates[bi]);
//printvec(prod, "add-" + std::to_string(bi));
}
prod = trim(prod);
return prod;
}
//assumes a > b
number sub(number a, number b) {
a = trim(a); b = trim(b);
number sub(a.begin(), a.end());
int carry = 0;
for(int i = 0; i < a.size(); i++) {
int diff = a[i] - carry;
if ( i < b.size() ){
diff -= b[i];
}
if (diff >= 0) {
sub[i] = diff;
carry = 0;
} else {
carry = 1;
sub[i] = 10 + diff;
}
}
sub = trim(sub);
return sub;
}
number getone() {
vector<int> one; one.push_back(1);
return one;
}
number getzero() {
vector<int> zero; zero.push_back(0);
return zero;
}
number slowexp(number a, number exp) {
exp = trim(exp);
a = trim(a);
if (exp == getzero()) {
return getone();
} else if (exp == getone()) {
return a;
}
else {
number subexp = sub(exp, getone());
number prod = product(a, slowexp(a, subexp));
return prod;
}
}
int main() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
number n[2];
for(int i = 0; i < 2; i++) {
string ns; cin>>ns;
for(char c : ns) {
n[i].push_back(c - '0');
}
reverse(n[i].begin(), n[i].end());
}
number p = slowexp(n[0], n[1]);
reverse(p.begin(), p.end());
for(auto d : p) {
cout<<d;
}
return 0;
}
| [
"siddu.druid@gmail.com"
] | siddu.druid@gmail.com |
19ecaed655a69ccc8b7851d866f1aa7cf1b3e77e | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/vc6addon/ide/pkgs/bld/src/javadbg.cpp | 9d5f68fe921f3df61f04fb0dd7b7e53789ac2bb4 | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56,718 | cpp | //
// CDebugJavaGeneralPage
// The general debugger options page for Java projects. This page
// lets the user enter the class file to debug, the HTML page
// containing the applet, and/or the parameters to the applet/application.
//
// CParamGridWnd
// The grid for entering applet parameters.
//
#include "stdafx.h"
#include "javadbg.h"
#include "htmlfile.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
//----------------------------------------------------------------
// CDebugJavaGeneralPage: the page to handle the general options
//----------------------------------------------------------------
BEGIN_IDE_CONTROL_MAP(CDebugJavaGeneralPage, IDDP_JAVA_DEBUG_GENERAL, IDS_DEBUG_OPTIONS)
MAP_EDIT(IDC_JAVA_CALLING_PROG, P_Java_ClassFileName)
MAP_RADIO(IDC_JAVA_USE_BROWSER, IDC_JAVA_USE_STANDALONE, 1, P_Java_DebugUsing)
END_IDE_CONTROL_MAP()
BEGIN_MESSAGE_MAP(CDebugJavaGeneralPage, CDebugPageTab)
//{{AFX_MSG_MAP(CDebugJavaGeneralPage)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//----------------------------------------------------------------
// CDebugJavaGeneralPage::OnInitDialog
BOOL CDebugJavaGeneralPage::OnInitDialog()
{
if ( !COptionMiniPage::OnInitDialog() ) {
return FALSE;
}
return TRUE;
}
//----------------------------------------------------------------
// CDebugJavaGeneralPage::InitPage
void CDebugJavaGeneralPage::InitPage()
{
COptionMiniPage::InitPage();
}
//----------------------------------------------------------------
// CDebugJavaGeneralPage::CommitPage
void CDebugJavaGeneralPage::CommitPage()
{
// REVIEW(briancr): do we need to do anything here?
}
//----------------------------------------------------------------
// CDebugJavaGeneralPage::OnPropChange
BOOL CDebugJavaGeneralPage::OnPropChange(UINT idProp)
{
// we want to enable/disable properties based on property changes
switch (idProp) {
case P_Java_ClassFileName: {
OnChangeClassFileName();
break;
}
case P_Java_DebugUsing: {
OnChangeDebugUsing();
break;
}
}
// call our base-class
return CDebugPageTab::OnPropChange(idProp);
}
//----------------------------------------------------------------
// CDebugJavaGeneralPage::Validate
BOOL CDebugJavaGeneralPage::Validate()
{
return CDebugPageTab::Validate();
}
void CDebugJavaGeneralPage::OnChangeClassFileName()
{
// we don't allow the user to enter a path or .class extension
// (other extensions are allowed because we can't tell the
// difference between the extension in java.lang.String and
// an invalid extension)
// get the class name
CString strClassName;
m_pSlob->GetStrProp(P_Java_ClassFileName, strClassName);
// split the class name into parts
// (and eliminate any path that's entered)
TCHAR szFileName[_MAX_PATH];
TCHAR szExt[_MAX_EXT];
_tsplitpath(strClassName, NULL, NULL, szFileName, szExt);
// remove the extension if it's .class
CString strNewClassName;
if (_tcscmp(szExt, _T(".class")) == 0) {
strNewClassName = CString(szFileName);
}
else {
strNewClassName = CString(szFileName) + CString(szExt);
}
// only set the class name prop if the new class name is different
if (strNewClassName != strClassName) {
// set the class name prop
m_pSlob->SetStrProp(P_Java_ClassFileName, strNewClassName);
}
}
void CDebugJavaGeneralPage::OnChangeDebugUsing()
{
// when the user changes debug using (selects browser or stand-alone),
// we need to set other properties
// if debug using browser:
// - if P_Java_ParamSource is unknown:
// - if P_Java_HTMLPage contains a valid page:
// - set P_Java_ParamSource to Java_ParamSource_HTMLPage
// (get the params from the HTML page)
// - if P_Java_HTMLPage does not contain a page:
// - set P_Java_ParamSource to Java_ParamSource_User
// (get the params from the user)
// get debug using
int nDebugUsing = Java_DebugUsing_Unknown;
GPT gptDebugUsing = m_pSlob->GetIntProp(P_Java_DebugUsing, nDebugUsing);
if (gptDebugUsing != ambiguous && nDebugUsing == Java_DebugUsing_Browser) {
// get the param source
int nParamSource = Java_ParamSource_Unknown;
GPT gptParamSource = m_pSlob->GetIntProp(P_Java_ParamSource, nParamSource);
// only change P_Java_ParamSource if it's not ambiguous and is unknown
if (gptParamSource != ambiguous && nParamSource == Java_ParamSource_Unknown) {
// first, set the param source to be the HTML page
m_pSlob->SetIntProp(P_Java_ParamSource, Java_ParamSource_HTMLPage);
// get the HTML page
CString strHTMLPage;
m_pSlob->GetStrProp(P_Java_HTMLPage, strHTMLPage);
// if the HTML page is empty, set the param source to be the param grid (user)
if (strHTMLPage.IsEmpty()) {
// set the param source
m_pSlob->SetIntProp(P_Java_ParamSource, Java_ParamSource_User);
}
}
}
}
//----------------------------------------------------------------
// CDebugJavaBrowserPage: the page to handle the browser options
//----------------------------------------------------------------
BEGIN_IDE_CONTROL_MAP(CDebugJavaBrowserPage, IDDP_JAVA_DEBUG_BROWSER, IDS_JAVA_PAGE_BROWSER)
MAP_EDIT(IDC_JAVA_BROWSER, P_Java_Browser)
MAP_RADIO(IDC_JAVA_USE_HTML_PARAMS, IDC_JAVA_USE_USER_PARAMS, 1, P_Java_ParamSource)
MAP_EDIT(IDC_JAVA_HTML_PAGE, P_Java_HTMLPage)
END_IDE_CONTROL_MAP()
BEGIN_MESSAGE_MAP(CDebugJavaBrowserPage, CDebugPageTab)
//{{AFX_MSG_MAP(CDebugJavaBrowserPage)
ON_WM_DESTROY()
//}}AFX_MSG_MAP
ON_CONTROL(GN_CHANGE, IDC_JAVA_PARAMS, OnChangeParamGrid)
END_MESSAGE_MAP()
//----------------------------------------------------------------
// CDebugJavaBrowserPage::OnInitDialog
BOOL CDebugJavaBrowserPage::OnInitDialog()
{
if ( !CDebugPageTab::OnInitDialog() ) {
return FALSE;
}
// init grid
m_pgridParams = new CParamGridWnd;
BOOL fRet = m_pgridParams->ReplaceControl(this, IDC_JAVA_PARAMS_HOLDER, IDC_JAVA_PARAMS,
WS_VISIBLE | WS_CHILD | WS_BORDER | WS_VSCROLL | WS_TABSTOP, 0, GRIDWND_TB_ALL, TRUE);
return TRUE;
}
//----------------------------------------------------------------
// CDebugJavaBrowserPage::OnDestroy
void CDebugJavaBrowserPage::OnDestroy()
{
delete m_pgridParams;
}
//----------------------------------------------------------------
// CDebugJavaBrowserPage::InitPage
void CDebugJavaBrowserPage::InitPage()
{
CDebugPageTab::InitPage();
// Show the grid
m_pgridParams->ShowWindow(SW_SHOW);
}
//----------------------------------------------------------------
// CDebugJavaBrowserPage::CommitPage
void CDebugJavaBrowserPage::CommitPage()
{
// REVIEW(briancr): do we need to do anything here?
}
//----------------------------------------------------------------
// CDebugJavaBrowserPage::OnPropChange
BOOL CDebugJavaBrowserPage::OnPropChange(UINT idProp)
{
// we want to enable/disable properties based on property changes
switch (idProp) {
case P_Java_Browser: {
OnChangeBrowser();
break;
}
case P_Java_HTMLPage: {
UpdateParamGrid();
break;
}
// user has changed the param source
case P_Java_ParamSource: {
OnChangeParamSource();
break;
}
}
// call our base-class
return CDebugPageTab::OnPropChange(idProp);
}
//----------------------------------------------------------------
// CDebugJavaBrowserPage::Validate
BOOL CDebugJavaBrowserPage::Validate()
{
if (m_pgridParams->AcceptControl())
{
OnChangeParamGrid();
}
return CDebugPageTab::Validate();
}
//----------------------------------------------------------------
// CDebugJavaBrowserPage::OnChangeBrowser
void CDebugJavaBrowserPage::OnChangeBrowser()
{
// remove any quotes around the browser name
// get the browser's name
CString strBrowser;
if (m_pSlob->GetStrProp(P_Java_Browser, strBrowser) == valid) {
CString strNewBrowser = strBrowser;
// trim white space
strNewBrowser.TrimLeft();
strNewBrowser.TrimRight();
// only look for quotes if the string is not empty
if (!strNewBrowser.IsEmpty()) {
// is the first character a quote?
if (strNewBrowser[0] == _T('\"')) {
// trim it
strNewBrowser = strNewBrowser.Mid(1);
}
// is the last character a quote?
int nLen = strNewBrowser.GetLength();
if (strNewBrowser[nLen-1] == _T('\"')) {
// trim it
strNewBrowser = strNewBrowser.Left(nLen-1);
}
// only set the browser property if it's different
if (strNewBrowser != strBrowser) {
m_pSlob->SetStrProp(P_Java_Browser, strNewBrowser);
}
}
}
}
//----------------------------------------------------------------
// CDebugJavaBrowserPage::OnChangeParamGrid
void CDebugJavaBrowserPage::OnChangeParamGrid()
{
// we'll only set the arg properties if the param source is not ambiguous
// and the current args are not ambiguous
// this prevents the configuration b's args from overwriting configuration a's args
// get the param source
int nParamSource = Java_ParamSource_Unknown;
GPT gptParamSource = m_pSlob->GetIntProp(P_Java_ParamSource, nParamSource);
if (gptParamSource != ambiguous && nParamSource != Java_ParamSource_Unknown) {
// get the args to find out if they're ambiguous
CString strCurrentHTMLArgs;
if (m_pSlob->GetStrProp(P_Java_HTMLArgs, strCurrentHTMLArgs) != ambiguous) {
// get the args from the grid
CString strHTMLArgs = m_pgridParams->GetParamsAsHTML();
// set the HTML style args
m_pSlob->SetStrProp(P_Java_HTMLArgs, strHTMLArgs);
}
}
}
//----------------------------------------------------------------
// CDebugJavaBrowserPage::OnChangeParamSource
void CDebugJavaBrowserPage::OnChangeParamSource()
{
// enable/disable controls based on the param source
// if the param source is unknown (only initially):
// - disable HTML page
// - disable param grid
// if the param source is HTML page:
// - enable HTML page
// - enable and read-only param grid
// - read the HTML page and fill the grid
// if the param source is user:
// - disable HTML page
// - enable param grid
// get the param source
int nParamSource = Java_ParamSource_Unknown;
GPT gptParamSource = m_pSlob->GetIntProp(P_Java_ParamSource, nParamSource);
// enable/disable HTML page
CDebugPageTab::OnPropChange(P_Java_HTMLPage);
CWnd* pControl = (CWnd*)GetDlgItem(IDC_JAVA_HTML_PAGE_TXT);
ASSERT(pControl != NULL);
pControl->EnableWindow(gptParamSource != ambiguous && nParamSource == Java_ParamSource_HTMLPage);
// enable/disable param grid
m_pgridParams->EnableWindow(gptParamSource != ambiguous && nParamSource != Java_ParamSource_Unknown);
m_pgridParams->SetReadOnly(gptParamSource != ambiguous && nParamSource == Java_ParamSource_HTMLPage);
m_pgridParams->Invalidate();
// update the param grid
UpdateParamGrid();
}
//----------------------------------------------------------------
// CDebugJavaBrowserPage::UpdateParamGrid
void CDebugJavaBrowserPage::UpdateParamGrid()
{
// get the param source
int nParamSource = Java_ParamSource_Unknown;
GPT gptParamSource = m_pSlob->GetIntProp(P_Java_ParamSource, nParamSource);
CString strParams;
// only read the params from the HTML page, if the HTML page is the param source
if (gptParamSource != ambiguous && nParamSource == Java_ParamSource_HTMLPage) {
// read the params from the HTML page and fill the grid
// get the HTML page
CString strHTMLPage;
m_pSlob->GetStrProp(P_Java_HTMLPage, strHTMLPage);
if (!strHTMLPage.IsEmpty()) {
// get the class file name
CString strClassFileName;
m_pSlob->GetStrProp(P_Java_ClassFileName, strClassFileName);
// is there a class file specified?
if (!strClassFileName.IsEmpty()) {
// attempt to read params from the page
CPath pathClass;
pathClass.Create(strClassFileName);
strClassFileName = pathClass.GetFileName();
// open the HTML file
CHTMLPageFile fileHTML;
if (fileHTML.Open(strHTMLPage, CFile::modeRead)) {
// read params from page
fileHTML.ReadParamBlock(strClassFileName, strParams);
fileHTML.Close();
}
}
}
}
// otherwise fill the param grid from the props
else if (gptParamSource != ambiguous && nParamSource == Java_ParamSource_User) {
// get the params
m_pSlob->GetStrProp(P_Java_HTMLArgs, strParams);
}
// fill the param grid
m_pgridParams->SetParamsFromHTML(strParams);
}
//----------------------------------------------------------------
// CDebugJavaStandalonePage: the page to handle the stand-alone options
//----------------------------------------------------------------
BEGIN_IDE_CONTROL_MAP(CDebugJavaStandalonePage, IDDP_JAVA_DEBUG_STANDALONE, IDS_JAVA_PAGE_STANDALONE)
MAP_EDIT(IDC_JAVA_STANDALONE, P_Java_Standalone)
MAP_EDIT(IDC_JAVA_STANDALONE_ARGS, P_Java_StandaloneArgs)
MAP_EDIT(IDC_JAVA_PROG_ARGS, P_Java_Args)
#ifdef STANDALONE_APPLET
MAP_RADIO(IDC_JAVA_STANDALONE_APPLET, IDC_JAVA_STANDALONE_APP, 1, P_Java_DebugStandalone)
#endif
END_IDE_CONTROL_MAP()
BEGIN_MESSAGE_MAP(CDebugJavaStandalonePage, CDebugPageTab)
//{{AFX_MSG_MAP(CDebugJavaStandalonePage)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//----------------------------------------------------------------
// CDebugJavaStandalonePage::OnInitDialog
BOOL CDebugJavaStandalonePage::OnInitDialog()
{
if ( !CDebugPageTab::OnInitDialog() ) {
return FALSE;
}
return TRUE;
}
//----------------------------------------------------------------
// CDebugJavaStandalonePage::InitPage
void CDebugJavaStandalonePage::InitPage()
{
CDebugPageTab::InitPage();
}
//----------------------------------------------------------------
// CDebugJavaStandalonePage::CommitPage
void CDebugJavaStandalonePage::CommitPage()
{
// REVIEW(briancr): do we need to do anything here?
}
//----------------------------------------------------------------
// CDebugJavaStandalonePage::OnPropChange
BOOL CDebugJavaStandalonePage::OnPropChange(UINT idProp)
{
// we want to enable/disable properties based on property changes
switch (idProp) {
case P_Java_Standalone: {
OnChangeStandalone();
break;
}
}
// call our base-class
return CDebugPageTab::OnPropChange(idProp);
}
//----------------------------------------------------------------
// CDebugJavaStandalonePage::Validate
BOOL CDebugJavaStandalonePage::Validate()
{
return CDebugPageTab::Validate();
}
//----------------------------------------------------------------
// CDebugJavaStandalonePage::OnChangeStandalone
void CDebugJavaStandalonePage::OnChangeStandalone()
{
// remove any quotes around the stand-alone interpreter name
// get the interpreter's name
CString strStandalone;
if (m_pSlob->GetStrProp(P_Java_Standalone, strStandalone) == valid) {
CString strNewStandalone = strStandalone;
// trim white space
strNewStandalone.TrimLeft();
strNewStandalone.TrimRight();
// only look for quotes if the string is not empty
if (!strNewStandalone.IsEmpty()) {
// is the first character a quote?
if (strNewStandalone[0] == _T('\"')) {
// trim it
strNewStandalone = strNewStandalone.Mid(1);
}
// is the last character a quote?
int nLen = strNewStandalone.GetLength();
if (strNewStandalone[nLen-1] == _T('\"')) {
// trim it
strNewStandalone = strNewStandalone.Left(nLen-1);
}
// only set the browser property if it's different
if (strNewStandalone != strStandalone) {
m_pSlob->SetStrProp(P_Java_Standalone, strNewStandalone);
}
}
}
#ifdef STANDALONE_APPLET
// update P_Java_DebugStandalone
CDebugPageTab::OnPropChange(P_Java_DebugStandalone);
#endif
}
//----------------------------------------------------------------
// CDebugJavaAddlClasses: page for handling additional classes
//----------------------------------------------------------------
BEGIN_IDE_CONTROL_MAP(CDebugJavaAddlClassesPage, IDDP_JAVA_DEBUG_ADDL_CLASSES, IDS_JAVA_DEBUG_ADDL_CLASSES)
MAP_CHECK(IDC_LOAD_DLL_PROMPT, P_PromptForDlls)
END_IDE_CONTROL_MAP()
//----------------------------------------------------------------
// CDebugJavaAddlClassesPage::OnInitDialog
BOOL CDebugJavaAddlClassesPage::OnInitDialog()
{
CRect rc;
HBLDTARGET hTarget;
CString str;
if ( !COptionMiniPage::OnInitDialog() ) {
return FALSE;
}
// Get the correct location for the grid
CWnd *pReplace = GetDlgItem(IDC_GRID_HOLDER);
ASSERT(pReplace != NULL);
// Init GridList
g_BldSysIFace.InitTargetEnum();
while ((hTarget = g_BldSysIFace.GetNextTarget(str)) != NO_TARGET)
{
GRIDINFO *pGI = new GRIDINFO;
pGI->hTarget = hTarget;
pGI->pGrid = new CAddlClassesGridWnd;
BOOL fRet = pGI->pGrid->ReplaceControl(this, IDC_GRID_HOLDER, IDC_DLLS_LIST,
WS_VISIBLE | WS_CHILD | WS_BORDER | WS_VSCROLL | WS_TABSTOP, 0, GRIDWND_TB_NEWDEL, FALSE);
pGI->pGrid->AddRow(new CAddlClassesGridRow((CAddlClassesGridWnd*)pGI->pGrid));
pGI->pGrid->ShowWindow(SW_HIDE);
m_GridList.AddTail(pGI);
}
// HACK - If the project file is an exe, we won't get any targets
if (m_GridList.IsEmpty())
{
ASSERT( ((CProxySlob *)m_pSlob)->IsSingle() );
GRIDINFO *pGI = new GRIDINFO;
hTarget = g_BldSysIFace.GetTarget(((CProxySlob *)m_pSlob)->GetBaseConfig()->GetConfigurationName(), ACTIVE_BUILDER);
pGI->hTarget = hTarget;
pGI->pGrid = new CAddlClassesGridWnd;
BOOL fRet = pGI->pGrid->ReplaceControl(this, IDC_GRID_HOLDER, IDC_DLLS_LIST,
WS_VISIBLE | WS_CHILD | WS_BORDER | WS_VSCROLL | WS_TABSTOP, 0, GRIDWND_TB_NEWDEL, FALSE);
pGI->pGrid->AddRow(new CAddlClassesGridRow((CAddlClassesGridWnd*)pGI->pGrid));
pGI->pGrid->ShowWindow(SW_HIDE);
m_GridList.AddTail(pGI);
}
m_pGridActive = ((GRIDINFO *)m_GridList.GetHead())->pGrid;
// Load info from src package (which got it from the vcp file)
InitGrids();
// and kill the holder window
pReplace->DestroyWindow();
return TRUE;
}
#if 0 // can't browse for .class files
//----------------------------------------------------------------
// CDebugJavaAddlClassesPage:: OnBrowse
void CDebugJavaAddlClassesPage::OnBrowse()
{
// set up browse dialog
CFileDialog dlg(TRUE);
// browse dialog title
CString strDlgTitle;
VERIFY(strDlgTitle.LoadString(IDS_JAVA_BROWSE_CLASS));
dlg.m_ofn.lpstrTitle = strDlgTitle;
// browse dialog attributes
dlg.m_ofn.Flags |= OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_NONETWORKBUTTON;
// browse dialog filters
CString strClassFilter;
VERIFY(strClassFilter.LoadString(IDS_JAVA_FILTER_CLASS));
CString strFilter;
AppendFilterSuffix(strFilter, dlg.m_ofn, strClassFilter);
dlg.m_ofn.lpstrFilter = strFilter;
dlg.m_ofn.nFilterIndex = 1;
// bring up the browse dialog
if (dlg.DoModal() == IDOK) {
// get the name of the class specified
CString strLocalClass = dlg.GetPathName();
// fill in the grid
CEdit* pEdit = (CEdit*)m_pGridActive->GetDlgItem(1);
ASSERT(pEdit != NULL);
pEdit->SetWindowText(strLocalClass);
pEdit->SetSel(0, -1);
pEdit->SetFocus();
}
}
#endif
//----------------------------------------------------------------
// CDebugJavaAddlClassesPage::InitGrids
void CDebugJavaAddlClassesPage::InitGrids()
{
if (g_VPROJIdeInterface.Initialize()) // make sure we are initialised!
{
POSITION pos = m_GridList.GetHeadPosition();
while (pos != NULL)
{
GRIDINFO *pGI = (GRIDINFO *)m_GridList.GetNext(pos);
// Add blank rows to the grid for the src package to fill in.
int cRows;
g_VPROJIdeInterface.GetDLLInfo()->GetDLLCount((ULONG)pGI->hTarget, &cRows);
for (int i=0; i < cRows; i++)
{
pGI->pGrid->AddRow(new CAddlClassesGridRow((CAddlClassesGridWnd*)(pGI->pGrid)));
}
CPtrList listDLLs;
// get the DLL info...
g_VPROJIdeInterface.GetDLLInfo()->InitDLLList((ULONG)pGI->hTarget, listDLLs);
int iRow = 0;
POSITION pos = listDLLs.GetHeadPosition();
while (pos != NULL)
{
DLLREC *pDLLRec = (DLLREC *)listDLLs.GetNext(pos);
// The last row will always be a new row
CDLLGridRow *pRow = (CDLLGridRow *)pGI->pGrid->GetRow(iRow++);
pRow->m_fPreload = pDLLRec->fPreload;
pRow->m_strLocalName = pDLLRec->strLocalName;
pRow->m_strRemoteName = pDLLRec->strRemoteName;
}
}
}
}
//----------------------------------------------------------------
// CDebugJavaAddlClassesPage::InitPage
void CDebugJavaAddlClassesPage::InitPage()
{
// call the base class's InitPage
CDebugAdditionalDllPage::InitPage();
// set the local name column to be a fixed full width
// (i.e. hide remote name column)
// figure out the width minus the preload column
CRect rectCaptionRow;
m_pGridActive->GetCaptionRow()->GetRect(rectCaptionRow);
int cxName = rectCaptionRow.Width() - m_pGridActive->GetColumnWidth(COL_PRELOAD);
// set the width of the local name column and fix it
m_pGridActive->SetColumnWidth(COL_LOCALNAME, cxName);
m_pGridActive->GetCaptionRow()->SetColumnFixedWidth(COL_LOCALNAME);
// set the width of the remote name column
m_pGridActive->SetColumnWidth(COL_REMOTENAME, 0);
m_pGridActive->ResetSize();
m_pGridActive->Invalidate(FALSE); // INEFFICIENT
m_pGridActive->ResetScrollBars();
}
//----------------------------------------------------------------
// Java: grid control window for handling parameters
//----------------------------------------------------------------
IMPLEMENT_DYNAMIC(CParamGridWnd, CGridControlWnd)
BEGIN_MESSAGE_MAP(CParamGridWnd, CGridControlWnd)
//{{AFX_MSG_MAP(CGridControlWnd)
ON_WM_CREATE()
ON_WM_DESTROY()
ON_WM_PAINT()
ON_WM_KILLFOCUS()
ON_WM_GETDLGCODE()
ON_BN_CLICKED(ID_GRD_NEW, OnGridNew)
ON_BN_CLICKED(ID_GRD_DELETE, OnGridDelete)
ON_BN_CLICKED(ID_GRD_MOVEUP, OnGridMoveUp)
ON_BN_CLICKED(ID_GRD_MOVEDOWN, OnGridMoveDown)
ON_WM_RBUTTONDOWN()
ON_WM_RBUTTONUP()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONDBLCLK()
ON_WM_LBUTTONUP()
ON_WM_KEYDOWN()
ON_WM_SIZE()
ON_WM_SYSKEYDOWN()
ON_WM_MOUSEMOVE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//----------------------------------------------------------------
// CParamGridWnd::CParamGridWnd
CParamGridWnd::CParamGridWnd(int nColumns, BOOL bDisplayCaption)
: CGridControlWnd(nColumns, bDisplayCaption),
m_bReadOnly(FALSE)
{
// no sorting needed for params
EnableSort(FALSE);
EnableAutoSort(FALSE);
// no multi selection
EnableMultiSelect(FALSE);
// enable drag n drop
m_bEnableDragRow = TRUE;
// set up read-only grid colors
// (toggled by changing m_bSysDefaultColors)
m_colorWindowText = GetSysColor(COLOR_WINDOWTEXT);
m_colorWindow = GetSysColor(COLOR_BTNFACE);
m_colorHighlight = GetSysColor(COLOR_HIGHLIGHT);
m_colorHighlightText = GetSysColor(COLOR_HIGHLIGHTTEXT);
// add one row (the add row)
AddRow(new CParamGridRow(this));
}
//----------------------------------------------------------------
// CParamGridWnd::~CParamGridWnd
CParamGridWnd::~CParamGridWnd()
{
// CGridWnd's dtor destroys the rows
}
//----------------------------------------------------------------
// CParamGridWnd::OnGridNew
afx_msg void CParamGridWnd::OnGridNew()
{
// only process this event if we're not read-only
if (!m_bReadOnly) {
// activate the new row
CGridRow* pSelRow = GetTailRow();
if (pSelRow != NULL) {
Select(pSelRow);
// Auto-activate the edit box in the Name column
ActivateNextControl();
}
CGridControlWnd::OnGridNew();
}
}
//----------------------------------------------------------------
// CParamGridWnd::OnGridDelete
afx_msg void CParamGridWnd::OnGridDelete()
{
// only process this event if we're not read-only
if (!m_bReadOnly) {
if (m_pActiveElement == NULL) {
DoRowDelete();
}
CGridControlWnd::OnGridDelete();
}
}
//----------------------------------------------------------------
// CParamGridWnd::OnGridMoveUp
afx_msg void CParamGridWnd::OnGridMoveUp()
{
// only process this event if we're not read-only
if (!m_bReadOnly) {
// if either of these asserts fire, this function needs to be
// fixed to deal with multiple selection
ASSERT(m_selection.GetCount() == 1);
DoRowMove(GetRowIndex((CParamGridRow*)GetRowAt(m_posCurRow)) - 1);
}
}
//----------------------------------------------------------------
// CParamGridWnd::OnGridMoveDown
afx_msg void CParamGridWnd::OnGridMoveDown()
{
// only process this event if we're not read-only
if (!m_bReadOnly) {
// if either of these asserts fire, this function needs to be
// fixed to deal with multiple selection
ASSERT(m_selection.GetCount() == 1);
DoRowMove(GetRowIndex((CParamGridRow*)GetRowAt(m_posCurRow)) + 1);
}
}
//----------------------------------------------------------------
// CParamGridWnd::OnCreate
afx_msg int CParamGridWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CGridControlWnd::OnCreate(lpCreateStruct) == -1)
return -1;
// set the grid's captions
CString strColCaption;
VERIFY(strColCaption.LoadString(IDS_JAVA_PARAM_COL_NAME));
SetColumnCaption(CParamGridRow::GRID_COL_NAME, strColCaption);
VERIFY(strColCaption.LoadString(IDS_JAVA_PARAM_COL_VALUE));
SetColumnCaption(CParamGridRow::GRID_COL_VALUE, strColCaption);
// set the column width
CRect rectGrid;
GetCaptionRow()->GetRect(rectGrid);
SetColumnWidth(CParamGridRow::GRID_COL_NAME, rectGrid.Width() / 2);
SetColumnWidth(CParamGridRow::GRID_COL_VALUE, rectGrid.Width() / 2);
// select the first row
Select(GetRow(0));
return 0;
}
//----------------------------------------------------------------
// CParamGridWnd::OnDestroy
afx_msg void CParamGridWnd::OnDestroy()
{
CGridControlWnd::OnDestroy();
}
//----------------------------------------------------------------
// CParamGridWnd::OnPaint
void CParamGridWnd::OnPaint()
{
// do normal painting if we're enabled
if (IsWindowEnabled()) {
// if we're read-only, adjust the colors before painting
if (m_bReadOnly) {
// we set up the read-only colors at construction time
// now we'll just use m_bSysDefaultColors to toggle
// between the system colors and our read-only colors
m_bSysDefaultColors = FALSE;
}
// paint
CGridControlWnd::OnPaint();
// if we're read-only, toggle back to system colors
if (m_bReadOnly) {
m_bSysDefaultColors = TRUE;
}
}
else {
// we're disabled or read-only
CPaintDC dc(this);
CGridRow* pRow;
CRect rowRect;
GetClientRect(rowRect);
// Draw the captions first
pRow = GetCaptionRow();
rowRect.bottom = rowRect.top + pRow->GetRowHeight();
if (dc.m_ps.rcPaint.top < rowRect.bottom)
{
CFont* pOldFont = dc.SelectObject(GetCaptionFont());
pRow->Draw(&dc, rowRect);
dc.SelectObject(pOldFont);
}
// Setup clip rect around the actual grid (client less captions)
rowRect.top = rowRect.bottom;
rowRect.bottom = dc.m_ps.rcPaint.bottom;
dc.SetBkColor(GetSysColor(COLOR_BTNFACE));
dc.ExtTextOut(0, 0, ETO_OPAQUE, rowRect, NULL, 0, NULL);
}
}
//----------------------------------------------------------------
// CParamGridWnd::DoDragDrop
void CParamGridWnd::DoDragDrop(CPoint point)
{
// figure out where we're dropping the selected row(s)
// convert the point to an element
CGridElement* pElement = ElementFromPoint(point);
// if the point doesn't convert, then drop after the last row
if (pElement == NULL) {
CGridRow* pRow = (CGridRow*)m_rows.GetTail();
if (pRow == NULL)
return;
pElement = pRow->ElementFromPoint(point);
}
// at this point, the element must not be NULL
ASSERT(pElement != NULL);
// get the row from the element
CGridRow* pRow = pElement->GetRow();
// we can't insert in the caption row
if (pRow == GetCaptionRow())
return;
// move the selected row(s) to the new position
DoRowMove(GetRowIndex((CParamGridRow*)pRow));
}
//----------------------------------------------------------------
// CParamGridWnd::OnGetDlgCode
afx_msg UINT CParamGridWnd::OnGetDlgCode()
{
return CGridControlWnd::OnGetDlgCode() | DLGC_WANTARROWS | DLGC_WANTCHARS;
}
//----------------------------------------------------------------
// CParamGridWnd::ProcessKeyboard
BOOL CParamGridWnd::ProcessKeyboard(MSG* pMsg, BOOL bPreTrans /*= FALSE*/)
{
// determine the type of message
switch (pMsg->message) {
case WM_KEYDOWN: {
// determine the key pressed
switch (pMsg->wParam) {
case VK_TAB: {
// control-tab is mdi window switching
if (GetKeyState(VK_CONTROL) < 0)
break;
// if there's no active element and we're in a dialog, don't do anything
if (m_pActiveElement == NULL && m_bParentIsDialog)
break;
// we're finished with the current control
if (!AcceptControl(FALSE))
return TRUE;
// tab to the next (prev) control
if (GetKeyState(VK_SHIFT) < 0)
ActivatePrevControl();
else
ActivateNextControl();
return TRUE;
}
case VK_RETURN: {
// if there's an active element, then accept the changes,
// and select the next row
if (m_pActiveElement != NULL && (GetKeyState(VK_CONTROL) >= 0)) {
AcceptControl();
// get the next row
POSITION posNextRow = m_posCurRow;
GetNextRow(posNextRow);
// select the next row
if (posNextRow != NULL) {
Select(GetRowAt(posNextRow));
}
return TRUE;
}
break;
}
case VK_UP: {
// Alt+Up moves the row up one
if (GetKeyState(VK_MENU) < 0) {
OnGridMoveUp();
return TRUE;
}
break;
}
case VK_DOWN: {
// Alt+Down moves the row down one
if (GetKeyState(VK_MENU) < 0) {
OnGridMoveDown();
return TRUE;
}
break;
}
}
break;
}
}
return CGridControlWnd::ProcessKeyboard(pMsg, bPreTrans);
}
//----------------------------------------------------------------
// CParamGridWnd::OnCmdMsg
BOOL CParamGridWnd::OnCmdMsg(UINT nID, int nCode, void *pExtra, AFX_CMDHANDLERINFO *pHandlerInfo)
{
return CGridControlWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}
//----------------------------------------------------------------
// CParamGridWnd::OnKillFocus
void CParamGridWnd::OnKillFocus(CWnd* pNewWnd)
{
// call the base class
CGridControlWnd::OnKillFocus(pNewWnd);
// send grid change notification
GridChange();
}
//----------------------------------------------------------------
// CParamGridWnd::DoRowMove
void CParamGridWnd::DoRowMove(int nToIndex)
{
// the index to move the selected rows to must be valid
if (nToIndex >= GetRowCount() - 1) // -1 because of new row
nToIndex = GetRowCount() - 2; // -2 because of new row
if (nToIndex < 0)
return;
// Notify the grid window of these moves
// the grid can cancel any or all of the row moves
CParamGridRow** pMoveRows = new CParamGridRow*[m_selection.GetCount()];
int cMove = 0;
// go through all selected rows and notify the grid of the move
int nDest = nToIndex;
for (POSITION posSel = GetHeadSelPosition(); posSel != NULL; ) {
// get the row to move
CParamGridRow* pSelRow = (CParamGridRow*)GetNextSel(posSel);
// don't move the new row
if (pSelRow->IsNewRow()) {
Deselect(pSelRow);
}
else {
// get the index of the row to move
int nSrcIndex = GetRowIndex(pSelRow);
// notify the grid that this row is moving; if the grid
// returns FALSE, don't move the row
if (!OnRowMove(nSrcIndex, nDest++)) {
Deselect(pSelRow);
nDest--;
}
else {
// store the row in our array of rows to move
pMoveRows[cMove++] = pSelRow;
}
}
}
// remove the selected rows
for (posSel = GetHeadSelPosition(); posSel != NULL; ) {
// get the row to remove
CParamGridRow* pSelRow = (CParamGridRow*)GetNextSel(posSel);
// Remove the row from the grid
POSITION pos = m_rows.Find(pSelRow);
ASSERT(pos != NULL);
// update m_posTopVisibleRow if the row we're about to delete is the
// top visible row
if (m_posTopVisibleRow == pos) {
// make the previous row the top visible row
GetPrevRow(m_posTopVisibleRow);
// we don't want to make the caption row the visible row
if (m_posTopVisibleRow != NULL && (GetRowAt(m_posTopVisibleRow) == GetCaptionRow())) {
m_posTopVisibleRow = NULL;
m_cyScroll = 0;
}
}
// remove the row
m_rows.RemoveAt(pos);
}
// move each row from our temp list into the grid's list of rows
// figure the starting row to insert after
POSITION posTarget = m_rows.FindIndex(nToIndex);
ASSERT(posTarget != NULL);
for (int iCur = 0; iCur < cMove; iCur++) {
posTarget = m_rows.InsertAfter(posTarget, pMoveRows[iCur]);
}
// delete the array of moved rows
delete [] pMoveRows;
// repaint
AdjustTopVisible();
ResetSize(); // INEFFICIENT
Invalidate(FALSE); // INEFFICIENT
ResetScrollBars();
// scroll the first row in the selection into view
// get the first row in the selection list
POSITION posSelHead = GetHeadSelPosition();
CGridRow* pSelRow = (posSelHead == NULL) ? NULL : (CGridRow*) GetNextSel(posSelHead);
if (pSelRow != NULL) {
// scroll this row into view
ScrollIntoView(pSelRow);
}
// if no rows are selected, select the "new" row
if (m_selection.IsEmpty()) {
CParamGridRow* pRow = GetTailRow();
if (pRow != NULL)
Select(pRow);
}
// send grid change notification
GridChange();
}
//----------------------------------------------------------------
// CParamGridWnd::OnRowMove
BOOL CParamGridWnd::OnRowMove(int nSrcIndex, int nDestIndex)
{
return TRUE;
}
//----------------------------------------------------------------
// CParamGridWnd::DoRowDelete
void CParamGridWnd::DoRowDelete()
{
// don't try to delete anything with an empty selection list
if (m_selection.IsEmpty())
return;
// figure out the row to select after the deletion is done: it should be
// the row after the first element in the selection list
POSITION posNewSel = NULL;
// go through the selection list and delete all selected rows
for (POSITION posSel = GetHeadSelPosition(); posSel != NULL; ) {
// get the selected row
CParamGridRow* pSelRow = (CParamGridRow*)GetNextSel(posSel);
// if we're deleting the last selected row, the selected row should
// be the row following the last selected node
if (posSel == NULL) {
posNewSel = m_rows.Find(pSelRow);
m_rows.GetNext(posNewSel);
}
// don't delete the last row (the add row)
if (!pSelRow->IsNewRow()) {
// delete the row
RemoveRow(pSelRow);
delete pSelRow;
}
else {
// deselect the last row, since you can't delete it
Deselect(pSelRow);
}
}
// Redraw
Invalidate(FALSE);
ResetScrollBars();
// if there's no row to select, default to the last row in the grid
if (posNewSel == NULL)
posNewSel = GetTailRowPosition();
// Set the selection
CGridControlRow* pSelRow = (CGridControlRow*)GetRowAt(posNewSel);
// this row should not be the caption row
ASSERT((CGridRow*)pSelRow != (CGridRow*)GetCaptionRow());
SetActiveElement(pSelRow);
Select(pSelRow);
// send grid change notification
GridChange();
}
//----------------------------------------------------------------
// CParamGridWnd::GetCurSel
int CParamGridWnd::GetCurSel()
{
// we should have exactly one item selected
if (m_selection.GetCount() != 1)
return -1;
return GetRowIndex((CParamGridRow*)GetRowAt(m_posCurRow));
}
//----------------------------------------------------------------
// CParamGridWnd::GetRowIndex
int CParamGridWnd::GetRowIndex(const CParamGridRow* pRow) const
{
// iterate through the rows until the one given is found
int nIndex = 0;
for (POSITION pos = GetHeadRowPosition(); pos != NULL; nIndex++) {
if ((CParamGridRow*)GetNextRow(pos) == pRow)
return nIndex;
}
return -1;
}
//----------------------------------------------------------------
// CParamGridWnd::SetReadOnly
inline void CParamGridWnd::SetReadOnly(BOOL bReadOnly)
{
m_bReadOnly = bReadOnly;
if (m_bReadOnly) {
// no selection for a read-only grid
// go through selection list and deselect everything
for (POSITION posSel = GetHeadSelPosition(); posSel != NULL; ) {
CParamGridRow* pSelRow = (CParamGridRow*)GetNextSel(posSel);
Deselect(pSelRow);
}
}
}
//----------------------------------------------------------------
// CParamGridWnd::IsReadOnly
inline BOOL CParamGridWnd::IsReadOnly()
{
return m_bReadOnly;
}
//----------------------------------------------------------------
// CParamGridWnd::GetTailRow
inline CParamGridRow* CParamGridWnd::GetTailRow() const
{
if (m_rows.IsEmpty())
return NULL;
return (CParamGridRow*)m_rows.GetTail();
}
//----------------------------------------------------------------
// CParamGridWnd::GetTailRowPosition
inline POSITION CParamGridWnd::GetTailRowPosition() const
{
return m_rows.GetTailPosition();
}
//----------------------------------------------------------------
// CParamGridWnd::GetTailSelPosition
inline POSITION CParamGridWnd::GetTailSelPosition() const
{
return m_selection.GetTailPosition();
}
//----------------------------------------------------------------
// CParamGridWnd::SetParamsFromHTML
inline void CParamGridWnd::SetParamsFromHTML(LPCSTR pszHTMLParams)
{
if (m_strHTMLParams != CString(pszHTMLParams)) {
m_strHTMLParams = pszHTMLParams;
SetGridFromHTML(m_strHTMLParams);
CParamGridRow* pRow = (CParamGridRow*)GetRowAt(GetTailRowPosition());
SetActiveElement(pRow);
Select(pRow);
}
// send grid change notification
GridChange();
}
//----------------------------------------------------------------
// CParamGridWnd::GetParamsAsHTML
inline CString CParamGridWnd::GetParamsAsHTML()
{
m_strHTMLParams = GetHTMLFromGrid();
return m_strHTMLParams;
}
//----------------------------------------------------------------
// CParamGridWnd::GetParamsAsCmdLine
inline CString CParamGridWnd::GetParamsAsCmdLine()
{
return GetCmdLineFromGrid();
}
//----------------------------------------------------------------
// CParamGridWnd::DeleteAllRows
void CParamGridWnd::DeleteAllRows()
{
// delete all rows (even the new row)
for (POSITION posRow = GetHeadRowPosition(); posRow != NULL; ) {
// get the row to delete
CParamGridRow* pRow = (CParamGridRow*)GetNextRow(posRow);
RemoveRow(pRow, FALSE);
}
}
//----------------------------------------------------------------
// CParamGridWnd::SetGridFromHTML
void CParamGridWnd::SetGridFromHTML(LPCSTR pszParams)
{
// this function expects the parameter string to be in the
// HTML applet parameter format:
// <param name="param name" value="param value">
// delete everything in the grid
DeleteAllRows();
CString strParams = pszParams;
CString strName;
CString strValue;
// read each param line from the string until there are no more
BOOL bMore = TRUE;
while (bMore) {
// get a param line (<param ...>)
bMore = GetParamLine(strParams, strName, strValue);
// if either the name or value has a value, enter it in the grid
if (!strName.IsEmpty() || !strValue.IsEmpty()) {
// create a row for this param
CParamGridRow* pNewRow = new CParamGridRow(this);
pNewRow->SetColumnText(CParamGridRow::GRID_COL_NAME, strName);
pNewRow->SetColumnText(CParamGridRow::GRID_COL_VALUE, strValue);
// add this row
AddRow(pNewRow);
}
}
// add the new row
AddRow(new CParamGridRow(this));
}
//----------------------------------------------------------------
// CParamGridWnd::GetHTMLFromGrid
CString CParamGridWnd::GetHTMLFromGrid()
{
CString strParams;
CString strFormat;
strFormat.LoadString(IDS_JAVA_PARAMS_AS_HTML);
// go through each row in the grid and generate params for it
for (POSITION posRow = GetHeadRowPosition(); posRow != NULL; ) {
CParamGridRow* pRow = (CParamGridRow*)GetNextRow(posRow);
// don't generate params for the new row
if (!pRow->IsNewRow()) {
// get name and value for the row
CString strName;
CString strValue;
pRow->GetColumnText(CParamGridRow::GRID_COL_NAME, strName);
pRow->GetColumnText(CParamGridRow::GRID_COL_VALUE, strValue);
// generate params
CString strParam;
strParam.Format(strFormat, strName, strValue);
strParams += strParam;
}
}
return strParams;
}
//----------------------------------------------------------------
// CParamGridWnd::GetCmdLineFromGrid
CString CParamGridWnd::GetCmdLineFromGrid()
{
CString strParams;
// go through each row in the grid and generate a command line from it
for (POSITION posRow = GetHeadRowPosition(); posRow != NULL; ) {
CParamGridRow* pRow = (CParamGridRow*)GetNextRow(posRow);
// don't generate any cmd line args for the new row
if (!pRow->IsNewRow()) {
// get the name and value for the row
CString strName;
CString strValue;
pRow->GetColumnText(CParamGridRow::GRID_COL_NAME, strName);
pRow->GetColumnText(CParamGridRow::GRID_COL_VALUE, strValue);
// trim white space from name and value
strName.TrimLeft();
strName.TrimRight();
strValue.TrimLeft();
strValue.TrimRight();
// append the name
strParams += strName;
// if name and value are both not empty, put an equal
// sign between them, so params are name=value format
if (!strName.IsEmpty() && !strValue.IsEmpty()) {
strParams += _T("=");
}
// append the value
strParams += strValue;
// add a space to separate params
strParams += _T(" ");
}
}
// trim trailing white space
strParams.TrimRight();
return strParams;
}
//----------------------------------------------------------------
// CParamGridWnd::GridChange
void CParamGridWnd::GridChange()
{
// send a GN_CHANGE message to the parent
WPARAM wParam = (WPARAM)MAKELONG(GetDlgCtrlID(), GN_CHANGE);
ASSERT(LOWORD(wParam) != 0);
LPARAM lParam = (LPARAM)GetSafeHwnd();
ASSERT(lParam != 0);
CWnd* pParent = GetParent();
ASSERT(pParent != NULL);
pParent->SendMessage(WM_COMMAND, wParam, lParam);
}
//----------------------------------------------------------------
// CParamGridWnd::GetParamLine
BOOL CParamGridWnd::GetParamLine(CString& strParams, CString& strName, CString& strValue)
{
strName.Empty();
strValue.Empty();
CString strNameToken;
CString strValueToken;
// the param line is in the format:
// <param name="name" value="value">
// sets of tokens to skip while extracting the name and value
TCHAR* pszSkipTokens1[] = { _T("<"), _T("param"), _T("name"), _T("="), NULL, _T("\""), NULL };
TCHAR* pszSkipTokens2[] = { _T("value"), _T("="), NULL, _T("\""), NULL };
TCHAR* pszSkipTokens3[] = { _T(">"), NULL };
// skip all initial tokens
if (SkipTokens(strParams, pszSkipTokens1)) {
// get the name
if (GetQuotedString(strParams, strNameToken)) {
// skip all tokens between name and value
if (SkipTokens(strParams, pszSkipTokens2)) {
// get the value
if (GetQuotedString(strParams, strValueToken)) {
// skip all ending tokens
if (SkipTokens(strParams, pszSkipTokens3)) {
strName = strNameToken;
strValue = strValueToken;
return TRUE;
}
}
}
}
}
return FALSE;
}
//----------------------------------------------------------------
// CParamGridWnd::SkipTokens
BOOL CParamGridWnd::SkipTokens(CString& strString, TCHAR* pszSkipTokens[])
{
// skip all tokens given
for (int i = 0; pszSkipTokens[i] != NULL; i++) {
// remove any leading white space
strString.TrimLeft();
// get the length of the expected token
int nTokenLen = _tcslen(pszSkipTokens[i]);
// extract what we expect to be the token
CString strToken = strString.Left(nTokenLen);
// lower case the token
strToken.MakeLower();
// is this the token we expect?
if (strToken != pszSkipTokens[i]) {
// token not found
return FALSE;
}
// skip the token
strString = strString.Mid(nTokenLen);
}
return TRUE;
}
//----------------------------------------------------------------
// CParamGridWnd::GetQuotedString
BOOL CParamGridWnd::GetQuotedString(CString& strString, CString& strValue)
{
int nEndName = -1;
// the string may or may not really be quoted
if (strString[0] == _T('\"')) {
// find ending quote
// + 2 to include beginning and ending quote
nEndName = strString.Mid(1).Find(_T('\"')) + 2;
// if we didn't find the end of the value, assume
// the end of the string is the end of the value
if (nEndName < 2)
nEndName = strString.GetLength();
}
else {
// name is not quoted, find ending white space
nEndName = strString.FindOneOf(_T(" \r\n\t>"));
// if we didn't find the end of the value, assume
// the end of the string is the end of the value
if (nEndName == -1)
nEndName = strString.GetLength();
}
// copy the value out of the string
strValue = strString.Left(nEndName);
// discard the value from the string
strString = strString.Mid(nEndName);
return TRUE;
}
void CParamGridWnd::OnRButtonDown(UINT nFlags, CPoint point)
{
// only process this event if we're not read-only
if (!m_bReadOnly)
CGridControlWnd::OnRButtonDown(nFlags, point);
}
void CParamGridWnd::OnRButtonUp(UINT nFlags, CPoint point)
{
// only process this event if we're not read-only
if (!m_bReadOnly)
CGridControlWnd::OnRButtonUp(nFlags, point);
}
void CParamGridWnd::OnLButtonDown(UINT nFlags, CPoint point)
{
// only process this event if we're not read-only
if (!m_bReadOnly)
CGridControlWnd::OnLButtonDown(nFlags, point);
}
void CParamGridWnd::OnLButtonDblClk(UINT nFlags, CPoint point)
{
// only process this event if we're not read-only
if (!m_bReadOnly)
CGridControlWnd::OnLButtonDblClk(nFlags, point);
}
void CParamGridWnd::OnLButtonUp(UINT nFlags, CPoint point)
{
// only process this event if we're not read-only
if (!m_bReadOnly)
CGridControlWnd::OnLButtonUp(nFlags, point);
}
void CParamGridWnd::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// only process this event if we're not read-only
if (!m_bReadOnly)
CGridControlWnd::OnKeyDown(nChar, nRepCnt, nFlags);
}
void CParamGridWnd::OnSize(UINT nType, int cx, int cy)
{
// override OnSize to fix bug in CGridWnd::OnSize
// the bug is that when SetActiveElement in CGridWnd::OnSize
// is called, the column should be specified as m_nCurColumn.
// Rather than make this change for all grids, which is slightly
// risky, we'll just do it for the param grid
CGridElement* pActiveElement = m_pActiveElement;
SetActiveElement(NULL);
// call the base class
CGridControlWnd::OnSize(nType, cx, cy);
if (pActiveElement != NULL)
SetActiveElement(pActiveElement, m_nCurColumn);
}
void CParamGridWnd::OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// only process this event if we're not read-only
if (!m_bReadOnly)
CGridControlWnd::OnSysKeyDown(nChar, nRepCnt, nFlags);
}
void CParamGridWnd::OnMouseMove(UINT nFlags, CPoint point)
{
// only process this event if we're not read-only
if (!m_bReadOnly)
CGridControlWnd::OnMouseMove(nFlags, point);
}
BOOL CParamGridWnd::OnToolTipText(UINT nID, NMHDR* pNMHDR, LRESULT* pResult)
{
// only process this event if we're not read-only
if (!m_bReadOnly)
return CGridControlWnd::OnToolTipText(nID, pNMHDR, pResult);
return FALSE;
}
//----------------------------------------------------------------
// CParamGridRow: row for handling parameters
//----------------------------------------------------------------
//----------------------------------------------------------------
// CParamGridRow::CParamGridRow
CParamGridRow::CParamGridRow(CParamGridWnd* pGrid)
: CGridControlRow(pGrid)
{
}
//----------------------------------------------------------------
// CParamGridRow::~CParamGridRow
CParamGridRow::~CParamGridRow()
{
}
//----------------------------------------------------------------
// CParamGridRow::DrawCell
// Need to override DrawCell in order to draw the focus rectangle in the
// name column of the last row (the "new" row)
void CParamGridRow::DrawCell(CDC *pDC, const CRect& cellRect, int nColumn)
{
// let the base class actually draw the cell
CGridControlRow::DrawCell(pDC, cellRect, nColumn);
// only draw the focus rect if the grid is not read-only
if (!((CParamGridWnd*)GetGrid())->IsReadOnly()) {
// Draw a focus rect in the name column of the new row
if (IsNewRow() && nColumn == GRID_COL_NAME) {
// adjust the focus rect for margins
CRect rectText = cellRect;
AdjustForMargins(rectText, nColumn);
pDC->DrawFocusRect(rectText);
}
}
}
//----------------------------------------------------------------
// CParamGridRow::OnActivate
void CParamGridRow::OnActivate(BOOL bActivate, int nColumn)
{
// are we activating a column?
if (bActivate && nColumn >= 0) {
// create an edit control in the column
CreateControl(edit, nColumn, ES_AUTOHSCROLL);
}
else {
// deactivating: remove the control from the column
CreateControl(none, -1);
}
}
//----------------------------------------------------------------
// CParamGridRow::OnAccept
BOOL CParamGridRow::OnAccept(CWnd* pControlWnd)
{
CParamGridWnd* pGrid = GetParamGrid();
int nCol = pGrid->m_nControlColumn;
// store the text the user entered into the column
CString str;
if (pControlWnd != NULL) {
switch (pGrid->m_nControlColumn) {
case GRID_COL_NAME:
pControlWnd->GetWindowText(str);
QuoteString(str);
m_strName = str;
break;
case GRID_COL_VALUE:
pControlWnd->GetWindowText(str);
QuoteString(str);
m_strValue = str;
break;
default:
// should only be name or value columns
ASSERT(FALSE);
break;
}
}
// If the user has deleted the name and value, remove the row
// (but don't ever delete the last row - it's the "new" row)
if (!IsNewRow() && (m_strName.IsEmpty() && m_strValue.IsEmpty())) {
// only the current row will be selected, so DoDelete will
// just delete one row
GetParamGrid()->DoRowDelete();
return TRUE;
}
// if the user has entered something in the last row (the "new" row),
// create a new "new" row
if (IsNewRow() && !str.IsEmpty()) {
pGrid->AddRow(new CParamGridRow(pGrid));
// Make sure the new row is added at the tail
ASSERT(pGrid->GetTailRow() != this);
}
return TRUE;
}
//----------------------------------------------------------------
// CParamGridRow::ResetSize
void CParamGridRow::ResetSize(CDC* pDC)
{
// get the text metrics
TEXTMETRIC tm;
pDC->GetTextMetrics(&tm);
// set the row height
m_cyHeight = tm.tmHeight + tm.tmExternalLeading + 3;
}
//----------------------------------------------------------------
// CParamGridRow::GetColumnText
void CParamGridRow::GetColumnText(int nColumn, CString& str)
{
// get the text for given column
switch (nColumn) {
case GRID_COL_NAME:
str = m_strName;
break;
case GRID_COL_VALUE:
str = m_strValue;
break;
default:
// should only be name or value columns
ASSERT(FALSE);
}
}
//----------------------------------------------------------------
// CParamGridRow::SetColumnText
void CParamGridRow::SetColumnText(int nColumn, LPCSTR pszValue)
{
// set the text for the given column
switch (nColumn) {
case GRID_COL_NAME:
m_strName = pszValue;
break;
case GRID_COL_VALUE:
m_strValue = pszValue;
break;
default:
// should only be name or value columns
ASSERT(FALSE);
}
}
//----------------------------------------------------------------
// CParamGridRow::GetParamGrid
inline CParamGridWnd* CParamGridRow::GetParamGrid()
{
return (CParamGridWnd*)GetGrid();
}
//----------------------------------------------------------------
// CParamGridRow::IsNewRow
inline BOOL CParamGridRow::IsNewRow()
{
return (GetParamGrid()->GetTailRow() == this);
}
//----------------------------------------------------------------
// CParamGridRow::QuoteString
void CParamGridRow::QuoteString(CString& str)
{
// if the given string contains white space and is not quoted,
// put quotes around it
// search the string for white space
if (str.FindOneOf(_T(" \t\n\r")) != -1) {
// is the string already quoted?
int nLen = str.GetLength();
if (str[0] != _T('\"') || str[nLen-1] != _T('\"')) {
// put quotes around the string
str = _T("\"") + str + _T("\"");
}
}
}
//----------------------------------------------------------------
// CAddlClassesGridWnd: grid control window for handling addl classes
//----------------------------------------------------------------
// NOTE: there are really only two columns for the additional classes grid.
// Having three makes the derivation from CDLLGridWnd much simpler. We'll just
// fix the size of the second column so you never see the third.
CAddlClassesGridWnd::CAddlClassesGridWnd(int nColumns /*= 3*/, BOOL bDisplayCaption /*= TRUE*/)
: CDLLGridWnd(nColumns, bDisplayCaption)
{
// No browsing for classes.
m_bEnableEllipse = FALSE;
}
//----------------------------------------------------------------
// CAddlClassesGridRow: grid row for handling addl classes
//----------------------------------------------------------------
CAddlClassesGridRow::CAddlClassesGridRow(CAddlClassesGridWnd* pGridWnd, CAddlClassesGridRow* pParent /*= NULL*/)
: CDLLGridRow(pGridWnd, pParent)
{
}
void CAddlClassesGridRow::GetColumnText(int nColumn, CString& rStr)
{
switch (nColumn) {
case COL_LOCALNAME:
rStr = m_strLocalName;
// Remove path and .class extension.
if (!rStr.IsEmpty()) {
CString strClassExt;
VERIFY(strClassExt.LoadString(IDS_JAVA_CLASS_EXT));
TCHAR szFileName[_MAX_FNAME];
TCHAR szExt[_MAX_EXT];
_tsplitpath(rStr, NULL, NULL, szFileName, szExt);
CString strExt = CString(szExt);
strExt.MakeLower();
if (strExt == strClassExt) {
*szExt = _T('\0');
}
rStr = CString(szFileName) + CString(szExt);
}
break;
default:
CDLLGridRow::GetColumnText(nColumn, rStr);
break;
}
}
void CAddlClassesGridRow::OnActivate(BOOL bActivate, int nColumn)
{
if (bActivate) {
switch (nColumn) {
case COL_LOCALNAME:
GetDLLGrid()->m_bEnableEllipse = FALSE;
CreateControl(edit, nColumn, ES_AUTOHSCROLL);
break;
default:
CDLLGridRow::OnActivate(bActivate, nColumn);
break;
}
}
else {
CDLLGridRow::OnActivate(bActivate, nColumn);
}
}
BOOL CAddlClassesGridRow::OnAccept(CWnd *pControlWnd)
{
CString str;
CAddlClassesGridWnd *pGrid = (CAddlClassesGridWnd*)GetDLLGrid();
int nCol = pGrid->m_nControlColumn;
if (pControlWnd != NULL)
{
switch ( pGrid->m_nControlColumn )
{
case COL_PRELOAD:
GetDLLGrid()->SetFocus();
break;
case COL_LOCALNAME:
pControlWnd->GetWindowText(str);
m_strLocalName = str;
break;
case COL_REMOTENAME:
pControlWnd->GetWindowText(str);
m_strRemoteName = str;
break;
default:
ASSERT(FALSE);
break;
}
}
// If the user has deleted both the local and remote name, remove the row
// (but don't ever delete the last row - it's the "new" row)
if (this != pGrid->GetLastRow() &&
(nCol == COL_LOCALNAME || nCol == COL_REMOTENAME) &&
(m_strRemoteName.IsEmpty() && m_strLocalName.IsEmpty())
) {
// only the current row will be selected
GetDLLGrid()->DoDelete();
return TRUE;
}
if (this == pGrid->GetLastRow()
&& (nCol == COL_LOCALNAME || nCol == COL_REMOTENAME)
&& !str.IsEmpty() ) {
pGrid->AddRow(new CAddlClassesGridRow((CAddlClassesGridWnd*)pGrid));
// Make sure the new row is added at the tail
ASSERT( pGrid->GetLastRow() != this );
}
return TRUE;
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
4ad8a70844445ebec0c44fafc27d32dcfd0a864c | c51febc209233a9160f41913d895415704d2391f | /library/ATF/tagPALETTEENTRY.hpp | f18c90cdfc4f3a90c1018b1b3407c16d857d5d23 | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 315 | hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct tagPALETTEENTRY
{
char peRed;
char peGreen;
char peBlue;
char peFlags;
};
END_ATF_NAMESPACE
| [
"b1ll.cipher@yandex.ru"
] | b1ll.cipher@yandex.ru |
5432c7aa8251c6276a130cfbbd37ad73e6f110e9 | c9bbd90aec6bd43c53b68c0c77c9648fbce6d425 | /15) Алгоритм Дейкстры/d_v2.cpp | c13d927a4410ae69ba6a8f135996aa681b7cbe8e | [] | no_license | u7er/TSVPS | 9c82170b0fb437740a42f1390c77f54ab40282c6 | 91a52f8821800f0592c0e19664f5556cf52823b2 | refs/heads/master | 2021-08-31T18:26:39.285566 | 2017-12-22T10:42:28 | 2017-12-22T10:42:28 | 108,965,241 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,601 | cpp | #include <stdio.h>
#include <vector>
#include <algorithm>
#include <map>
#include <math.h>
using namespace std;
int count_vertex, count_edges, trudoemkost = 0;
vector <int> p;
vector <int> vershiny;
struct edge {
int x, y, w;
};
int search_index_min(vector <int> m) {
int index = 0;
int min = m[0];
for (int i = 1; i < m.size(); i++) {
if (m[i] < min) {
min = m[i];
index = i;
}
}
return index;
}
vector <int> raznost(vector <int> a, vector <int> b) {
vector <int> c;
vector <int>::iterator it;
for (int i = 1; i < a.size(); i++) {
if (find(a.begin(), a.end(), a[i]) != a.end() && find(b.begin(), b.end(), a[i]) == b.end()) {
it = find(a.begin(), a.end(), a[i]);
c.push_back(it[0]);
}
}
return c;
}
int cost_of_transit(vector <edge> e, int x, int y) {
if (x == y) return 0;
for (int i = 0; i < count_edges; i++) {
if ((x == e[i].x && y == e[i].y) || (x == e[i].y && y == e[i].x)) {
return e[i].w;
}
}
return (int) pow(10, 5);
}
bool equal_check(vector <int> a, vector <int> b) {
int count = 0;
if (a.size() == b.size()) {
for (int i = 0; i < a.size(); i++) {
if (find(b.begin(), b.end(), a[i]) != b.end()) count++;
}
if (count == a.size()) return true;
else return false;
}
else return false;
}
vector <int> deikstra(vector <edge> e) {
vector <int> S, D(count_vertex + 1), v_s, weights;
S.push_back(1);
for (int i = 1; i <= count_vertex; i++) {
D[i] = cost_of_transit(e, 1, i);
if (i != count_vertex) p[i + 1] = 1;
}
v_s = raznost(vershiny, S);
while (!equal_check(vershiny, S)) {
trudoemkost++;
for (int i = 0; i < v_s.size(); i++) {
weights.push_back(D[v_s[i]]);
}
int index = search_index_min(weights);
int w = v_s[index];
S.push_back(w);
v_s = raznost(vershiny, S);
for (int i = 0; i < v_s.size(); i++) {
trudoemkost += 2;
int cost = cost_of_transit(e, w, v_s[i]);
if (D[v_s[i]] < D[w] + cost) continue;
else {
D[v_s[i]] = D[w] + cost;
p[v_s[i]] = w;
}
}
weights.clear();
}
return D;
}
int main() {
FILE *file = fopen("input.txt", "r");
fscanf(file, "%d %d", &count_edges, &count_vertex);
vector <edge> edges(count_edges);
vector <int> length_paths, path;
vershiny.resize(count_vertex);
p.resize(count_vertex + 1);
for (int i = 0; i < count_vertex; i++) {
vershiny[i] = i + 1;
}
int temp = 0;
while (!feof(file)) {
fscanf(file, "%d %d %d", &edges[temp].x, &edges[temp].y, &edges[temp].w);
temp++;
}
length_paths = deikstra(edges);
printf("Source graph: \n");
for (int i = 0; i < count_edges; i++) {
printf("[%d,%d] %d\n", edges[i].x, edges[i].y, edges[i].w);
}
printf("\n");
for (int i = 2; i <= count_vertex; i++) {
// Start - 1; Vertex - i; weight - length_paths[i];
for (int k = i; ; k = p[k]) {
path.push_back(k);
if (k == 0) break;
}
reverse(path.begin(), path.end());
printf("Path from 1 to %d: ", i);
for (int k = 1; k < path.size(); k++) {
printf("%d ", path[k]);
if (k != path.size() - 1) printf(" ");
}
printf("\n");
path.clear();
}
printf("Operations: %d\n", trudoemkost);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
a04eca4baf85e134de7de7c95a7a678048ff6321 | 4f5505e172aab9d03a8fc75d1bc052deb8e1f85f | /Hacker Rank/p36.cpp | b884a0b603aa850651343e07a4c8c0910ee921ca | [] | no_license | Sartech-B/Competitive-Programming | 625fa038730725a23e4288df2759a65c96e0cf9a | 6d609f10c19945f3c19b52955d2bdb1561082b3c | refs/heads/master | 2020-12-05T05:04:23.100117 | 2020-01-06T02:23:39 | 2020-01-06T02:23:39 | 232,015,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
long int a[n], b[n];
for(int i=0; i<n; i++)
{
cin>>a[i];
b[i] = a[i];
}
int ans1 = 0, ans2 = 0;
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(a[i]>a[j])
{
swap(a[i], a[j]);
ans1++;
}
}
}
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(b[i]<b[j])
{
swap(b[i], b[j]);
ans2++;
}
}
}
cout<<min(ans1, ans2)<<endl;
} | [
"sarthakbawal@gmail.com"
] | sarthakbawal@gmail.com |
290c20684fdaaf1aeece226b78752229ae96e4ea | 564a820c13ffd1b28fa23b35244fa8c029839885 | /block_matching/src/doc_analyzer/Matcher/blockmatching.cpp | 97eb4c72d943ee14219e2753f9a34bbd6cd1c7b6 | [] | no_license | NotMichaelChen/index_update | 1ccc584cca3b2829c80cae4172705a70c083950a | 7c5fa88ea65915791f610d7c93ee93ea7b2b5fb9 | refs/heads/master | 2021-01-01T15:33:03.748899 | 2019-10-22T00:26:16 | 2019-10-22T00:26:16 | 97,640,100 | 3 | 3 | null | 2018-11-30T00:11:21 | 2017-07-18T20:17:21 | C++ | UTF-8 | C++ | false | false | 7,962 | cpp | #include "blockmatching.hpp"
#include <map>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include "utility/util.hpp"
//is 1 overlapped by 2
bool isOverlap(int oldbegin1, int newbegin1, int oldlen, int oldbegin2, int newbegin2, int newlen) {
return
oldbegin1 >= oldbegin2 &&
oldbegin1 + oldlen <= oldbegin2 + newlen &&
newbegin1 >= newbegin2 &&
newbegin1 + oldlen <= newbegin2 + newlen;
}
void extendBlock(std::shared_ptr<Block> block, StringEncoder& se) {
auto oldend = se.getOldEnd();
auto newend = se.getNewEnd();
//Go past end of block
auto olditer = se.getOldIter() + block->oldendloc()+1;
auto newiter = se.getNewIter() + block->newendloc()+1;
while(olditer != oldend && newiter != newend && *olditer == *newiter) {
block->len++;
olditer++;
newiter++;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::vector<std::shared_ptr<Block>> getCommonBlocks(int minsize, StringEncoder& se) {
std::vector<std::shared_ptr<Block>> commonblocks;
//Impossible to have common blocks if one doc is smaller than the minimum block size
if(se.getOldSize() < minsize || se.getNewSize() < minsize || minsize < 1)
return commonblocks;
//Represents a candidate block obtained from the old document
struct CandidateBlock {
CandidateBlock(int o, std::vector<int> r) : oldloc(o), run(r) {}
int oldloc;
std::vector<int> run;
};
//Stores a "candidate block", extracted from the old doc
//Each candidate can be matched multiple times with blocks from the new doc
std::unordered_multimap<unsigned int, CandidateBlock> potentialblocks;
//Get all possible blocks in the old file
std::vector<int> newblock;
for(auto olditer = se.getOldIter(); olditer != se.getOldEnd() - (minsize-1); ++olditer) {
newblock.insert(newblock.end(), olditer, olditer+minsize);
unsigned int blockhash = Utility::hashVector(newblock);
CandidateBlock tempblock(olditer - se.getOldIter(), move(newblock));
potentialblocks.insert(std::make_pair(blockhash, tempblock));
newblock.clear();
}
auto newbeginiter = se.getNewIter();
//Check each block in the new file for a match with a block in the old file
std::vector<int> blockcheck;
for(auto newiter = se.getNewIter(); newiter != se.getNewEnd() - (minsize-1); ++newiter) {
blockcheck.insert(blockcheck.end(), newiter, newiter+minsize);
unsigned int blockhash = Utility::hashVector(blockcheck);
//Get all blocks that match the current block's hash
auto blockmatchrange = potentialblocks.equal_range(blockhash);
for(auto matchedblock = blockmatchrange.first; matchedblock != blockmatchrange.second; ++matchedblock) {
//Double-check equality
if(blockcheck == matchedblock->second.run) {
commonblocks.push_back(std::make_shared<Block>(matchedblock->second.oldloc, newiter - newbeginiter, matchedblock->second.run.size()));
}
}
blockcheck.clear();
}
return commonblocks;
}
void extendBlocks(std::vector<std::shared_ptr<Block>>& commonblocks, StringEncoder& se) {
if(commonblocks.size() <= 1)
return;
std::sort(commonblocks.begin(), commonblocks.end(), compareStrict);
//Create a vector of chars to store deleted locations
//Can't use bools since vector<bool> is special
std::vector<char> isdeleted(commonblocks.size());
//Extend every block
for(auto iter = commonblocks.begin(); iter != commonblocks.end(); iter++) {
extendBlock(*iter, se);
}
//Eliminate overlaps
size_t index = 0;
while(index < commonblocks.size()) {
//Potential overlap as long as the other block's begin is before this block's end
int oldendloc = commonblocks[index]->oldendloc();
for(auto overlapchecker = commonblocks.begin() + index + 1; overlapchecker != commonblocks.end() && (*overlapchecker)->oldloc <= oldendloc; overlapchecker++) {
if(isdeleted[overlapchecker - commonblocks.begin()])
continue;
if(isOverlap((*overlapchecker)->oldloc, (*overlapchecker)->newloc, (*overlapchecker)->len,
commonblocks[index]->oldloc, commonblocks[index]->newloc, commonblocks[index]->len))
{
isdeleted[overlapchecker - commonblocks.begin()] = 1;
}
}
do {
index++;
} while(index < commonblocks.size() && isdeleted[index]);
}
//Copy over valid blocks
std::vector<std::shared_ptr<Block>> newblocks;
for(size_t i = 0; i < commonblocks.size(); i++) {
if(!isdeleted[i])
newblocks.push_back(commonblocks[i]);
}
commonblocks.swap(newblocks);
}
//Resolve blocks that are intersecting
//Should be run after extendBlocks
void resolveIntersections(std::vector<std::shared_ptr<Block>>& allblocks) {
//List of blocks to add to the main list later
//NOTE: It is impossible for blocks generated from intersection resolution to
//be a duplicate from an original block in allblocks.
//Consider a b c d e, a b c f c d e. "a b" would be generated from intersection resolution,
//but it is impossible for that block to be generated normally since it is possible to extend that block,
//so the extended version would be added, which is a b c.
std::vector<std::shared_ptr<Block>> addedblocks;
//First, sort based on old locations
std::sort(allblocks.begin(), allblocks.end(), compareOld);
for(size_t i = 0; i < allblocks.size(); i++) {
for(size_t j = i+1; j < allblocks.size(); j++) {
//break if intersections are not possible anymore
if(allblocks[j]->oldloc > allblocks[i]->oldendloc())
break;
//Intersection occurs if B.end > A.end >= B.begin > A.begin
//We know that B.begin > A.begin (iterating in sorted order)
//We know that A.end >= B.begin (is our breaking condition)
//Thus we only need to check B.end > A.end
if(allblocks[j]->oldendloc() > allblocks[i]->oldendloc()) {
//calculate how much the current block needs to shrink by
int shrunksize = allblocks[j]->oldloc - allblocks[i]->oldloc;
//No point adding zero-length blocks
if(shrunksize > 0) {
addedblocks.push_back(std::make_shared<Block>(
allblocks[i]->oldloc,
allblocks[i]->newloc,
shrunksize
));
}
}
}
}
//Now sort based on new locations
sort(allblocks.begin(), allblocks.end(), compareNew);
for(size_t i = 0; i < allblocks.size(); i++) {
for(size_t j = i+1; j < allblocks.size(); j++) {
if(allblocks[j]->newloc > allblocks[i]->newendloc())
break;
if(allblocks[j]->newendloc() > allblocks[i]->newendloc()) {
int shrunksize = allblocks[j]->newloc - allblocks[i]->newloc;
if(shrunksize > 0) {
addedblocks.push_back(std::make_shared<Block>(
allblocks[i]->oldloc,
allblocks[i]->newloc,
shrunksize
));
}
}
}
}
//remove duplicates
std::sort(addedblocks.begin(), addedblocks.end(), compareStrict);
addedblocks.erase(std::unique(addedblocks.begin(), addedblocks.end()), addedblocks.end());
//append the list of added blocks
allblocks.insert(allblocks.end(), addedblocks.begin(), addedblocks.end());
} | [
"mzc12345@gmail.com"
] | mzc12345@gmail.com |
2c09b77c9929378d8c48cd9228737b32cdacdd21 | c73b9c4d9d1f61fdb706d0bb2b5e35d222c1ea5c | /OMP.cpp | f5a20680bf5e36b71b1d1d3a74accd0b49f5d449 | [] | no_license | gk023/dcomp | 52c73e326955bef775c2aee0fa99dc5a1e92da72 | fb134004c58d598596a8511935df14f3d7ded18b | refs/heads/master | 2020-05-26T15:29:24.822493 | 2019-06-04T16:56:54 | 2019-06-04T16:56:54 | 188,286,454 | 0 | 0 | null | 2019-06-03T15:08:55 | 2019-05-23T18:27:29 | C++ | UTF-8 | C++ | false | false | 773 | cpp | // file OMP.cpp
//
// Definitions for the OMP class
//
// Programmer: Garrett King
//
//*****************************************
#include <complex>
#include <cmath>
#include "OMP.h"
//Get optical potential with parameters V, r, a, W, rw, aw for a
//nucleus with A nucleons
OMP::OMP(double V, double r, double a, double W, double rw, double aw, double A)
{
re_vol = V;
re_rad = r;
re_dif = a;
im_vol = W;
im_rad = rw;
im_dif = aw;
mass_num = A;
}
OMP::~OMP()
{ }
std::complex<double> OMP::pot(double rad)
{
double Vv;
double Wv;
Vv = -1. * re_vol/(1.+exp( (rad - pow(mass_num, 1./3.)*re_rad) / re_dif ) );
Wv = -1. * im_vol/(1.+exp( (rad - pow(mass_num, 1./3.)*im_rad) / im_dif ) );
return std::complex<double> (Vv,Wv);
}
| [
"kinggar1@msu.edu"
] | kinggar1@msu.edu |
f0196036cb1092a41fa1d1ed595d36b5b3354788 | 0e8bd6ecee37b391299e8a41c842ce2786864e55 | /src/Magnum/Test/RectangleTextureGLTest.cpp | ad438db17f6b2a28ecbc075d37726d49810cddcc | [
"MIT"
] | permissive | 91yuan/magnum | c3fc8a0287bcd2a8d62ac5db5aec905b9e185468 | 929329b1f8363ac5e6f8688423c6c6854014865e | refs/heads/master | 2021-01-19T16:41:37.924578 | 2017-08-21T17:23:50 | 2017-08-21T20:17:31 | 101,019,156 | 1 | 0 | null | 2017-08-22T03:54:43 | 2017-08-22T03:54:43 | null | UTF-8 | C++ | false | false | 20,021 | cpp | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017
Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Corrade/Containers/Array.h>
#include <Corrade/TestSuite/Compare/Container.h>
#include "Magnum/Context.h"
#include "Magnum/Extensions.h"
#include "Magnum/BufferImage.h"
#include "Magnum/Image.h"
#include "Magnum/ImageFormat.h"
#include "Magnum/OpenGLTester.h"
#include "Magnum/PixelFormat.h"
#include "Magnum/RectangleTexture.h"
#include "Magnum/TextureFormat.h"
#include "Magnum/Math/Color.h"
#include "Magnum/Math/Range.h"
#include "Magnum/OpenGLTester.h"
namespace Magnum { namespace Test {
struct RectangleTextureGLTest: OpenGLTester {
explicit RectangleTextureGLTest();
void construct();
void wrap();
void bind();
void bindImage();
void sampling();
void samplingSRGBDecode();
void samplingBorderInteger();
void samplingSwizzle();
void samplingDepthStencilMode();
void storage();
void image();
void compressedImage();
void imageBuffer();
void compressedImageBuffer();
void subImage();
void compressedSubImage();
void subImageBuffer();
void compressedSubImageBuffer();
void subImageQuery();
void compressedSubImageQuery();
void subImageQueryBuffer();
void compressedSubImageQueryBuffer();
void invalidateImage();
void invalidateSubImage();
};
namespace {
constexpr UnsignedByte Data[]{
0, 0, 0, 0, 0, 0, 0, 0,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
enum: std::size_t { PixelStorageDataCount = 2 };
const struct {
const char* name;
Containers::ArrayView<const UnsignedByte> data;
PixelStorage storage;
Containers::ArrayView<const UnsignedByte> dataSparse;
std::size_t offset;
} PixelStorageData[PixelStorageDataCount]{
{"default pixel storage",
Containers::arrayView(Data).suffix(8), {},
Containers::arrayView(Data).suffix(8), 0},
#if !defined(MAGNUM_TARGET_GLES2) || !defined(MAGNUM_TARGET_WEBGL)
{"skip Y",
Containers::arrayView(Data).suffix(8), PixelStorage{}.setSkip({0, 1, 0}),
Containers::arrayView(Data), 8}
#endif
};
}
RectangleTextureGLTest::RectangleTextureGLTest() {
addTests({&RectangleTextureGLTest::construct,
&RectangleTextureGLTest::wrap,
&RectangleTextureGLTest::bind,
&RectangleTextureGLTest::bindImage,
&RectangleTextureGLTest::sampling,
&RectangleTextureGLTest::samplingSRGBDecode,
&RectangleTextureGLTest::samplingBorderInteger,
&RectangleTextureGLTest::samplingSwizzle,
&RectangleTextureGLTest::samplingDepthStencilMode,
&RectangleTextureGLTest::storage});
addInstancedTests({
&RectangleTextureGLTest::image,
&RectangleTextureGLTest::imageBuffer,
&RectangleTextureGLTest::subImage,
&RectangleTextureGLTest::subImageBuffer,
&RectangleTextureGLTest::subImageQuery,
&RectangleTextureGLTest::subImageQueryBuffer},
PixelStorageDataCount);
addTests({&RectangleTextureGLTest::compressedImage,
&RectangleTextureGLTest::compressedImageBuffer,
&RectangleTextureGLTest::compressedSubImage,
&RectangleTextureGLTest::compressedSubImageBuffer,
&RectangleTextureGLTest::compressedSubImageQuery,
&RectangleTextureGLTest::compressedSubImageQueryBuffer,
&RectangleTextureGLTest::invalidateImage,
&RectangleTextureGLTest::invalidateSubImage});
}
void RectangleTextureGLTest::construct() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
{
RectangleTexture texture;
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(texture.id() > 0);
}
MAGNUM_VERIFY_NO_ERROR();
}
void RectangleTextureGLTest::wrap() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
GLuint id;
glGenTextures(1, &id);
/* Releasing won't delete anything */
{
auto texture = RectangleTexture::wrap(id, ObjectFlag::DeleteOnDestruction);
CORRADE_COMPARE(texture.release(), id);
}
/* ...so we can wrap it again */
RectangleTexture::wrap(id);
glDeleteTextures(1, &id);
}
void RectangleTextureGLTest::bind() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.bind(15);
MAGNUM_VERIFY_NO_ERROR();
AbstractTexture::unbind(15);
MAGNUM_VERIFY_NO_ERROR();
AbstractTexture::bind(7, {&texture, nullptr, &texture});
MAGNUM_VERIFY_NO_ERROR();
AbstractTexture::unbind(7, 3);
MAGNUM_VERIFY_NO_ERROR();
}
void RectangleTextureGLTest::bindImage() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::shader_image_load_store>())
CORRADE_SKIP(Extensions::GL::ARB::shader_image_load_store::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setStorage(TextureFormat::RGBA8, Vector2i{32})
.bindImage(2, ImageAccess::ReadWrite, ImageFormat::RGBA8);
MAGNUM_VERIFY_NO_ERROR();
AbstractTexture::unbindImage(2);
MAGNUM_VERIFY_NO_ERROR();
AbstractTexture::bindImages(1, {&texture, nullptr, &texture});
MAGNUM_VERIFY_NO_ERROR();
AbstractTexture::unbindImages(1, 3);
MAGNUM_VERIFY_NO_ERROR();
}
void RectangleTextureGLTest::sampling() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setMinificationFilter(Sampler::Filter::Linear)
.setMagnificationFilter(Sampler::Filter::Linear)
.setWrapping(Sampler::Wrapping::ClampToBorder)
.setBorderColor(Color3(0.5f))
.setMaxAnisotropy(Sampler::maxMaxAnisotropy())
.setCompareMode(Sampler::CompareMode::CompareRefToTexture)
.setCompareFunction(Sampler::CompareFunction::GreaterOrEqual);
MAGNUM_VERIFY_NO_ERROR();
}
void RectangleTextureGLTest::samplingSRGBDecode() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
if(!Context::current().isExtensionSupported<Extensions::GL::EXT::texture_sRGB_decode>())
CORRADE_SKIP(Extensions::GL::EXT::texture_sRGB_decode::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setSRGBDecode(false);
MAGNUM_VERIFY_NO_ERROR();
}
void RectangleTextureGLTest::samplingBorderInteger() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
if(!Context::current().isExtensionSupported<Extensions::GL::EXT::texture_integer>())
CORRADE_SKIP(Extensions::GL::EXT::texture_integer::string() + std::string(" is not supported."));
RectangleTexture a;
a.setWrapping(Sampler::Wrapping::ClampToBorder)
.setBorderColor(Vector4i(1, 56, 78, -2));
RectangleTexture b;
b.setWrapping(Sampler::Wrapping::ClampToBorder)
.setBorderColor(Vector4ui(35, 56, 78, 15));
MAGNUM_VERIFY_NO_ERROR();
}
void RectangleTextureGLTest::samplingSwizzle() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_swizzle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_swizzle::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setSwizzle<'b', 'g', 'r', '0'>();
MAGNUM_VERIFY_NO_ERROR();
}
void RectangleTextureGLTest::samplingDepthStencilMode() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::stencil_texturing>())
CORRADE_SKIP(Extensions::GL::ARB::stencil_texturing::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setDepthStencilMode(Sampler::DepthStencilMode::StencilIndex);
MAGNUM_VERIFY_NO_ERROR();
}
void RectangleTextureGLTest::storage() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setStorage(TextureFormat::RGBA8, Vector2i(32));
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(texture.imageSize(), Vector2i(32));
MAGNUM_VERIFY_NO_ERROR();
}
void RectangleTextureGLTest::image() {
setTestCaseDescription(PixelStorageData[testCaseInstanceId()].name);
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setImage(TextureFormat::RGBA8, ImageView2D{
PixelStorageData[testCaseInstanceId()].storage,
PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i(2),
PixelStorageData[testCaseInstanceId()].dataSparse});
MAGNUM_VERIFY_NO_ERROR();
Image2D image = texture.image({PixelStorageData[testCaseInstanceId()].storage,
PixelFormat::RGBA, PixelType::UnsignedByte});
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(image.size(), Vector2i(2));
CORRADE_COMPARE_AS(Containers::arrayCast<UnsignedByte>(image.data()).suffix(PixelStorageData[testCaseInstanceId()].offset),
PixelStorageData[testCaseInstanceId()].data,
TestSuite::Compare::Container);
}
void RectangleTextureGLTest::imageBuffer() {
setTestCaseDescription(PixelStorageData[testCaseInstanceId()].name);
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setImage(TextureFormat::RGBA8, BufferImage2D{
PixelStorageData[testCaseInstanceId()].storage,
PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i(2),
PixelStorageData[testCaseInstanceId()].dataSparse,
BufferUsage::StaticDraw});
MAGNUM_VERIFY_NO_ERROR();
BufferImage2D image = texture.image({PixelStorageData[testCaseInstanceId()].storage,
PixelFormat::RGBA, PixelType::UnsignedByte}, BufferUsage::StaticRead);
const auto imageData = image.buffer().data();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(image.size(), Vector2i(2));
CORRADE_COMPARE_AS(Containers::arrayCast<UnsignedByte>(imageData).suffix(PixelStorageData[testCaseInstanceId()].offset),
PixelStorageData[testCaseInstanceId()].data,
TestSuite::Compare::Container);
}
namespace {
constexpr UnsignedByte Zero[4*4*4]{};
constexpr UnsignedByte SubDataComplete[]{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0, 0, 0, 0,
0, 0, 0, 0, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
}
void RectangleTextureGLTest::subImage() {
setTestCaseDescription(PixelStorageData[testCaseInstanceId()].name);
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setImage(TextureFormat::RGBA8,
ImageView2D(PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i(4), Zero));
texture.setSubImage(Vector2i(1), ImageView2D{
PixelStorageData[testCaseInstanceId()].storage,
PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i(2),
PixelStorageData[testCaseInstanceId()].dataSparse});
MAGNUM_VERIFY_NO_ERROR();
Image2D image = texture.image({PixelFormat::RGBA, PixelType::UnsignedByte});
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(image.size(), Vector2i(4));
CORRADE_COMPARE_AS(Containers::arrayCast<UnsignedByte>(image.data()),
Containers::arrayView(SubDataComplete), TestSuite::Compare::Container);
}
void RectangleTextureGLTest::subImageBuffer() {
setTestCaseDescription(PixelStorageData[testCaseInstanceId()].name);
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setImage(TextureFormat::RGBA8,
ImageView2D(PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i(4), Zero));
texture.setSubImage(Vector2i(1), BufferImage2D{
PixelStorageData[testCaseInstanceId()].storage,
PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i(2),
PixelStorageData[testCaseInstanceId()].dataSparse,
BufferUsage::StaticDraw});
MAGNUM_VERIFY_NO_ERROR();
BufferImage2D image = texture.image({PixelFormat::RGBA, PixelType::UnsignedByte}, BufferUsage::StaticRead);
const auto imageData = image.buffer().data();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(image.size(), Vector2i(4));
CORRADE_COMPARE_AS(Containers::arrayCast<UnsignedByte>(imageData),
Containers::arrayView(SubDataComplete),
TestSuite::Compare::Container);
}
void RectangleTextureGLTest::subImageQuery() {
setTestCaseDescription(PixelStorageData[testCaseInstanceId()].name);
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::get_texture_sub_image>())
CORRADE_SKIP(Extensions::GL::ARB::get_texture_sub_image::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setStorage(TextureFormat::RGBA8, Vector2i{4})
.setSubImage({}, ImageView2D{PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i{4}, SubDataComplete});
MAGNUM_VERIFY_NO_ERROR();
Image2D image = texture.subImage(Range2Di::fromSize(Vector2i{1}, Vector2i{2}),
{PixelStorageData[testCaseInstanceId()].storage,
PixelFormat::RGBA, PixelType::UnsignedByte});
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(image.size(), Vector2i{2});
CORRADE_COMPARE_AS(Containers::arrayCast<UnsignedByte>(image.data()).suffix(PixelStorageData[testCaseInstanceId()].offset),
PixelStorageData[testCaseInstanceId()].data,
TestSuite::Compare::Container);
}
void RectangleTextureGLTest::subImageQueryBuffer() {
setTestCaseDescription(PixelStorageData[testCaseInstanceId()].name);
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::get_texture_sub_image>())
CORRADE_SKIP(Extensions::GL::ARB::get_texture_sub_image::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setStorage(TextureFormat::RGBA8, Vector2i{4})
.setSubImage({}, ImageView2D{PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i{4}, SubDataComplete});
MAGNUM_VERIFY_NO_ERROR();
BufferImage2D image = texture.subImage(Range2Di::fromSize(Vector2i{1}, Vector2i{2}),
{PixelStorageData[testCaseInstanceId()].storage,
PixelFormat::RGBA, PixelType::UnsignedByte}, BufferUsage::StaticRead);
const auto imageData = image.buffer().data();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(image.size(), Vector2i{2});
CORRADE_COMPARE_AS(Containers::arrayCast<UnsignedByte>(imageData).suffix(PixelStorageData[testCaseInstanceId()].offset),
PixelStorageData[testCaseInstanceId()].data,
TestSuite::Compare::Container);
}
void RectangleTextureGLTest::compressedImage() {
CORRADE_SKIP("No rectangle texture compression format exists.");
}
void RectangleTextureGLTest::compressedImageBuffer() {
CORRADE_SKIP("No rectangle texture compression format exists.");
}
void RectangleTextureGLTest::compressedSubImage() {
CORRADE_SKIP("No rectangle texture compression format exists.");
}
void RectangleTextureGLTest::compressedSubImageBuffer() {
CORRADE_SKIP("No rectangle texture compression format exists.");
}
void RectangleTextureGLTest::compressedSubImageQuery() {
CORRADE_SKIP("No rectangle texture compression format exists.");
}
void RectangleTextureGLTest::compressedSubImageQueryBuffer() {
CORRADE_SKIP("No rectangle texture compression format exists.");
}
void RectangleTextureGLTest::invalidateImage() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setStorage(TextureFormat::RGBA8, Vector2i(32));
texture.invalidateImage();
MAGNUM_VERIFY_NO_ERROR();
}
void RectangleTextureGLTest::invalidateSubImage() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::texture_rectangle>())
CORRADE_SKIP(Extensions::GL::ARB::texture_rectangle::string() + std::string(" is not supported."));
RectangleTexture texture;
texture.setStorage(TextureFormat::RGBA8, Vector2i(32));
texture.invalidateSubImage(Vector2i(4), Vector2i(16));
MAGNUM_VERIFY_NO_ERROR();
}
}}
CORRADE_TEST_MAIN(Magnum::Test::RectangleTextureGLTest)
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
879134a7c14923e5cee73c763871101ea5f4058e | eee81611a5961254832c7ce8f0bd9357d400c6a3 | /libs/oss/others/APL/opencore/oscl/oscl/osclbase/src/pvlogger_accessories.h | 8b577515db7b9d72f7ddbb04daf7c8d46c05442a | [] | no_license | easycodec/emlinux-ssd1935 | ba829b2743529bf98bc229a69c27ed3dcb166a8d | 34782c27c8a4d7f915467637f8974c69345719e4 | refs/heads/master | 2020-07-30T14:12:19.210694 | 2016-01-09T10:09:45 | 2016-01-09T10:09:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,603 | h | /* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
* -------------------------------------------------------------------
*/
#ifndef PVLOGGER_ACCESSORIES_H_INCLUDED
#define PVLOGGER_ACCESSORIES_H_INCLUDED
#ifndef OSCL_BASE_H_INCLUDED
#include "oscl_base.h"
#endif
#ifndef PVLOGGER_H_INCLUDED
#include "pvlogger.h"
#endif
/**
* Base class for all message formatters. This class defines the interface to
* the message formatter. There are two kinds of msg formatting APIs, one to
* format text messages, and other to format opaque message buffers.
*/
class PVLoggerLayout
{
public:
typedef PVLogger::message_id_type message_id_type;
virtual ~PVLoggerLayout() {}
/**
* Formats the string and copies it to the given buffer.
*
* @return The length of the string not including the trailing '\0'
*/
virtual int32 FormatString(char* formatBuf, int32 formatBufSize,
message_id_type msgID, const char * fmt,
va_list va) = 0;
/**
* Formats the data and copies it to the given buffer.
*
* @return The length of the buffer used.
*/
virtual int32 FormatOpaqueMessage(char* formatBuf, int32 formatBufSize,
message_id_type msgID, int32 numPairs,
va_list va) = 0;
};
/**
* Base class for all message filters. This class defines the interface to
* the message filters. There are two kinds of msg filtering APIs, one to
* filter text messages, and other to filter opaque message buffers.
*/
class PVLoggerFilter
{
public:
virtual ~PVLoggerFilter() {}
typedef PVLogger::message_id_type message_id_type;
typedef PVLogger::log_level_type log_level_type;
typedef PVLogger::filter_status_type filter_status_type;
virtual filter_status_type FilterString(char* tag, message_id_type msgID, log_level_type level) = 0;
virtual filter_status_type FilterOpaqueMessge(char* tag, message_id_type msgID, log_level_type level) = 0;
};
const PVLoggerFilter::filter_status_type PVLOGGER_FILTER_ACCEPT = 1;
const PVLoggerFilter::filter_status_type PVLOGGER_FILTER_REJECT = 2;
const PVLoggerFilter::filter_status_type PVLOGGER_FILTER_NEUTRAL = 3;
/**
* Example filter that allows all messages to be logged.
*/
class AllPassFilter : public PVLoggerFilter
{
public:
typedef PVLoggerFilter::message_id_type message_id_type;
typedef PVLoggerFilter::log_level_type log_level_type;
typedef PVLoggerFilter::filter_status_type filter_status_type;
AllPassFilter() {};
virtual ~AllPassFilter() {};
filter_status_type FilterString(char* tag, message_id_type msgID, log_level_type level)
{
OSCL_UNUSED_ARG(tag);
OSCL_UNUSED_ARG(msgID);
OSCL_UNUSED_ARG(level);
return (PVLOGGER_FILTER_ACCEPT);
};
filter_status_type FilterOpaqueMessge(char* tag, message_id_type msgID, log_level_type level)
{
OSCL_UNUSED_ARG(tag);
OSCL_UNUSED_ARG(msgID);
OSCL_UNUSED_ARG(level);
return (PVLOGGER_FILTER_ACCEPT);
};
};
/**
* Base class for all message appenders. This class defines the interface to
* the message appenders. There are two kinds of msg appender APIs, one to
* append text messages, and other to append opaque message buffers.
*/
class PVLoggerAppender
{
public:
typedef PVLogger::message_id_type message_id_type;
virtual ~PVLoggerAppender() {}
virtual void AppendString(message_id_type msgID, const char *fmt, va_list va) = 0;
virtual void AppendBuffers(message_id_type msgID, int32 numPairs, va_list va) = 0;
};
#endif
| [
"acassis@gmail.com"
] | acassis@gmail.com |
f396cb61d5cdb07791e8004386d61eb53a7166fd | 2f16099c2311e817fd1287573ba98d9acb3582ec | /shootinggame/player_bullet_spread.cpp | e1acedcc55dcc0230312243ebe7255fa75281e46 | [] | no_license | jiwonan/ShootingGame01 | 80ca7d47f1f9afbfedc73a27266458190a3887d1 | 8b9eaf5bc11c1dfd4eab15a36ae4f85aebac1441 | refs/heads/master | 2022-11-05T15:25:17.595442 | 2020-06-11T11:42:27 | 2020-06-11T11:42:27 | 267,024,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,141 | cpp | #include "player_bullet_spread.h"
#include "global.h"
PlayerBulletSpread::PlayerBulletSpread(int x, int y, float vx, float vy)
{
posX = x;
posY = y;
velX = vx;
velY = vy;
isDead = false;
}
void PlayerBulletSpread::Update()
{
posX += velX;
posY += velY;
if (posX<0 || posX>WINDOW_WIDTH ||
posY<0 || posY>WINDOW_HEIGHT)
{
isDead = true;
}
}
void PlayerBulletSpread::Render()
{
TextureElement* bullet = textureManager.GetTexture(GAME_PLAYER_BULLET_1);
// Rendering of scene objects can happen here
bullet->sprite->Begin(D3DXSPRITE_ALPHABLEND);
RECT srcRect;
srcRect.left = 0;
srcRect.top = 0;
srcRect.bottom = 11;
srcRect.right = 11;
D3DXVECTOR3 pos(posX - 5, posY - 5, 0);
bullet->sprite->Draw(bullet->texture, &srcRect, nullptr, &pos, D3DCOLOR_XRGB(255, 255, 255));
bullet->sprite->End();
}
bool PlayerBulletSpread::IsDead()
{
return isDead;
}
float PlayerBulletSpread::GetRadius()
{
return 6.0f;
}
D3DXVECTOR2 PlayerBulletSpread::GetPosition()
{
return D3DXVECTOR2(posX, posY);
}
void PlayerBulletSpread::Hit()
{
isDead = true;
} | [
"s2018s31@e-mirim.hs.kr"
] | s2018s31@e-mirim.hs.kr |
28a4f6005ff49e9c4dbe92e9b250aa3afe07a93d | 5cad8d9664c8316cce7bc57128ca4b378a93998a | /CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/gnu/javax/net/ssl/provider/EncryptedPreMasterSecret.h | ae9382142c31c990a8998dadd6b3c145251cb008 | [
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"GPL-3.0-only",
"curl",
"Zlib",
"LicenseRef-scancode-warranty-disclaimer",
"OpenSSL",
"GPL-1.0-or-later",
"MIT",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"BSD-3-... | permissive | huaweicloud/huaweicloud-sdk-c-obs | 0c60d61e16de5c0d8d3c0abc9446b5269e7462d4 | fcd0bf67f209cc96cf73197e9c0df143b1d097c4 | refs/heads/master | 2023-09-05T11:42:28.709499 | 2023-08-05T08:52:56 | 2023-08-05T08:52:56 | 163,231,391 | 41 | 21 | Apache-2.0 | 2023-06-28T07:18:06 | 2018-12-27T01:15:05 | C | UTF-8 | C++ | false | false | 1,520 | h |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __gnu_javax_net_ssl_provider_EncryptedPreMasterSecret__
#define __gnu_javax_net_ssl_provider_EncryptedPreMasterSecret__
#pragma interface
#include <gnu/javax/net/ssl/provider/ExchangeKeys.h>
#include <gcj/array.h>
extern "Java"
{
namespace gnu
{
namespace javax
{
namespace net
{
namespace ssl
{
namespace provider
{
class EncryptedPreMasterSecret;
class ProtocolVersion;
}
}
}
}
}
namespace java
{
namespace nio
{
class ByteBuffer;
}
}
}
class gnu::javax::net::ssl::provider::EncryptedPreMasterSecret : public ::gnu::javax::net::ssl::provider::ExchangeKeys
{
public:
EncryptedPreMasterSecret(::java::nio::ByteBuffer *, ::gnu::javax::net::ssl::provider::ProtocolVersion *);
EncryptedPreMasterSecret(JArray< jbyte > *, ::gnu::javax::net::ssl::provider::ProtocolVersion *);
::java::nio::ByteBuffer * buffer();
JArray< jbyte > * encryptedSecret();
void setEncryptedSecret(JArray< jbyte > *, jint, jint);
jint length();
::java::lang::String * toString();
::java::lang::String * toString(::java::lang::String *);
private:
::gnu::javax::net::ssl::provider::ProtocolVersion * __attribute__((aligned(__alignof__( ::gnu::javax::net::ssl::provider::ExchangeKeys)))) version;
public:
static ::java::lang::Class class$;
};
#endif // __gnu_javax_net_ssl_provider_EncryptedPreMasterSecret__
| [
"xiangshijian1@huawei.com"
] | xiangshijian1@huawei.com |
a5a27b61e6455bf58cbf3e2c3cbd53e09c7ab324 | 6c0089dfcc5be28c923808fe21327b617dfeb8ac | /Assignment2/assignment2.cpp | 88e85bf5ab8eba4d293b7b44759711de15146193 | [] | no_license | rich-hart/ICG_HW | 9153a4bdb9cd46415304f75e317ff7a8ac7c3e5e | 919e75098cd304e05e7771c199e4adc87ff8190c | refs/heads/master | 2016-09-10T21:17:18.794230 | 2013-06-26T17:15:02 | 2013-06-26T17:15:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,842 | cpp | /*
Richard Hart
Assignment 2
*/
#include "include/Angel.h"
#include <math.h>
#define BUFFER_SIZE 100000
#define RED 0
#define RED_SHADED 1
#define WHITE 2
#define BLACK 3
#define MULTI_COLORED 4
#define SHADE_CENTER 0
#define SHADE_OFF_CENTER 1
#define SHADE_VERTEXS 2
//Angel Code:
vec2 vertices[BUFFER_SIZE] ;// Specifiy the vertices for a triangle
vec2 *ver_pointer;
int NumPoints = 0;
void Vertex_Array_Object(void);
void Initialize_Buffer_Object(void);
void Load_Shaders(void);
//---------
// My Code:
//define constants
#define PI 3.14159265
#define SHAPE_BUFFER_SIZE 100000
#define VECT_BUFFER_SIZE 100000
//arrays to hold shape and color data of objects
vec2 shape_buffer[SHAPE_BUFFER_SIZE];
vec2 *shape_pointer;
int index = 0;
vec4 colors[BUFFER_SIZE] ;
int color_index=0;
//this loads vertex data from my buffer into angel's
void load_data(vec2 *ver_pointer,vec2 *shape_pointer);
//functions that load data needed to generate an object into my buffer
void load_triangle(vec2 A, vec2 B, vec2 C);
void load_color(float r, float g, float b, float a);
void load_multi_color(void);
//functions used to generate shapes
float Degre_To_Rads(float degree);
void Make_Poly(float cx, float cy, float a, float b, float r,float rotate, int sides,int color, int shade_location);
void Make_Square(void);
void Make_Equil_Tri(void);
void Make_Circle(void);
void Make_Ellipse(void);
void Create_Shapes(void);
//load 3 non co-plainer points into the shape buffer render a triangle.
void load_triangle(vec2 A, vec2 B, vec2 C){
shape_buffer[index]=A;
index++;
shape_buffer[index]=B;
index++;
shape_buffer[index]=C;
index++;
}
// defines the color of a triangle that was just added into the shape buffer.
//must be called after load_triangle.
void load_color(float r, float g, float b, float a){
for(int i=0;i<3;i++){
colors[color_index]=vec4(r,g,b,a);
color_index++;
}
}
// defines a multicolored shading for a triangle that was just added into the shape buffer.
//must be called after load_triangle.
void load_multi_color(void){
colors[color_index]=vec4(1.0,0.0,0.0,1.0);
color_index++;
colors[color_index]=vec4(0.0,1.0,0.0,1.0);
color_index++;
colors[color_index]=vec4(0.0,0.0,1.0,1.0);
color_index++;
}
// loads data from my buffer into angels vertex buffer
void load_data(vec2 *ver_pointer,vec2 *shape_pointer){
NumPoints=index;
shape_pointer=shape_buffer;
for(int i=0;i<NumPoints;i++){
*ver_pointer= *shape_pointer;
ver_pointer++;
shape_pointer++;
}
}
float Degre_To_Rads(float degree){
return (degree / 180.0 )*M_PI;
}
//creates an polygon who's vertexes lie on the ellipse equation (x/a)^2+(y/b)^2=r^2
void Make_Poly(float cx, float cy, float a, float b, float r,float rotate, int sides,int color, int shade_location){
vec2 vect_buffer[sides];
vec2 temp1;
vec2 temp2;
vec2 temp3;
vec2 center;
vec2 off_center;
float x;
float y;
float degree=rotate;
// calculating the vertex locations of the polygon and storing them temperarily in the vect_buffer array
for(int i=0; i<=sides;i++){
x=sqrt(r)*a*cos(Degre_To_Rads(degree))+cx;
y=sqrt(r)*b*sin(Degre_To_Rads(degree))+cy;
vect_buffer[i]=vec2(x,y);
degree=degree+(360.0/(float)sides);
}
center=vec2(cx,cy);
off_center=vect_buffer[0];
// deciding how the triangles that create the polygon will be constructed e.g.
for(int i=0; i<=sides;i++){
temp1=vect_buffer[i%sides];
temp2=vect_buffer[(i+1)%sides];
switch (shade_location){
// all triangles have a common vertex at the center of the polygon
case SHADE_CENTER:
temp3=center;
break;
//the first vertex created for the polygon will also be a vertex for every triangle the makes up the polygon.
case SHADE_OFF_CENTER:
temp3=off_center;
break;
//every three vertex's that are read from the vect_buffer array will form a triangle in the polygon.
case SHADE_VERTEXS:
temp3=vect_buffer[(i+2)%sides];
break;
}
load_triangle(temp1,temp2,temp3);
switch ( color )
{
//color the triangle red.
case RED:
load_color(1.0,0.0,0.0,1.0);
break;
//color the traingle based on some function associated with the current angle
case RED_SHADED:
load_color(float(i)/float(sides),0.0,0.0,1.0);
break;
//color the tri white
case WHITE:
load_color(1.0,1.0,1.0,1.0);
break;
//color the tri black
case BLACK:
load_color(0.0,0.0,0.0,1.0);
break;
//create a multicolored tri
case MULTI_COLORED:
load_multi_color();
break;
default:
break;
}
}
}
// create an ellispe by making a polygon of many sides..
void Make_Ellipse(void){
Make_Poly(-0.5,0.5,2.0,1.0,.01,0.0,360,RED,SHADE_CENTER);
}
// create an ellispe by making a polygon of many sides..
void Make_Circle(void){
Make_Poly(0.5,0.5,1.0,1.0,.05,0.0,360,RED_SHADED,SHADE_OFF_CENTER);
}
// make an equalateral tri
void Make_Equil_Tri(void){
Make_Poly(0.0,0.5,1.0,1.0,.05,90.0,3,MULTI_COLORED,SHADE_VERTEXS);
}
//create a black and white square pattern.
void Make_Square(void){
float center_to_vertex_length = sqrt(pow(.5,2)+pow(.5,2));
int color;
for(int i = 0 ; i <= 8;i++){
if (i%2){
color=BLACK;
} else {
color=WHITE;
}
Make_Poly(0.0,-0.5,1.0,1.0,center_to_vertex_length*pow(2.0,-1.0*i),45.0,4,color,SHADE_CENTER);
}
}
// the function that defines that shaped to be displays
void Create_Shapes(void){
Make_Ellipse();
Make_Circle();
Make_Equil_Tri();
Make_Square();
}
void
init( void )
{
ver_pointer=vertices;
Create_Shapes();
load_data(ver_pointer,shape_pointer);
Vertex_Array_Object();
Initialize_Buffer_Object();
Load_Shaders();
}
//----------------------------------------------------------------------------
void
display( void )
{
glClear( GL_COLOR_BUFFER_BIT ); // clear the window
glDrawArrays( GL_TRIANGLES, 0, NumPoints ); // draw the points
glFlush();
}
//----------------------------------------------------------------------------
void
keyboard( unsigned char key, int x, int y )
{
switch ( key ) {
case 033:
exit( EXIT_SUCCESS );
break;
}
}
//----------------------------------------------------------------------------
int
main( int argc, char **argv )
{
puts("Testing Textmate Editing");
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA );
glutInitWindowSize( 512, 512 );
glutCreateWindow( "Assignment 2" );
glewExperimental=GL_TRUE;
glewInit();
init();
glutDisplayFunc( display );
glutKeyboardFunc( keyboard );
glutMainLoop();
return 0;
}
void Vertex_Array_Object(void){
// Create a vertex array object
GLuint vao[1];
glGenVertexArrays( 1, vao );
glBindVertexArray( vao[0] );
}
void Initialize_Buffer_Object(void){
// Create and initialize a buffer object
GLuint buffer;
glGenBuffers( 1, &buffer );
glBindBuffer( GL_ARRAY_BUFFER, buffer );
glBufferData( GL_ARRAY_BUFFER, sizeof(vertices)+sizeof(colors), NULL, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER,0, sizeof(vertices), vertices );
glBufferSubData( GL_ARRAY_BUFFER,sizeof(vertices), sizeof(colors), colors );
}
void Load_Shaders(void){
// Load shaders and use the resulting shader program
GLuint program = InitShader( "vshader21.glsl", "fshader21.glsl" );
glUseProgram( program );
// Initialize the vertex position attribute from the vertex shader
GLuint loc = glGetAttribLocation( program, "vPosition" );
glEnableVertexAttribArray( loc );
glVertexAttribPointer( loc, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );
//Initialize the vertex position attribute from the vertex shader
GLuint loc2 = glGetAttribLocation( program, "vColor" );
glEnableVertexAttribArray( loc2 );
glVertexAttribPointer( loc2, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)) );
glClearColor( 0.0, 0.0, 0.0, 1.0 ); // black background
}
| [
"RichHOHart@gmail.com"
] | RichHOHart@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.